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