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