Update change log
[platform/upstream/gcc48.git] / gcc / mcf.c
1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2    basic block and edge frequency counts.
3    Copyright (C) 2008-2013 Free Software Foundation, Inc.
4    Contributed by Paul Yuan (yingbo.com@gmail.com) and
5                   Vinodha Ramasamy (vinodha@google.com).
6
7 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* References:
23    [1] "Feedback-directed Optimizations in GCC with Estimated Edge Profiles
24         from Hardware Event Sampling", Vinodha Ramasamy, Paul Yuan, Dehao Chen,
25         and Robert Hundt; GCC Summit 2008.
26    [2] "Complementing Missing and Inaccurate Profiling Using a Minimum Cost
27         Circulation Algorithm", Roy Levin, Ilan Newman and Gadi Haber;
28         HiPEAC '08.
29
30    Algorithm to smooth basic block and edge counts:
31    1. create_fixup_graph: Create fixup graph by translating function CFG into
32       a graph that satisfies MCF algorithm requirements.
33    2. find_max_flow: Find maximal flow.
34    3. compute_residual_flow: Form residual network.
35    4. Repeat:
36       cancel_negative_cycle: While G contains a negative cost cycle C, reverse
37       the flow on the found cycle by the minimum residual capacity in that
38       cycle.
39    5. Form the minimal cost flow
40       f(u,v) = rf(v, u).
41    6. adjust_cfg_counts: Update initial edge weights with corrected weights.
42       delta(u.v) = f(u,v) -f(v,u).
43       w*(u,v) = w(u,v) + delta(u,v).  */
44
45 #include "config.h"
46 #include "system.h"
47 #include "coretypes.h"
48 #include "basic-block.h"
49 #include "gcov-io.h"
50 #include "profile.h"
51 #include "dumpfile.h"
52
53 /* CAP_INFINITY: Constant to represent infinite capacity.  */
54 #define CAP_INFINITY INTTYPE_MAXIMUM (HOST_WIDEST_INT)
55
56 /* COST FUNCTION.  */
57 #define K_POS(b)        ((b))
58 #define K_NEG(b)        (50 * (b))
59 #define COST(k, w)      ((k) / mcf_ln ((w) + 2))
60 /* Limit the number of iterations for cancel_negative_cycles() to ensure
61    reasonable compile time.  */
62 #define MAX_ITER(n, e)  10 + (1000000 / ((n) * (e)))
63 typedef enum
64 {
65   INVALID_EDGE,
66   VERTEX_SPLIT_EDGE,        /* Edge to represent vertex with w(e) = w(v).  */
67   REDIRECT_EDGE,            /* Edge after vertex transformation.  */
68   REVERSE_EDGE,
69   SOURCE_CONNECT_EDGE,      /* Single edge connecting to single source.  */
70   SINK_CONNECT_EDGE,        /* Single edge connecting to single sink.  */
71   BALANCE_EDGE,             /* Edge connecting with source/sink: cp(e) = 0.  */
72   REDIRECT_NORMALIZED_EDGE, /* Normalized edge for a redirect edge.  */
73   REVERSE_NORMALIZED_EDGE   /* Normalized edge for a reverse edge.  */
74 } edge_type;
75
76 /* Structure to represent an edge in the fixup graph.  */
77 typedef struct fixup_edge_d
78 {
79   int src;
80   int dest;
81   /* Flag denoting type of edge and attributes for the flow field.  */
82   edge_type type;
83   bool is_rflow_valid;
84   /* Index to the normalization vertex added for this edge.  */
85   int norm_vertex_index;
86   /* Flow for this edge.  */
87   gcov_type flow;
88   /* Residual flow for this edge - used during negative cycle canceling.  */
89   gcov_type rflow;
90   gcov_type weight;
91   gcov_type cost;
92   gcov_type max_capacity;
93 } fixup_edge_type;
94
95 typedef fixup_edge_type *fixup_edge_p;
96
97
98 /* Structure to represent a vertex in the fixup graph.  */
99 typedef struct fixup_vertex_d
100 {
101   vec<fixup_edge_p> succ_edges;
102 } fixup_vertex_type;
103
104 typedef fixup_vertex_type *fixup_vertex_p;
105
106 /* Fixup graph used in the MCF algorithm.  */
107 typedef struct fixup_graph_d
108 {
109   /* Current number of vertices for the graph.  */
110   int num_vertices;
111   /* Current number of edges for the graph.  */
112   int num_edges;
113   /* Index of new entry vertex.  */
114   int new_entry_index;
115   /* Index of new exit vertex.  */
116   int new_exit_index;
117   /* Fixup vertex list. Adjacency list for fixup graph.  */
118   fixup_vertex_p vertex_list;
119   /* Fixup edge list.  */
120   fixup_edge_p edge_list;
121 } fixup_graph_type;
122
123 typedef struct queue_d
124 {
125   int *queue;
126   int head;
127   int tail;
128   int size;
129 } queue_type;
130
131 /* Structure used in the maximal flow routines to find augmenting path.  */
132 typedef struct augmenting_path_d
133 {
134   /* Queue used to hold vertex indices.  */
135   queue_type queue_list;
136   /* Vector to hold chain of pred vertex indices in augmenting path.  */
137   int *bb_pred;
138   /* Vector that indicates if basic block i has been visited.  */
139   int *is_visited;
140 } augmenting_path_type;
141
142
143 /* Function definitions.  */
144
145 /* Dump routines to aid debugging.  */
146
147 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format.  */
148
149 static void
150 print_basic_block (FILE *file, fixup_graph_type *fixup_graph, int n)
151 {
152   if (n == ENTRY_BLOCK)
153     fputs ("ENTRY", file);
154   else if (n == ENTRY_BLOCK + 1)
155     fputs ("ENTRY''", file);
156   else if (n == 2 * EXIT_BLOCK)
157     fputs ("EXIT", file);
158   else if (n == 2 * EXIT_BLOCK + 1)
159     fputs ("EXIT''", file);
160   else if (n == fixup_graph->new_exit_index)
161     fputs ("NEW_EXIT", file);
162   else if (n == fixup_graph->new_entry_index)
163     fputs ("NEW_ENTRY", file);
164   else
165     {
166       fprintf (file, "%d", n / 2);
167       if (n % 2)
168         fputs ("''", file);
169       else
170         fputs ("'", file);
171     }
172 }
173
174
175 /* Print edge S->D for given fixup_graph with n' and n'' format.
176    PARAMETERS:
177    S is the index of the source vertex of the edge (input) and
178    D is the index of the destination vertex of the edge (input) for the given
179    fixup_graph (input).  */
180
181 static void
182 print_edge (FILE *file, fixup_graph_type *fixup_graph, int s, int d)
183 {
184   print_basic_block (file, fixup_graph, s);
185   fputs ("->", file);
186   print_basic_block (file, fixup_graph, d);
187 }
188
189
190 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
191    file.  */
192 static void
193 dump_fixup_edge (FILE *file, fixup_graph_type *fixup_graph, fixup_edge_p fedge)
194 {
195   if (!fedge)
196     {
197       fputs ("NULL fixup graph edge.\n", file);
198       return;
199     }
200
201   print_edge (file, fixup_graph, fedge->src, fedge->dest);
202   fputs (": ", file);
203
204   if (fedge->type)
205     {
206       fprintf (file, "flow/capacity=" HOST_WIDEST_INT_PRINT_DEC "/",
207                fedge->flow);
208       if (fedge->max_capacity == CAP_INFINITY)
209         fputs ("+oo,", file);
210       else
211         fprintf (file, "" HOST_WIDEST_INT_PRINT_DEC ",", fedge->max_capacity);
212     }
213
214   if (fedge->is_rflow_valid)
215     {
216       if (fedge->rflow == CAP_INFINITY)
217         fputs (" rflow=+oo.", file);
218       else
219         fprintf (file, " rflow=" HOST_WIDEST_INT_PRINT_DEC ",", fedge->rflow);
220     }
221
222   fprintf (file, " cost=" HOST_WIDEST_INT_PRINT_DEC ".", fedge->cost);
223
224   fprintf (file, "\t(%d->%d)", fedge->src, fedge->dest);
225
226   if (fedge->type)
227     {
228       switch (fedge->type)
229         {
230         case VERTEX_SPLIT_EDGE:
231           fputs (" @VERTEX_SPLIT_EDGE", file);
232           break;
233
234         case REDIRECT_EDGE:
235           fputs (" @REDIRECT_EDGE", file);
236           break;
237
238         case SOURCE_CONNECT_EDGE:
239           fputs (" @SOURCE_CONNECT_EDGE", file);
240           break;
241
242         case SINK_CONNECT_EDGE:
243           fputs (" @SINK_CONNECT_EDGE", file);
244           break;
245
246         case REVERSE_EDGE:
247           fputs (" @REVERSE_EDGE", file);
248           break;
249
250         case BALANCE_EDGE:
251           fputs (" @BALANCE_EDGE", file);
252           break;
253
254         case REDIRECT_NORMALIZED_EDGE:
255         case REVERSE_NORMALIZED_EDGE:
256           fputs ("  @NORMALIZED_EDGE", file);
257           break;
258
259         default:
260           fputs (" @INVALID_EDGE", file);
261           break;
262         }
263     }
264   fputs ("\n", file);
265 }
266
267
268 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
269    file. The input string MSG is printed out as a heading.  */
270
271 static void
272 dump_fixup_graph (FILE *file, fixup_graph_type *fixup_graph, const char *msg)
273 {
274   int i, j;
275   int fnum_vertices, fnum_edges;
276
277   fixup_vertex_p fvertex_list, pfvertex;
278   fixup_edge_p pfedge;
279
280   gcc_assert (fixup_graph);
281   fvertex_list = fixup_graph->vertex_list;
282   fnum_vertices = fixup_graph->num_vertices;
283   fnum_edges = fixup_graph->num_edges;
284
285   fprintf (file, "\nDump fixup graph for %s(): %s.\n",
286            current_function_name (), msg);
287   fprintf (file,
288            "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
289            fnum_vertices, fnum_edges, fixup_graph->new_exit_index);
290
291   for (i = 0; i < fnum_vertices; i++)
292     {
293       pfvertex = fvertex_list + i;
294       fprintf (file, "vertex_list[%d]: %d succ fixup edges.\n",
295                i, pfvertex->succ_edges.length ());
296
297       for (j = 0; pfvertex->succ_edges.iterate (j, &pfedge);
298            j++)
299         {
300           /* Distinguish forward edges and backward edges in the residual flow
301              network.  */
302           if (pfedge->type)
303             fputs ("(f) ", file);
304           else if (pfedge->is_rflow_valid)
305             fputs ("(b) ", file);
306           dump_fixup_edge (file, fixup_graph, pfedge);
307         }
308     }
309
310   fputs ("\n", file);
311 }
312
313
314 /* Utility routines.  */
315 /* ln() implementation: approximate calculation. Returns ln of X.  */
316
317 static double
318 mcf_ln (double x)
319 {
320 #define E       2.71828
321   int l = 1;
322   double m = E;
323
324   gcc_assert (x >= 0);
325
326   while (m < x)
327     {
328       m *= E;
329       l++;
330     }
331
332   return l;
333 }
334
335
336 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
337    implementation) by John Carmack.  Returns sqrt of X.  */
338
339 static double
340 mcf_sqrt (double x)
341 {
342 #define MAGIC_CONST1    0x1fbcf800
343 #define MAGIC_CONST2    0x5f3759df
344   union {
345     int intPart;
346     float floatPart;
347   } convertor, convertor2;
348
349   gcc_assert (x >= 0);
350
351   convertor.floatPart = x;
352   convertor2.floatPart = x;
353   convertor.intPart = MAGIC_CONST1 + (convertor.intPart >> 1);
354   convertor2.intPart = MAGIC_CONST2 - (convertor2.intPart >> 1);
355
356   return 0.5f * (convertor.floatPart + (x * convertor2.floatPart));
357 }
358
359
360 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
361    (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
362    added set to COST.  */
363
364 static fixup_edge_p
365 add_edge (fixup_graph_type *fixup_graph, int src, int dest, gcov_type cost)
366 {
367   fixup_vertex_p curr_vertex = fixup_graph->vertex_list + src;
368   fixup_edge_p curr_edge = fixup_graph->edge_list + fixup_graph->num_edges;
369   curr_edge->src = src;
370   curr_edge->dest = dest;
371   curr_edge->cost = cost;
372   fixup_graph->num_edges++;
373   if (dump_file)
374     dump_fixup_edge (dump_file, fixup_graph, curr_edge);
375   curr_vertex->succ_edges.safe_push (curr_edge);
376   return curr_edge;
377 }
378
379
380 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
381    MAX_CAPACITY to the edge_list in the fixup graph.  */
382
383 static void
384 add_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest,
385                 edge_type type, gcov_type weight, gcov_type cost,
386                 gcov_type max_capacity)
387 {
388   fixup_edge_p curr_edge = add_edge(fixup_graph, src, dest, cost);
389   curr_edge->type = type;
390   curr_edge->weight = weight;
391   curr_edge->max_capacity = max_capacity;
392 }
393
394
395 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
396    to the fixup graph.  */
397
398 static void
399 add_rfixup_edge (fixup_graph_type *fixup_graph, int src, int dest,
400                  gcov_type rflow, gcov_type cost)
401 {
402   fixup_edge_p curr_edge = add_edge (fixup_graph, src, dest, cost);
403   curr_edge->rflow = rflow;
404   curr_edge->is_rflow_valid = true;
405   /* This edge is not a valid edge - merely used to hold residual flow.  */
406   curr_edge->type = INVALID_EDGE;
407 }
408
409
410 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
411    exist in the FIXUP_GRAPH.  */
412
413 static fixup_edge_p
414 find_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest)
415 {
416   int j;
417   fixup_edge_p pfedge;
418   fixup_vertex_p pfvertex;
419
420   gcc_assert (src < fixup_graph->num_vertices);
421
422   pfvertex = fixup_graph->vertex_list + src;
423
424   for (j = 0; pfvertex->succ_edges.iterate (j, &pfedge);
425        j++)
426     if (pfedge->dest == dest)
427       return pfedge;
428
429   return NULL;
430 }
431
432
433 /* Cleanup routine to free structures in FIXUP_GRAPH.  */
434
435 static void
436 delete_fixup_graph (fixup_graph_type *fixup_graph)
437 {
438   int i;
439   int fnum_vertices = fixup_graph->num_vertices;
440   fixup_vertex_p pfvertex = fixup_graph->vertex_list;
441
442   for (i = 0; i < fnum_vertices; i++, pfvertex++)
443     pfvertex->succ_edges.release ();
444
445   free (fixup_graph->vertex_list);
446   free (fixup_graph->edge_list);
447 }
448
449
450 /* Creates a fixup graph FIXUP_GRAPH from the function CFG.  */
451
452 static void
453 create_fixup_graph (fixup_graph_type *fixup_graph)
454 {
455   double sqrt_avg_vertex_weight = 0;
456   double total_vertex_weight = 0;
457   double k_pos = 0;
458   double k_neg = 0;
459   /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v).  */
460   gcov_type *diff_out_in = NULL;
461   gcov_type supply_value = 1, demand_value = 0;
462   gcov_type fcost = 0;
463   int new_entry_index = 0, new_exit_index = 0;
464   int i = 0, j = 0;
465   int new_index = 0;
466   basic_block bb;
467   edge e;
468   edge_iterator ei;
469   fixup_edge_p pfedge, r_pfedge;
470   fixup_edge_p fedge_list;
471   int fnum_edges;
472
473   /* Each basic_block will be split into 2 during vertex transformation.  */
474   int fnum_vertices_after_transform =  2 * n_basic_blocks;
475   int fnum_edges_after_transform = n_edges + n_basic_blocks;
476
477   /* Count the new SOURCE and EXIT vertices to be added.  */
478   int fmax_num_vertices =
479     fnum_vertices_after_transform + n_edges + n_basic_blocks + 2;
480
481   /* In create_fixup_graph: Each basic block and edge can be split into 3
482      edges. Number of balance edges = n_basic_blocks. So after
483      create_fixup_graph:
484      max_edges = 4 * n_basic_blocks + 3 * n_edges
485      Accounting for residual flow edges
486      max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
487      = 8 * n_basic_blocks + 6 * n_edges
488      < 8 * n_basic_blocks + 8 * n_edges.  */
489   int fmax_num_edges = 8 * (n_basic_blocks + n_edges);
490
491   /* Initial num of vertices in the fixup graph.  */
492   fixup_graph->num_vertices = n_basic_blocks;
493
494   /* Fixup graph vertex list.  */
495   fixup_graph->vertex_list =
496     (fixup_vertex_p) xcalloc (fmax_num_vertices, sizeof (fixup_vertex_type));
497
498   /* Fixup graph edge list.  */
499   fixup_graph->edge_list =
500     (fixup_edge_p) xcalloc (fmax_num_edges, sizeof (fixup_edge_type));
501
502   diff_out_in =
503     (gcov_type *) xcalloc (1 + fnum_vertices_after_transform,
504                            sizeof (gcov_type));
505
506   /* Compute constants b, k_pos, k_neg used in the cost function calculation.
507      b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b.  */
508   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
509     total_vertex_weight += bb->count;
510
511   sqrt_avg_vertex_weight = mcf_sqrt (total_vertex_weight / n_basic_blocks);
512
513   k_pos = K_POS (sqrt_avg_vertex_weight);
514   k_neg = K_NEG (sqrt_avg_vertex_weight);
515
516   /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
517      connected by an edge e from v' to v''. w(e) = w(v).  */
518
519   if (dump_file)
520     fprintf (dump_file, "\nVertex transformation:\n");
521
522   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
523   {
524     /* v'->v'': index1->(index1+1).  */
525     i = 2 * bb->index;
526     fcost = (gcov_type) COST (k_pos, bb->count);
527     add_fixup_edge (fixup_graph, i, i + 1, VERTEX_SPLIT_EDGE, bb->count,
528                     fcost, CAP_INFINITY);
529     fixup_graph->num_vertices++;
530
531     FOR_EACH_EDGE (e, ei, bb->succs)
532     {
533       /* Edges with ignore attribute set should be treated like they don't
534          exist.  */
535       if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
536         continue;
537       j = 2 * e->dest->index;
538       fcost = (gcov_type) COST (k_pos, e->count);
539       add_fixup_edge (fixup_graph, i + 1, j, REDIRECT_EDGE, e->count, fcost,
540                       CAP_INFINITY);
541     }
542   }
543
544   /* After vertex transformation.  */
545   gcc_assert (fixup_graph->num_vertices == fnum_vertices_after_transform);
546   /* Redirect edges are not added for edges with ignore attribute.  */
547   gcc_assert (fixup_graph->num_edges <= fnum_edges_after_transform);
548
549   fnum_edges_after_transform = fixup_graph->num_edges;
550
551   /* 2. Initialize D(v).  */
552   for (i = 0; i < fnum_edges_after_transform; i++)
553     {
554       pfedge = fixup_graph->edge_list + i;
555       diff_out_in[pfedge->src] += pfedge->weight;
556       diff_out_in[pfedge->dest] -= pfedge->weight;
557     }
558
559   /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3.  */
560   for (i = 0; i <= 3; i++)
561     diff_out_in[i] = 0;
562
563   /* 3. Add reverse edges: needed to decrease counts during smoothing.  */
564   if (dump_file)
565     fprintf (dump_file, "\nReverse edges:\n");
566   for (i = 0; i < fnum_edges_after_transform; i++)
567     {
568       pfedge = fixup_graph->edge_list + i;
569       if ((pfedge->src == 0) || (pfedge->src == 2))
570         continue;
571       r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
572       if (!r_pfedge && pfedge->weight)
573         {
574           /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
575              capacity is 0.  */
576           fcost = (gcov_type) COST (k_neg, pfedge->weight);
577           add_fixup_edge (fixup_graph, pfedge->dest, pfedge->src,
578                           REVERSE_EDGE, 0, fcost, pfedge->weight);
579         }
580     }
581
582   /* 4. Create single source and sink. Connect new source vertex s' to function
583      entry block. Connect sink vertex t' to function exit.  */
584   if (dump_file)
585     fprintf (dump_file, "\ns'->S, T->t':\n");
586
587   new_entry_index = fixup_graph->new_entry_index = fixup_graph->num_vertices;
588   fixup_graph->num_vertices++;
589   /* Set supply_value to 1 to avoid zero count function ENTRY.  */
590   add_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK, SOURCE_CONNECT_EDGE,
591                   1 /* supply_value */, 0, 1 /* supply_value */);
592
593   /* Create new exit with EXIT_BLOCK as single pred.  */
594   new_exit_index = fixup_graph->new_exit_index = fixup_graph->num_vertices;
595   fixup_graph->num_vertices++;
596   add_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index,
597                   SINK_CONNECT_EDGE,
598                   0 /* demand_value */, 0, 0 /* demand_value */);
599
600   /* Connect vertices with unbalanced D(v) to source/sink.  */
601   if (dump_file)
602     fprintf (dump_file, "\nD(v) balance:\n");
603   /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
604      diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2.  */
605   for (i = 4; i < new_entry_index; i += 2)
606     {
607       if (diff_out_in[i] > 0)
608         {
609           add_fixup_edge (fixup_graph, i, new_exit_index, BALANCE_EDGE, 0, 0,
610                           diff_out_in[i]);
611           demand_value += diff_out_in[i];
612         }
613       else if (diff_out_in[i] < 0)
614         {
615           add_fixup_edge (fixup_graph, new_entry_index, i, BALANCE_EDGE, 0, 0,
616                           -diff_out_in[i]);
617           supply_value -= diff_out_in[i];
618         }
619     }
620
621   /* Set supply = demand.  */
622   if (dump_file)
623     {
624       fprintf (dump_file, "\nAdjust supply and demand:\n");
625       fprintf (dump_file, "supply_value=" HOST_WIDEST_INT_PRINT_DEC "\n",
626                supply_value);
627       fprintf (dump_file, "demand_value=" HOST_WIDEST_INT_PRINT_DEC "\n",
628                demand_value);
629     }
630
631   if (demand_value > supply_value)
632     {
633       pfedge = find_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK);
634       pfedge->max_capacity += (demand_value - supply_value);
635     }
636   else
637     {
638       pfedge = find_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index);
639       pfedge->max_capacity += (supply_value - demand_value);
640     }
641
642   /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
643      created by the vertex transformation step from self-edges in the original
644      CFG and by the reverse edges added earlier.  */
645   if (dump_file)
646     fprintf (dump_file, "\nNormalize edges:\n");
647
648   fnum_edges = fixup_graph->num_edges;
649   fedge_list = fixup_graph->edge_list;
650
651   for (i = 0; i < fnum_edges; i++)
652     {
653       pfedge = fedge_list + i;
654       r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
655       if (((pfedge->type == VERTEX_SPLIT_EDGE)
656            || (pfedge->type == REDIRECT_EDGE)) && r_pfedge)
657         {
658           new_index = fixup_graph->num_vertices;
659           fixup_graph->num_vertices++;
660
661           if (dump_file)
662             {
663               fprintf (dump_file, "\nAnti-parallel edge:\n");
664               dump_fixup_edge (dump_file, fixup_graph, pfedge);
665               dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
666               fprintf (dump_file, "New vertex is %d.\n", new_index);
667               fprintf (dump_file, "------------------\n");
668             }
669
670           pfedge->cost /= 2;
671           pfedge->norm_vertex_index = new_index;
672           if (dump_file)
673             {
674               fprintf (dump_file, "After normalization:\n");
675               dump_fixup_edge (dump_file, fixup_graph, pfedge);
676             }
677
678           /* Add a new fixup edge: new_index->src.  */
679           add_fixup_edge (fixup_graph, new_index, pfedge->src,
680                           REVERSE_NORMALIZED_EDGE, 0, r_pfedge->cost,
681                           r_pfedge->max_capacity);
682           gcc_assert (fixup_graph->num_vertices <= fmax_num_vertices);
683
684           /* Edge: r_pfedge->src -> r_pfedge->dest
685              ==> r_pfedge->src -> new_index.  */
686           r_pfedge->dest = new_index;
687           r_pfedge->type = REVERSE_NORMALIZED_EDGE;
688           r_pfedge->cost = pfedge->cost;
689           r_pfedge->max_capacity = pfedge->max_capacity;
690           if (dump_file)
691             dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
692         }
693     }
694
695   if (dump_file)
696     dump_fixup_graph (dump_file, fixup_graph, "After create_fixup_graph()");
697
698   /* Cleanup.  */
699   free (diff_out_in);
700 }
701
702
703 /* Allocates space for the structures in AUGMENTING_PATH.  The space needed is
704    proportional to the number of nodes in the graph, which is given by
705    GRAPH_SIZE.  */
706
707 static void
708 init_augmenting_path (augmenting_path_type *augmenting_path, int graph_size)
709 {
710   augmenting_path->queue_list.queue = (int *)
711     xcalloc (graph_size + 2, sizeof (int));
712   augmenting_path->queue_list.size = graph_size + 2;
713   augmenting_path->bb_pred = (int *) xcalloc (graph_size, sizeof (int));
714   augmenting_path->is_visited = (int *) xcalloc (graph_size, sizeof (int));
715 }
716
717 /* Free the structures in AUGMENTING_PATH.  */
718 static void
719 free_augmenting_path (augmenting_path_type *augmenting_path)
720 {
721   free (augmenting_path->queue_list.queue);
722   free (augmenting_path->bb_pred);
723   free (augmenting_path->is_visited);
724 }
725
726
727 /* Queue routines. Assumes queue will never overflow.  */
728
729 static void
730 init_queue (queue_type *queue_list)
731 {
732   gcc_assert (queue_list);
733   queue_list->head = 0;
734   queue_list->tail = 0;
735 }
736
737 /* Return true if QUEUE_LIST is empty.  */
738 static bool
739 is_empty (queue_type *queue_list)
740 {
741   return (queue_list->head == queue_list->tail);
742 }
743
744 /* Insert element X into QUEUE_LIST.  */
745 static void
746 enqueue (queue_type *queue_list, int x)
747 {
748   gcc_assert (queue_list->tail < queue_list->size);
749   queue_list->queue[queue_list->tail] = x;
750   (queue_list->tail)++;
751 }
752
753 /* Return the first element in QUEUE_LIST.  */
754 static int
755 dequeue (queue_type *queue_list)
756 {
757   int x;
758   gcc_assert (queue_list->head >= 0);
759   x = queue_list->queue[queue_list->head];
760   (queue_list->head)++;
761   return x;
762 }
763
764
765 /* Finds a negative cycle in the residual network using
766    the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
767    minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
768    considered.
769
770 Parameters:
771    FIXUP_GRAPH - Residual graph  (input/output)
772    The following are allocated/freed by the caller:
773    PI - Vector to hold predecessors in path  (pi = pred index)
774    D - D[I] holds minimum cost of path from i to sink
775    CYCLE - Vector to hold the minimum cost cycle
776
777 Return:
778    true if a negative cycle was found, false otherwise.  */
779
780 static bool
781 cancel_negative_cycle (fixup_graph_type *fixup_graph,
782                        int *pi, gcov_type *d, int *cycle)
783 {
784   int i, j, k;
785   int fnum_vertices, fnum_edges;
786   fixup_edge_p fedge_list, pfedge, r_pfedge;
787   bool found_cycle = false;
788   int cycle_start = 0, cycle_end = 0;
789   gcov_type sum_cost = 0, cycle_flow = 0;
790   int new_entry_index;
791   bool propagated = false;
792
793   gcc_assert (fixup_graph);
794   fnum_vertices = fixup_graph->num_vertices;
795   fnum_edges = fixup_graph->num_edges;
796   fedge_list = fixup_graph->edge_list;
797   new_entry_index = fixup_graph->new_entry_index;
798
799   /* Initialize.  */
800   /* Skip ENTRY.  */
801   for (i = 1; i < fnum_vertices; i++)
802     {
803       d[i] = CAP_INFINITY;
804       pi[i] = -1;
805       cycle[i] = -1;
806     }
807   d[ENTRY_BLOCK] = 0;
808
809   /* Relax.  */
810   for (k = 1; k < fnum_vertices; k++)
811   {
812     propagated = false;
813     for (i = 0; i < fnum_edges; i++)
814       {
815         pfedge = fedge_list + i;
816         if (pfedge->src == new_entry_index)
817           continue;
818         if (pfedge->is_rflow_valid && pfedge->rflow
819             && d[pfedge->src] != CAP_INFINITY
820             && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
821           {
822             d[pfedge->dest] = d[pfedge->src] + pfedge->cost;
823             pi[pfedge->dest] = pfedge->src;
824             propagated = true;
825           }
826       }
827     if (!propagated)
828       break;
829   }
830
831   if (!propagated)
832   /* No negative cycles exist.  */
833     return 0;
834
835   /* Detect.  */
836   for (i = 0; i < fnum_edges; i++)
837     {
838       pfedge = fedge_list + i;
839       if (pfedge->src == new_entry_index)
840         continue;
841       if (pfedge->is_rflow_valid && pfedge->rflow
842           && d[pfedge->src] != CAP_INFINITY
843           && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
844         {
845           found_cycle = true;
846           break;
847         }
848     }
849
850   if (!found_cycle)
851     return 0;
852
853   /* Augment the cycle with the cycle's minimum residual capacity.  */
854   found_cycle = false;
855   cycle[0] = pfedge->dest;
856   j = pfedge->dest;
857
858   for (i = 1; i < fnum_vertices; i++)
859     {
860       j = pi[j];
861       cycle[i] = j;
862       for (k = 0; k < i; k++)
863         {
864           if (cycle[k] == j)
865             {
866               /* cycle[k] -> ... -> cycle[i].  */
867               cycle_start = k;
868               cycle_end = i;
869               found_cycle = true;
870               break;
871             }
872         }
873       if (found_cycle)
874         break;
875     }
876
877   gcc_assert (cycle[cycle_start] == cycle[cycle_end]);
878   if (dump_file)
879     fprintf (dump_file, "\nNegative cycle length is %d:\n",
880              cycle_end - cycle_start);
881
882   sum_cost = 0;
883   cycle_flow = CAP_INFINITY;
884   for (k = cycle_start; k < cycle_end; k++)
885     {
886       pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
887       cycle_flow = MIN (cycle_flow, pfedge->rflow);
888       sum_cost += pfedge->cost;
889       if (dump_file)
890         fprintf (dump_file, "%d ", cycle[k]);
891     }
892
893   if (dump_file)
894     {
895       fprintf (dump_file, "%d", cycle[k]);
896       fprintf (dump_file,
897                ": (" HOST_WIDEST_INT_PRINT_DEC ", " HOST_WIDEST_INT_PRINT_DEC
898                ")\n", sum_cost, cycle_flow);
899       fprintf (dump_file,
900                "Augment cycle with " HOST_WIDEST_INT_PRINT_DEC "\n",
901                cycle_flow);
902     }
903
904   for (k = cycle_start; k < cycle_end; k++)
905     {
906       pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
907       r_pfedge = find_fixup_edge (fixup_graph, cycle[k], cycle[k + 1]);
908       pfedge->rflow -= cycle_flow;
909       if (pfedge->type)
910         pfedge->flow += cycle_flow;
911       r_pfedge->rflow += cycle_flow;
912       if (r_pfedge->type)
913         r_pfedge->flow -= cycle_flow;
914     }
915
916   return true;
917 }
918
919
920 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
921    the edges. ENTRY and EXIT vertices should not be considered.  */
922
923 static void
924 compute_residual_flow (fixup_graph_type *fixup_graph)
925 {
926   int i;
927   int fnum_edges;
928   fixup_edge_p fedge_list, pfedge;
929
930   gcc_assert (fixup_graph);
931
932   if (dump_file)
933     fputs ("\ncompute_residual_flow():\n", dump_file);
934
935   fnum_edges = fixup_graph->num_edges;
936   fedge_list = fixup_graph->edge_list;
937
938   for (i = 0; i < fnum_edges; i++)
939     {
940       pfedge = fedge_list + i;
941       pfedge->rflow = pfedge->max_capacity - pfedge->flow;
942       pfedge->is_rflow_valid = true;
943       add_rfixup_edge (fixup_graph, pfedge->dest, pfedge->src, pfedge->flow,
944                        -pfedge->cost);
945     }
946 }
947
948
949 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
950    SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
951    this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
952    to reflect the path found.
953    Returns: 0 if no augmenting path is found, 1 otherwise.  */
954
955 static int
956 find_augmenting_path (fixup_graph_type *fixup_graph,
957                       augmenting_path_type *augmenting_path, int source,
958                       int sink)
959 {
960   int u = 0;
961   int i;
962   fixup_vertex_p fvertex_list, pfvertex;
963   fixup_edge_p pfedge;
964   int *bb_pred, *is_visited;
965   queue_type *queue_list;
966
967   gcc_assert (augmenting_path);
968   bb_pred = augmenting_path->bb_pred;
969   gcc_assert (bb_pred);
970   is_visited = augmenting_path->is_visited;
971   gcc_assert (is_visited);
972   queue_list = &(augmenting_path->queue_list);
973
974   gcc_assert (fixup_graph);
975
976   fvertex_list = fixup_graph->vertex_list;
977
978   for (u = 0; u < fixup_graph->num_vertices; u++)
979     is_visited[u] = 0;
980
981   init_queue (queue_list);
982   enqueue (queue_list, source);
983   bb_pred[source] = -1;
984
985   while (!is_empty (queue_list))
986     {
987       u = dequeue (queue_list);
988       is_visited[u] = 1;
989       pfvertex = fvertex_list + u;
990       for (i = 0; pfvertex->succ_edges.iterate (i, &pfedge);
991            i++)
992         {
993           int dest = pfedge->dest;
994           if ((pfedge->rflow > 0) && (is_visited[dest] == 0))
995             {
996               enqueue (queue_list, dest);
997               bb_pred[dest] = u;
998               is_visited[dest] = 1;
999               if (dest == sink)
1000                 return 1;
1001             }
1002         }
1003     }
1004
1005   return 0;
1006 }
1007
1008
1009 /* Routine to find the maximal flow:
1010    Algorithm:
1011    1. Initialize flow to 0
1012    2. Find an augmenting path form source to sink.
1013    3. Send flow equal to the path's residual capacity along the edges of this path.
1014    4. Repeat steps 2 and 3 until no new augmenting path is found.
1015
1016 Parameters:
1017 SOURCE: index of source vertex (input)
1018 SINK: index of sink vertex    (input)
1019 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1020              set to have a valid maximal flow by this routine. (input)
1021 Return: Maximum flow possible.  */
1022
1023 static gcov_type
1024 find_max_flow (fixup_graph_type *fixup_graph, int source, int sink)
1025 {
1026   int fnum_edges;
1027   augmenting_path_type augmenting_path;
1028   int *bb_pred;
1029   gcov_type max_flow = 0;
1030   int i, u;
1031   fixup_edge_p fedge_list, pfedge, r_pfedge;
1032
1033   gcc_assert (fixup_graph);
1034
1035   fnum_edges = fixup_graph->num_edges;
1036   fedge_list = fixup_graph->edge_list;
1037
1038   /* Initialize flow to 0.  */
1039   for (i = 0; i < fnum_edges; i++)
1040     {
1041       pfedge = fedge_list + i;
1042       pfedge->flow = 0;
1043     }
1044
1045   compute_residual_flow (fixup_graph);
1046
1047   init_augmenting_path (&augmenting_path, fixup_graph->num_vertices);
1048
1049   bb_pred = augmenting_path.bb_pred;
1050   while (find_augmenting_path (fixup_graph, &augmenting_path, source, sink))
1051     {
1052       /* Determine the amount by which we can increment the flow.  */
1053       gcov_type increment = CAP_INFINITY;
1054       for (u = sink; u != source; u = bb_pred[u])
1055         {
1056           pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1057           increment = MIN (increment, pfedge->rflow);
1058         }
1059       max_flow += increment;
1060
1061       /* Now increment the flow. EXIT vertex index is 1.  */
1062       for (u = sink; u != source; u = bb_pred[u])
1063         {
1064           pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1065           r_pfedge = find_fixup_edge (fixup_graph, u, bb_pred[u]);
1066           if (pfedge->type)
1067             {
1068               /* forward edge.  */
1069               pfedge->flow += increment;
1070               pfedge->rflow -= increment;
1071               r_pfedge->rflow += increment;
1072             }
1073           else
1074             {
1075               /* backward edge.  */
1076               gcc_assert (r_pfedge->type);
1077               r_pfedge->rflow += increment;
1078               r_pfedge->flow -= increment;
1079               pfedge->rflow -= increment;
1080             }
1081         }
1082
1083       if (dump_file)
1084         {
1085           fprintf (dump_file, "\nDump augmenting path:\n");
1086           for (u = sink; u != source; u = bb_pred[u])
1087             {
1088               print_basic_block (dump_file, fixup_graph, u);
1089               fprintf (dump_file, "<-");
1090             }
1091           fprintf (dump_file,
1092                    "ENTRY  (path_capacity=" HOST_WIDEST_INT_PRINT_DEC ")\n",
1093                    increment);
1094           fprintf (dump_file,
1095                    "Network flow is " HOST_WIDEST_INT_PRINT_DEC ".\n",
1096                    max_flow);
1097         }
1098     }
1099
1100   free_augmenting_path (&augmenting_path);
1101   if (dump_file)
1102     dump_fixup_graph (dump_file, fixup_graph, "After find_max_flow()");
1103   return max_flow;
1104 }
1105
1106
1107 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1108    after applying the find_minimum_cost_flow() routine.  */
1109
1110 static void
1111 adjust_cfg_counts (fixup_graph_type *fixup_graph)
1112 {
1113   basic_block bb;
1114   edge e;
1115   edge_iterator ei;
1116   int i, j;
1117   fixup_edge_p pfedge, pfedge_n;
1118
1119   gcc_assert (fixup_graph);
1120
1121   if (dump_file)
1122     fprintf (dump_file, "\nadjust_cfg_counts():\n");
1123
1124   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
1125     {
1126       i = 2 * bb->index;
1127
1128       /* Fixup BB.  */
1129       if (dump_file)
1130         fprintf (dump_file,
1131                  "BB%d: " HOST_WIDEST_INT_PRINT_DEC "", bb->index, bb->count);
1132
1133       pfedge = find_fixup_edge (fixup_graph, i, i + 1);
1134       if (pfedge->flow)
1135         {
1136           bb->count += pfedge->flow;
1137           if (dump_file)
1138             {
1139               fprintf (dump_file, " + " HOST_WIDEST_INT_PRINT_DEC "(",
1140                        pfedge->flow);
1141               print_edge (dump_file, fixup_graph, i, i + 1);
1142               fprintf (dump_file, ")");
1143             }
1144         }
1145
1146       pfedge_n =
1147         find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1148       /* Deduct flow from normalized reverse edge.  */
1149       if (pfedge->norm_vertex_index && pfedge_n->flow)
1150         {
1151           bb->count -= pfedge_n->flow;
1152           if (dump_file)
1153             {
1154               fprintf (dump_file, " - " HOST_WIDEST_INT_PRINT_DEC "(",
1155                        pfedge_n->flow);
1156               print_edge (dump_file, fixup_graph, i + 1,
1157                           pfedge->norm_vertex_index);
1158               fprintf (dump_file, ")");
1159             }
1160         }
1161       if (dump_file)
1162         fprintf (dump_file, " = " HOST_WIDEST_INT_PRINT_DEC "\n", bb->count);
1163
1164       /* Fixup edge.  */
1165       FOR_EACH_EDGE (e, ei, bb->succs)
1166         {
1167           /* Treat edges with ignore attribute set as if they don't exist.  */
1168           if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1169             continue;
1170
1171           j = 2 * e->dest->index;
1172           if (dump_file)
1173             fprintf (dump_file, "%d->%d: " HOST_WIDEST_INT_PRINT_DEC "",
1174                      bb->index, e->dest->index, e->count);
1175
1176           pfedge = find_fixup_edge (fixup_graph, i + 1, j);
1177
1178           if (bb->index != e->dest->index)
1179             {
1180               /* Non-self edge.  */
1181               if (pfedge->flow)
1182                 {
1183                   e->count += pfedge->flow;
1184                   if (dump_file)
1185                     {
1186                       fprintf (dump_file, " + " HOST_WIDEST_INT_PRINT_DEC "(",
1187                                pfedge->flow);
1188                       print_edge (dump_file, fixup_graph, i + 1, j);
1189                       fprintf (dump_file, ")");
1190                     }
1191                 }
1192
1193               pfedge_n =
1194                 find_fixup_edge (fixup_graph, j, pfedge->norm_vertex_index);
1195               /* Deduct flow from normalized reverse edge.  */
1196               if (pfedge->norm_vertex_index && pfedge_n->flow)
1197                 {
1198                   e->count -= pfedge_n->flow;
1199                   if (dump_file)
1200                     {
1201                       fprintf (dump_file, " - " HOST_WIDEST_INT_PRINT_DEC "(",
1202                                pfedge_n->flow);
1203                       print_edge (dump_file, fixup_graph, j,
1204                                   pfedge->norm_vertex_index);
1205                       fprintf (dump_file, ")");
1206                     }
1207                 }
1208             }
1209           else
1210             {
1211               /* Handle self edges. Self edge is split with a normalization
1212                  vertex. Here i=j.  */
1213               pfedge = find_fixup_edge (fixup_graph, j, i + 1);
1214               pfedge_n =
1215                 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1216               e->count += pfedge_n->flow;
1217               bb->count += pfedge_n->flow;
1218               if (dump_file)
1219                 {
1220                   fprintf (dump_file, "(self edge)");
1221                   fprintf (dump_file, " + " HOST_WIDEST_INT_PRINT_DEC "(",
1222                            pfedge_n->flow);
1223                   print_edge (dump_file, fixup_graph, i + 1,
1224                               pfedge->norm_vertex_index);
1225                   fprintf (dump_file, ")");
1226                 }
1227             }
1228
1229           if (bb->count)
1230             e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1231           if (dump_file)
1232             fprintf (dump_file, " = " HOST_WIDEST_INT_PRINT_DEC "\t(%.1f%%)\n",
1233                      e->count, e->probability * 100.0 / REG_BR_PROB_BASE);
1234         }
1235     }
1236
1237   ENTRY_BLOCK_PTR->count = sum_edge_counts (ENTRY_BLOCK_PTR->succs);
1238   EXIT_BLOCK_PTR->count = sum_edge_counts (EXIT_BLOCK_PTR->preds);
1239
1240   /* Compute edge probabilities.  */
1241   FOR_ALL_BB (bb)
1242     {
1243       if (bb->count)
1244         {
1245           FOR_EACH_EDGE (e, ei, bb->succs)
1246             e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1247         }
1248       else
1249         {
1250           int total = 0;
1251           FOR_EACH_EDGE (e, ei, bb->succs)
1252             if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1253               total++;
1254           if (total)
1255             {
1256               FOR_EACH_EDGE (e, ei, bb->succs)
1257                 {
1258                   if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1259                     e->probability = REG_BR_PROB_BASE / total;
1260                   else
1261                     e->probability = 0;
1262                 }
1263             }
1264           else
1265             {
1266               total += EDGE_COUNT (bb->succs);
1267               FOR_EACH_EDGE (e, ei, bb->succs)
1268                   e->probability = REG_BR_PROB_BASE / total;
1269             }
1270         }
1271     }
1272
1273   if (dump_file)
1274     {
1275       fprintf (dump_file, "\nCheck %s() CFG flow conservation:\n",
1276                current_function_name ());
1277       FOR_EACH_BB (bb)
1278         {
1279           if ((bb->count != sum_edge_counts (bb->preds))
1280                || (bb->count != sum_edge_counts (bb->succs)))
1281             {
1282               fprintf (dump_file,
1283                        "BB%d(" HOST_WIDEST_INT_PRINT_DEC ")  **INVALID**: ",
1284                        bb->index, bb->count);
1285               fprintf (stderr,
1286                        "******** BB%d(" HOST_WIDEST_INT_PRINT_DEC
1287                        ")  **INVALID**: \n", bb->index, bb->count);
1288               fprintf (dump_file, "in_edges=" HOST_WIDEST_INT_PRINT_DEC " ",
1289                        sum_edge_counts (bb->preds));
1290               fprintf (dump_file, "out_edges=" HOST_WIDEST_INT_PRINT_DEC "\n",
1291                        sum_edge_counts (bb->succs));
1292             }
1293          }
1294     }
1295 }
1296
1297
1298 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1299    flow.
1300 Algorithm:
1301 1. Find maximal flow.
1302 2. Form residual network
1303 3. Repeat:
1304   While G contains a negative cost cycle C, reverse the flow on the found cycle
1305   by the minimum residual capacity in that cycle.
1306 4. Form the minimal cost flow
1307   f(u,v) = rf(v, u)
1308 Input:
1309   FIXUP_GRAPH - Initial fixup graph.
1310   The flow field is modified to represent the minimum cost flow.  */
1311
1312 static void
1313 find_minimum_cost_flow (fixup_graph_type *fixup_graph)
1314 {
1315   /* Holds the index of predecessor in path.  */
1316   int *pred;
1317   /* Used to hold the minimum cost cycle.  */
1318   int *cycle;
1319   /* Used to record the number of iterations of cancel_negative_cycle.  */
1320   int iteration;
1321   /* Vector d[i] holds the minimum cost of path from i to sink.  */
1322   gcov_type *d;
1323   int fnum_vertices;
1324   int new_exit_index;
1325   int new_entry_index;
1326
1327   gcc_assert (fixup_graph);
1328   fnum_vertices = fixup_graph->num_vertices;
1329   new_exit_index = fixup_graph->new_exit_index;
1330   new_entry_index = fixup_graph->new_entry_index;
1331
1332   find_max_flow (fixup_graph, new_entry_index, new_exit_index);
1333
1334   /* Initialize the structures for find_negative_cycle().  */
1335   pred = (int *) xcalloc (fnum_vertices, sizeof (int));
1336   d = (gcov_type *) xcalloc (fnum_vertices, sizeof (gcov_type));
1337   cycle = (int *) xcalloc (fnum_vertices, sizeof (int));
1338
1339   /* Repeatedly find and cancel negative cost cycles, until
1340      no more negative cycles exist. This also updates the flow field
1341      to represent the minimum cost flow so far.  */
1342   iteration = 0;
1343   while (cancel_negative_cycle (fixup_graph, pred, d, cycle))
1344     {
1345       iteration++;
1346       if (iteration > MAX_ITER (fixup_graph->num_vertices,
1347                                 fixup_graph->num_edges))
1348         break;
1349     }
1350
1351   if (dump_file)
1352     dump_fixup_graph (dump_file, fixup_graph,
1353                       "After find_minimum_cost_flow()");
1354
1355   /* Cleanup structures.  */
1356   free (pred);
1357   free (d);
1358   free (cycle);
1359 }
1360
1361
1362 /* Compute the sum of the edge counts in TO_EDGES.  */
1363
1364 gcov_type
1365 sum_edge_counts (vec<edge, va_gc> *to_edges)
1366 {
1367   gcov_type sum = 0;
1368   edge e;
1369   edge_iterator ei;
1370
1371   FOR_EACH_EDGE (e, ei, to_edges)
1372     {
1373       if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1374         continue;
1375       sum += e->count;
1376     }
1377   return sum;
1378 }
1379
1380
1381 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1382    a minimum cost flow algorithm, to ensure that the flow consistency rule is
1383    obeyed: sum of outgoing edges = sum of incoming edges for each basic
1384    block.  */
1385
1386 void
1387 mcf_smooth_cfg (void)
1388 {
1389   fixup_graph_type fixup_graph;
1390   memset (&fixup_graph, 0, sizeof (fixup_graph));
1391   create_fixup_graph (&fixup_graph);
1392   find_minimum_cost_flow (&fixup_graph);
1393   adjust_cfg_counts (&fixup_graph);
1394   delete_fixup_graph (&fixup_graph);
1395 }