1 /* Loop manipulation code for GNU compiler.
2    Copyright (C) 2002-2014 Free Software Foundation, Inc.
3 
4 This file is part of GCC.
5 
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10 
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15 
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19 
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "rtl.h"
25 #include "basic-block.h"
26 #include "cfgloop.h"
27 #include "tree.h"
28 #include "tree-ssa-alias.h"
29 #include "internal-fn.h"
30 #include "gimple-expr.h"
31 #include "is-a.h"
32 #include "gimple.h"
33 #include "gimple-iterator.h"
34 #include "gimplify-me.h"
35 #include "tree-ssa-loop-manip.h"
36 #include "dumpfile.h"
37 
38 static void copy_loops_to (struct loop **, int,
39 			   struct loop *);
40 static void loop_redirect_edge (edge, basic_block);
41 static void remove_bbs (basic_block *, int);
42 static bool rpe_enum_p (const_basic_block, const void *);
43 static int find_path (edge, basic_block **);
44 static void fix_loop_placements (struct loop *, bool *);
45 static bool fix_bb_placement (basic_block);
46 static void fix_bb_placements (basic_block, bool *, bitmap);
47 
48 /* Checks whether basic block BB is dominated by DATA.  */
49 static bool
rpe_enum_p(const_basic_block bb,const void * data)50 rpe_enum_p (const_basic_block bb, const void *data)
51 {
52   return dominated_by_p (CDI_DOMINATORS, bb, (const_basic_block) data);
53 }
54 
55 /* Remove basic blocks BBS.  NBBS is the number of the basic blocks.  */
56 
57 static void
remove_bbs(basic_block * bbs,int nbbs)58 remove_bbs (basic_block *bbs, int nbbs)
59 {
60   int i;
61 
62   for (i = 0; i < nbbs; i++)
63     delete_basic_block (bbs[i]);
64 }
65 
66 /* Find path -- i.e. the basic blocks dominated by edge E and put them
67    into array BBS, that will be allocated large enough to contain them.
68    E->dest must have exactly one predecessor for this to work (it is
69    easy to achieve and we do not put it here because we do not want to
70    alter anything by this function).  The number of basic blocks in the
71    path is returned.  */
72 static int
find_path(edge e,basic_block ** bbs)73 find_path (edge e, basic_block **bbs)
74 {
75   gcc_assert (EDGE_COUNT (e->dest->preds) <= 1);
76 
77   /* Find bbs in the path.  */
78   *bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
79   return dfs_enumerate_from (e->dest, 0, rpe_enum_p, *bbs,
80 			     n_basic_blocks_for_fn (cfun), e->dest);
81 }
82 
83 /* Fix placement of basic block BB inside loop hierarchy --
84    Let L be a loop to that BB belongs.  Then every successor of BB must either
85      1) belong to some superloop of loop L, or
86      2) be a header of loop K such that K->outer is superloop of L
87    Returns true if we had to move BB into other loop to enforce this condition,
88    false if the placement of BB was already correct (provided that placements
89    of its successors are correct).  */
90 static bool
fix_bb_placement(basic_block bb)91 fix_bb_placement (basic_block bb)
92 {
93   edge e;
94   edge_iterator ei;
95   struct loop *loop = current_loops->tree_root, *act;
96 
97   FOR_EACH_EDGE (e, ei, bb->succs)
98     {
99       if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
100 	continue;
101 
102       act = e->dest->loop_father;
103       if (act->header == e->dest)
104 	act = loop_outer (act);
105 
106       if (flow_loop_nested_p (loop, act))
107 	loop = act;
108     }
109 
110   if (loop == bb->loop_father)
111     return false;
112 
113   remove_bb_from_loops (bb);
114   add_bb_to_loop (bb, loop);
115 
116   return true;
117 }
118 
119 /* Fix placement of LOOP inside loop tree, i.e. find the innermost superloop
120    of LOOP to that leads at least one exit edge of LOOP, and set it
121    as the immediate superloop of LOOP.  Return true if the immediate superloop
122    of LOOP changed.
123 
124    IRRED_INVALIDATED is set to true if a change in the loop structures might
125    invalidate the information about irreducible regions.  */
126 
127 static bool
fix_loop_placement(struct loop * loop,bool * irred_invalidated)128 fix_loop_placement (struct loop *loop, bool *irred_invalidated)
129 {
130   unsigned i;
131   edge e;
132   vec<edge> exits = get_loop_exit_edges (loop);
133   struct loop *father = current_loops->tree_root, *act;
134   bool ret = false;
135 
136   FOR_EACH_VEC_ELT (exits, i, e)
137     {
138       act = find_common_loop (loop, e->dest->loop_father);
139       if (flow_loop_nested_p (father, act))
140 	father = act;
141     }
142 
143   if (father != loop_outer (loop))
144     {
145       for (act = loop_outer (loop); act != father; act = loop_outer (act))
146 	act->num_nodes -= loop->num_nodes;
147       flow_loop_tree_node_remove (loop);
148       flow_loop_tree_node_add (father, loop);
149 
150       /* The exit edges of LOOP no longer exits its original immediate
151 	 superloops; remove them from the appropriate exit lists.  */
152       FOR_EACH_VEC_ELT (exits, i, e)
153 	{
154 	  /* We may need to recompute irreducible loops.  */
155 	  if (e->flags & EDGE_IRREDUCIBLE_LOOP)
156 	    *irred_invalidated = true;
157 	  rescan_loop_exit (e, false, false);
158 	}
159 
160       ret = true;
161     }
162 
163   exits.release ();
164   return ret;
165 }
166 
167 /* Fix placements of basic blocks inside loop hierarchy stored in loops; i.e.
168    enforce condition condition stated in description of fix_bb_placement. We
169    start from basic block FROM that had some of its successors removed, so that
170    his placement no longer has to be correct, and iteratively fix placement of
171    its predecessors that may change if placement of FROM changed.  Also fix
172    placement of subloops of FROM->loop_father, that might also be altered due
173    to this change; the condition for them is similar, except that instead of
174    successors we consider edges coming out of the loops.
175 
176    If the changes may invalidate the information about irreducible regions,
177    IRRED_INVALIDATED is set to true.
178 
179    If LOOP_CLOSED_SSA_INVLIDATED is non-zero then all basic blocks with
180    changed loop_father are collected there. */
181 
182 static void
fix_bb_placements(basic_block from,bool * irred_invalidated,bitmap loop_closed_ssa_invalidated)183 fix_bb_placements (basic_block from,
184 		   bool *irred_invalidated,
185 		   bitmap loop_closed_ssa_invalidated)
186 {
187   sbitmap in_queue;
188   basic_block *queue, *qtop, *qbeg, *qend;
189   struct loop *base_loop, *target_loop;
190   edge e;
191 
192   /* We pass through blocks back-reachable from FROM, testing whether some
193      of their successors moved to outer loop.  It may be necessary to
194      iterate several times, but it is finite, as we stop unless we move
195      the basic block up the loop structure.  The whole story is a bit
196      more complicated due to presence of subloops, those are moved using
197      fix_loop_placement.  */
198 
199   base_loop = from->loop_father;
200   /* If we are already in the outermost loop, the basic blocks cannot be moved
201      outside of it.  If FROM is the header of the base loop, it cannot be moved
202      outside of it, either.  In both cases, we can end now.  */
203   if (base_loop == current_loops->tree_root
204       || from == base_loop->header)
205     return;
206 
207   in_queue = sbitmap_alloc (last_basic_block_for_fn (cfun));
208   bitmap_clear (in_queue);
209   bitmap_set_bit (in_queue, from->index);
210   /* Prevent us from going out of the base_loop.  */
211   bitmap_set_bit (in_queue, base_loop->header->index);
212 
213   queue = XNEWVEC (basic_block, base_loop->num_nodes + 1);
214   qtop = queue + base_loop->num_nodes + 1;
215   qbeg = queue;
216   qend = queue + 1;
217   *qbeg = from;
218 
219   while (qbeg != qend)
220     {
221       edge_iterator ei;
222       from = *qbeg;
223       qbeg++;
224       if (qbeg == qtop)
225 	qbeg = queue;
226       bitmap_clear_bit (in_queue, from->index);
227 
228       if (from->loop_father->header == from)
229 	{
230 	  /* Subloop header, maybe move the loop upward.  */
231 	  if (!fix_loop_placement (from->loop_father, irred_invalidated))
232 	    continue;
233 	  target_loop = loop_outer (from->loop_father);
234 	  if (loop_closed_ssa_invalidated)
235 	    {
236 	      basic_block *bbs = get_loop_body (from->loop_father);
237 	      for (unsigned i = 0; i < from->loop_father->num_nodes; ++i)
238 		bitmap_set_bit (loop_closed_ssa_invalidated, bbs[i]->index);
239 	      free (bbs);
240 	    }
241 	}
242       else
243 	{
244 	  /* Ordinary basic block.  */
245 	  if (!fix_bb_placement (from))
246 	    continue;
247 	  target_loop = from->loop_father;
248 	  if (loop_closed_ssa_invalidated)
249 	    bitmap_set_bit (loop_closed_ssa_invalidated, from->index);
250 	}
251 
252       FOR_EACH_EDGE (e, ei, from->succs)
253 	{
254 	  if (e->flags & EDGE_IRREDUCIBLE_LOOP)
255 	    *irred_invalidated = true;
256 	}
257 
258       /* Something has changed, insert predecessors into queue.  */
259       FOR_EACH_EDGE (e, ei, from->preds)
260 	{
261 	  basic_block pred = e->src;
262 	  struct loop *nca;
263 
264 	  if (e->flags & EDGE_IRREDUCIBLE_LOOP)
265 	    *irred_invalidated = true;
266 
267 	  if (bitmap_bit_p (in_queue, pred->index))
268 	    continue;
269 
270 	  /* If it is subloop, then it either was not moved, or
271 	     the path up the loop tree from base_loop do not contain
272 	     it.  */
273 	  nca = find_common_loop (pred->loop_father, base_loop);
274 	  if (pred->loop_father != base_loop
275 	      && (nca == base_loop
276 		  || nca != pred->loop_father))
277 	    pred = pred->loop_father->header;
278 	  else if (!flow_loop_nested_p (target_loop, pred->loop_father))
279 	    {
280 	      /* If PRED is already higher in the loop hierarchy than the
281 		 TARGET_LOOP to that we moved FROM, the change of the position
282 		 of FROM does not affect the position of PRED, so there is no
283 		 point in processing it.  */
284 	      continue;
285 	    }
286 
287 	  if (bitmap_bit_p (in_queue, pred->index))
288 	    continue;
289 
290 	  /* Schedule the basic block.  */
291 	  *qend = pred;
292 	  qend++;
293 	  if (qend == qtop)
294 	    qend = queue;
295 	  bitmap_set_bit (in_queue, pred->index);
296 	}
297     }
298   free (in_queue);
299   free (queue);
300 }
301 
302 /* Removes path beginning at edge E, i.e. remove basic blocks dominated by E
303    and update loop structures and dominators.  Return true if we were able
304    to remove the path, false otherwise (and nothing is affected then).  */
305 bool
remove_path(edge e)306 remove_path (edge e)
307 {
308   edge ae;
309   basic_block *rem_bbs, *bord_bbs, from, bb;
310   vec<basic_block> dom_bbs;
311   int i, nrem, n_bord_bbs;
312   sbitmap seen;
313   bool irred_invalidated = false;
314   edge_iterator ei;
315   struct loop *l, *f;
316 
317   if (!can_remove_branch_p (e))
318     return false;
319 
320   /* Keep track of whether we need to update information about irreducible
321      regions.  This is the case if the removed area is a part of the
322      irreducible region, or if the set of basic blocks that belong to a loop
323      that is inside an irreducible region is changed, or if such a loop is
324      removed.  */
325   if (e->flags & EDGE_IRREDUCIBLE_LOOP)
326     irred_invalidated = true;
327 
328   /* We need to check whether basic blocks are dominated by the edge
329      e, but we only have basic block dominators.  This is easy to
330      fix -- when e->dest has exactly one predecessor, this corresponds
331      to blocks dominated by e->dest, if not, split the edge.  */
332   if (!single_pred_p (e->dest))
333     e = single_pred_edge (split_edge (e));
334 
335   /* It may happen that by removing path we remove one or more loops
336      we belong to.  In this case first unloop the loops, then proceed
337      normally.   We may assume that e->dest is not a header of any loop,
338      as it now has exactly one predecessor.  */
339   for (l = e->src->loop_father; loop_outer (l); l = f)
340     {
341       f = loop_outer (l);
342       if (dominated_by_p (CDI_DOMINATORS, l->latch, e->dest))
343         unloop (l, &irred_invalidated, NULL);
344     }
345 
346   /* Identify the path.  */
347   nrem = find_path (e, &rem_bbs);
348 
349   n_bord_bbs = 0;
350   bord_bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
351   seen = sbitmap_alloc (last_basic_block_for_fn (cfun));
352   bitmap_clear (seen);
353 
354   /* Find "border" hexes -- i.e. those with predecessor in removed path.  */
355   for (i = 0; i < nrem; i++)
356     bitmap_set_bit (seen, rem_bbs[i]->index);
357   if (!irred_invalidated)
358     FOR_EACH_EDGE (ae, ei, e->src->succs)
359       if (ae != e && ae->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
360 	  && !bitmap_bit_p (seen, ae->dest->index)
361 	  && ae->flags & EDGE_IRREDUCIBLE_LOOP)
362 	{
363 	  irred_invalidated = true;
364 	  break;
365 	}
366 
367   for (i = 0; i < nrem; i++)
368     {
369       bb = rem_bbs[i];
370       FOR_EACH_EDGE (ae, ei, rem_bbs[i]->succs)
371 	if (ae->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
372 	    && !bitmap_bit_p (seen, ae->dest->index))
373 	  {
374 	    bitmap_set_bit (seen, ae->dest->index);
375 	    bord_bbs[n_bord_bbs++] = ae->dest;
376 
377 	    if (ae->flags & EDGE_IRREDUCIBLE_LOOP)
378 	      irred_invalidated = true;
379 	  }
380     }
381 
382   /* Remove the path.  */
383   from = e->src;
384   remove_branch (e);
385   dom_bbs.create (0);
386 
387   /* Cancel loops contained in the path.  */
388   for (i = 0; i < nrem; i++)
389     if (rem_bbs[i]->loop_father->header == rem_bbs[i])
390       cancel_loop_tree (rem_bbs[i]->loop_father);
391 
392   remove_bbs (rem_bbs, nrem);
393   free (rem_bbs);
394 
395   /* Find blocks whose dominators may be affected.  */
396   bitmap_clear (seen);
397   for (i = 0; i < n_bord_bbs; i++)
398     {
399       basic_block ldom;
400 
401       bb = get_immediate_dominator (CDI_DOMINATORS, bord_bbs[i]);
402       if (bitmap_bit_p (seen, bb->index))
403 	continue;
404       bitmap_set_bit (seen, bb->index);
405 
406       for (ldom = first_dom_son (CDI_DOMINATORS, bb);
407 	   ldom;
408 	   ldom = next_dom_son (CDI_DOMINATORS, ldom))
409 	if (!dominated_by_p (CDI_DOMINATORS, from, ldom))
410 	  dom_bbs.safe_push (ldom);
411     }
412 
413   free (seen);
414 
415   /* Recount dominators.  */
416   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, true);
417   dom_bbs.release ();
418   free (bord_bbs);
419 
420   /* Fix placements of basic blocks inside loops and the placement of
421      loops in the loop tree.  */
422   fix_bb_placements (from, &irred_invalidated, NULL);
423   fix_loop_placements (from->loop_father, &irred_invalidated);
424 
425   if (irred_invalidated
426       && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
427     mark_irreducible_loops ();
428 
429   return true;
430 }
431 
432 /* Creates place for a new LOOP in loops structure of FN.  */
433 
434 void
place_new_loop(struct function * fn,struct loop * loop)435 place_new_loop (struct function *fn, struct loop *loop)
436 {
437   loop->num = number_of_loops (fn);
438   vec_safe_push (loops_for_fn (fn)->larray, loop);
439 }
440 
441 /* Given LOOP structure with filled header and latch, find the body of the
442    corresponding loop and add it to loops tree.  Insert the LOOP as a son of
443    outer.  */
444 
445 void
add_loop(struct loop * loop,struct loop * outer)446 add_loop (struct loop *loop, struct loop *outer)
447 {
448   basic_block *bbs;
449   int i, n;
450   struct loop *subloop;
451   edge e;
452   edge_iterator ei;
453 
454   /* Add it to loop structure.  */
455   place_new_loop (cfun, loop);
456   flow_loop_tree_node_add (outer, loop);
457 
458   /* Find its nodes.  */
459   bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
460   n = get_loop_body_with_size (loop, bbs, n_basic_blocks_for_fn (cfun));
461 
462   for (i = 0; i < n; i++)
463     {
464       if (bbs[i]->loop_father == outer)
465 	{
466 	  remove_bb_from_loops (bbs[i]);
467 	  add_bb_to_loop (bbs[i], loop);
468 	  continue;
469 	}
470 
471       loop->num_nodes++;
472 
473       /* If we find a direct subloop of OUTER, move it to LOOP.  */
474       subloop = bbs[i]->loop_father;
475       if (loop_outer (subloop) == outer
476 	  && subloop->header == bbs[i])
477 	{
478 	  flow_loop_tree_node_remove (subloop);
479 	  flow_loop_tree_node_add (loop, subloop);
480 	}
481     }
482 
483   /* Update the information about loop exit edges.  */
484   for (i = 0; i < n; i++)
485     {
486       FOR_EACH_EDGE (e, ei, bbs[i]->succs)
487 	{
488 	  rescan_loop_exit (e, false, false);
489 	}
490     }
491 
492   free (bbs);
493 }
494 
495 /* Multiply all frequencies in LOOP by NUM/DEN.  */
496 
497 void
scale_loop_frequencies(struct loop * loop,int num,int den)498 scale_loop_frequencies (struct loop *loop, int num, int den)
499 {
500   basic_block *bbs;
501 
502   bbs = get_loop_body (loop);
503   scale_bbs_frequencies_int (bbs, loop->num_nodes, num, den);
504   free (bbs);
505 }
506 
507 /* Multiply all frequencies in LOOP by SCALE/REG_BR_PROB_BASE.
508    If ITERATION_BOUND is non-zero, scale even further if loop is predicted
509    to iterate too many times.  */
510 
511 void
scale_loop_profile(struct loop * loop,int scale,gcov_type iteration_bound)512 scale_loop_profile (struct loop *loop, int scale, gcov_type iteration_bound)
513 {
514   gcov_type iterations = expected_loop_iterations_unbounded (loop);
515   edge e;
516   edge_iterator ei;
517 
518   if (dump_file && (dump_flags & TDF_DETAILS))
519     fprintf (dump_file, ";; Scaling loop %i with scale %f, "
520 	     "bounding iterations to %i from guessed %i\n",
521 	     loop->num, (double)scale / REG_BR_PROB_BASE,
522 	     (int)iteration_bound, (int)iterations);
523 
524   /* See if loop is predicted to iterate too many times.  */
525   if (iteration_bound && iterations > 0
526       && apply_probability (iterations, scale) > iteration_bound)
527     {
528       /* Fixing loop profile for different trip count is not trivial; the exit
529 	 probabilities has to be updated to match and frequencies propagated down
530 	 to the loop body.
531 
532 	 We fully update only the simple case of loop with single exit that is
533 	 either from the latch or BB just before latch and leads from BB with
534 	 simple conditional jump.   This is OK for use in vectorizer.  */
535       e = single_exit (loop);
536       if (e)
537 	{
538 	  edge other_e;
539 	  int freq_delta;
540 	  gcov_type count_delta;
541 
542           FOR_EACH_EDGE (other_e, ei, e->src->succs)
543 	    if (!(other_e->flags & (EDGE_ABNORMAL | EDGE_FAKE))
544 		&& e != other_e)
545 	      break;
546 
547 	  /* Probability of exit must be 1/iterations.  */
548 	  freq_delta = EDGE_FREQUENCY (e);
549 	  e->probability = REG_BR_PROB_BASE / iteration_bound;
550 	  other_e->probability = inverse_probability (e->probability);
551 	  freq_delta -= EDGE_FREQUENCY (e);
552 
553 	  /* Adjust counts accordingly.  */
554 	  count_delta = e->count;
555 	  e->count = apply_probability (e->src->count, e->probability);
556 	  other_e->count = apply_probability (e->src->count, other_e->probability);
557 	  count_delta -= e->count;
558 
559 	  /* If latch exists, change its frequency and count, since we changed
560 	     probability of exit.  Theoretically we should update everything from
561 	     source of exit edge to latch, but for vectorizer this is enough.  */
562 	  if (loop->latch
563 	      && loop->latch != e->src)
564 	    {
565 	      loop->latch->frequency += freq_delta;
566 	      if (loop->latch->frequency < 0)
567 		loop->latch->frequency = 0;
568 	      loop->latch->count += count_delta;
569 	      if (loop->latch->count < 0)
570 		loop->latch->count = 0;
571 	    }
572 	}
573 
574       /* Roughly speaking we want to reduce the loop body profile by the
575 	 the difference of loop iterations.  We however can do better if
576 	 we look at the actual profile, if it is available.  */
577       scale = RDIV (iteration_bound * scale, iterations);
578       if (loop->header->count)
579 	{
580 	  gcov_type count_in = 0;
581 
582 	  FOR_EACH_EDGE (e, ei, loop->header->preds)
583 	    if (e->src != loop->latch)
584 	      count_in += e->count;
585 
586 	  if (count_in != 0)
587 	    scale = GCOV_COMPUTE_SCALE (count_in * iteration_bound,
588                                         loop->header->count);
589 	}
590       else if (loop->header->frequency)
591 	{
592 	  int freq_in = 0;
593 
594 	  FOR_EACH_EDGE (e, ei, loop->header->preds)
595 	    if (e->src != loop->latch)
596 	      freq_in += EDGE_FREQUENCY (e);
597 
598 	  if (freq_in != 0)
599 	    scale = GCOV_COMPUTE_SCALE (freq_in * iteration_bound,
600                                         loop->header->frequency);
601 	}
602       if (!scale)
603 	scale = 1;
604     }
605 
606   if (scale == REG_BR_PROB_BASE)
607     return;
608 
609   /* Scale the actual probabilities.  */
610   scale_loop_frequencies (loop, scale, REG_BR_PROB_BASE);
611   if (dump_file && (dump_flags & TDF_DETAILS))
612     fprintf (dump_file, ";; guessed iterations are now %i\n",
613 	     (int)expected_loop_iterations_unbounded (loop));
614 }
615 
616 /* Recompute dominance information for basic blocks outside LOOP.  */
617 
618 static void
update_dominators_in_loop(struct loop * loop)619 update_dominators_in_loop (struct loop *loop)
620 {
621   vec<basic_block> dom_bbs = vNULL;
622   sbitmap seen;
623   basic_block *body;
624   unsigned i;
625 
626   seen = sbitmap_alloc (last_basic_block_for_fn (cfun));
627   bitmap_clear (seen);
628   body = get_loop_body (loop);
629 
630   for (i = 0; i < loop->num_nodes; i++)
631     bitmap_set_bit (seen, body[i]->index);
632 
633   for (i = 0; i < loop->num_nodes; i++)
634     {
635       basic_block ldom;
636 
637       for (ldom = first_dom_son (CDI_DOMINATORS, body[i]);
638 	   ldom;
639 	   ldom = next_dom_son (CDI_DOMINATORS, ldom))
640 	if (!bitmap_bit_p (seen, ldom->index))
641 	  {
642 	    bitmap_set_bit (seen, ldom->index);
643 	    dom_bbs.safe_push (ldom);
644 	  }
645     }
646 
647   iterate_fix_dominators (CDI_DOMINATORS, dom_bbs, false);
648   free (body);
649   free (seen);
650   dom_bbs.release ();
651 }
652 
653 /* Creates an if region as shown above. CONDITION is used to create
654    the test for the if.
655 
656    |
657    |     -------------                 -------------
658    |     |  pred_bb  |                 |  pred_bb  |
659    |     -------------                 -------------
660    |           |                             |
661    |           |                             | ENTRY_EDGE
662    |           | ENTRY_EDGE                  V
663    |           |             ====>     -------------
664    |           |                       |  cond_bb  |
665    |           |                       | CONDITION |
666    |           |                       -------------
667    |           V                        /         \
668    |     -------------         e_false /           \ e_true
669    |     |  succ_bb  |                V             V
670    |     -------------         -----------       -----------
671    |                           | false_bb |      | true_bb |
672    |                           -----------       -----------
673    |                                   \           /
674    |                                    \         /
675    |                                     V       V
676    |                                   -------------
677    |                                   |  join_bb  |
678    |                                   -------------
679    |                                         | exit_edge (result)
680    |                                         V
681    |                                    -----------
682    |                                    | succ_bb |
683    |                                    -----------
684    |
685  */
686 
687 edge
create_empty_if_region_on_edge(edge entry_edge,tree condition)688 create_empty_if_region_on_edge (edge entry_edge, tree condition)
689 {
690 
691   basic_block cond_bb, true_bb, false_bb, join_bb;
692   edge e_true, e_false, exit_edge;
693   gimple cond_stmt;
694   tree simple_cond;
695   gimple_stmt_iterator gsi;
696 
697   cond_bb = split_edge (entry_edge);
698 
699   /* Insert condition in cond_bb.  */
700   gsi = gsi_last_bb (cond_bb);
701   simple_cond =
702     force_gimple_operand_gsi (&gsi, condition, true, NULL,
703 			      false, GSI_NEW_STMT);
704   cond_stmt = gimple_build_cond_from_tree (simple_cond, NULL_TREE, NULL_TREE);
705   gsi = gsi_last_bb (cond_bb);
706   gsi_insert_after (&gsi, cond_stmt, GSI_NEW_STMT);
707 
708   join_bb = split_edge (single_succ_edge (cond_bb));
709 
710   e_true = single_succ_edge (cond_bb);
711   true_bb = split_edge (e_true);
712 
713   e_false = make_edge (cond_bb, join_bb, 0);
714   false_bb = split_edge (e_false);
715 
716   e_true->flags &= ~EDGE_FALLTHRU;
717   e_true->flags |= EDGE_TRUE_VALUE;
718   e_false->flags &= ~EDGE_FALLTHRU;
719   e_false->flags |= EDGE_FALSE_VALUE;
720 
721   set_immediate_dominator (CDI_DOMINATORS, cond_bb, entry_edge->src);
722   set_immediate_dominator (CDI_DOMINATORS, true_bb, cond_bb);
723   set_immediate_dominator (CDI_DOMINATORS, false_bb, cond_bb);
724   set_immediate_dominator (CDI_DOMINATORS, join_bb, cond_bb);
725 
726   exit_edge = single_succ_edge (join_bb);
727 
728   if (single_pred_p (exit_edge->dest))
729     set_immediate_dominator (CDI_DOMINATORS, exit_edge->dest, join_bb);
730 
731   return exit_edge;
732 }
733 
734 /* create_empty_loop_on_edge
735    |
736    |    - pred_bb -                   ------ pred_bb ------
737    |   |           |                 | iv0 = initial_value |
738    |    -----|-----                   ---------|-----------
739    |         |                       ______    | entry_edge
740    |         | entry_edge           /      |   |
741    |         |             ====>   |      -V---V- loop_header -------------
742    |         V                     |     | iv_before = phi (iv0, iv_after) |
743    |    - succ_bb -                |      ---|-----------------------------
744    |   |           |               |         |
745    |    -----------                |      ---V--- loop_body ---------------
746    |                               |     | iv_after = iv_before + stride   |
747    |                               |     | if (iv_before < upper_bound)    |
748    |                               |      ---|--------------\--------------
749    |                               |         |               \ exit_e
750    |                               |         V                \
751    |                               |       - loop_latch -      V- succ_bb -
752    |                               |      |              |     |           |
753    |                               |       /-------------       -----------
754    |                                \ ___ /
755 
756    Creates an empty loop as shown above, the IV_BEFORE is the SSA_NAME
757    that is used before the increment of IV. IV_BEFORE should be used for
758    adding code to the body that uses the IV.  OUTER is the outer loop in
759    which the new loop should be inserted.
760 
761    Both INITIAL_VALUE and UPPER_BOUND expressions are gimplified and
762    inserted on the loop entry edge.  This implies that this function
763    should be used only when the UPPER_BOUND expression is a loop
764    invariant.  */
765 
766 struct loop *
create_empty_loop_on_edge(edge entry_edge,tree initial_value,tree stride,tree upper_bound,tree iv,tree * iv_before,tree * iv_after,struct loop * outer)767 create_empty_loop_on_edge (edge entry_edge,
768 			   tree initial_value,
769 			   tree stride, tree upper_bound,
770 			   tree iv,
771 			   tree *iv_before,
772 			   tree *iv_after,
773 			   struct loop *outer)
774 {
775   basic_block loop_header, loop_latch, succ_bb, pred_bb;
776   struct loop *loop;
777   gimple_stmt_iterator gsi;
778   gimple_seq stmts;
779   gimple cond_expr;
780   tree exit_test;
781   edge exit_e;
782   int prob;
783 
784   gcc_assert (entry_edge && initial_value && stride && upper_bound && iv);
785 
786   /* Create header, latch and wire up the loop.  */
787   pred_bb = entry_edge->src;
788   loop_header = split_edge (entry_edge);
789   loop_latch = split_edge (single_succ_edge (loop_header));
790   succ_bb = single_succ (loop_latch);
791   make_edge (loop_header, succ_bb, 0);
792   redirect_edge_succ_nodup (single_succ_edge (loop_latch), loop_header);
793 
794   /* Set immediate dominator information.  */
795   set_immediate_dominator (CDI_DOMINATORS, loop_header, pred_bb);
796   set_immediate_dominator (CDI_DOMINATORS, loop_latch, loop_header);
797   set_immediate_dominator (CDI_DOMINATORS, succ_bb, loop_header);
798 
799   /* Initialize a loop structure and put it in a loop hierarchy.  */
800   loop = alloc_loop ();
801   loop->header = loop_header;
802   loop->latch = loop_latch;
803   add_loop (loop, outer);
804 
805   /* TODO: Fix frequencies and counts.  */
806   prob = REG_BR_PROB_BASE / 2;
807 
808   scale_loop_frequencies (loop, REG_BR_PROB_BASE - prob, REG_BR_PROB_BASE);
809 
810   /* Update dominators.  */
811   update_dominators_in_loop (loop);
812 
813   /* Modify edge flags.  */
814   exit_e = single_exit (loop);
815   exit_e->flags = EDGE_LOOP_EXIT | EDGE_FALSE_VALUE;
816   single_pred_edge (loop_latch)->flags = EDGE_TRUE_VALUE;
817 
818   /* Construct IV code in loop.  */
819   initial_value = force_gimple_operand (initial_value, &stmts, true, iv);
820   if (stmts)
821     {
822       gsi_insert_seq_on_edge (loop_preheader_edge (loop), stmts);
823       gsi_commit_edge_inserts ();
824     }
825 
826   upper_bound = force_gimple_operand (upper_bound, &stmts, true, NULL);
827   if (stmts)
828     {
829       gsi_insert_seq_on_edge (loop_preheader_edge (loop), stmts);
830       gsi_commit_edge_inserts ();
831     }
832 
833   gsi = gsi_last_bb (loop_header);
834   create_iv (initial_value, stride, iv, loop, &gsi, false,
835 	     iv_before, iv_after);
836 
837   /* Insert loop exit condition.  */
838   cond_expr = gimple_build_cond
839     (LT_EXPR, *iv_before, upper_bound, NULL_TREE, NULL_TREE);
840 
841   exit_test = gimple_cond_lhs (cond_expr);
842   exit_test = force_gimple_operand_gsi (&gsi, exit_test, true, NULL,
843 					false, GSI_NEW_STMT);
844   gimple_cond_set_lhs (cond_expr, exit_test);
845   gsi = gsi_last_bb (exit_e->src);
846   gsi_insert_after (&gsi, cond_expr, GSI_NEW_STMT);
847 
848   split_block_after_labels (loop_header);
849 
850   return loop;
851 }
852 
853 /* Make area between HEADER_EDGE and LATCH_EDGE a loop by connecting
854    latch to header and update loop tree and dominators
855    accordingly. Everything between them plus LATCH_EDGE destination must
856    be dominated by HEADER_EDGE destination, and back-reachable from
857    LATCH_EDGE source.  HEADER_EDGE is redirected to basic block SWITCH_BB,
858    FALSE_EDGE of SWITCH_BB to original destination of HEADER_EDGE and
859    TRUE_EDGE of SWITCH_BB to original destination of LATCH_EDGE.
860    Returns the newly created loop.  Frequencies and counts in the new loop
861    are scaled by FALSE_SCALE and in the old one by TRUE_SCALE.  */
862 
863 struct loop *
loopify(edge latch_edge,edge header_edge,basic_block switch_bb,edge true_edge,edge false_edge,bool redirect_all_edges,unsigned true_scale,unsigned false_scale)864 loopify (edge latch_edge, edge header_edge,
865 	 basic_block switch_bb, edge true_edge, edge false_edge,
866 	 bool redirect_all_edges, unsigned true_scale, unsigned false_scale)
867 {
868   basic_block succ_bb = latch_edge->dest;
869   basic_block pred_bb = header_edge->src;
870   struct loop *loop = alloc_loop ();
871   struct loop *outer = loop_outer (succ_bb->loop_father);
872   int freq;
873   gcov_type cnt;
874   edge e;
875   edge_iterator ei;
876 
877   loop->header = header_edge->dest;
878   loop->latch = latch_edge->src;
879 
880   freq = EDGE_FREQUENCY (header_edge);
881   cnt = header_edge->count;
882 
883   /* Redirect edges.  */
884   loop_redirect_edge (latch_edge, loop->header);
885   loop_redirect_edge (true_edge, succ_bb);
886 
887   /* During loop versioning, one of the switch_bb edge is already properly
888      set. Do not redirect it again unless redirect_all_edges is true.  */
889   if (redirect_all_edges)
890     {
891       loop_redirect_edge (header_edge, switch_bb);
892       loop_redirect_edge (false_edge, loop->header);
893 
894       /* Update dominators.  */
895       set_immediate_dominator (CDI_DOMINATORS, switch_bb, pred_bb);
896       set_immediate_dominator (CDI_DOMINATORS, loop->header, switch_bb);
897     }
898 
899   set_immediate_dominator (CDI_DOMINATORS, succ_bb, switch_bb);
900 
901   /* Compute new loop.  */
902   add_loop (loop, outer);
903 
904   /* Add switch_bb to appropriate loop.  */
905   if (switch_bb->loop_father)
906     remove_bb_from_loops (switch_bb);
907   add_bb_to_loop (switch_bb, outer);
908 
909   /* Fix frequencies.  */
910   if (redirect_all_edges)
911     {
912       switch_bb->frequency = freq;
913       switch_bb->count = cnt;
914       FOR_EACH_EDGE (e, ei, switch_bb->succs)
915 	{
916 	  e->count = apply_probability (switch_bb->count, e->probability);
917 	}
918     }
919   scale_loop_frequencies (loop, false_scale, REG_BR_PROB_BASE);
920   scale_loop_frequencies (succ_bb->loop_father, true_scale, REG_BR_PROB_BASE);
921   update_dominators_in_loop (loop);
922 
923   return loop;
924 }
925 
926 /* Remove the latch edge of a LOOP and update loops to indicate that
927    the LOOP was removed.  After this function, original loop latch will
928    have no successor, which caller is expected to fix somehow.
929 
930    If this may cause the information about irreducible regions to become
931    invalid, IRRED_INVALIDATED is set to true.
932 
933    LOOP_CLOSED_SSA_INVALIDATED, if non-NULL, is a bitmap where we store
934    basic blocks that had non-trivial update on their loop_father.*/
935 
936 void
unloop(struct loop * loop,bool * irred_invalidated,bitmap loop_closed_ssa_invalidated)937 unloop (struct loop *loop, bool *irred_invalidated,
938 	bitmap loop_closed_ssa_invalidated)
939 {
940   basic_block *body;
941   struct loop *ploop;
942   unsigned i, n;
943   basic_block latch = loop->latch;
944   bool dummy = false;
945 
946   if (loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP)
947     *irred_invalidated = true;
948 
949   /* This is relatively straightforward.  The dominators are unchanged, as
950      loop header dominates loop latch, so the only thing we have to care of
951      is the placement of loops and basic blocks inside the loop tree.  We
952      move them all to the loop->outer, and then let fix_bb_placements do
953      its work.  */
954 
955   body = get_loop_body (loop);
956   n = loop->num_nodes;
957   for (i = 0; i < n; i++)
958     if (body[i]->loop_father == loop)
959       {
960 	remove_bb_from_loops (body[i]);
961 	add_bb_to_loop (body[i], loop_outer (loop));
962       }
963   free (body);
964 
965   while (loop->inner)
966     {
967       ploop = loop->inner;
968       flow_loop_tree_node_remove (ploop);
969       flow_loop_tree_node_add (loop_outer (loop), ploop);
970     }
971 
972   /* Remove the loop and free its data.  */
973   delete_loop (loop);
974 
975   remove_edge (single_succ_edge (latch));
976 
977   /* We do not pass IRRED_INVALIDATED to fix_bb_placements here, as even if
978      there is an irreducible region inside the cancelled loop, the flags will
979      be still correct.  */
980   fix_bb_placements (latch, &dummy, loop_closed_ssa_invalidated);
981 }
982 
983 /* Fix placement of superloops of LOOP inside loop tree, i.e. ensure that
984    condition stated in description of fix_loop_placement holds for them.
985    It is used in case when we removed some edges coming out of LOOP, which
986    may cause the right placement of LOOP inside loop tree to change.
987 
988    IRRED_INVALIDATED is set to true if a change in the loop structures might
989    invalidate the information about irreducible regions.  */
990 
991 static void
fix_loop_placements(struct loop * loop,bool * irred_invalidated)992 fix_loop_placements (struct loop *loop, bool *irred_invalidated)
993 {
994   struct loop *outer;
995 
996   while (loop_outer (loop))
997     {
998       outer = loop_outer (loop);
999       if (!fix_loop_placement (loop, irred_invalidated))
1000 	break;
1001 
1002       /* Changing the placement of a loop in the loop tree may alter the
1003 	 validity of condition 2) of the description of fix_bb_placement
1004 	 for its preheader, because the successor is the header and belongs
1005 	 to the loop.  So call fix_bb_placements to fix up the placement
1006 	 of the preheader and (possibly) of its predecessors.  */
1007       fix_bb_placements (loop_preheader_edge (loop)->src,
1008 			 irred_invalidated, NULL);
1009       loop = outer;
1010     }
1011 }
1012 
1013 /* Duplicate loop bounds and other information we store about
1014    the loop into its duplicate.  */
1015 
1016 void
copy_loop_info(struct loop * loop,struct loop * target)1017 copy_loop_info (struct loop *loop, struct loop *target)
1018 {
1019   gcc_checking_assert (!target->any_upper_bound && !target->any_estimate);
1020   target->any_upper_bound = loop->any_upper_bound;
1021   target->nb_iterations_upper_bound = loop->nb_iterations_upper_bound;
1022   target->any_estimate = loop->any_estimate;
1023   target->nb_iterations_estimate = loop->nb_iterations_estimate;
1024   target->estimate_state = loop->estimate_state;
1025   target->warned_aggressive_loop_optimizations
1026     |= loop->warned_aggressive_loop_optimizations;
1027 }
1028 
1029 /* Copies copy of LOOP as subloop of TARGET loop, placing newly
1030    created loop into loops structure.  */
1031 struct loop *
duplicate_loop(struct loop * loop,struct loop * target)1032 duplicate_loop (struct loop *loop, struct loop *target)
1033 {
1034   struct loop *cloop;
1035   cloop = alloc_loop ();
1036   place_new_loop (cfun, cloop);
1037 
1038   copy_loop_info (loop, cloop);
1039 
1040   /* Mark the new loop as copy of LOOP.  */
1041   set_loop_copy (loop, cloop);
1042 
1043   /* Add it to target.  */
1044   flow_loop_tree_node_add (target, cloop);
1045 
1046   return cloop;
1047 }
1048 
1049 /* Copies structure of subloops of LOOP into TARGET loop, placing
1050    newly created loops into loop tree.  */
1051 void
duplicate_subloops(struct loop * loop,struct loop * target)1052 duplicate_subloops (struct loop *loop, struct loop *target)
1053 {
1054   struct loop *aloop, *cloop;
1055 
1056   for (aloop = loop->inner; aloop; aloop = aloop->next)
1057     {
1058       cloop = duplicate_loop (aloop, target);
1059       duplicate_subloops (aloop, cloop);
1060     }
1061 }
1062 
1063 /* Copies structure of subloops of N loops, stored in array COPIED_LOOPS,
1064    into TARGET loop, placing newly created loops into loop tree.  */
1065 static void
copy_loops_to(struct loop ** copied_loops,int n,struct loop * target)1066 copy_loops_to (struct loop **copied_loops, int n, struct loop *target)
1067 {
1068   struct loop *aloop;
1069   int i;
1070 
1071   for (i = 0; i < n; i++)
1072     {
1073       aloop = duplicate_loop (copied_loops[i], target);
1074       duplicate_subloops (copied_loops[i], aloop);
1075     }
1076 }
1077 
1078 /* Redirects edge E to basic block DEST.  */
1079 static void
loop_redirect_edge(edge e,basic_block dest)1080 loop_redirect_edge (edge e, basic_block dest)
1081 {
1082   if (e->dest == dest)
1083     return;
1084 
1085   redirect_edge_and_branch_force (e, dest);
1086 }
1087 
1088 /* Check whether LOOP's body can be duplicated.  */
1089 bool
can_duplicate_loop_p(const struct loop * loop)1090 can_duplicate_loop_p (const struct loop *loop)
1091 {
1092   int ret;
1093   basic_block *bbs = get_loop_body (loop);
1094 
1095   ret = can_copy_bbs_p (bbs, loop->num_nodes);
1096   free (bbs);
1097 
1098   return ret;
1099 }
1100 
1101 /* Sets probability and count of edge E to zero.  The probability and count
1102    is redistributed evenly to the remaining edges coming from E->src.  */
1103 
1104 static void
set_zero_probability(edge e)1105 set_zero_probability (edge e)
1106 {
1107   basic_block bb = e->src;
1108   edge_iterator ei;
1109   edge ae, last = NULL;
1110   unsigned n = EDGE_COUNT (bb->succs);
1111   gcov_type cnt = e->count, cnt1;
1112   unsigned prob = e->probability, prob1;
1113 
1114   gcc_assert (n > 1);
1115   cnt1 = cnt / (n - 1);
1116   prob1 = prob / (n - 1);
1117 
1118   FOR_EACH_EDGE (ae, ei, bb->succs)
1119     {
1120       if (ae == e)
1121 	continue;
1122 
1123       ae->probability += prob1;
1124       ae->count += cnt1;
1125       last = ae;
1126     }
1127 
1128   /* Move the rest to one of the edges.  */
1129   last->probability += prob % (n - 1);
1130   last->count += cnt % (n - 1);
1131 
1132   e->probability = 0;
1133   e->count = 0;
1134 }
1135 
1136 /* Duplicates body of LOOP to given edge E NDUPL times.  Takes care of updating
1137    loop structure and dominators.  E's destination must be LOOP header for
1138    this to work, i.e. it must be entry or latch edge of this loop; these are
1139    unique, as the loops must have preheaders for this function to work
1140    correctly (in case E is latch, the function unrolls the loop, if E is entry
1141    edge, it peels the loop).  Store edges created by copying ORIG edge from
1142    copies corresponding to set bits in WONT_EXIT bitmap (bit 0 corresponds to
1143    original LOOP body, the other copies are numbered in order given by control
1144    flow through them) into TO_REMOVE array.  Returns false if duplication is
1145    impossible.  */
1146 
1147 bool
duplicate_loop_to_header_edge(struct loop * loop,edge e,unsigned int ndupl,sbitmap wont_exit,edge orig,vec<edge> * to_remove,int flags)1148 duplicate_loop_to_header_edge (struct loop *loop, edge e,
1149 			       unsigned int ndupl, sbitmap wont_exit,
1150 			       edge orig, vec<edge> *to_remove,
1151 			       int flags)
1152 {
1153   struct loop *target, *aloop;
1154   struct loop **orig_loops;
1155   unsigned n_orig_loops;
1156   basic_block header = loop->header, latch = loop->latch;
1157   basic_block *new_bbs, *bbs, *first_active;
1158   basic_block new_bb, bb, first_active_latch = NULL;
1159   edge ae, latch_edge;
1160   edge spec_edges[2], new_spec_edges[2];
1161 #define SE_LATCH 0
1162 #define SE_ORIG 1
1163   unsigned i, j, n;
1164   int is_latch = (latch == e->src);
1165   int scale_act = 0, *scale_step = NULL, scale_main = 0;
1166   int scale_after_exit = 0;
1167   int p, freq_in, freq_le, freq_out_orig;
1168   int prob_pass_thru, prob_pass_wont_exit, prob_pass_main;
1169   int add_irreducible_flag;
1170   basic_block place_after;
1171   bitmap bbs_to_scale = NULL;
1172   bitmap_iterator bi;
1173 
1174   gcc_assert (e->dest == loop->header);
1175   gcc_assert (ndupl > 0);
1176 
1177   if (orig)
1178     {
1179       /* Orig must be edge out of the loop.  */
1180       gcc_assert (flow_bb_inside_loop_p (loop, orig->src));
1181       gcc_assert (!flow_bb_inside_loop_p (loop, orig->dest));
1182     }
1183 
1184   n = loop->num_nodes;
1185   bbs = get_loop_body_in_dom_order (loop);
1186   gcc_assert (bbs[0] == loop->header);
1187   gcc_assert (bbs[n  - 1] == loop->latch);
1188 
1189   /* Check whether duplication is possible.  */
1190   if (!can_copy_bbs_p (bbs, loop->num_nodes))
1191     {
1192       free (bbs);
1193       return false;
1194     }
1195   new_bbs = XNEWVEC (basic_block, loop->num_nodes);
1196 
1197   /* In case we are doing loop peeling and the loop is in the middle of
1198      irreducible region, the peeled copies will be inside it too.  */
1199   add_irreducible_flag = e->flags & EDGE_IRREDUCIBLE_LOOP;
1200   gcc_assert (!is_latch || !add_irreducible_flag);
1201 
1202   /* Find edge from latch.  */
1203   latch_edge = loop_latch_edge (loop);
1204 
1205   if (flags & DLTHE_FLAG_UPDATE_FREQ)
1206     {
1207       /* Calculate coefficients by that we have to scale frequencies
1208 	 of duplicated loop bodies.  */
1209       freq_in = header->frequency;
1210       freq_le = EDGE_FREQUENCY (latch_edge);
1211       if (freq_in == 0)
1212 	freq_in = 1;
1213       if (freq_in < freq_le)
1214 	freq_in = freq_le;
1215       freq_out_orig = orig ? EDGE_FREQUENCY (orig) : freq_in - freq_le;
1216       if (freq_out_orig > freq_in - freq_le)
1217 	freq_out_orig = freq_in - freq_le;
1218       prob_pass_thru = RDIV (REG_BR_PROB_BASE * freq_le, freq_in);
1219       prob_pass_wont_exit =
1220 	      RDIV (REG_BR_PROB_BASE * (freq_le + freq_out_orig), freq_in);
1221 
1222       if (orig
1223 	  && REG_BR_PROB_BASE - orig->probability != 0)
1224 	{
1225 	  /* The blocks that are dominated by a removed exit edge ORIG have
1226 	     frequencies scaled by this.  */
1227 	  scale_after_exit
1228               = GCOV_COMPUTE_SCALE (REG_BR_PROB_BASE,
1229                                     REG_BR_PROB_BASE - orig->probability);
1230 	  bbs_to_scale = BITMAP_ALLOC (NULL);
1231 	  for (i = 0; i < n; i++)
1232 	    {
1233 	      if (bbs[i] != orig->src
1234 		  && dominated_by_p (CDI_DOMINATORS, bbs[i], orig->src))
1235 		bitmap_set_bit (bbs_to_scale, i);
1236 	    }
1237 	}
1238 
1239       scale_step = XNEWVEC (int, ndupl);
1240 
1241       for (i = 1; i <= ndupl; i++)
1242 	scale_step[i - 1] = bitmap_bit_p (wont_exit, i)
1243 				? prob_pass_wont_exit
1244 				: prob_pass_thru;
1245 
1246       /* Complete peeling is special as the probability of exit in last
1247 	 copy becomes 1.  */
1248       if (flags & DLTHE_FLAG_COMPLETTE_PEEL)
1249 	{
1250 	  int wanted_freq = EDGE_FREQUENCY (e);
1251 
1252 	  if (wanted_freq > freq_in)
1253 	    wanted_freq = freq_in;
1254 
1255 	  gcc_assert (!is_latch);
1256 	  /* First copy has frequency of incoming edge.  Each subsequent
1257 	     frequency should be reduced by prob_pass_wont_exit.  Caller
1258 	     should've managed the flags so all except for original loop
1259 	     has won't exist set.  */
1260 	  scale_act = GCOV_COMPUTE_SCALE (wanted_freq, freq_in);
1261 	  /* Now simulate the duplication adjustments and compute header
1262 	     frequency of the last copy.  */
1263 	  for (i = 0; i < ndupl; i++)
1264 	    wanted_freq = combine_probabilities (wanted_freq, scale_step[i]);
1265 	  scale_main = GCOV_COMPUTE_SCALE (wanted_freq, freq_in);
1266 	}
1267       else if (is_latch)
1268 	{
1269 	  prob_pass_main = bitmap_bit_p (wont_exit, 0)
1270 				? prob_pass_wont_exit
1271 				: prob_pass_thru;
1272 	  p = prob_pass_main;
1273 	  scale_main = REG_BR_PROB_BASE;
1274 	  for (i = 0; i < ndupl; i++)
1275 	    {
1276 	      scale_main += p;
1277 	      p = combine_probabilities (p, scale_step[i]);
1278 	    }
1279 	  scale_main = GCOV_COMPUTE_SCALE (REG_BR_PROB_BASE, scale_main);
1280 	  scale_act = combine_probabilities (scale_main, prob_pass_main);
1281 	}
1282       else
1283 	{
1284 	  scale_main = REG_BR_PROB_BASE;
1285 	  for (i = 0; i < ndupl; i++)
1286 	    scale_main = combine_probabilities (scale_main, scale_step[i]);
1287 	  scale_act = REG_BR_PROB_BASE - prob_pass_thru;
1288 	}
1289       for (i = 0; i < ndupl; i++)
1290 	gcc_assert (scale_step[i] >= 0 && scale_step[i] <= REG_BR_PROB_BASE);
1291       gcc_assert (scale_main >= 0 && scale_main <= REG_BR_PROB_BASE
1292 		  && scale_act >= 0  && scale_act <= REG_BR_PROB_BASE);
1293     }
1294 
1295   /* Loop the new bbs will belong to.  */
1296   target = e->src->loop_father;
1297 
1298   /* Original loops.  */
1299   n_orig_loops = 0;
1300   for (aloop = loop->inner; aloop; aloop = aloop->next)
1301     n_orig_loops++;
1302   orig_loops = XNEWVEC (struct loop *, n_orig_loops);
1303   for (aloop = loop->inner, i = 0; aloop; aloop = aloop->next, i++)
1304     orig_loops[i] = aloop;
1305 
1306   set_loop_copy (loop, target);
1307 
1308   first_active = XNEWVEC (basic_block, n);
1309   if (is_latch)
1310     {
1311       memcpy (first_active, bbs, n * sizeof (basic_block));
1312       first_active_latch = latch;
1313     }
1314 
1315   spec_edges[SE_ORIG] = orig;
1316   spec_edges[SE_LATCH] = latch_edge;
1317 
1318   place_after = e->src;
1319   for (j = 0; j < ndupl; j++)
1320     {
1321       /* Copy loops.  */
1322       copy_loops_to (orig_loops, n_orig_loops, target);
1323 
1324       /* Copy bbs.  */
1325       copy_bbs (bbs, n, new_bbs, spec_edges, 2, new_spec_edges, loop,
1326 		place_after, true);
1327       place_after = new_spec_edges[SE_LATCH]->src;
1328 
1329       if (flags & DLTHE_RECORD_COPY_NUMBER)
1330 	for (i = 0; i < n; i++)
1331 	  {
1332 	    gcc_assert (!new_bbs[i]->aux);
1333 	    new_bbs[i]->aux = (void *)(size_t)(j + 1);
1334 	  }
1335 
1336       /* Note whether the blocks and edges belong to an irreducible loop.  */
1337       if (add_irreducible_flag)
1338 	{
1339 	  for (i = 0; i < n; i++)
1340 	    new_bbs[i]->flags |= BB_DUPLICATED;
1341 	  for (i = 0; i < n; i++)
1342 	    {
1343 	      edge_iterator ei;
1344 	      new_bb = new_bbs[i];
1345 	      if (new_bb->loop_father == target)
1346 		new_bb->flags |= BB_IRREDUCIBLE_LOOP;
1347 
1348 	      FOR_EACH_EDGE (ae, ei, new_bb->succs)
1349 		if ((ae->dest->flags & BB_DUPLICATED)
1350 		    && (ae->src->loop_father == target
1351 			|| ae->dest->loop_father == target))
1352 		  ae->flags |= EDGE_IRREDUCIBLE_LOOP;
1353 	    }
1354 	  for (i = 0; i < n; i++)
1355 	    new_bbs[i]->flags &= ~BB_DUPLICATED;
1356 	}
1357 
1358       /* Redirect the special edges.  */
1359       if (is_latch)
1360 	{
1361 	  redirect_edge_and_branch_force (latch_edge, new_bbs[0]);
1362 	  redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1363 					  loop->header);
1364 	  set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], latch);
1365 	  latch = loop->latch = new_bbs[n - 1];
1366 	  e = latch_edge = new_spec_edges[SE_LATCH];
1367 	}
1368       else
1369 	{
1370 	  redirect_edge_and_branch_force (new_spec_edges[SE_LATCH],
1371 					  loop->header);
1372 	  redirect_edge_and_branch_force (e, new_bbs[0]);
1373 	  set_immediate_dominator (CDI_DOMINATORS, new_bbs[0], e->src);
1374 	  e = new_spec_edges[SE_LATCH];
1375 	}
1376 
1377       /* Record exit edge in this copy.  */
1378       if (orig && bitmap_bit_p (wont_exit, j + 1))
1379 	{
1380 	  if (to_remove)
1381 	    to_remove->safe_push (new_spec_edges[SE_ORIG]);
1382 	  set_zero_probability (new_spec_edges[SE_ORIG]);
1383 
1384 	  /* Scale the frequencies of the blocks dominated by the exit.  */
1385 	  if (bbs_to_scale)
1386 	    {
1387 	      EXECUTE_IF_SET_IN_BITMAP (bbs_to_scale, 0, i, bi)
1388 		{
1389 		  scale_bbs_frequencies_int (new_bbs + i, 1, scale_after_exit,
1390 					     REG_BR_PROB_BASE);
1391 		}
1392 	    }
1393 	}
1394 
1395       /* Record the first copy in the control flow order if it is not
1396 	 the original loop (i.e. in case of peeling).  */
1397       if (!first_active_latch)
1398 	{
1399 	  memcpy (first_active, new_bbs, n * sizeof (basic_block));
1400 	  first_active_latch = new_bbs[n - 1];
1401 	}
1402 
1403       /* Set counts and frequencies.  */
1404       if (flags & DLTHE_FLAG_UPDATE_FREQ)
1405 	{
1406 	  scale_bbs_frequencies_int (new_bbs, n, scale_act, REG_BR_PROB_BASE);
1407 	  scale_act = combine_probabilities (scale_act, scale_step[j]);
1408 	}
1409     }
1410   free (new_bbs);
1411   free (orig_loops);
1412 
1413   /* Record the exit edge in the original loop body, and update the frequencies.  */
1414   if (orig && bitmap_bit_p (wont_exit, 0))
1415     {
1416       if (to_remove)
1417 	to_remove->safe_push (orig);
1418       set_zero_probability (orig);
1419 
1420       /* Scale the frequencies of the blocks dominated by the exit.  */
1421       if (bbs_to_scale)
1422 	{
1423 	  EXECUTE_IF_SET_IN_BITMAP (bbs_to_scale, 0, i, bi)
1424 	    {
1425 	      scale_bbs_frequencies_int (bbs + i, 1, scale_after_exit,
1426 					 REG_BR_PROB_BASE);
1427 	    }
1428 	}
1429     }
1430 
1431   /* Update the original loop.  */
1432   if (!is_latch)
1433     set_immediate_dominator (CDI_DOMINATORS, e->dest, e->src);
1434   if (flags & DLTHE_FLAG_UPDATE_FREQ)
1435     {
1436       scale_bbs_frequencies_int (bbs, n, scale_main, REG_BR_PROB_BASE);
1437       free (scale_step);
1438     }
1439 
1440   /* Update dominators of outer blocks if affected.  */
1441   for (i = 0; i < n; i++)
1442     {
1443       basic_block dominated, dom_bb;
1444       vec<basic_block> dom_bbs;
1445       unsigned j;
1446 
1447       bb = bbs[i];
1448       bb->aux = 0;
1449 
1450       dom_bbs = get_dominated_by (CDI_DOMINATORS, bb);
1451       FOR_EACH_VEC_ELT (dom_bbs, j, dominated)
1452 	{
1453 	  if (flow_bb_inside_loop_p (loop, dominated))
1454 	    continue;
1455 	  dom_bb = nearest_common_dominator (
1456 			CDI_DOMINATORS, first_active[i], first_active_latch);
1457 	  set_immediate_dominator (CDI_DOMINATORS, dominated, dom_bb);
1458 	}
1459       dom_bbs.release ();
1460     }
1461   free (first_active);
1462 
1463   free (bbs);
1464   BITMAP_FREE (bbs_to_scale);
1465 
1466   return true;
1467 }
1468 
1469 /* A callback for make_forwarder block, to redirect all edges except for
1470    MFB_KJ_EDGE to the entry part.  E is the edge for that we should decide
1471    whether to redirect it.  */
1472 
1473 edge mfb_kj_edge;
1474 bool
mfb_keep_just(edge e)1475 mfb_keep_just (edge e)
1476 {
1477   return e != mfb_kj_edge;
1478 }
1479 
1480 /* True when a candidate preheader BLOCK has predecessors from LOOP.  */
1481 
1482 static bool
has_preds_from_loop(basic_block block,struct loop * loop)1483 has_preds_from_loop (basic_block block, struct loop *loop)
1484 {
1485   edge e;
1486   edge_iterator ei;
1487 
1488   FOR_EACH_EDGE (e, ei, block->preds)
1489     if (e->src->loop_father == loop)
1490       return true;
1491   return false;
1492 }
1493 
1494 /* Creates a pre-header for a LOOP.  Returns newly created block.  Unless
1495    CP_SIMPLE_PREHEADERS is set in FLAGS, we only force LOOP to have single
1496    entry; otherwise we also force preheader block to have only one successor.
1497    When CP_FALLTHRU_PREHEADERS is set in FLAGS, we force the preheader block
1498    to be a fallthru predecessor to the loop header and to have only
1499    predecessors from outside of the loop.
1500    The function also updates dominators.  */
1501 
1502 basic_block
create_preheader(struct loop * loop,int flags)1503 create_preheader (struct loop *loop, int flags)
1504 {
1505   edge e, fallthru;
1506   basic_block dummy;
1507   int nentry = 0;
1508   bool irred = false;
1509   bool latch_edge_was_fallthru;
1510   edge one_succ_pred = NULL, single_entry = NULL;
1511   edge_iterator ei;
1512 
1513   FOR_EACH_EDGE (e, ei, loop->header->preds)
1514     {
1515       if (e->src == loop->latch)
1516 	continue;
1517       irred |= (e->flags & EDGE_IRREDUCIBLE_LOOP) != 0;
1518       nentry++;
1519       single_entry = e;
1520       if (single_succ_p (e->src))
1521 	one_succ_pred = e;
1522     }
1523   gcc_assert (nentry);
1524   if (nentry == 1)
1525     {
1526       bool need_forwarder_block = false;
1527 
1528       /* We do not allow entry block to be the loop preheader, since we
1529 	     cannot emit code there.  */
1530       if (single_entry->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1531         need_forwarder_block = true;
1532       else
1533         {
1534           /* If we want simple preheaders, also force the preheader to have
1535              just a single successor.  */
1536           if ((flags & CP_SIMPLE_PREHEADERS)
1537               && !single_succ_p (single_entry->src))
1538             need_forwarder_block = true;
1539           /* If we want fallthru preheaders, also create forwarder block when
1540              preheader ends with a jump or has predecessors from loop.  */
1541           else if ((flags & CP_FALLTHRU_PREHEADERS)
1542                    && (JUMP_P (BB_END (single_entry->src))
1543                        || has_preds_from_loop (single_entry->src, loop)))
1544             need_forwarder_block = true;
1545         }
1546       if (! need_forwarder_block)
1547 	return NULL;
1548     }
1549 
1550   mfb_kj_edge = loop_latch_edge (loop);
1551   latch_edge_was_fallthru = (mfb_kj_edge->flags & EDGE_FALLTHRU) != 0;
1552   fallthru = make_forwarder_block (loop->header, mfb_keep_just, NULL);
1553   dummy = fallthru->src;
1554   loop->header = fallthru->dest;
1555 
1556   /* Try to be clever in placing the newly created preheader.  The idea is to
1557      avoid breaking any "fallthruness" relationship between blocks.
1558 
1559      The preheader was created just before the header and all incoming edges
1560      to the header were redirected to the preheader, except the latch edge.
1561      So the only problematic case is when this latch edge was a fallthru
1562      edge: it is not anymore after the preheader creation so we have broken
1563      the fallthruness.  We're therefore going to look for a better place.  */
1564   if (latch_edge_was_fallthru)
1565     {
1566       if (one_succ_pred)
1567 	e = one_succ_pred;
1568       else
1569 	e = EDGE_PRED (dummy, 0);
1570 
1571       move_block_after (dummy, e->src);
1572     }
1573 
1574   if (irred)
1575     {
1576       dummy->flags |= BB_IRREDUCIBLE_LOOP;
1577       single_succ_edge (dummy)->flags |= EDGE_IRREDUCIBLE_LOOP;
1578     }
1579 
1580   if (dump_file)
1581     fprintf (dump_file, "Created preheader block for loop %i\n",
1582 	     loop->num);
1583 
1584   if (flags & CP_FALLTHRU_PREHEADERS)
1585     gcc_assert ((single_succ_edge (dummy)->flags & EDGE_FALLTHRU)
1586                 && !JUMP_P (BB_END (dummy)));
1587 
1588   return dummy;
1589 }
1590 
1591 /* Create preheaders for each loop; for meaning of FLAGS see create_preheader.  */
1592 
1593 void
create_preheaders(int flags)1594 create_preheaders (int flags)
1595 {
1596   struct loop *loop;
1597 
1598   if (!current_loops)
1599     return;
1600 
1601   FOR_EACH_LOOP (loop, 0)
1602     create_preheader (loop, flags);
1603   loops_state_set (LOOPS_HAVE_PREHEADERS);
1604 }
1605 
1606 /* Forces all loop latches to have only single successor.  */
1607 
1608 void
force_single_succ_latches(void)1609 force_single_succ_latches (void)
1610 {
1611   struct loop *loop;
1612   edge e;
1613 
1614   FOR_EACH_LOOP (loop, 0)
1615     {
1616       if (loop->latch != loop->header && single_succ_p (loop->latch))
1617 	continue;
1618 
1619       e = find_edge (loop->latch, loop->header);
1620       gcc_checking_assert (e != NULL);
1621 
1622       split_edge (e);
1623     }
1624   loops_state_set (LOOPS_HAVE_SIMPLE_LATCHES);
1625 }
1626 
1627 /* This function is called from loop_version.  It splits the entry edge
1628    of the loop we want to version, adds the versioning condition, and
1629    adjust the edges to the two versions of the loop appropriately.
1630    e is an incoming edge. Returns the basic block containing the
1631    condition.
1632 
1633    --- edge e ---- > [second_head]
1634 
1635    Split it and insert new conditional expression and adjust edges.
1636 
1637     --- edge e ---> [cond expr] ---> [first_head]
1638 			|
1639 			+---------> [second_head]
1640 
1641   THEN_PROB is the probability of then branch of the condition.  */
1642 
1643 static basic_block
lv_adjust_loop_entry_edge(basic_block first_head,basic_block second_head,edge e,void * cond_expr,unsigned then_prob)1644 lv_adjust_loop_entry_edge (basic_block first_head, basic_block second_head,
1645 			   edge e, void *cond_expr, unsigned then_prob)
1646 {
1647   basic_block new_head = NULL;
1648   edge e1;
1649 
1650   gcc_assert (e->dest == second_head);
1651 
1652   /* Split edge 'e'. This will create a new basic block, where we can
1653      insert conditional expr.  */
1654   new_head = split_edge (e);
1655 
1656   lv_add_condition_to_bb (first_head, second_head, new_head,
1657 			  cond_expr);
1658 
1659   /* Don't set EDGE_TRUE_VALUE in RTL mode, as it's invalid there.  */
1660   e = single_succ_edge (new_head);
1661   e1 = make_edge (new_head, first_head,
1662 		  current_ir_type () == IR_GIMPLE ? EDGE_TRUE_VALUE : 0);
1663   e1->probability = then_prob;
1664   e->probability = REG_BR_PROB_BASE - then_prob;
1665   e1->count = apply_probability (e->count, e1->probability);
1666   e->count = apply_probability (e->count, e->probability);
1667 
1668   set_immediate_dominator (CDI_DOMINATORS, first_head, new_head);
1669   set_immediate_dominator (CDI_DOMINATORS, second_head, new_head);
1670 
1671   /* Adjust loop header phi nodes.  */
1672   lv_adjust_loop_header_phi (first_head, second_head, new_head, e1);
1673 
1674   return new_head;
1675 }
1676 
1677 /* Main entry point for Loop Versioning transformation.
1678 
1679    This transformation given a condition and a loop, creates
1680    -if (condition) { loop_copy1 } else { loop_copy2 },
1681    where loop_copy1 is the loop transformed in one way, and loop_copy2
1682    is the loop transformed in another way (or unchanged). 'condition'
1683    may be a run time test for things that were not resolved by static
1684    analysis (overlapping ranges (anti-aliasing), alignment, etc.).
1685 
1686    THEN_PROB is the probability of the then edge of the if.  THEN_SCALE
1687    is the ratio by that the frequencies in the original loop should
1688    be scaled.  ELSE_SCALE is the ratio by that the frequencies in the
1689    new loop should be scaled.
1690 
1691    If PLACE_AFTER is true, we place the new loop after LOOP in the
1692    instruction stream, otherwise it is placed before LOOP.  */
1693 
1694 struct loop *
loop_version(struct loop * loop,void * cond_expr,basic_block * condition_bb,unsigned then_prob,unsigned then_scale,unsigned else_scale,bool place_after)1695 loop_version (struct loop *loop,
1696 	      void *cond_expr, basic_block *condition_bb,
1697 	      unsigned then_prob, unsigned then_scale, unsigned else_scale,
1698 	      bool place_after)
1699 {
1700   basic_block first_head, second_head;
1701   edge entry, latch_edge, true_edge, false_edge;
1702   int irred_flag;
1703   struct loop *nloop;
1704   basic_block cond_bb;
1705 
1706   /* Record entry and latch edges for the loop */
1707   entry = loop_preheader_edge (loop);
1708   irred_flag = entry->flags & EDGE_IRREDUCIBLE_LOOP;
1709   entry->flags &= ~EDGE_IRREDUCIBLE_LOOP;
1710 
1711   /* Note down head of loop as first_head.  */
1712   first_head = entry->dest;
1713 
1714   /* Duplicate loop.  */
1715   if (!cfg_hook_duplicate_loop_to_header_edge (loop, entry, 1,
1716 					       NULL, NULL, NULL, 0))
1717     {
1718       entry->flags |= irred_flag;
1719       return NULL;
1720     }
1721 
1722   /* After duplication entry edge now points to new loop head block.
1723      Note down new head as second_head.  */
1724   second_head = entry->dest;
1725 
1726   /* Split loop entry edge and insert new block with cond expr.  */
1727   cond_bb =  lv_adjust_loop_entry_edge (first_head, second_head,
1728 					entry, cond_expr, then_prob);
1729   if (condition_bb)
1730     *condition_bb = cond_bb;
1731 
1732   if (!cond_bb)
1733     {
1734       entry->flags |= irred_flag;
1735       return NULL;
1736     }
1737 
1738   latch_edge = single_succ_edge (get_bb_copy (loop->latch));
1739 
1740   extract_cond_bb_edges (cond_bb, &true_edge, &false_edge);
1741   nloop = loopify (latch_edge,
1742 		   single_pred_edge (get_bb_copy (loop->header)),
1743 		   cond_bb, true_edge, false_edge,
1744 		   false /* Do not redirect all edges.  */,
1745 		   then_scale, else_scale);
1746 
1747   copy_loop_info (loop, nloop);
1748 
1749   /* loopify redirected latch_edge. Update its PENDING_STMTS.  */
1750   lv_flush_pending_stmts (latch_edge);
1751 
1752   /* loopify redirected condition_bb's succ edge. Update its PENDING_STMTS.  */
1753   extract_cond_bb_edges (cond_bb, &true_edge, &false_edge);
1754   lv_flush_pending_stmts (false_edge);
1755   /* Adjust irreducible flag.  */
1756   if (irred_flag)
1757     {
1758       cond_bb->flags |= BB_IRREDUCIBLE_LOOP;
1759       loop_preheader_edge (loop)->flags |= EDGE_IRREDUCIBLE_LOOP;
1760       loop_preheader_edge (nloop)->flags |= EDGE_IRREDUCIBLE_LOOP;
1761       single_pred_edge (cond_bb)->flags |= EDGE_IRREDUCIBLE_LOOP;
1762     }
1763 
1764   if (place_after)
1765     {
1766       basic_block *bbs = get_loop_body_in_dom_order (nloop), after;
1767       unsigned i;
1768 
1769       after = loop->latch;
1770 
1771       for (i = 0; i < nloop->num_nodes; i++)
1772 	{
1773 	  move_block_after (bbs[i], after);
1774 	  after = bbs[i];
1775 	}
1776       free (bbs);
1777     }
1778 
1779   /* At this point condition_bb is loop preheader with two successors,
1780      first_head and second_head.   Make sure that loop preheader has only
1781      one successor.  */
1782   split_edge (loop_preheader_edge (loop));
1783   split_edge (loop_preheader_edge (nloop));
1784 
1785   return nloop;
1786 }
1787