Backport from GCC mainline.
[platform/upstream/linaro-gcc.git] / gcc / tree-ssa-coalesce.c
1 /* Coalesce SSA_NAMES together for the out-of-ssa pass.
2    Copyright (C) 2004-2016 Free Software Foundation, Inc.
3    Contributed by Andrew MacLeod <amacleod@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License 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 "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "predict.h"
28 #include "tm_p.h"
29 #include "ssa.h"
30 #include "tree-pretty-print.h"
31 #include "diagnostic-core.h"
32 #include "dumpfile.h"
33 #include "gimple-iterator.h"
34 #include "tree-ssa-live.h"
35 #include "tree-ssa-coalesce.h"
36 #include "explow.h"
37 #include "tree-dfa.h"
38 #include "stor-layout.h"
39
40 /* This set of routines implements a coalesce_list.  This is an object which
41    is used to track pairs of ssa_names which are desirable to coalesce
42    together to avoid copies.  Costs are associated with each pair, and when
43    all desired information has been collected, the object can be used to
44    order the pairs for processing.  */
45
46 /* This structure defines a pair entry.  */
47
48 struct coalesce_pair
49 {
50   int first_element;
51   int second_element;
52   int cost;
53
54   /* A count of the number of unique partitions this pair would conflict
55      with if coalescing was successful.  This is the secondary sort key,
56      given two pairs with equal costs, we will prefer the pair with a smaller
57      conflict set.
58
59      This is lazily initialized when we discover two coalescing pairs have
60      the same primary cost.
61
62      Note this is not updated and propagated as pairs are coalesced.  */
63   int conflict_count;
64
65   /* The order in which coalescing pairs are discovered is recorded in this
66      field, which is used as the final tie breaker when sorting coalesce
67      pairs.  */
68   int index;
69 };
70
71 /* This represents a conflict graph.  Implemented as an array of bitmaps.
72    A full matrix is used for conflicts rather than just upper triangular form.
73    this makes it much simpler and faster to perform conflict merges.  */
74
75 struct ssa_conflicts
76 {
77   bitmap_obstack obstack;       /* A place to allocate our bitmaps.  */
78   vec<bitmap> conflicts;
79 };
80
81 /* The narrow API of the qsort comparison function doesn't allow easy
82    access to additional arguments.  So we have two globals (ick) to hold
83    the data we need.  They're initialized before the call to qsort and
84    wiped immediately after.  */
85 static ssa_conflicts *conflicts_;
86 static var_map map_;
87
88 /* Coalesce pair hashtable helpers.  */
89
90 struct coalesce_pair_hasher : nofree_ptr_hash <coalesce_pair>
91 {
92   static inline hashval_t hash (const coalesce_pair *);
93   static inline bool equal (const coalesce_pair *, const coalesce_pair *);
94 };
95
96 /* Hash function for coalesce list.  Calculate hash for PAIR.   */
97
98 inline hashval_t
99 coalesce_pair_hasher::hash (const coalesce_pair *pair)
100 {
101   hashval_t a = (hashval_t)(pair->first_element);
102   hashval_t b = (hashval_t)(pair->second_element);
103
104   return b * (b - 1) / 2 + a;
105 }
106
107 /* Equality function for coalesce list hash table.  Compare PAIR1 and PAIR2,
108    returning TRUE if the two pairs are equivalent.  */
109
110 inline bool
111 coalesce_pair_hasher::equal (const coalesce_pair *p1, const coalesce_pair *p2)
112 {
113   return (p1->first_element == p2->first_element
114           && p1->second_element == p2->second_element);
115 }
116
117 typedef hash_table<coalesce_pair_hasher> coalesce_table_type;
118 typedef coalesce_table_type::iterator coalesce_iterator_type;
119
120
121 struct cost_one_pair
122 {
123   int first_element;
124   int second_element;
125   cost_one_pair *next;
126 };
127
128 /* This structure maintains the list of coalesce pairs.  */
129
130 struct coalesce_list
131 {
132   coalesce_table_type *list;    /* Hash table.  */
133   coalesce_pair **sorted;       /* List when sorted.  */
134   int num_sorted;               /* Number in the sorted list.  */
135   cost_one_pair *cost_one_list;/* Single use coalesces with cost 1.  */
136 };
137
138 #define NO_BEST_COALESCE        -1
139 #define MUST_COALESCE_COST      INT_MAX
140
141
142 /* Return cost of execution of copy instruction with FREQUENCY.  */
143
144 static inline int
145 coalesce_cost (int frequency, bool optimize_for_size)
146 {
147   /* Base costs on BB frequencies bounded by 1.  */
148   int cost = frequency;
149
150   if (!cost)
151     cost = 1;
152
153   if (optimize_for_size)
154     cost = 1;
155
156   return cost;
157 }
158
159
160 /* Return the cost of executing a copy instruction in basic block BB.  */
161
162 static inline int
163 coalesce_cost_bb (basic_block bb)
164 {
165   return coalesce_cost (bb->frequency, optimize_bb_for_size_p (bb));
166 }
167
168
169 /* Return the cost of executing a copy instruction on edge E.  */
170
171 static inline int
172 coalesce_cost_edge (edge e)
173 {
174   int mult = 1;
175
176   /* Inserting copy on critical edge costs more than inserting it elsewhere.  */
177   if (EDGE_CRITICAL_P (e))
178     mult = 2;
179   if (e->flags & EDGE_ABNORMAL)
180     return MUST_COALESCE_COST;
181   if (e->flags & EDGE_EH)
182     {
183       edge e2;
184       edge_iterator ei;
185       FOR_EACH_EDGE (e2, ei, e->dest->preds)
186         if (e2 != e)
187           {
188             /* Putting code on EH edge that leads to BB
189                with multiple predecestors imply splitting of
190                edge too.  */
191             if (mult < 2)
192               mult = 2;
193             /* If there are multiple EH predecestors, we
194                also copy EH regions and produce separate
195                landing pad.  This is expensive.  */
196             if (e2->flags & EDGE_EH)
197               {
198                 mult = 5;
199                 break;
200               }
201           }
202     }
203
204   return coalesce_cost (EDGE_FREQUENCY (e),
205                         optimize_edge_for_size_p (e)) * mult;
206 }
207
208
209 /* Retrieve a pair to coalesce from the cost_one_list in CL.  Returns the
210    2 elements via P1 and P2.  1 is returned by the function if there is a pair,
211    NO_BEST_COALESCE is returned if there aren't any.  */
212
213 static inline int
214 pop_cost_one_pair (coalesce_list *cl, int *p1, int *p2)
215 {
216   cost_one_pair *ptr;
217
218   ptr = cl->cost_one_list;
219   if (!ptr)
220     return NO_BEST_COALESCE;
221
222   *p1 = ptr->first_element;
223   *p2 = ptr->second_element;
224   cl->cost_one_list = ptr->next;
225
226   free (ptr);
227
228   return 1;
229 }
230
231 /* Retrieve the most expensive remaining pair to coalesce from CL.  Returns the
232    2 elements via P1 and P2.  Their calculated cost is returned by the function.
233    NO_BEST_COALESCE is returned if the coalesce list is empty.  */
234
235 static inline int
236 pop_best_coalesce (coalesce_list *cl, int *p1, int *p2)
237 {
238   coalesce_pair *node;
239   int ret;
240
241   if (cl->sorted == NULL)
242     return pop_cost_one_pair (cl, p1, p2);
243
244   if (cl->num_sorted == 0)
245     return pop_cost_one_pair (cl, p1, p2);
246
247   node = cl->sorted[--(cl->num_sorted)];
248   *p1 = node->first_element;
249   *p2 = node->second_element;
250   ret = node->cost;
251   free (node);
252
253   return ret;
254 }
255
256
257 /* Create a new empty coalesce list object and return it.  */
258
259 static inline coalesce_list *
260 create_coalesce_list (void)
261 {
262   coalesce_list *list;
263   unsigned size = num_ssa_names * 3;
264
265   if (size < 40)
266     size = 40;
267
268   list = (coalesce_list *) xmalloc (sizeof (struct coalesce_list));
269   list->list = new coalesce_table_type (size);
270   list->sorted = NULL;
271   list->num_sorted = 0;
272   list->cost_one_list = NULL;
273   return list;
274 }
275
276
277 /* Delete coalesce list CL.  */
278
279 static inline void
280 delete_coalesce_list (coalesce_list *cl)
281 {
282   gcc_assert (cl->cost_one_list == NULL);
283   delete cl->list;
284   cl->list = NULL;
285   free (cl->sorted);
286   gcc_assert (cl->num_sorted == 0);
287   free (cl);
288 }
289
290 /* Return the number of unique coalesce pairs in CL.  */
291
292 static inline int
293 num_coalesce_pairs (coalesce_list *cl)
294 {
295   return cl->list->elements ();
296 }
297
298 /* Find a matching coalesce pair object in CL for the pair P1 and P2.  If
299    one isn't found, return NULL if CREATE is false, otherwise create a new
300    coalesce pair object and return it.  */
301
302 static coalesce_pair *
303 find_coalesce_pair (coalesce_list *cl, int p1, int p2, bool create)
304 {
305   struct coalesce_pair p;
306   coalesce_pair **slot;
307   unsigned int hash;
308
309   /* Normalize so that p1 is the smaller value.  */
310   if (p2 < p1)
311     {
312       p.first_element = p2;
313       p.second_element = p1;
314     }
315   else
316     {
317       p.first_element = p1;
318       p.second_element = p2;
319     }
320
321   hash = coalesce_pair_hasher::hash (&p);
322   slot = cl->list->find_slot_with_hash (&p, hash, create ? INSERT : NO_INSERT);
323   if (!slot)
324     return NULL;
325
326   if (!*slot)
327     {
328       struct coalesce_pair * pair = XNEW (struct coalesce_pair);
329       gcc_assert (cl->sorted == NULL);
330       pair->first_element = p.first_element;
331       pair->second_element = p.second_element;
332       pair->cost = 0;
333       pair->index = num_coalesce_pairs (cl);
334       pair->conflict_count = 0;
335       *slot = pair;
336     }
337
338   return (struct coalesce_pair *) *slot;
339 }
340
341 static inline void
342 add_cost_one_coalesce (coalesce_list *cl, int p1, int p2)
343 {
344   cost_one_pair *pair;
345
346   pair = XNEW (cost_one_pair);
347   pair->first_element = p1;
348   pair->second_element = p2;
349   pair->next = cl->cost_one_list;
350   cl->cost_one_list = pair;
351 }
352
353
354 /* Add a coalesce between P1 and P2 in list CL with a cost of VALUE.  */
355
356 static inline void
357 add_coalesce (coalesce_list *cl, int p1, int p2, int value)
358 {
359   coalesce_pair *node;
360
361   gcc_assert (cl->sorted == NULL);
362   if (p1 == p2)
363     return;
364
365   node = find_coalesce_pair (cl, p1, p2, true);
366
367   /* Once the value is at least MUST_COALESCE_COST - 1, leave it that way.  */
368   if (node->cost < MUST_COALESCE_COST - 1)
369     {
370       if (value < MUST_COALESCE_COST - 1)
371         node->cost += value;
372       else
373         node->cost = value;
374     }
375 }
376
377 /* Compute and record how many unique conflicts would exist for the
378    representative partition for each coalesce pair in CL.
379
380    CONFLICTS is the conflict graph and MAP is the current partition view.  */
381
382 static void
383 initialize_conflict_count (coalesce_pair *p,
384                            ssa_conflicts *conflicts,
385                            var_map map)
386 {
387   int p1 = var_to_partition (map, ssa_name (p->first_element));
388   int p2 = var_to_partition (map, ssa_name (p->second_element));
389
390   /* 4 cases.  If both P1 and P2 have conflicts, then build their
391      union and count the members.  Else handle the degenerate cases
392      in the obvious ways.  */
393   if (conflicts->conflicts[p1] && conflicts->conflicts[p2])
394     p->conflict_count = bitmap_count_unique_bits (conflicts->conflicts[p1],
395                                                   conflicts->conflicts[p2]);
396   else if (conflicts->conflicts[p1])
397     p->conflict_count = bitmap_count_bits (conflicts->conflicts[p1]);
398   else if (conflicts->conflicts[p2])
399     p->conflict_count = bitmap_count_bits (conflicts->conflicts[p2]);
400   else
401     p->conflict_count = 0;
402 }
403
404
405 /* Comparison function to allow qsort to sort P1 and P2 in Ascending order.  */
406
407 static int
408 compare_pairs (const void *p1, const void *p2)
409 {
410   coalesce_pair *const *const pp1 = (coalesce_pair *const *) p1;
411   coalesce_pair *const *const pp2 = (coalesce_pair *const *) p2;
412   int result;
413
414   result = (* pp1)->cost - (* pp2)->cost;
415   /* We use the size of the resulting conflict set as the secondary sort key.
416      Given two equal costing coalesce pairs, we want to prefer the pair that
417      has the smaller conflict set.  */
418   if (result == 0)
419     {
420       if (flag_expensive_optimizations)
421         {
422           /* Lazily initialize the conflict counts as it's fairly expensive
423              to compute.  */
424           if ((*pp2)->conflict_count == 0)
425             initialize_conflict_count (*pp2, conflicts_, map_);
426           if ((*pp1)->conflict_count == 0)
427             initialize_conflict_count (*pp1, conflicts_, map_);
428
429           result = (*pp2)->conflict_count - (*pp1)->conflict_count;
430         }
431
432       /* And if everything else is equal, then sort based on which
433          coalesce pair was found first.  */
434       if (result == 0)
435         result = (*pp2)->index - (*pp1)->index;
436     }
437
438   return result;
439 }
440
441 /* Iterate over CL using ITER, returning values in PAIR.  */
442
443 #define FOR_EACH_PARTITION_PAIR(PAIR, ITER, CL)         \
444   FOR_EACH_HASH_TABLE_ELEMENT (*(CL)->list, (PAIR), coalesce_pair_p, (ITER))
445
446
447 /* Prepare CL for removal of preferred pairs.  When finished they are sorted
448    in order from most important coalesce to least important.  */
449
450 static void
451 sort_coalesce_list (coalesce_list *cl, ssa_conflicts *conflicts, var_map map)
452 {
453   unsigned x, num;
454   coalesce_pair *p;
455   coalesce_iterator_type ppi;
456
457   gcc_assert (cl->sorted == NULL);
458
459   num = num_coalesce_pairs (cl);
460   cl->num_sorted = num;
461   if (num == 0)
462     return;
463
464   /* Allocate a vector for the pair pointers.  */
465   cl->sorted = XNEWVEC (coalesce_pair *, num);
466
467   /* Populate the vector with pointers to the pairs.  */
468   x = 0;
469   FOR_EACH_PARTITION_PAIR (p, ppi, cl)
470     cl->sorted[x++] = p;
471   gcc_assert (x == num);
472
473   /* Already sorted.  */
474   if (num == 1)
475     return;
476
477   /* We don't want to depend on qsort_r, so we have to stuff away
478      additional data into globals so it can be referenced in
479      compare_pairs.  */
480   conflicts_ = conflicts;
481   map_ = map;
482   qsort (cl->sorted, num, sizeof (coalesce_pair *), compare_pairs);
483   conflicts_ = NULL;
484   map_ = NULL;
485 }
486
487
488 /* Send debug info for coalesce list CL to file F.  */
489
490 static void
491 dump_coalesce_list (FILE *f, coalesce_list *cl)
492 {
493   coalesce_pair *node;
494   coalesce_iterator_type ppi;
495
496   int x;
497   tree var;
498
499   if (cl->sorted == NULL)
500     {
501       fprintf (f, "Coalesce List:\n");
502       FOR_EACH_PARTITION_PAIR (node, ppi, cl)
503         {
504           tree var1 = ssa_name (node->first_element);
505           tree var2 = ssa_name (node->second_element);
506           print_generic_expr (f, var1, TDF_SLIM);
507           fprintf (f, " <-> ");
508           print_generic_expr (f, var2, TDF_SLIM);
509           fprintf (f, "  (%1d, %1d), ", node->cost, node->conflict_count);
510           fprintf (f, "\n");
511         }
512     }
513   else
514     {
515       fprintf (f, "Sorted Coalesce list:\n");
516       for (x = cl->num_sorted - 1 ; x >=0; x--)
517         {
518           node = cl->sorted[x];
519           fprintf (f, "(%d, %d) ", node->cost, node->conflict_count);
520           var = ssa_name (node->first_element);
521           print_generic_expr (f, var, TDF_SLIM);
522           fprintf (f, " <-> ");
523           var = ssa_name (node->second_element);
524           print_generic_expr (f, var, TDF_SLIM);
525           fprintf (f, "\n");
526         }
527     }
528 }
529
530
531 /* Return an empty new conflict graph for SIZE elements.  */
532
533 static inline ssa_conflicts *
534 ssa_conflicts_new (unsigned size)
535 {
536   ssa_conflicts *ptr;
537
538   ptr = XNEW (ssa_conflicts);
539   bitmap_obstack_initialize (&ptr->obstack);
540   ptr->conflicts.create (size);
541   ptr->conflicts.safe_grow_cleared (size);
542   return ptr;
543 }
544
545
546 /* Free storage for conflict graph PTR.  */
547
548 static inline void
549 ssa_conflicts_delete (ssa_conflicts *ptr)
550 {
551   bitmap_obstack_release (&ptr->obstack);
552   ptr->conflicts.release ();
553   free (ptr);
554 }
555
556
557 /* Test if elements X and Y conflict in graph PTR.  */
558
559 static inline bool
560 ssa_conflicts_test_p (ssa_conflicts *ptr, unsigned x, unsigned y)
561 {
562   bitmap bx = ptr->conflicts[x];
563   bitmap by = ptr->conflicts[y];
564
565   gcc_checking_assert (x != y);
566
567   if (bx)
568     /* Avoid the lookup if Y has no conflicts.  */
569     return by ? bitmap_bit_p (bx, y) : false;
570   else
571     return false;
572 }
573
574
575 /* Add a conflict with Y to the bitmap for X in graph PTR.  */
576
577 static inline void
578 ssa_conflicts_add_one (ssa_conflicts *ptr, unsigned x, unsigned y)
579 {
580   bitmap bx = ptr->conflicts[x];
581   /* If there are no conflicts yet, allocate the bitmap and set bit.  */
582   if (! bx)
583     bx = ptr->conflicts[x] = BITMAP_ALLOC (&ptr->obstack);
584   bitmap_set_bit (bx, y);
585 }
586
587
588 /* Add conflicts between X and Y in graph PTR.  */
589
590 static inline void
591 ssa_conflicts_add (ssa_conflicts *ptr, unsigned x, unsigned y)
592 {
593   gcc_checking_assert (x != y);
594   ssa_conflicts_add_one (ptr, x, y);
595   ssa_conflicts_add_one (ptr, y, x);
596 }
597
598
599 /* Merge all Y's conflict into X in graph PTR.  */
600
601 static inline void
602 ssa_conflicts_merge (ssa_conflicts *ptr, unsigned x, unsigned y)
603 {
604   unsigned z;
605   bitmap_iterator bi;
606   bitmap bx = ptr->conflicts[x];
607   bitmap by = ptr->conflicts[y];
608
609   gcc_checking_assert (x != y);
610   if (! by)
611     return;
612
613   /* Add a conflict between X and every one Y has.  If the bitmap doesn't
614      exist, then it has already been coalesced, and we don't need to add a
615      conflict.  */
616   EXECUTE_IF_SET_IN_BITMAP (by, 0, z, bi)
617     {
618       bitmap bz = ptr->conflicts[z];
619       if (bz)
620         bitmap_set_bit (bz, x);
621     }
622
623   if (bx)
624     {
625       /* If X has conflicts, add Y's to X.  */
626       bitmap_ior_into (bx, by);
627       BITMAP_FREE (by);
628       ptr->conflicts[y] = NULL;
629     }
630   else
631     {
632       /* If X has no conflicts, simply use Y's.  */
633       ptr->conflicts[x] = by;
634       ptr->conflicts[y] = NULL;
635     }
636 }
637
638
639 /* Dump a conflicts graph.  */
640
641 static void
642 ssa_conflicts_dump (FILE *file, ssa_conflicts *ptr)
643 {
644   unsigned x;
645   bitmap b;
646
647   fprintf (file, "\nConflict graph:\n");
648
649   FOR_EACH_VEC_ELT (ptr->conflicts, x, b)
650     if (b)
651       {
652         fprintf (file, "%d: ", x);
653         dump_bitmap (file, b);
654       }
655 }
656
657
658 /* This structure is used to efficiently record the current status of live
659    SSA_NAMES when building a conflict graph.
660    LIVE_BASE_VAR has a bit set for each base variable which has at least one
661    ssa version live.
662    LIVE_BASE_PARTITIONS is an array of bitmaps using the basevar table as an
663    index, and is used to track what partitions of each base variable are
664    live.  This makes it easy to add conflicts between just live partitions
665    with the same base variable.
666    The values in LIVE_BASE_PARTITIONS are only valid if the base variable is
667    marked as being live.  This delays clearing of these bitmaps until
668    they are actually needed again.  */
669
670 struct live_track
671 {
672   bitmap_obstack obstack;       /* A place to allocate our bitmaps.  */
673   bitmap live_base_var;         /* Indicates if a basevar is live.  */
674   bitmap *live_base_partitions; /* Live partitions for each basevar.  */
675   var_map map;                  /* Var_map being used for partition mapping.  */
676 };
677
678
679 /* This routine will create a new live track structure based on the partitions
680    in MAP.  */
681
682 static live_track *
683 new_live_track (var_map map)
684 {
685   live_track *ptr;
686   int lim, x;
687
688   /* Make sure there is a partition view in place.  */
689   gcc_assert (map->partition_to_base_index != NULL);
690
691   ptr = (live_track *) xmalloc (sizeof (live_track));
692   ptr->map = map;
693   lim = num_basevars (map);
694   bitmap_obstack_initialize (&ptr->obstack);
695   ptr->live_base_partitions = (bitmap *) xmalloc (sizeof (bitmap *) * lim);
696   ptr->live_base_var = BITMAP_ALLOC (&ptr->obstack);
697   for (x = 0; x < lim; x++)
698     ptr->live_base_partitions[x] = BITMAP_ALLOC (&ptr->obstack);
699   return ptr;
700 }
701
702
703 /* This routine will free the memory associated with PTR.  */
704
705 static void
706 delete_live_track (live_track *ptr)
707 {
708   bitmap_obstack_release (&ptr->obstack);
709   free (ptr->live_base_partitions);
710   free (ptr);
711 }
712
713
714 /* This function will remove PARTITION from the live list in PTR.  */
715
716 static inline void
717 live_track_remove_partition (live_track *ptr, int partition)
718 {
719   int root;
720
721   root = basevar_index (ptr->map, partition);
722   bitmap_clear_bit (ptr->live_base_partitions[root], partition);
723   /* If the element list is empty, make the base variable not live either.  */
724   if (bitmap_empty_p (ptr->live_base_partitions[root]))
725     bitmap_clear_bit (ptr->live_base_var, root);
726 }
727
728
729 /* This function will adds PARTITION to the live list in PTR.  */
730
731 static inline void
732 live_track_add_partition (live_track *ptr, int partition)
733 {
734   int root;
735
736   root = basevar_index (ptr->map, partition);
737   /* If this base var wasn't live before, it is now.  Clear the element list
738      since it was delayed until needed.  */
739   if (bitmap_set_bit (ptr->live_base_var, root))
740     bitmap_clear (ptr->live_base_partitions[root]);
741   bitmap_set_bit (ptr->live_base_partitions[root], partition);
742
743 }
744
745
746 /* Clear the live bit for VAR in PTR.  */
747
748 static inline void
749 live_track_clear_var (live_track *ptr, tree var)
750 {
751   int p;
752
753   p = var_to_partition (ptr->map, var);
754   if (p != NO_PARTITION)
755     live_track_remove_partition (ptr, p);
756 }
757
758
759 /* Return TRUE if VAR is live in PTR.  */
760
761 static inline bool
762 live_track_live_p (live_track *ptr, tree var)
763 {
764   int p, root;
765
766   p = var_to_partition (ptr->map, var);
767   if (p != NO_PARTITION)
768     {
769       root = basevar_index (ptr->map, p);
770       if (bitmap_bit_p (ptr->live_base_var, root))
771         return bitmap_bit_p (ptr->live_base_partitions[root], p);
772     }
773   return false;
774 }
775
776
777 /* This routine will add USE to PTR.  USE will be marked as live in both the
778    ssa live map and the live bitmap for the root of USE.  */
779
780 static inline void
781 live_track_process_use (live_track *ptr, tree use)
782 {
783   int p;
784
785   p = var_to_partition (ptr->map, use);
786   if (p == NO_PARTITION)
787     return;
788
789   /* Mark as live in the appropriate live list.  */
790   live_track_add_partition (ptr, p);
791 }
792
793
794 /* This routine will process a DEF in PTR.  DEF will be removed from the live
795    lists, and if there are any other live partitions with the same base
796    variable, conflicts will be added to GRAPH.  */
797
798 static inline void
799 live_track_process_def (live_track *ptr, tree def, ssa_conflicts *graph)
800 {
801   int p, root;
802   bitmap b;
803   unsigned x;
804   bitmap_iterator bi;
805
806   p = var_to_partition (ptr->map, def);
807   if (p == NO_PARTITION)
808     return;
809
810   /* Clear the liveness bit.  */
811   live_track_remove_partition (ptr, p);
812
813   /* If the bitmap isn't empty now, conflicts need to be added.  */
814   root = basevar_index (ptr->map, p);
815   if (bitmap_bit_p (ptr->live_base_var, root))
816     {
817       b = ptr->live_base_partitions[root];
818       EXECUTE_IF_SET_IN_BITMAP (b, 0, x, bi)
819         ssa_conflicts_add (graph, p, x);
820     }
821 }
822
823
824 /* Initialize PTR with the partitions set in INIT.  */
825
826 static inline void
827 live_track_init (live_track *ptr, bitmap init)
828 {
829   unsigned p;
830   bitmap_iterator bi;
831
832   /* Mark all live on exit partitions.  */
833   EXECUTE_IF_SET_IN_BITMAP (init, 0, p, bi)
834     live_track_add_partition (ptr, p);
835 }
836
837
838 /* This routine will clear all live partitions in PTR.   */
839
840 static inline void
841 live_track_clear_base_vars (live_track *ptr)
842 {
843   /* Simply clear the live base list.  Anything marked as live in the element
844      lists will be cleared later if/when the base variable ever comes alive
845      again.  */
846   bitmap_clear (ptr->live_base_var);
847 }
848
849
850 /* Build a conflict graph based on LIVEINFO.  Any partitions which are in the
851    partition view of the var_map liveinfo is based on get entries in the
852    conflict graph.  Only conflicts between ssa_name partitions with the same
853    base variable are added.  */
854
855 static ssa_conflicts *
856 build_ssa_conflict_graph (tree_live_info_p liveinfo)
857 {
858   ssa_conflicts *graph;
859   var_map map;
860   basic_block bb;
861   ssa_op_iter iter;
862   live_track *live;
863   basic_block entry;
864
865   /* If inter-variable coalescing is enabled, we may attempt to
866      coalesce variables from different base variables, including
867      different parameters, so we have to make sure default defs live
868      at the entry block conflict with each other.  */
869   if (flag_tree_coalesce_vars)
870     entry = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
871   else
872     entry = NULL;
873
874   map = live_var_map (liveinfo);
875   graph = ssa_conflicts_new (num_var_partitions (map));
876
877   live = new_live_track (map);
878
879   FOR_EACH_BB_FN (bb, cfun)
880     {
881       /* Start with live on exit temporaries.  */
882       live_track_init (live, live_on_exit (liveinfo, bb));
883
884       for (gimple_stmt_iterator gsi = gsi_last_bb (bb); !gsi_end_p (gsi);
885            gsi_prev (&gsi))
886         {
887           tree var;
888           gimple *stmt = gsi_stmt (gsi);
889
890           /* A copy between 2 partitions does not introduce an interference
891              by itself.  If they did, you would never be able to coalesce
892              two things which are copied.  If the two variables really do
893              conflict, they will conflict elsewhere in the program.
894
895              This is handled by simply removing the SRC of the copy from the
896              live list, and processing the stmt normally.  */
897           if (is_gimple_assign (stmt))
898             {
899               tree lhs = gimple_assign_lhs (stmt);
900               tree rhs1 = gimple_assign_rhs1 (stmt);
901               if (gimple_assign_copy_p (stmt)
902                   && TREE_CODE (lhs) == SSA_NAME
903                   && TREE_CODE (rhs1) == SSA_NAME)
904                 live_track_clear_var (live, rhs1);
905             }
906           else if (is_gimple_debug (stmt))
907             continue;
908
909           /* For stmts with more than one SSA_NAME definition pretend all the
910              SSA_NAME outputs but the first one are live at this point, so
911              that conflicts are added in between all those even when they are
912              actually not really live after the asm, because expansion might
913              copy those into pseudos after the asm and if multiple outputs
914              share the same partition, it might overwrite those that should
915              be live.  E.g.
916              asm volatile (".." : "=r" (a) : "=r" (b) : "0" (a), "1" (a));
917              return a;
918              See PR70593.  */
919           bool first = true;
920           FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_DEF)
921             if (first)
922               first = false;
923             else
924               live_track_process_use (live, var);
925
926           FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_DEF)
927             live_track_process_def (live, var, graph);
928
929           FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_USE)
930             live_track_process_use (live, var);
931         }
932
933       /* If result of a PHI is unused, looping over the statements will not
934          record any conflicts since the def was never live.  Since the PHI node
935          is going to be translated out of SSA form, it will insert a copy.
936          There must be a conflict recorded between the result of the PHI and
937          any variables that are live.  Otherwise the out-of-ssa translation
938          may create incorrect code.  */
939       for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
940            gsi_next (&gsi))
941         {
942           gphi *phi = gsi.phi ();
943           tree result = PHI_RESULT (phi);
944           if (live_track_live_p (live, result))
945             live_track_process_def (live, result, graph);
946         }
947
948       /* Pretend there are defs for params' default defs at the start
949          of the (post-)entry block.  This will prevent PARM_DECLs from
950          coalescing into the same partition.  Although RESULT_DECLs'
951          default defs don't have a useful initial value, we have to
952          prevent them from coalescing with PARM_DECLs' default defs
953          too, otherwise assign_parms would attempt to assign different
954          RTL to the same partition.  */
955       if (bb == entry)
956         {
957           unsigned i;
958           for (i = 1; i < num_ssa_names; i++)
959             {
960               tree var = ssa_name (i);
961
962               if (!var
963                   || !SSA_NAME_IS_DEFAULT_DEF (var)
964                   || !SSA_NAME_VAR (var)
965                   || VAR_P (SSA_NAME_VAR (var)))
966                 continue;
967
968               live_track_process_def (live, var, graph);
969               /* Process a use too, so that it remains live and
970                  conflicts with other parms' default defs, even unused
971                  ones.  */
972               live_track_process_use (live, var);
973             }
974         }
975
976      live_track_clear_base_vars (live);
977     }
978
979   delete_live_track (live);
980   return graph;
981 }
982
983
984 /* Shortcut routine to print messages to file F of the form:
985    "STR1 EXPR1 STR2 EXPR2 STR3."  */
986
987 static inline void
988 print_exprs (FILE *f, const char *str1, tree expr1, const char *str2,
989              tree expr2, const char *str3)
990 {
991   fprintf (f, "%s", str1);
992   print_generic_expr (f, expr1, TDF_SLIM);
993   fprintf (f, "%s", str2);
994   print_generic_expr (f, expr2, TDF_SLIM);
995   fprintf (f, "%s", str3);
996 }
997
998
999 /* Print a failure to coalesce a MUST_COALESCE pair X and Y.  */
1000
1001 static inline void
1002 fail_abnormal_edge_coalesce (int x, int y)
1003 {
1004   fprintf (stderr, "\nUnable to coalesce ssa_names %d and %d",x, y);
1005   fprintf (stderr, " which are marked as MUST COALESCE.\n");
1006   print_generic_expr (stderr, ssa_name (x), TDF_SLIM);
1007   fprintf (stderr, " and  ");
1008   print_generic_stmt (stderr, ssa_name (y), TDF_SLIM);
1009
1010   internal_error ("SSA corruption");
1011 }
1012
1013 /* Call CALLBACK for all PARM_DECLs and RESULT_DECLs for which
1014    assign_parms may ask for a default partition.  */
1015
1016 static void
1017 for_all_parms (void (*callback)(tree var, void *arg), void *arg)
1018 {
1019   for (tree var = DECL_ARGUMENTS (current_function_decl); var;
1020        var = DECL_CHAIN (var))
1021     callback (var, arg);
1022   if (!VOID_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
1023     callback (DECL_RESULT (current_function_decl), arg);
1024   if (cfun->static_chain_decl)
1025     callback (cfun->static_chain_decl, arg);
1026 }
1027
1028 /* Create a default def for VAR.  */
1029
1030 static void
1031 create_default_def (tree var, void *arg ATTRIBUTE_UNUSED)
1032 {
1033   if (!is_gimple_reg (var))
1034     return;
1035
1036   tree ssa = get_or_create_ssa_default_def (cfun, var);
1037   gcc_assert (ssa);
1038 }
1039
1040 /* Register VAR's default def in MAP.  */
1041
1042 static void
1043 register_default_def (tree var, void *map_)
1044 {
1045   var_map map = (var_map)map_;
1046
1047   if (!is_gimple_reg (var))
1048     return;
1049
1050   tree ssa = ssa_default_def (cfun, var);
1051   gcc_assert (ssa);
1052
1053   register_ssa_partition (map, ssa);
1054 }
1055
1056 /* If VAR is an SSA_NAME associated with a PARM_DECL or a RESULT_DECL,
1057    and the DECL's default def is unused (i.e., it was introduced by
1058    create_default_def), mark VAR and the default def for
1059    coalescing.  */
1060
1061 static void
1062 coalesce_with_default (tree var, coalesce_list *cl, bitmap used_in_copy)
1063 {
1064   if (SSA_NAME_IS_DEFAULT_DEF (var)
1065       || !SSA_NAME_VAR (var)
1066       || VAR_P (SSA_NAME_VAR (var)))
1067     return;
1068
1069   tree ssa = ssa_default_def (cfun, SSA_NAME_VAR (var));
1070   if (!has_zero_uses (ssa))
1071     return;
1072
1073   add_cost_one_coalesce (cl, SSA_NAME_VERSION (ssa), SSA_NAME_VERSION (var));
1074   bitmap_set_bit (used_in_copy, SSA_NAME_VERSION (var));
1075   /* Default defs will have their used_in_copy bits set at the end of
1076      create_outofssa_var_map.  */
1077 }
1078
1079 /* This function creates a var_map for the current function as well as creating
1080    a coalesce list for use later in the out of ssa process.  */
1081
1082 static var_map
1083 create_outofssa_var_map (coalesce_list *cl, bitmap used_in_copy)
1084 {
1085   gimple_stmt_iterator gsi;
1086   basic_block bb;
1087   tree var;
1088   gimple *stmt;
1089   tree first;
1090   var_map map;
1091   ssa_op_iter iter;
1092   int v1, v2, cost;
1093   unsigned i;
1094
1095   for_all_parms (create_default_def, NULL);
1096
1097   map = init_var_map (num_ssa_names);
1098
1099   for_all_parms (register_default_def, map);
1100
1101   FOR_EACH_BB_FN (bb, cfun)
1102     {
1103       tree arg;
1104
1105       for (gphi_iterator gpi = gsi_start_phis (bb);
1106            !gsi_end_p (gpi);
1107            gsi_next (&gpi))
1108         {
1109           gphi *phi = gpi.phi ();
1110           size_t i;
1111           int ver;
1112           tree res;
1113           bool saw_copy = false;
1114
1115           res = gimple_phi_result (phi);
1116           ver = SSA_NAME_VERSION (res);
1117           register_ssa_partition (map, res);
1118
1119           /* Register ssa_names and coalesces between the args and the result
1120              of all PHI.  */
1121           for (i = 0; i < gimple_phi_num_args (phi); i++)
1122             {
1123               edge e = gimple_phi_arg_edge (phi, i);
1124               arg = PHI_ARG_DEF (phi, i);
1125               if (TREE_CODE (arg) != SSA_NAME)
1126                 continue;
1127
1128               register_ssa_partition (map, arg);
1129               if (gimple_can_coalesce_p (arg, res)
1130                   || (e->flags & EDGE_ABNORMAL))
1131                 {
1132                   saw_copy = true;
1133                   bitmap_set_bit (used_in_copy, SSA_NAME_VERSION (arg));
1134                   if ((e->flags & EDGE_ABNORMAL) == 0)
1135                     {
1136                       int cost = coalesce_cost_edge (e);
1137                       if (cost == 1 && has_single_use (arg))
1138                         add_cost_one_coalesce (cl, ver, SSA_NAME_VERSION (arg));
1139                       else
1140                         add_coalesce (cl, ver, SSA_NAME_VERSION (arg), cost);
1141                     }
1142                 }
1143             }
1144           if (saw_copy)
1145             bitmap_set_bit (used_in_copy, ver);
1146         }
1147
1148       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1149         {
1150           stmt = gsi_stmt (gsi);
1151
1152           if (is_gimple_debug (stmt))
1153             continue;
1154
1155           /* Register USE and DEF operands in each statement.  */
1156           FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, (SSA_OP_DEF|SSA_OP_USE))
1157             register_ssa_partition (map, var);
1158
1159           /* Check for copy coalesces.  */
1160           switch (gimple_code (stmt))
1161             {
1162             case GIMPLE_ASSIGN:
1163               {
1164                 tree lhs = gimple_assign_lhs (stmt);
1165                 tree rhs1 = gimple_assign_rhs1 (stmt);
1166                 if (gimple_assign_ssa_name_copy_p (stmt)
1167                     && gimple_can_coalesce_p (lhs, rhs1))
1168                   {
1169                     v1 = SSA_NAME_VERSION (lhs);
1170                     v2 = SSA_NAME_VERSION (rhs1);
1171                     cost = coalesce_cost_bb (bb);
1172                     add_coalesce (cl, v1, v2, cost);
1173                     bitmap_set_bit (used_in_copy, v1);
1174                     bitmap_set_bit (used_in_copy, v2);
1175                   }
1176               }
1177               break;
1178
1179             case GIMPLE_RETURN:
1180               {
1181                 tree res = DECL_RESULT (current_function_decl);
1182                 if (VOID_TYPE_P (TREE_TYPE (res))
1183                     || !is_gimple_reg (res))
1184                   break;
1185                 tree rhs1 = gimple_return_retval (as_a <greturn *> (stmt));
1186                 if (!rhs1)
1187                   break;
1188                 tree lhs = ssa_default_def (cfun, res);
1189                 gcc_assert (lhs);
1190                 if (TREE_CODE (rhs1) == SSA_NAME
1191                     && gimple_can_coalesce_p (lhs, rhs1))
1192                   {
1193                     v1 = SSA_NAME_VERSION (lhs);
1194                     v2 = SSA_NAME_VERSION (rhs1);
1195                     cost = coalesce_cost_bb (bb);
1196                     add_coalesce (cl, v1, v2, cost);
1197                     bitmap_set_bit (used_in_copy, v1);
1198                     bitmap_set_bit (used_in_copy, v2);
1199                   }
1200                 break;
1201               }
1202
1203             case GIMPLE_ASM:
1204               {
1205                 gasm *asm_stmt = as_a <gasm *> (stmt);
1206                 unsigned long noutputs, i;
1207                 unsigned long ninputs;
1208                 tree *outputs, link;
1209                 noutputs = gimple_asm_noutputs (asm_stmt);
1210                 ninputs = gimple_asm_ninputs (asm_stmt);
1211                 outputs = (tree *) alloca (noutputs * sizeof (tree));
1212                 for (i = 0; i < noutputs; ++i)
1213                   {
1214                     link = gimple_asm_output_op (asm_stmt, i);
1215                     outputs[i] = TREE_VALUE (link);
1216                   }
1217
1218                 for (i = 0; i < ninputs; ++i)
1219                   {
1220                     const char *constraint;
1221                     tree input;
1222                     char *end;
1223                     unsigned long match;
1224
1225                     link = gimple_asm_input_op (asm_stmt, i);
1226                     constraint
1227                       = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
1228                     input = TREE_VALUE (link);
1229
1230                     if (TREE_CODE (input) != SSA_NAME)
1231                       continue;
1232
1233                     match = strtoul (constraint, &end, 10);
1234                     if (match >= noutputs || end == constraint)
1235                       continue;
1236
1237                     if (TREE_CODE (outputs[match]) != SSA_NAME)
1238                       continue;
1239
1240                     v1 = SSA_NAME_VERSION (outputs[match]);
1241                     v2 = SSA_NAME_VERSION (input);
1242
1243                     if (gimple_can_coalesce_p (outputs[match], input))
1244                       {
1245                         cost = coalesce_cost (REG_BR_PROB_BASE,
1246                                               optimize_bb_for_size_p (bb));
1247                         add_coalesce (cl, v1, v2, cost);
1248                         bitmap_set_bit (used_in_copy, v1);
1249                         bitmap_set_bit (used_in_copy, v2);
1250                       }
1251                   }
1252                 break;
1253               }
1254
1255             default:
1256               break;
1257             }
1258         }
1259     }
1260
1261   /* Now process result decls and live on entry variables for entry into
1262      the coalesce list.  */
1263   first = NULL_TREE;
1264   for (i = 1; i < num_ssa_names; i++)
1265     {
1266       var = ssa_name (i);
1267       if (var != NULL_TREE && !virtual_operand_p (var))
1268         {
1269           coalesce_with_default (var, cl, used_in_copy);
1270
1271           /* Add coalesces between all the result decls.  */
1272           if (SSA_NAME_VAR (var)
1273               && TREE_CODE (SSA_NAME_VAR (var)) == RESULT_DECL)
1274             {
1275               bitmap_set_bit (used_in_copy, SSA_NAME_VERSION (var));
1276               if (first == NULL_TREE)
1277                 first = var;
1278               else
1279                 {
1280                   gcc_assert (gimple_can_coalesce_p (var, first));
1281                   v1 = SSA_NAME_VERSION (first);
1282                   v2 = SSA_NAME_VERSION (var);
1283                   cost = coalesce_cost_bb (EXIT_BLOCK_PTR_FOR_FN (cfun));
1284                   add_coalesce (cl, v1, v2, cost);
1285                 }
1286             }
1287           /* Mark any default_def variables as being in the coalesce list
1288              since they will have to be coalesced with the base variable.  If
1289              not marked as present, they won't be in the coalesce view. */
1290           if (SSA_NAME_IS_DEFAULT_DEF (var)
1291               && (!has_zero_uses (var)
1292                   || (SSA_NAME_VAR (var)
1293                       && !VAR_P (SSA_NAME_VAR (var)))))
1294             bitmap_set_bit (used_in_copy, SSA_NAME_VERSION (var));
1295         }
1296     }
1297
1298   return map;
1299 }
1300
1301
1302 /* Attempt to coalesce ssa versions X and Y together using the partition
1303    mapping in MAP and checking conflicts in GRAPH.  Output any debug info to
1304    DEBUG, if it is nun-NULL.  */
1305
1306 static inline bool
1307 attempt_coalesce (var_map map, ssa_conflicts *graph, int x, int y,
1308                   FILE *debug)
1309 {
1310   int z;
1311   tree var1, var2;
1312   int p1, p2;
1313
1314   p1 = var_to_partition (map, ssa_name (x));
1315   p2 = var_to_partition (map, ssa_name (y));
1316
1317   if (debug)
1318     {
1319       fprintf (debug, "(%d)", x);
1320       print_generic_expr (debug, partition_to_var (map, p1), TDF_SLIM);
1321       fprintf (debug, " & (%d)", y);
1322       print_generic_expr (debug, partition_to_var (map, p2), TDF_SLIM);
1323     }
1324
1325   if (p1 == p2)
1326     {
1327       if (debug)
1328         fprintf (debug, ": Already Coalesced.\n");
1329       return true;
1330     }
1331
1332   if (debug)
1333     fprintf (debug, " [map: %d, %d] ", p1, p2);
1334
1335
1336   if (!ssa_conflicts_test_p (graph, p1, p2))
1337     {
1338       var1 = partition_to_var (map, p1);
1339       var2 = partition_to_var (map, p2);
1340
1341       z = var_union (map, var1, var2);
1342       if (z == NO_PARTITION)
1343         {
1344           if (debug)
1345             fprintf (debug, ": Unable to perform partition union.\n");
1346           return false;
1347         }
1348
1349       /* z is the new combined partition.  Remove the other partition from
1350          the list, and merge the conflicts.  */
1351       if (z == p1)
1352         ssa_conflicts_merge (graph, p1, p2);
1353       else
1354         ssa_conflicts_merge (graph, p2, p1);
1355
1356       if (debug)
1357         fprintf (debug, ": Success -> %d\n", z);
1358
1359       return true;
1360     }
1361
1362   if (debug)
1363     fprintf (debug, ": Fail due to conflict\n");
1364
1365   return false;
1366 }
1367
1368
1369 /* Attempt to Coalesce partitions in MAP which occur in the list CL using
1370    GRAPH.  Debug output is sent to DEBUG if it is non-NULL.  */
1371
1372 static void
1373 coalesce_partitions (var_map map, ssa_conflicts *graph, coalesce_list *cl,
1374                      FILE *debug)
1375 {
1376   int x = 0, y = 0;
1377   tree var1, var2;
1378   int cost;
1379   basic_block bb;
1380   edge e;
1381   edge_iterator ei;
1382
1383   /* First, coalesce all the copies across abnormal edges.  These are not placed
1384      in the coalesce list because they do not need to be sorted, and simply
1385      consume extra memory/compilation time in large programs.  */
1386
1387   FOR_EACH_BB_FN (bb, cfun)
1388     {
1389       FOR_EACH_EDGE (e, ei, bb->preds)
1390         if (e->flags & EDGE_ABNORMAL)
1391           {
1392             gphi_iterator gsi;
1393             for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1394                  gsi_next (&gsi))
1395               {
1396                 gphi *phi = gsi.phi ();
1397                 tree arg = PHI_ARG_DEF (phi, e->dest_idx);
1398                 if (SSA_NAME_IS_DEFAULT_DEF (arg)
1399                     && (!SSA_NAME_VAR (arg)
1400                         || TREE_CODE (SSA_NAME_VAR (arg)) != PARM_DECL))
1401                   continue;
1402
1403                 tree res = PHI_RESULT (phi);
1404                 int v1 = SSA_NAME_VERSION (res);
1405                 int v2 = SSA_NAME_VERSION (arg);
1406
1407                 if (debug)
1408                   fprintf (debug, "Abnormal coalesce: ");
1409
1410                 if (!attempt_coalesce (map, graph, v1, v2, debug))
1411                   fail_abnormal_edge_coalesce (v1, v2);
1412               }
1413           }
1414     }
1415
1416   /* Now process the items in the coalesce list.  */
1417
1418   while ((cost = pop_best_coalesce (cl, &x, &y)) != NO_BEST_COALESCE)
1419     {
1420       var1 = ssa_name (x);
1421       var2 = ssa_name (y);
1422
1423       /* Assert the coalesces have the same base variable.  */
1424       gcc_assert (gimple_can_coalesce_p (var1, var2));
1425
1426       if (debug)
1427         fprintf (debug, "Coalesce list: ");
1428       attempt_coalesce (map, graph, x, y, debug);
1429     }
1430 }
1431
1432
1433 /* Hashtable support for storing SSA names hashed by their SSA_NAME_VAR.  */
1434
1435 struct ssa_name_var_hash : nofree_ptr_hash <tree_node>
1436 {
1437   static inline hashval_t hash (const tree_node *);
1438   static inline int equal (const tree_node *, const tree_node *);
1439 };
1440
1441 inline hashval_t
1442 ssa_name_var_hash::hash (const_tree n)
1443 {
1444   return DECL_UID (SSA_NAME_VAR (n));
1445 }
1446
1447 inline int
1448 ssa_name_var_hash::equal (const tree_node *n1, const tree_node *n2)
1449 {
1450   return SSA_NAME_VAR (n1) == SSA_NAME_VAR (n2);
1451 }
1452
1453
1454 /* Output partition map MAP with coalescing plan PART to file F.  */
1455
1456 void
1457 dump_part_var_map (FILE *f, partition part, var_map map)
1458 {
1459   int t;
1460   unsigned x, y;
1461   int p;
1462
1463   fprintf (f, "\nCoalescible Partition map \n\n");
1464
1465   for (x = 0; x < map->num_partitions; x++)
1466     {
1467       if (map->view_to_partition != NULL)
1468         p = map->view_to_partition[x];
1469       else
1470         p = x;
1471
1472       if (ssa_name (p) == NULL_TREE
1473           || virtual_operand_p (ssa_name (p)))
1474         continue;
1475
1476       t = 0;
1477       for (y = 1; y < num_ssa_names; y++)
1478         {
1479           tree var = version_to_var (map, y);
1480           if (!var)
1481             continue;
1482           int q = var_to_partition (map, var);
1483           p = partition_find (part, q);
1484           gcc_assert (map->partition_to_base_index[q]
1485                       == map->partition_to_base_index[p]);
1486
1487           if (p == (int)x)
1488             {
1489               if (t++ == 0)
1490                 {
1491                   fprintf (f, "Partition %d, base %d (", x,
1492                            map->partition_to_base_index[q]);
1493                   print_generic_expr (f, partition_to_var (map, q), TDF_SLIM);
1494                   fprintf (f, " - ");
1495                 }
1496               fprintf (f, "%d ", y);
1497             }
1498         }
1499       if (t != 0)
1500         fprintf (f, ")\n");
1501     }
1502   fprintf (f, "\n");
1503 }
1504
1505 /* Given SSA_NAMEs NAME1 and NAME2, return true if they are candidates for
1506    coalescing together, false otherwise.
1507
1508    This must stay consistent with compute_samebase_partition_bases and 
1509    compute_optimized_partition_bases.  */
1510
1511 bool
1512 gimple_can_coalesce_p (tree name1, tree name2)
1513 {
1514   /* First check the SSA_NAME's associated DECL.  Without
1515      optimization, we only want to coalesce if they have the same DECL
1516      or both have no associated DECL.  */
1517   tree var1 = SSA_NAME_VAR (name1);
1518   tree var2 = SSA_NAME_VAR (name2);
1519   var1 = (var1 && (!VAR_P (var1) || !DECL_IGNORED_P (var1))) ? var1 : NULL_TREE;
1520   var2 = (var2 && (!VAR_P (var2) || !DECL_IGNORED_P (var2))) ? var2 : NULL_TREE;
1521   if (var1 != var2 && !flag_tree_coalesce_vars)
1522     return false;
1523
1524   /* Now check the types.  If the types are the same, then we should
1525      try to coalesce V1 and V2.  */
1526   tree t1 = TREE_TYPE (name1);
1527   tree t2 = TREE_TYPE (name2);
1528   if (t1 == t2)
1529     {
1530     check_modes:
1531       /* If the base variables are the same, we're good: none of the
1532          other tests below could possibly fail.  */
1533       var1 = SSA_NAME_VAR (name1);
1534       var2 = SSA_NAME_VAR (name2);
1535       if (var1 == var2)
1536         return true;
1537
1538       /* We don't want to coalesce two SSA names if one of the base
1539          variables is supposed to be a register while the other is
1540          supposed to be on the stack.  Anonymous SSA names most often
1541          take registers, but when not optimizing, user variables
1542          should go on the stack, so coalescing them with the anonymous
1543          variable as the partition leader would end up assigning the
1544          user variable to a register.  Don't do that!  */
1545       bool reg1 = use_register_for_decl (name1);
1546       bool reg2 = use_register_for_decl (name2);
1547       if (reg1 != reg2)
1548         return false;
1549
1550       /* Check that the promoted modes and unsignedness are the same.
1551          We don't want to coalesce if the promoted modes would be
1552          different, or if they would sign-extend differently.  Only
1553          PARM_DECLs and RESULT_DECLs have different promotion rules,
1554          so skip the test if both are variables, or both are anonymous
1555          SSA_NAMEs.  */
1556       int unsigned1, unsigned2;
1557       return ((!var1 || VAR_P (var1)) && (!var2 || VAR_P (var2)))
1558         || ((promote_ssa_mode (name1, &unsigned1)
1559              == promote_ssa_mode (name2, &unsigned2))
1560             && unsigned1 == unsigned2);
1561     }
1562
1563   /* If alignment requirements are different, we can't coalesce.  */
1564   if (MINIMUM_ALIGNMENT (t1,
1565                          var1 ? DECL_MODE (var1) : TYPE_MODE (t1),
1566                          var1 ? LOCAL_DECL_ALIGNMENT (var1) : TYPE_ALIGN (t1))
1567       != MINIMUM_ALIGNMENT (t2,
1568                             var2 ? DECL_MODE (var2) : TYPE_MODE (t2),
1569                             var2 ? LOCAL_DECL_ALIGNMENT (var2) : TYPE_ALIGN (t2)))
1570     return false;
1571
1572   /* If the types are not the same, check for a canonical type match.  This
1573      (for example) allows coalescing when the types are fundamentally the
1574      same, but just have different names. 
1575
1576      Note pointer types with different address spaces may have the same
1577      canonical type.  Those are rejected for coalescing by the
1578      types_compatible_p check.  */
1579   if (TYPE_CANONICAL (t1)
1580       && TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2)
1581       && types_compatible_p (t1, t2))
1582     goto check_modes;
1583
1584   return false;
1585 }
1586
1587 /* Fill in MAP's partition_to_base_index, with one index for each
1588    partition of SSA names USED_IN_COPIES and related by CL coalesce
1589    possibilities.  This must match gimple_can_coalesce_p in the
1590    optimized case.  */
1591
1592 static void
1593 compute_optimized_partition_bases (var_map map, bitmap used_in_copies,
1594                                    coalesce_list *cl)
1595 {
1596   int parts = num_var_partitions (map);
1597   partition tentative = partition_new (parts);
1598
1599   /* Partition the SSA versions so that, for each coalescible
1600      pair, both of its members are in the same partition in
1601      TENTATIVE.  */
1602   gcc_assert (!cl->sorted);
1603   coalesce_pair *node;
1604   coalesce_iterator_type ppi;
1605   FOR_EACH_PARTITION_PAIR (node, ppi, cl)
1606     {
1607       tree v1 = ssa_name (node->first_element);
1608       int p1 = partition_find (tentative, var_to_partition (map, v1));
1609       tree v2 = ssa_name (node->second_element);
1610       int p2 = partition_find (tentative, var_to_partition (map, v2));
1611
1612       if (p1 == p2)
1613         continue;
1614
1615       partition_union (tentative, p1, p2);
1616     }
1617
1618   /* We have to deal with cost one pairs too.  */
1619   for (cost_one_pair *co = cl->cost_one_list; co; co = co->next)
1620     {
1621       tree v1 = ssa_name (co->first_element);
1622       int p1 = partition_find (tentative, var_to_partition (map, v1));
1623       tree v2 = ssa_name (co->second_element);
1624       int p2 = partition_find (tentative, var_to_partition (map, v2));
1625
1626       if (p1 == p2)
1627         continue;
1628
1629       partition_union (tentative, p1, p2);
1630     }
1631
1632   /* And also with abnormal edges.  */
1633   basic_block bb;
1634   edge e;
1635   edge_iterator ei;
1636   FOR_EACH_BB_FN (bb, cfun)
1637     {
1638       FOR_EACH_EDGE (e, ei, bb->preds)
1639         if (e->flags & EDGE_ABNORMAL)
1640           {
1641             gphi_iterator gsi;
1642             for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1643                  gsi_next (&gsi))
1644               {
1645                 gphi *phi = gsi.phi ();
1646                 tree arg = PHI_ARG_DEF (phi, e->dest_idx);
1647                 if (SSA_NAME_IS_DEFAULT_DEF (arg)
1648                     && (!SSA_NAME_VAR (arg)
1649                         || TREE_CODE (SSA_NAME_VAR (arg)) != PARM_DECL))
1650                   continue;
1651
1652                 tree res = PHI_RESULT (phi);
1653
1654                 int p1 = partition_find (tentative, var_to_partition (map, res));
1655                 int p2 = partition_find (tentative, var_to_partition (map, arg));
1656
1657                 if (p1 == p2)
1658                   continue;
1659
1660                 partition_union (tentative, p1, p2);
1661               }
1662           }
1663     }
1664
1665   map->partition_to_base_index = XCNEWVEC (int, parts);
1666   auto_vec<unsigned int> index_map (parts);
1667   if (parts)
1668     index_map.quick_grow (parts);
1669
1670   const unsigned no_part = -1;
1671   unsigned count = parts;
1672   while (count)
1673     index_map[--count] = no_part;
1674
1675   /* Initialize MAP's mapping from partition to base index, using
1676      as base indices an enumeration of the TENTATIVE partitions in
1677      which each SSA version ended up, so that we compute conflicts
1678      between all SSA versions that ended up in the same potential
1679      coalesce partition.  */
1680   bitmap_iterator bi;
1681   unsigned i;
1682   EXECUTE_IF_SET_IN_BITMAP (used_in_copies, 0, i, bi)
1683     {
1684       int pidx = var_to_partition (map, ssa_name (i));
1685       int base = partition_find (tentative, pidx);
1686       if (index_map[base] != no_part)
1687         continue;
1688       index_map[base] = count++;
1689     }
1690
1691   map->num_basevars = count;
1692
1693   EXECUTE_IF_SET_IN_BITMAP (used_in_copies, 0, i, bi)
1694     {
1695       int pidx = var_to_partition (map, ssa_name (i));
1696       int base = partition_find (tentative, pidx);
1697       gcc_assert (index_map[base] < count);
1698       map->partition_to_base_index[pidx] = index_map[base];
1699     }
1700
1701   if (dump_file && (dump_flags & TDF_DETAILS))
1702     dump_part_var_map (dump_file, tentative, map);
1703
1704   partition_delete (tentative);
1705 }
1706
1707 /* Hashtable helpers.  */
1708
1709 struct tree_int_map_hasher : nofree_ptr_hash <tree_int_map>
1710 {
1711   static inline hashval_t hash (const tree_int_map *);
1712   static inline bool equal (const tree_int_map *, const tree_int_map *);
1713 };
1714
1715 inline hashval_t
1716 tree_int_map_hasher::hash (const tree_int_map *v)
1717 {
1718   return tree_map_base_hash (v);
1719 }
1720
1721 inline bool
1722 tree_int_map_hasher::equal (const tree_int_map *v, const tree_int_map *c)
1723 {
1724   return tree_int_map_eq (v, c);
1725 }
1726
1727 /* This routine will initialize the basevar fields of MAP with base
1728    names.  Partitions will share the same base if they have the same
1729    SSA_NAME_VAR, or, being anonymous variables, the same type.  This
1730    must match gimple_can_coalesce_p in the non-optimized case.  */
1731
1732 static void
1733 compute_samebase_partition_bases (var_map map)
1734 {
1735   int x, num_part;
1736   tree var;
1737   struct tree_int_map *m, *mapstorage;
1738
1739   num_part = num_var_partitions (map);
1740   hash_table<tree_int_map_hasher> tree_to_index (num_part);
1741   /* We can have at most num_part entries in the hash tables, so it's
1742      enough to allocate so many map elements once, saving some malloc
1743      calls.  */
1744   mapstorage = m = XNEWVEC (struct tree_int_map, num_part);
1745
1746   /* If a base table already exists, clear it, otherwise create it.  */
1747   free (map->partition_to_base_index);
1748   map->partition_to_base_index = (int *) xmalloc (sizeof (int) * num_part);
1749
1750   /* Build the base variable list, and point partitions at their bases.  */
1751   for (x = 0; x < num_part; x++)
1752     {
1753       struct tree_int_map **slot;
1754       unsigned baseindex;
1755       var = partition_to_var (map, x);
1756       if (SSA_NAME_VAR (var)
1757           && (!VAR_P (SSA_NAME_VAR (var))
1758               || !DECL_IGNORED_P (SSA_NAME_VAR (var))))
1759         m->base.from = SSA_NAME_VAR (var);
1760       else
1761         /* This restricts what anonymous SSA names we can coalesce
1762            as it restricts the sets we compute conflicts for.
1763            Using TREE_TYPE to generate sets is the easiest as
1764            type equivalency also holds for SSA names with the same
1765            underlying decl.
1766
1767            Check gimple_can_coalesce_p when changing this code.  */
1768         m->base.from = (TYPE_CANONICAL (TREE_TYPE (var))
1769                         ? TYPE_CANONICAL (TREE_TYPE (var))
1770                         : TREE_TYPE (var));
1771       /* If base variable hasn't been seen, set it up.  */
1772       slot = tree_to_index.find_slot (m, INSERT);
1773       if (!*slot)
1774         {
1775           baseindex = m - mapstorage;
1776           m->to = baseindex;
1777           *slot = m;
1778           m++;
1779         }
1780       else
1781         baseindex = (*slot)->to;
1782       map->partition_to_base_index[x] = baseindex;
1783     }
1784
1785   map->num_basevars = m - mapstorage;
1786
1787   free (mapstorage);
1788 }
1789
1790 /* Reduce the number of copies by coalescing variables in the function.  Return
1791    a partition map with the resulting coalesces.  */
1792
1793 extern var_map
1794 coalesce_ssa_name (void)
1795 {
1796   tree_live_info_p liveinfo;
1797   ssa_conflicts *graph;
1798   coalesce_list *cl;
1799   bitmap used_in_copies = BITMAP_ALLOC (NULL);
1800   var_map map;
1801   unsigned int i;
1802
1803   cl = create_coalesce_list ();
1804   map = create_outofssa_var_map (cl, used_in_copies);
1805
1806   /* If this optimization is disabled, we need to coalesce all the
1807      names originating from the same SSA_NAME_VAR so debug info
1808      remains undisturbed.  */
1809   if (!flag_tree_coalesce_vars)
1810     {
1811       hash_table<ssa_name_var_hash> ssa_name_hash (10);
1812
1813       for (i = 1; i < num_ssa_names; i++)
1814         {
1815           tree a = ssa_name (i);
1816
1817           if (a
1818               && SSA_NAME_VAR (a)
1819               && !DECL_IGNORED_P (SSA_NAME_VAR (a))
1820               && (!has_zero_uses (a) || !SSA_NAME_IS_DEFAULT_DEF (a)
1821                   || !VAR_P (SSA_NAME_VAR (a))))
1822             {
1823               tree *slot = ssa_name_hash.find_slot (a, INSERT);
1824
1825               if (!*slot)
1826                 *slot = a;
1827               else
1828                 {
1829                   /* If the variable is a PARM_DECL or a RESULT_DECL, we
1830                      _require_ that all the names originating from it be
1831                      coalesced, because there must be a single partition
1832                      containing all the names so that it can be assigned
1833                      the canonical RTL location of the DECL safely.
1834                      If in_lto_p, a function could have been compiled
1835                      originally with optimizations and only the link
1836                      performed at -O0, so we can't actually require it.  */
1837                   const int cost
1838                     = (TREE_CODE (SSA_NAME_VAR (a)) == VAR_DECL || in_lto_p)
1839                       ? MUST_COALESCE_COST - 1 : MUST_COALESCE_COST;
1840                   add_coalesce (cl, SSA_NAME_VERSION (a),
1841                                 SSA_NAME_VERSION (*slot), cost);
1842                   bitmap_set_bit (used_in_copies, SSA_NAME_VERSION (a));
1843                   bitmap_set_bit (used_in_copies, SSA_NAME_VERSION (*slot));
1844                 }
1845             }
1846         }
1847     }
1848   if (dump_file && (dump_flags & TDF_DETAILS))
1849     dump_var_map (dump_file, map);
1850
1851   partition_view_bitmap (map, used_in_copies);
1852
1853   if (flag_tree_coalesce_vars)
1854     compute_optimized_partition_bases (map, used_in_copies, cl);
1855   else
1856     compute_samebase_partition_bases (map);
1857
1858   BITMAP_FREE (used_in_copies);
1859
1860   if (num_var_partitions (map) < 1)
1861     {
1862       delete_coalesce_list (cl);
1863       return map;
1864     }
1865
1866   if (dump_file && (dump_flags & TDF_DETAILS))
1867     dump_var_map (dump_file, map);
1868
1869   liveinfo = calculate_live_ranges (map, false);
1870
1871   if (dump_file && (dump_flags & TDF_DETAILS))
1872     dump_live_info (dump_file, liveinfo, LIVEDUMP_ENTRY);
1873
1874   /* Build a conflict graph.  */
1875   graph = build_ssa_conflict_graph (liveinfo);
1876   delete_tree_live_info (liveinfo);
1877   if (dump_file && (dump_flags & TDF_DETAILS))
1878     ssa_conflicts_dump (dump_file, graph);
1879
1880   sort_coalesce_list (cl, graph, map);
1881
1882   if (dump_file && (dump_flags & TDF_DETAILS))
1883     {
1884       fprintf (dump_file, "\nAfter sorting:\n");
1885       dump_coalesce_list (dump_file, cl);
1886     }
1887
1888   /* First, coalesce all live on entry variables to their base variable.
1889      This will ensure the first use is coming from the correct location.  */
1890
1891   if (dump_file && (dump_flags & TDF_DETAILS))
1892     dump_var_map (dump_file, map);
1893
1894   /* Now coalesce everything in the list.  */
1895   coalesce_partitions (map, graph, cl,
1896                        ((dump_flags & TDF_DETAILS) ? dump_file : NULL));
1897
1898   delete_coalesce_list (cl);
1899   ssa_conflicts_delete (graph);
1900
1901   return map;
1902 }
1903
1904 /* We need to pass two arguments to set_parm_default_def_partition,
1905    but for_all_parms only supports one.  Use a pair.  */
1906
1907 typedef std::pair<var_map, bitmap> parm_default_def_partition_arg;
1908
1909 /* Set in ARG's PARTS bitmap the bit corresponding to the partition in
1910    ARG's MAP containing VAR's default def.  */
1911
1912 static void
1913 set_parm_default_def_partition (tree var, void *arg_)
1914 {
1915   parm_default_def_partition_arg *arg = (parm_default_def_partition_arg *)arg_;
1916   var_map map = arg->first;
1917   bitmap parts = arg->second;
1918
1919   if (!is_gimple_reg (var))
1920     return;
1921
1922   tree ssa = ssa_default_def (cfun, var);
1923   gcc_assert (ssa);
1924
1925   int version = var_to_partition (map, ssa);
1926   gcc_assert (version != NO_PARTITION);
1927
1928   bool changed = bitmap_set_bit (parts, version);
1929   gcc_assert (changed);
1930 }
1931
1932 /* Allocate and return a bitmap that has a bit set for each partition
1933    that contains a default def for a parameter.  */
1934
1935 extern bitmap
1936 get_parm_default_def_partitions (var_map map)
1937 {
1938   bitmap parm_default_def_parts = BITMAP_ALLOC (NULL);
1939
1940   parm_default_def_partition_arg
1941     arg = std::make_pair (map, parm_default_def_parts);
1942
1943   for_all_parms (set_parm_default_def_partition, &arg);
1944
1945   return parm_default_def_parts;
1946 }