Daily bump.
[official-gcc.git] / gcc / mcf.c
blob6bba0facea5febc5fc5fa05baf5e406699e1b422
1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
3 Copyright (C) 2008-2015 Free Software Foundation, Inc.
4 Contributed by Paul Yuan (yingbo.com@gmail.com) and
5 Vinodha Ramasamy (vinodha@google.com).
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.
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.
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/>. */
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.
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). */
45 #include "config.h"
46 #include "system.h"
47 #include "coretypes.h"
48 #include "predict.h"
49 #include "tm.h"
50 #include "hard-reg-set.h"
51 #include "function.h"
52 #include "dominance.h"
53 #include "cfg.h"
54 #include "basic-block.h"
55 #include "gcov-io.h"
56 #include "profile.h"
57 #include "dumpfile.h"
59 /* CAP_INFINITY: Constant to represent infinite capacity. */
60 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
62 /* COST FUNCTION. */
63 #define K_POS(b) ((b))
64 #define K_NEG(b) (50 * (b))
65 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
66 /* Limit the number of iterations for cancel_negative_cycles() to ensure
67 reasonable compile time. */
68 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
69 typedef enum
71 INVALID_EDGE,
72 VERTEX_SPLIT_EDGE, /* Edge to represent vertex with w(e) = w(v). */
73 REDIRECT_EDGE, /* Edge after vertex transformation. */
74 REVERSE_EDGE,
75 SOURCE_CONNECT_EDGE, /* Single edge connecting to single source. */
76 SINK_CONNECT_EDGE, /* Single edge connecting to single sink. */
77 BALANCE_EDGE, /* Edge connecting with source/sink: cp(e) = 0. */
78 REDIRECT_NORMALIZED_EDGE, /* Normalized edge for a redirect edge. */
79 REVERSE_NORMALIZED_EDGE /* Normalized edge for a reverse edge. */
80 } edge_type;
82 /* Structure to represent an edge in the fixup graph. */
83 typedef struct fixup_edge_d
85 int src;
86 int dest;
87 /* Flag denoting type of edge and attributes for the flow field. */
88 edge_type type;
89 bool is_rflow_valid;
90 /* Index to the normalization vertex added for this edge. */
91 int norm_vertex_index;
92 /* Flow for this edge. */
93 gcov_type flow;
94 /* Residual flow for this edge - used during negative cycle canceling. */
95 gcov_type rflow;
96 gcov_type weight;
97 gcov_type cost;
98 gcov_type max_capacity;
99 } fixup_edge_type;
101 typedef fixup_edge_type *fixup_edge_p;
104 /* Structure to represent a vertex in the fixup graph. */
105 typedef struct fixup_vertex_d
107 vec<fixup_edge_p> succ_edges;
108 } fixup_vertex_type;
110 typedef fixup_vertex_type *fixup_vertex_p;
112 /* Fixup graph used in the MCF algorithm. */
113 typedef struct fixup_graph_d
115 /* Current number of vertices for the graph. */
116 int num_vertices;
117 /* Current number of edges for the graph. */
118 int num_edges;
119 /* Index of new entry vertex. */
120 int new_entry_index;
121 /* Index of new exit vertex. */
122 int new_exit_index;
123 /* Fixup vertex list. Adjacency list for fixup graph. */
124 fixup_vertex_p vertex_list;
125 /* Fixup edge list. */
126 fixup_edge_p edge_list;
127 } fixup_graph_type;
129 typedef struct queue_d
131 int *queue;
132 int head;
133 int tail;
134 int size;
135 } queue_type;
137 /* Structure used in the maximal flow routines to find augmenting path. */
138 typedef struct augmenting_path_d
140 /* Queue used to hold vertex indices. */
141 queue_type queue_list;
142 /* Vector to hold chain of pred vertex indices in augmenting path. */
143 int *bb_pred;
144 /* Vector that indicates if basic block i has been visited. */
145 int *is_visited;
146 } augmenting_path_type;
149 /* Function definitions. */
151 /* Dump routines to aid debugging. */
153 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
155 static void
156 print_basic_block (FILE *file, fixup_graph_type *fixup_graph, int n)
158 if (n == ENTRY_BLOCK)
159 fputs ("ENTRY", file);
160 else if (n == ENTRY_BLOCK + 1)
161 fputs ("ENTRY''", file);
162 else if (n == 2 * EXIT_BLOCK)
163 fputs ("EXIT", file);
164 else if (n == 2 * EXIT_BLOCK + 1)
165 fputs ("EXIT''", file);
166 else if (n == fixup_graph->new_exit_index)
167 fputs ("NEW_EXIT", file);
168 else if (n == fixup_graph->new_entry_index)
169 fputs ("NEW_ENTRY", file);
170 else
172 fprintf (file, "%d", n / 2);
173 if (n % 2)
174 fputs ("''", file);
175 else
176 fputs ("'", file);
181 /* Print edge S->D for given fixup_graph with n' and n'' format.
182 PARAMETERS:
183 S is the index of the source vertex of the edge (input) and
184 D is the index of the destination vertex of the edge (input) for the given
185 fixup_graph (input). */
187 static void
188 print_edge (FILE *file, fixup_graph_type *fixup_graph, int s, int d)
190 print_basic_block (file, fixup_graph, s);
191 fputs ("->", file);
192 print_basic_block (file, fixup_graph, d);
196 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
197 file. */
198 static void
199 dump_fixup_edge (FILE *file, fixup_graph_type *fixup_graph, fixup_edge_p fedge)
201 if (!fedge)
203 fputs ("NULL fixup graph edge.\n", file);
204 return;
207 print_edge (file, fixup_graph, fedge->src, fedge->dest);
208 fputs (": ", file);
210 if (fedge->type)
212 fprintf (file, "flow/capacity=%" PRId64 "/",
213 fedge->flow);
214 if (fedge->max_capacity == CAP_INFINITY)
215 fputs ("+oo,", file);
216 else
217 fprintf (file, "%" PRId64 ",", fedge->max_capacity);
220 if (fedge->is_rflow_valid)
222 if (fedge->rflow == CAP_INFINITY)
223 fputs (" rflow=+oo.", file);
224 else
225 fprintf (file, " rflow=%" PRId64 ",", fedge->rflow);
228 fprintf (file, " cost=%" PRId64 ".", fedge->cost);
230 fprintf (file, "\t(%d->%d)", fedge->src, fedge->dest);
232 if (fedge->type)
234 switch (fedge->type)
236 case VERTEX_SPLIT_EDGE:
237 fputs (" @VERTEX_SPLIT_EDGE", file);
238 break;
240 case REDIRECT_EDGE:
241 fputs (" @REDIRECT_EDGE", file);
242 break;
244 case SOURCE_CONNECT_EDGE:
245 fputs (" @SOURCE_CONNECT_EDGE", file);
246 break;
248 case SINK_CONNECT_EDGE:
249 fputs (" @SINK_CONNECT_EDGE", file);
250 break;
252 case REVERSE_EDGE:
253 fputs (" @REVERSE_EDGE", file);
254 break;
256 case BALANCE_EDGE:
257 fputs (" @BALANCE_EDGE", file);
258 break;
260 case REDIRECT_NORMALIZED_EDGE:
261 case REVERSE_NORMALIZED_EDGE:
262 fputs (" @NORMALIZED_EDGE", file);
263 break;
265 default:
266 fputs (" @INVALID_EDGE", file);
267 break;
270 fputs ("\n", file);
274 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
275 file. The input string MSG is printed out as a heading. */
277 static void
278 dump_fixup_graph (FILE *file, fixup_graph_type *fixup_graph, const char *msg)
280 int i, j;
281 int fnum_vertices, fnum_edges;
283 fixup_vertex_p fvertex_list, pfvertex;
284 fixup_edge_p pfedge;
286 gcc_assert (fixup_graph);
287 fvertex_list = fixup_graph->vertex_list;
288 fnum_vertices = fixup_graph->num_vertices;
289 fnum_edges = fixup_graph->num_edges;
291 fprintf (file, "\nDump fixup graph for %s(): %s.\n",
292 current_function_name (), msg);
293 fprintf (file,
294 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
295 fnum_vertices, fnum_edges, fixup_graph->new_exit_index);
297 for (i = 0; i < fnum_vertices; i++)
299 pfvertex = fvertex_list + i;
300 fprintf (file, "vertex_list[%d]: %d succ fixup edges.\n",
301 i, pfvertex->succ_edges.length ());
303 for (j = 0; pfvertex->succ_edges.iterate (j, &pfedge);
304 j++)
306 /* Distinguish forward edges and backward edges in the residual flow
307 network. */
308 if (pfedge->type)
309 fputs ("(f) ", file);
310 else if (pfedge->is_rflow_valid)
311 fputs ("(b) ", file);
312 dump_fixup_edge (file, fixup_graph, pfedge);
316 fputs ("\n", file);
320 /* Utility routines. */
321 /* ln() implementation: approximate calculation. Returns ln of X. */
323 static double
324 mcf_ln (double x)
326 #define E 2.71828
327 int l = 1;
328 double m = E;
330 gcc_assert (x >= 0);
332 while (m < x)
334 m *= E;
335 l++;
338 return l;
342 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
343 implementation) by John Carmack. Returns sqrt of X. */
345 static double
346 mcf_sqrt (double x)
348 #define MAGIC_CONST1 0x1fbcf800
349 #define MAGIC_CONST2 0x5f3759df
350 union {
351 int intPart;
352 float floatPart;
353 } convertor, convertor2;
355 gcc_assert (x >= 0);
357 convertor.floatPart = x;
358 convertor2.floatPart = x;
359 convertor.intPart = MAGIC_CONST1 + (convertor.intPart >> 1);
360 convertor2.intPart = MAGIC_CONST2 - (convertor2.intPart >> 1);
362 return 0.5f * (convertor.floatPart + (x * convertor2.floatPart));
366 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
367 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
368 added set to COST. */
370 static fixup_edge_p
371 add_edge (fixup_graph_type *fixup_graph, int src, int dest, gcov_type cost)
373 fixup_vertex_p curr_vertex = fixup_graph->vertex_list + src;
374 fixup_edge_p curr_edge = fixup_graph->edge_list + fixup_graph->num_edges;
375 curr_edge->src = src;
376 curr_edge->dest = dest;
377 curr_edge->cost = cost;
378 fixup_graph->num_edges++;
379 if (dump_file)
380 dump_fixup_edge (dump_file, fixup_graph, curr_edge);
381 curr_vertex->succ_edges.safe_push (curr_edge);
382 return curr_edge;
386 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
387 MAX_CAPACITY to the edge_list in the fixup graph. */
389 static void
390 add_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest,
391 edge_type type, gcov_type weight, gcov_type cost,
392 gcov_type max_capacity)
394 fixup_edge_p curr_edge = add_edge (fixup_graph, src, dest, cost);
395 curr_edge->type = type;
396 curr_edge->weight = weight;
397 curr_edge->max_capacity = max_capacity;
401 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
402 to the fixup graph. */
404 static void
405 add_rfixup_edge (fixup_graph_type *fixup_graph, int src, int dest,
406 gcov_type rflow, gcov_type cost)
408 fixup_edge_p curr_edge = add_edge (fixup_graph, src, dest, cost);
409 curr_edge->rflow = rflow;
410 curr_edge->is_rflow_valid = true;
411 /* This edge is not a valid edge - merely used to hold residual flow. */
412 curr_edge->type = INVALID_EDGE;
416 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
417 exist in the FIXUP_GRAPH. */
419 static fixup_edge_p
420 find_fixup_edge (fixup_graph_type *fixup_graph, int src, int dest)
422 int j;
423 fixup_edge_p pfedge;
424 fixup_vertex_p pfvertex;
426 gcc_assert (src < fixup_graph->num_vertices);
428 pfvertex = fixup_graph->vertex_list + src;
430 for (j = 0; pfvertex->succ_edges.iterate (j, &pfedge);
431 j++)
432 if (pfedge->dest == dest)
433 return pfedge;
435 return NULL;
439 /* Cleanup routine to free structures in FIXUP_GRAPH. */
441 static void
442 delete_fixup_graph (fixup_graph_type *fixup_graph)
444 int i;
445 int fnum_vertices = fixup_graph->num_vertices;
446 fixup_vertex_p pfvertex = fixup_graph->vertex_list;
448 for (i = 0; i < fnum_vertices; i++, pfvertex++)
449 pfvertex->succ_edges.release ();
451 free (fixup_graph->vertex_list);
452 free (fixup_graph->edge_list);
456 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
458 static void
459 create_fixup_graph (fixup_graph_type *fixup_graph)
461 double sqrt_avg_vertex_weight = 0;
462 double total_vertex_weight = 0;
463 double k_pos = 0;
464 double k_neg = 0;
465 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
466 gcov_type *diff_out_in = NULL;
467 gcov_type supply_value = 1, demand_value = 0;
468 gcov_type fcost = 0;
469 int new_entry_index = 0, new_exit_index = 0;
470 int i = 0, j = 0;
471 int new_index = 0;
472 basic_block bb;
473 edge e;
474 edge_iterator ei;
475 fixup_edge_p pfedge, r_pfedge;
476 fixup_edge_p fedge_list;
477 int fnum_edges;
479 /* Each basic_block will be split into 2 during vertex transformation. */
480 int fnum_vertices_after_transform = 2 * n_basic_blocks_for_fn (cfun);
481 int fnum_edges_after_transform =
482 n_edges_for_fn (cfun) + n_basic_blocks_for_fn (cfun);
484 /* Count the new SOURCE and EXIT vertices to be added. */
485 int fmax_num_vertices =
486 (fnum_vertices_after_transform + n_edges_for_fn (cfun)
487 + n_basic_blocks_for_fn (cfun) + 2);
489 /* In create_fixup_graph: Each basic block and edge can be split into 3
490 edges. Number of balance edges = n_basic_blocks. So after
491 create_fixup_graph:
492 max_edges = 4 * n_basic_blocks + 3 * n_edges
493 Accounting for residual flow edges
494 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
495 = 8 * n_basic_blocks + 6 * n_edges
496 < 8 * n_basic_blocks + 8 * n_edges. */
497 int fmax_num_edges = 8 * (n_basic_blocks_for_fn (cfun) +
498 n_edges_for_fn (cfun));
500 /* Initial num of vertices in the fixup graph. */
501 fixup_graph->num_vertices = n_basic_blocks_for_fn (cfun);
503 /* Fixup graph vertex list. */
504 fixup_graph->vertex_list =
505 (fixup_vertex_p) xcalloc (fmax_num_vertices, sizeof (fixup_vertex_type));
507 /* Fixup graph edge list. */
508 fixup_graph->edge_list =
509 (fixup_edge_p) xcalloc (fmax_num_edges, sizeof (fixup_edge_type));
511 diff_out_in =
512 (gcov_type *) xcalloc (1 + fnum_vertices_after_transform,
513 sizeof (gcov_type));
515 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
516 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
517 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
518 total_vertex_weight += bb->count;
520 sqrt_avg_vertex_weight = mcf_sqrt (total_vertex_weight /
521 n_basic_blocks_for_fn (cfun));
523 k_pos = K_POS (sqrt_avg_vertex_weight);
524 k_neg = K_NEG (sqrt_avg_vertex_weight);
526 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
527 connected by an edge e from v' to v''. w(e) = w(v). */
529 if (dump_file)
530 fprintf (dump_file, "\nVertex transformation:\n");
532 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
534 /* v'->v'': index1->(index1+1). */
535 i = 2 * bb->index;
536 fcost = (gcov_type) COST (k_pos, bb->count);
537 add_fixup_edge (fixup_graph, i, i + 1, VERTEX_SPLIT_EDGE, bb->count,
538 fcost, CAP_INFINITY);
539 fixup_graph->num_vertices++;
541 FOR_EACH_EDGE (e, ei, bb->succs)
543 /* Edges with ignore attribute set should be treated like they don't
544 exist. */
545 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
546 continue;
547 j = 2 * e->dest->index;
548 fcost = (gcov_type) COST (k_pos, e->count);
549 add_fixup_edge (fixup_graph, i + 1, j, REDIRECT_EDGE, e->count, fcost,
550 CAP_INFINITY);
554 /* After vertex transformation. */
555 gcc_assert (fixup_graph->num_vertices == fnum_vertices_after_transform);
556 /* Redirect edges are not added for edges with ignore attribute. */
557 gcc_assert (fixup_graph->num_edges <= fnum_edges_after_transform);
559 fnum_edges_after_transform = fixup_graph->num_edges;
561 /* 2. Initialize D(v). */
562 for (i = 0; i < fnum_edges_after_transform; i++)
564 pfedge = fixup_graph->edge_list + i;
565 diff_out_in[pfedge->src] += pfedge->weight;
566 diff_out_in[pfedge->dest] -= pfedge->weight;
569 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
570 for (i = 0; i <= 3; i++)
571 diff_out_in[i] = 0;
573 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
574 if (dump_file)
575 fprintf (dump_file, "\nReverse edges:\n");
576 for (i = 0; i < fnum_edges_after_transform; i++)
578 pfedge = fixup_graph->edge_list + i;
579 if ((pfedge->src == 0) || (pfedge->src == 2))
580 continue;
581 r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
582 if (!r_pfedge && pfedge->weight)
584 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
585 capacity is 0. */
586 fcost = (gcov_type) COST (k_neg, pfedge->weight);
587 add_fixup_edge (fixup_graph, pfedge->dest, pfedge->src,
588 REVERSE_EDGE, 0, fcost, pfedge->weight);
592 /* 4. Create single source and sink. Connect new source vertex s' to function
593 entry block. Connect sink vertex t' to function exit. */
594 if (dump_file)
595 fprintf (dump_file, "\ns'->S, T->t':\n");
597 new_entry_index = fixup_graph->new_entry_index = fixup_graph->num_vertices;
598 fixup_graph->num_vertices++;
599 /* Set supply_value to 1 to avoid zero count function ENTRY. */
600 add_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK, SOURCE_CONNECT_EDGE,
601 1 /* supply_value */, 0, 1 /* supply_value */);
603 /* Create new exit with EXIT_BLOCK as single pred. */
604 new_exit_index = fixup_graph->new_exit_index = fixup_graph->num_vertices;
605 fixup_graph->num_vertices++;
606 add_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index,
607 SINK_CONNECT_EDGE,
608 0 /* demand_value */, 0, 0 /* demand_value */);
610 /* Connect vertices with unbalanced D(v) to source/sink. */
611 if (dump_file)
612 fprintf (dump_file, "\nD(v) balance:\n");
613 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
614 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
615 for (i = 4; i < new_entry_index; i += 2)
617 if (diff_out_in[i] > 0)
619 add_fixup_edge (fixup_graph, i, new_exit_index, BALANCE_EDGE, 0, 0,
620 diff_out_in[i]);
621 demand_value += diff_out_in[i];
623 else if (diff_out_in[i] < 0)
625 add_fixup_edge (fixup_graph, new_entry_index, i, BALANCE_EDGE, 0, 0,
626 -diff_out_in[i]);
627 supply_value -= diff_out_in[i];
631 /* Set supply = demand. */
632 if (dump_file)
634 fprintf (dump_file, "\nAdjust supply and demand:\n");
635 fprintf (dump_file, "supply_value=%" PRId64 "\n",
636 supply_value);
637 fprintf (dump_file, "demand_value=%" PRId64 "\n",
638 demand_value);
641 if (demand_value > supply_value)
643 pfedge = find_fixup_edge (fixup_graph, new_entry_index, ENTRY_BLOCK);
644 pfedge->max_capacity += (demand_value - supply_value);
646 else
648 pfedge = find_fixup_edge (fixup_graph, 2 * EXIT_BLOCK + 1, new_exit_index);
649 pfedge->max_capacity += (supply_value - demand_value);
652 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
653 created by the vertex transformation step from self-edges in the original
654 CFG and by the reverse edges added earlier. */
655 if (dump_file)
656 fprintf (dump_file, "\nNormalize edges:\n");
658 fnum_edges = fixup_graph->num_edges;
659 fedge_list = fixup_graph->edge_list;
661 for (i = 0; i < fnum_edges; i++)
663 pfedge = fedge_list + i;
664 r_pfedge = find_fixup_edge (fixup_graph, pfedge->dest, pfedge->src);
665 if (((pfedge->type == VERTEX_SPLIT_EDGE)
666 || (pfedge->type == REDIRECT_EDGE)) && r_pfedge)
668 new_index = fixup_graph->num_vertices;
669 fixup_graph->num_vertices++;
671 if (dump_file)
673 fprintf (dump_file, "\nAnti-parallel edge:\n");
674 dump_fixup_edge (dump_file, fixup_graph, pfedge);
675 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
676 fprintf (dump_file, "New vertex is %d.\n", new_index);
677 fprintf (dump_file, "------------------\n");
680 pfedge->cost /= 2;
681 pfedge->norm_vertex_index = new_index;
682 if (dump_file)
684 fprintf (dump_file, "After normalization:\n");
685 dump_fixup_edge (dump_file, fixup_graph, pfedge);
688 /* Add a new fixup edge: new_index->src. */
689 add_fixup_edge (fixup_graph, new_index, pfedge->src,
690 REVERSE_NORMALIZED_EDGE, 0, r_pfedge->cost,
691 r_pfedge->max_capacity);
692 gcc_assert (fixup_graph->num_vertices <= fmax_num_vertices);
694 /* Edge: r_pfedge->src -> r_pfedge->dest
695 ==> r_pfedge->src -> new_index. */
696 r_pfedge->dest = new_index;
697 r_pfedge->type = REVERSE_NORMALIZED_EDGE;
698 r_pfedge->cost = pfedge->cost;
699 r_pfedge->max_capacity = pfedge->max_capacity;
700 if (dump_file)
701 dump_fixup_edge (dump_file, fixup_graph, r_pfedge);
705 if (dump_file)
706 dump_fixup_graph (dump_file, fixup_graph, "After create_fixup_graph()");
708 /* Cleanup. */
709 free (diff_out_in);
713 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
714 proportional to the number of nodes in the graph, which is given by
715 GRAPH_SIZE. */
717 static void
718 init_augmenting_path (augmenting_path_type *augmenting_path, int graph_size)
720 augmenting_path->queue_list.queue = (int *)
721 xcalloc (graph_size + 2, sizeof (int));
722 augmenting_path->queue_list.size = graph_size + 2;
723 augmenting_path->bb_pred = (int *) xcalloc (graph_size, sizeof (int));
724 augmenting_path->is_visited = (int *) xcalloc (graph_size, sizeof (int));
727 /* Free the structures in AUGMENTING_PATH. */
728 static void
729 free_augmenting_path (augmenting_path_type *augmenting_path)
731 free (augmenting_path->queue_list.queue);
732 free (augmenting_path->bb_pred);
733 free (augmenting_path->is_visited);
737 /* Queue routines. Assumes queue will never overflow. */
739 static void
740 init_queue (queue_type *queue_list)
742 gcc_assert (queue_list);
743 queue_list->head = 0;
744 queue_list->tail = 0;
747 /* Return true if QUEUE_LIST is empty. */
748 static bool
749 is_empty (queue_type *queue_list)
751 return (queue_list->head == queue_list->tail);
754 /* Insert element X into QUEUE_LIST. */
755 static void
756 enqueue (queue_type *queue_list, int x)
758 gcc_assert (queue_list->tail < queue_list->size);
759 queue_list->queue[queue_list->tail] = x;
760 (queue_list->tail)++;
763 /* Return the first element in QUEUE_LIST. */
764 static int
765 dequeue (queue_type *queue_list)
767 int x;
768 gcc_assert (queue_list->head >= 0);
769 x = queue_list->queue[queue_list->head];
770 (queue_list->head)++;
771 return x;
775 /* Finds a negative cycle in the residual network using
776 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
777 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
778 considered.
780 Parameters:
781 FIXUP_GRAPH - Residual graph (input/output)
782 The following are allocated/freed by the caller:
783 PI - Vector to hold predecessors in path (pi = pred index)
784 D - D[I] holds minimum cost of path from i to sink
785 CYCLE - Vector to hold the minimum cost cycle
787 Return:
788 true if a negative cycle was found, false otherwise. */
790 static bool
791 cancel_negative_cycle (fixup_graph_type *fixup_graph,
792 int *pi, gcov_type *d, int *cycle)
794 int i, j, k;
795 int fnum_vertices, fnum_edges;
796 fixup_edge_p fedge_list, pfedge, r_pfedge;
797 bool found_cycle = false;
798 int cycle_start = 0, cycle_end = 0;
799 gcov_type sum_cost = 0, cycle_flow = 0;
800 int new_entry_index;
801 bool propagated = false;
803 gcc_assert (fixup_graph);
804 fnum_vertices = fixup_graph->num_vertices;
805 fnum_edges = fixup_graph->num_edges;
806 fedge_list = fixup_graph->edge_list;
807 new_entry_index = fixup_graph->new_entry_index;
809 /* Initialize. */
810 /* Skip ENTRY. */
811 for (i = 1; i < fnum_vertices; i++)
813 d[i] = CAP_INFINITY;
814 pi[i] = -1;
815 cycle[i] = -1;
817 d[ENTRY_BLOCK] = 0;
819 /* Relax. */
820 for (k = 1; k < fnum_vertices; k++)
822 propagated = false;
823 for (i = 0; i < fnum_edges; i++)
825 pfedge = fedge_list + i;
826 if (pfedge->src == new_entry_index)
827 continue;
828 if (pfedge->is_rflow_valid && pfedge->rflow
829 && d[pfedge->src] != CAP_INFINITY
830 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
832 d[pfedge->dest] = d[pfedge->src] + pfedge->cost;
833 pi[pfedge->dest] = pfedge->src;
834 propagated = true;
837 if (!propagated)
838 break;
841 if (!propagated)
842 /* No negative cycles exist. */
843 return 0;
845 /* Detect. */
846 for (i = 0; i < fnum_edges; i++)
848 pfedge = fedge_list + i;
849 if (pfedge->src == new_entry_index)
850 continue;
851 if (pfedge->is_rflow_valid && pfedge->rflow
852 && d[pfedge->src] != CAP_INFINITY
853 && (d[pfedge->dest] > d[pfedge->src] + pfedge->cost))
855 found_cycle = true;
856 break;
860 if (!found_cycle)
861 return 0;
863 /* Augment the cycle with the cycle's minimum residual capacity. */
864 found_cycle = false;
865 cycle[0] = pfedge->dest;
866 j = pfedge->dest;
868 for (i = 1; i < fnum_vertices; i++)
870 j = pi[j];
871 cycle[i] = j;
872 for (k = 0; k < i; k++)
874 if (cycle[k] == j)
876 /* cycle[k] -> ... -> cycle[i]. */
877 cycle_start = k;
878 cycle_end = i;
879 found_cycle = true;
880 break;
883 if (found_cycle)
884 break;
887 gcc_assert (cycle[cycle_start] == cycle[cycle_end]);
888 if (dump_file)
889 fprintf (dump_file, "\nNegative cycle length is %d:\n",
890 cycle_end - cycle_start);
892 sum_cost = 0;
893 cycle_flow = CAP_INFINITY;
894 for (k = cycle_start; k < cycle_end; k++)
896 pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
897 cycle_flow = MIN (cycle_flow, pfedge->rflow);
898 sum_cost += pfedge->cost;
899 if (dump_file)
900 fprintf (dump_file, "%d ", cycle[k]);
903 if (dump_file)
905 fprintf (dump_file, "%d", cycle[k]);
906 fprintf (dump_file,
907 ": (%" PRId64 ", %" PRId64
908 ")\n", sum_cost, cycle_flow);
909 fprintf (dump_file,
910 "Augment cycle with %" PRId64 "\n",
911 cycle_flow);
914 for (k = cycle_start; k < cycle_end; k++)
916 pfedge = find_fixup_edge (fixup_graph, cycle[k + 1], cycle[k]);
917 r_pfedge = find_fixup_edge (fixup_graph, cycle[k], cycle[k + 1]);
918 pfedge->rflow -= cycle_flow;
919 if (pfedge->type)
920 pfedge->flow += cycle_flow;
921 r_pfedge->rflow += cycle_flow;
922 if (r_pfedge->type)
923 r_pfedge->flow -= cycle_flow;
926 return true;
930 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
931 the edges. ENTRY and EXIT vertices should not be considered. */
933 static void
934 compute_residual_flow (fixup_graph_type *fixup_graph)
936 int i;
937 int fnum_edges;
938 fixup_edge_p fedge_list, pfedge;
940 gcc_assert (fixup_graph);
942 if (dump_file)
943 fputs ("\ncompute_residual_flow():\n", dump_file);
945 fnum_edges = fixup_graph->num_edges;
946 fedge_list = fixup_graph->edge_list;
948 for (i = 0; i < fnum_edges; i++)
950 pfedge = fedge_list + i;
951 pfedge->rflow = pfedge->max_capacity - pfedge->flow;
952 pfedge->is_rflow_valid = true;
953 add_rfixup_edge (fixup_graph, pfedge->dest, pfedge->src, pfedge->flow,
954 -pfedge->cost);
959 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
960 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
961 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
962 to reflect the path found.
963 Returns: 0 if no augmenting path is found, 1 otherwise. */
965 static int
966 find_augmenting_path (fixup_graph_type *fixup_graph,
967 augmenting_path_type *augmenting_path, int source,
968 int sink)
970 int u = 0;
971 int i;
972 fixup_vertex_p fvertex_list, pfvertex;
973 fixup_edge_p pfedge;
974 int *bb_pred, *is_visited;
975 queue_type *queue_list;
977 gcc_assert (augmenting_path);
978 bb_pred = augmenting_path->bb_pred;
979 gcc_assert (bb_pred);
980 is_visited = augmenting_path->is_visited;
981 gcc_assert (is_visited);
982 queue_list = &(augmenting_path->queue_list);
984 gcc_assert (fixup_graph);
986 fvertex_list = fixup_graph->vertex_list;
988 for (u = 0; u < fixup_graph->num_vertices; u++)
989 is_visited[u] = 0;
991 init_queue (queue_list);
992 enqueue (queue_list, source);
993 bb_pred[source] = -1;
995 while (!is_empty (queue_list))
997 u = dequeue (queue_list);
998 is_visited[u] = 1;
999 pfvertex = fvertex_list + u;
1000 for (i = 0; pfvertex->succ_edges.iterate (i, &pfedge);
1001 i++)
1003 int dest = pfedge->dest;
1004 if ((pfedge->rflow > 0) && (is_visited[dest] == 0))
1006 enqueue (queue_list, dest);
1007 bb_pred[dest] = u;
1008 is_visited[dest] = 1;
1009 if (dest == sink)
1010 return 1;
1015 return 0;
1019 /* Routine to find the maximal flow:
1020 Algorithm:
1021 1. Initialize flow to 0
1022 2. Find an augmenting path form source to sink.
1023 3. Send flow equal to the path's residual capacity along the edges of this path.
1024 4. Repeat steps 2 and 3 until no new augmenting path is found.
1026 Parameters:
1027 SOURCE: index of source vertex (input)
1028 SINK: index of sink vertex (input)
1029 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1030 set to have a valid maximal flow by this routine. (input)
1031 Return: Maximum flow possible. */
1033 static gcov_type
1034 find_max_flow (fixup_graph_type *fixup_graph, int source, int sink)
1036 int fnum_edges;
1037 augmenting_path_type augmenting_path;
1038 int *bb_pred;
1039 gcov_type max_flow = 0;
1040 int i, u;
1041 fixup_edge_p fedge_list, pfedge, r_pfedge;
1043 gcc_assert (fixup_graph);
1045 fnum_edges = fixup_graph->num_edges;
1046 fedge_list = fixup_graph->edge_list;
1048 /* Initialize flow to 0. */
1049 for (i = 0; i < fnum_edges; i++)
1051 pfedge = fedge_list + i;
1052 pfedge->flow = 0;
1055 compute_residual_flow (fixup_graph);
1057 init_augmenting_path (&augmenting_path, fixup_graph->num_vertices);
1059 bb_pred = augmenting_path.bb_pred;
1060 while (find_augmenting_path (fixup_graph, &augmenting_path, source, sink))
1062 /* Determine the amount by which we can increment the flow. */
1063 gcov_type increment = CAP_INFINITY;
1064 for (u = sink; u != source; u = bb_pred[u])
1066 pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1067 increment = MIN (increment, pfedge->rflow);
1069 max_flow += increment;
1071 /* Now increment the flow. EXIT vertex index is 1. */
1072 for (u = sink; u != source; u = bb_pred[u])
1074 pfedge = find_fixup_edge (fixup_graph, bb_pred[u], u);
1075 r_pfedge = find_fixup_edge (fixup_graph, u, bb_pred[u]);
1076 if (pfedge->type)
1078 /* forward edge. */
1079 pfedge->flow += increment;
1080 pfedge->rflow -= increment;
1081 r_pfedge->rflow += increment;
1083 else
1085 /* backward edge. */
1086 gcc_assert (r_pfedge->type);
1087 r_pfedge->rflow += increment;
1088 r_pfedge->flow -= increment;
1089 pfedge->rflow -= increment;
1093 if (dump_file)
1095 fprintf (dump_file, "\nDump augmenting path:\n");
1096 for (u = sink; u != source; u = bb_pred[u])
1098 print_basic_block (dump_file, fixup_graph, u);
1099 fprintf (dump_file, "<-");
1101 fprintf (dump_file,
1102 "ENTRY (path_capacity=%" PRId64 ")\n",
1103 increment);
1104 fprintf (dump_file,
1105 "Network flow is %" PRId64 ".\n",
1106 max_flow);
1110 free_augmenting_path (&augmenting_path);
1111 if (dump_file)
1112 dump_fixup_graph (dump_file, fixup_graph, "After find_max_flow()");
1113 return max_flow;
1117 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1118 after applying the find_minimum_cost_flow() routine. */
1120 static void
1121 adjust_cfg_counts (fixup_graph_type *fixup_graph)
1123 basic_block bb;
1124 edge e;
1125 edge_iterator ei;
1126 int i, j;
1127 fixup_edge_p pfedge, pfedge_n;
1129 gcc_assert (fixup_graph);
1131 if (dump_file)
1132 fprintf (dump_file, "\nadjust_cfg_counts():\n");
1134 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
1135 EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
1137 i = 2 * bb->index;
1139 /* Fixup BB. */
1140 if (dump_file)
1141 fprintf (dump_file,
1142 "BB%d: %" PRId64 "", bb->index, bb->count);
1144 pfedge = find_fixup_edge (fixup_graph, i, i + 1);
1145 if (pfedge->flow)
1147 bb->count += pfedge->flow;
1148 if (dump_file)
1150 fprintf (dump_file, " + %" PRId64 "(",
1151 pfedge->flow);
1152 print_edge (dump_file, fixup_graph, i, i + 1);
1153 fprintf (dump_file, ")");
1157 pfedge_n =
1158 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1159 /* Deduct flow from normalized reverse edge. */
1160 if (pfedge->norm_vertex_index && pfedge_n->flow)
1162 bb->count -= pfedge_n->flow;
1163 if (dump_file)
1165 fprintf (dump_file, " - %" PRId64 "(",
1166 pfedge_n->flow);
1167 print_edge (dump_file, fixup_graph, i + 1,
1168 pfedge->norm_vertex_index);
1169 fprintf (dump_file, ")");
1172 if (dump_file)
1173 fprintf (dump_file, " = %" PRId64 "\n", bb->count);
1175 /* Fixup edge. */
1176 FOR_EACH_EDGE (e, ei, bb->succs)
1178 /* Treat edges with ignore attribute set as if they don't exist. */
1179 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1180 continue;
1182 j = 2 * e->dest->index;
1183 if (dump_file)
1184 fprintf (dump_file, "%d->%d: %" PRId64 "",
1185 bb->index, e->dest->index, e->count);
1187 pfedge = find_fixup_edge (fixup_graph, i + 1, j);
1189 if (bb->index != e->dest->index)
1191 /* Non-self edge. */
1192 if (pfedge->flow)
1194 e->count += pfedge->flow;
1195 if (dump_file)
1197 fprintf (dump_file, " + %" PRId64 "(",
1198 pfedge->flow);
1199 print_edge (dump_file, fixup_graph, i + 1, j);
1200 fprintf (dump_file, ")");
1204 pfedge_n =
1205 find_fixup_edge (fixup_graph, j, pfedge->norm_vertex_index);
1206 /* Deduct flow from normalized reverse edge. */
1207 if (pfedge->norm_vertex_index && pfedge_n->flow)
1209 e->count -= pfedge_n->flow;
1210 if (dump_file)
1212 fprintf (dump_file, " - %" PRId64 "(",
1213 pfedge_n->flow);
1214 print_edge (dump_file, fixup_graph, j,
1215 pfedge->norm_vertex_index);
1216 fprintf (dump_file, ")");
1220 else
1222 /* Handle self edges. Self edge is split with a normalization
1223 vertex. Here i=j. */
1224 pfedge = find_fixup_edge (fixup_graph, j, i + 1);
1225 pfedge_n =
1226 find_fixup_edge (fixup_graph, i + 1, pfedge->norm_vertex_index);
1227 e->count += pfedge_n->flow;
1228 bb->count += pfedge_n->flow;
1229 if (dump_file)
1231 fprintf (dump_file, "(self edge)");
1232 fprintf (dump_file, " + %" PRId64 "(",
1233 pfedge_n->flow);
1234 print_edge (dump_file, fixup_graph, i + 1,
1235 pfedge->norm_vertex_index);
1236 fprintf (dump_file, ")");
1240 if (bb->count)
1241 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1242 if (dump_file)
1243 fprintf (dump_file, " = %" PRId64 "\t(%.1f%%)\n",
1244 e->count, e->probability * 100.0 / REG_BR_PROB_BASE);
1248 ENTRY_BLOCK_PTR_FOR_FN (cfun)->count =
1249 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs);
1250 EXIT_BLOCK_PTR_FOR_FN (cfun)->count =
1251 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds);
1253 /* Compute edge probabilities. */
1254 FOR_ALL_BB_FN (bb, cfun)
1256 if (bb->count)
1258 FOR_EACH_EDGE (e, ei, bb->succs)
1259 e->probability = REG_BR_PROB_BASE * e->count / bb->count;
1261 else
1263 int total = 0;
1264 FOR_EACH_EDGE (e, ei, bb->succs)
1265 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1266 total++;
1267 if (total)
1269 FOR_EACH_EDGE (e, ei, bb->succs)
1271 if (!(e->flags & (EDGE_COMPLEX | EDGE_FAKE)))
1272 e->probability = REG_BR_PROB_BASE / total;
1273 else
1274 e->probability = 0;
1277 else
1279 total += EDGE_COUNT (bb->succs);
1280 FOR_EACH_EDGE (e, ei, bb->succs)
1281 e->probability = REG_BR_PROB_BASE / total;
1286 if (dump_file)
1288 fprintf (dump_file, "\nCheck %s() CFG flow conservation:\n",
1289 current_function_name ());
1290 FOR_EACH_BB_FN (bb, cfun)
1292 if ((bb->count != sum_edge_counts (bb->preds))
1293 || (bb->count != sum_edge_counts (bb->succs)))
1295 fprintf (dump_file,
1296 "BB%d(%" PRId64 ") **INVALID**: ",
1297 bb->index, bb->count);
1298 fprintf (stderr,
1299 "******** BB%d(%" PRId64
1300 ") **INVALID**: \n", bb->index, bb->count);
1301 fprintf (dump_file, "in_edges=%" PRId64 " ",
1302 sum_edge_counts (bb->preds));
1303 fprintf (dump_file, "out_edges=%" PRId64 "\n",
1304 sum_edge_counts (bb->succs));
1311 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1312 flow.
1313 Algorithm:
1314 1. Find maximal flow.
1315 2. Form residual network
1316 3. Repeat:
1317 While G contains a negative cost cycle C, reverse the flow on the found cycle
1318 by the minimum residual capacity in that cycle.
1319 4. Form the minimal cost flow
1320 f(u,v) = rf(v, u)
1321 Input:
1322 FIXUP_GRAPH - Initial fixup graph.
1323 The flow field is modified to represent the minimum cost flow. */
1325 static void
1326 find_minimum_cost_flow (fixup_graph_type *fixup_graph)
1328 /* Holds the index of predecessor in path. */
1329 int *pred;
1330 /* Used to hold the minimum cost cycle. */
1331 int *cycle;
1332 /* Used to record the number of iterations of cancel_negative_cycle. */
1333 int iteration;
1334 /* Vector d[i] holds the minimum cost of path from i to sink. */
1335 gcov_type *d;
1336 int fnum_vertices;
1337 int new_exit_index;
1338 int new_entry_index;
1340 gcc_assert (fixup_graph);
1341 fnum_vertices = fixup_graph->num_vertices;
1342 new_exit_index = fixup_graph->new_exit_index;
1343 new_entry_index = fixup_graph->new_entry_index;
1345 find_max_flow (fixup_graph, new_entry_index, new_exit_index);
1347 /* Initialize the structures for find_negative_cycle(). */
1348 pred = (int *) xcalloc (fnum_vertices, sizeof (int));
1349 d = (gcov_type *) xcalloc (fnum_vertices, sizeof (gcov_type));
1350 cycle = (int *) xcalloc (fnum_vertices, sizeof (int));
1352 /* Repeatedly find and cancel negative cost cycles, until
1353 no more negative cycles exist. This also updates the flow field
1354 to represent the minimum cost flow so far. */
1355 iteration = 0;
1356 while (cancel_negative_cycle (fixup_graph, pred, d, cycle))
1358 iteration++;
1359 if (iteration > MAX_ITER (fixup_graph->num_vertices,
1360 fixup_graph->num_edges))
1361 break;
1364 if (dump_file)
1365 dump_fixup_graph (dump_file, fixup_graph,
1366 "After find_minimum_cost_flow()");
1368 /* Cleanup structures. */
1369 free (pred);
1370 free (d);
1371 free (cycle);
1375 /* Compute the sum of the edge counts in TO_EDGES. */
1377 gcov_type
1378 sum_edge_counts (vec<edge, va_gc> *to_edges)
1380 gcov_type sum = 0;
1381 edge e;
1382 edge_iterator ei;
1384 FOR_EACH_EDGE (e, ei, to_edges)
1386 if (EDGE_INFO (e) && EDGE_INFO (e)->ignore)
1387 continue;
1388 sum += e->count;
1390 return sum;
1394 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1395 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1396 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1397 block. */
1399 void
1400 mcf_smooth_cfg (void)
1402 fixup_graph_type fixup_graph;
1403 memset (&fixup_graph, 0, sizeof (fixup_graph));
1404 create_fixup_graph (&fixup_graph);
1405 find_minimum_cost_flow (&fixup_graph);
1406 adjust_cfg_counts (&fixup_graph);
1407 delete_fixup_graph (&fixup_graph);