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
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
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/>. */
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;
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.
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
39 5. Form the minimal cost flow
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). */
47 #include "coretypes.h"
50 #include "hard-reg-set.h"
53 #include "dominance.h"
55 #include "basic-block.h"
60 /* CAP_INFINITY: Constant to represent infinite capacity. */
61 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
64 #define K_POS(b) ((b))
65 #define K_NEG(b) (50 * (b))
66 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
67 /* Limit the number of iterations for cancel_negative_cycles() to ensure
68 reasonable compile time. */
69 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
73 VERTEX_SPLIT_EDGE
, /* Edge to represent vertex with w(e) = w(v). */
74 REDIRECT_EDGE
, /* Edge after vertex transformation. */
76 SOURCE_CONNECT_EDGE
, /* Single edge connecting to single source. */
77 SINK_CONNECT_EDGE
, /* Single edge connecting to single sink. */
78 BALANCE_EDGE
, /* Edge connecting with source/sink: cp(e) = 0. */
79 REDIRECT_NORMALIZED_EDGE
, /* Normalized edge for a redirect edge. */
80 REVERSE_NORMALIZED_EDGE
/* Normalized edge for a reverse edge. */
83 /* Structure to represent an edge in the fixup graph. */
84 typedef struct fixup_edge_d
88 /* Flag denoting type of edge and attributes for the flow field. */
91 /* Index to the normalization vertex added for this edge. */
92 int norm_vertex_index
;
93 /* Flow for this edge. */
95 /* Residual flow for this edge - used during negative cycle canceling. */
99 gcov_type max_capacity
;
102 typedef fixup_edge_type
*fixup_edge_p
;
105 /* Structure to represent a vertex in the fixup graph. */
106 typedef struct fixup_vertex_d
108 vec
<fixup_edge_p
> succ_edges
;
111 typedef fixup_vertex_type
*fixup_vertex_p
;
113 /* Fixup graph used in the MCF algorithm. */
114 typedef struct fixup_graph_d
116 /* Current number of vertices for the graph. */
118 /* Current number of edges for the graph. */
120 /* Index of new entry vertex. */
122 /* Index of new exit vertex. */
124 /* Fixup vertex list. Adjacency list for fixup graph. */
125 fixup_vertex_p vertex_list
;
126 /* Fixup edge list. */
127 fixup_edge_p edge_list
;
130 typedef struct queue_d
138 /* Structure used in the maximal flow routines to find augmenting path. */
139 typedef struct augmenting_path_d
141 /* Queue used to hold vertex indices. */
142 queue_type queue_list
;
143 /* Vector to hold chain of pred vertex indices in augmenting path. */
145 /* Vector that indicates if basic block i has been visited. */
147 } augmenting_path_type
;
150 /* Function definitions. */
152 /* Dump routines to aid debugging. */
154 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
157 print_basic_block (FILE *file
, fixup_graph_type
*fixup_graph
, int n
)
159 if (n
== ENTRY_BLOCK
)
160 fputs ("ENTRY", file
);
161 else if (n
== ENTRY_BLOCK
+ 1)
162 fputs ("ENTRY''", file
);
163 else if (n
== 2 * EXIT_BLOCK
)
164 fputs ("EXIT", file
);
165 else if (n
== 2 * EXIT_BLOCK
+ 1)
166 fputs ("EXIT''", file
);
167 else if (n
== fixup_graph
->new_exit_index
)
168 fputs ("NEW_EXIT", file
);
169 else if (n
== fixup_graph
->new_entry_index
)
170 fputs ("NEW_ENTRY", file
);
173 fprintf (file
, "%d", n
/ 2);
182 /* Print edge S->D for given fixup_graph with n' and n'' format.
184 S is the index of the source vertex of the edge (input) and
185 D is the index of the destination vertex of the edge (input) for the given
186 fixup_graph (input). */
189 print_edge (FILE *file
, fixup_graph_type
*fixup_graph
, int s
, int d
)
191 print_basic_block (file
, fixup_graph
, s
);
193 print_basic_block (file
, fixup_graph
, d
);
197 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
200 dump_fixup_edge (FILE *file
, fixup_graph_type
*fixup_graph
, fixup_edge_p fedge
)
204 fputs ("NULL fixup graph edge.\n", file
);
208 print_edge (file
, fixup_graph
, fedge
->src
, fedge
->dest
);
213 fprintf (file
, "flow/capacity=%" PRId64
"/",
215 if (fedge
->max_capacity
== CAP_INFINITY
)
216 fputs ("+oo,", file
);
218 fprintf (file
, "%" PRId64
",", fedge
->max_capacity
);
221 if (fedge
->is_rflow_valid
)
223 if (fedge
->rflow
== CAP_INFINITY
)
224 fputs (" rflow=+oo.", file
);
226 fprintf (file
, " rflow=%" PRId64
",", fedge
->rflow
);
229 fprintf (file
, " cost=%" PRId64
".", fedge
->cost
);
231 fprintf (file
, "\t(%d->%d)", fedge
->src
, fedge
->dest
);
237 case VERTEX_SPLIT_EDGE
:
238 fputs (" @VERTEX_SPLIT_EDGE", file
);
242 fputs (" @REDIRECT_EDGE", file
);
245 case SOURCE_CONNECT_EDGE
:
246 fputs (" @SOURCE_CONNECT_EDGE", file
);
249 case SINK_CONNECT_EDGE
:
250 fputs (" @SINK_CONNECT_EDGE", file
);
254 fputs (" @REVERSE_EDGE", file
);
258 fputs (" @BALANCE_EDGE", file
);
261 case REDIRECT_NORMALIZED_EDGE
:
262 case REVERSE_NORMALIZED_EDGE
:
263 fputs (" @NORMALIZED_EDGE", file
);
267 fputs (" @INVALID_EDGE", file
);
275 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
276 file. The input string MSG is printed out as a heading. */
279 dump_fixup_graph (FILE *file
, fixup_graph_type
*fixup_graph
, const char *msg
)
282 int fnum_vertices
, fnum_edges
;
284 fixup_vertex_p fvertex_list
, pfvertex
;
287 gcc_assert (fixup_graph
);
288 fvertex_list
= fixup_graph
->vertex_list
;
289 fnum_vertices
= fixup_graph
->num_vertices
;
290 fnum_edges
= fixup_graph
->num_edges
;
292 fprintf (file
, "\nDump fixup graph for %s(): %s.\n",
293 current_function_name (), msg
);
295 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
296 fnum_vertices
, fnum_edges
, fixup_graph
->new_exit_index
);
298 for (i
= 0; i
< fnum_vertices
; i
++)
300 pfvertex
= fvertex_list
+ i
;
301 fprintf (file
, "vertex_list[%d]: %d succ fixup edges.\n",
302 i
, pfvertex
->succ_edges
.length ());
304 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
307 /* Distinguish forward edges and backward edges in the residual flow
310 fputs ("(f) ", file
);
311 else if (pfedge
->is_rflow_valid
)
312 fputs ("(b) ", file
);
313 dump_fixup_edge (file
, fixup_graph
, pfedge
);
321 /* Utility routines. */
322 /* ln() implementation: approximate calculation. Returns ln of X. */
343 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
344 implementation) by John Carmack. Returns sqrt of X. */
349 #define MAGIC_CONST1 0x1fbcf800
350 #define MAGIC_CONST2 0x5f3759df
354 } convertor
, convertor2
;
358 convertor
.floatPart
= x
;
359 convertor2
.floatPart
= x
;
360 convertor
.intPart
= MAGIC_CONST1
+ (convertor
.intPart
>> 1);
361 convertor2
.intPart
= MAGIC_CONST2
- (convertor2
.intPart
>> 1);
363 return 0.5f
* (convertor
.floatPart
+ (x
* convertor2
.floatPart
));
367 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
368 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
369 added set to COST. */
372 add_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, gcov_type cost
)
374 fixup_vertex_p curr_vertex
= fixup_graph
->vertex_list
+ src
;
375 fixup_edge_p curr_edge
= fixup_graph
->edge_list
+ fixup_graph
->num_edges
;
376 curr_edge
->src
= src
;
377 curr_edge
->dest
= dest
;
378 curr_edge
->cost
= cost
;
379 fixup_graph
->num_edges
++;
381 dump_fixup_edge (dump_file
, fixup_graph
, curr_edge
);
382 curr_vertex
->succ_edges
.safe_push (curr_edge
);
387 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
388 MAX_CAPACITY to the edge_list in the fixup graph. */
391 add_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
392 edge_type type
, gcov_type weight
, gcov_type cost
,
393 gcov_type max_capacity
)
395 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
396 curr_edge
->type
= type
;
397 curr_edge
->weight
= weight
;
398 curr_edge
->max_capacity
= max_capacity
;
402 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
403 to the fixup graph. */
406 add_rfixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
407 gcov_type rflow
, gcov_type cost
)
409 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
410 curr_edge
->rflow
= rflow
;
411 curr_edge
->is_rflow_valid
= true;
412 /* This edge is not a valid edge - merely used to hold residual flow. */
413 curr_edge
->type
= INVALID_EDGE
;
417 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
418 exist in the FIXUP_GRAPH. */
421 find_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
)
425 fixup_vertex_p pfvertex
;
427 gcc_assert (src
< fixup_graph
->num_vertices
);
429 pfvertex
= fixup_graph
->vertex_list
+ src
;
431 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
433 if (pfedge
->dest
== dest
)
440 /* Cleanup routine to free structures in FIXUP_GRAPH. */
443 delete_fixup_graph (fixup_graph_type
*fixup_graph
)
446 int fnum_vertices
= fixup_graph
->num_vertices
;
447 fixup_vertex_p pfvertex
= fixup_graph
->vertex_list
;
449 for (i
= 0; i
< fnum_vertices
; i
++, pfvertex
++)
450 pfvertex
->succ_edges
.release ();
452 free (fixup_graph
->vertex_list
);
453 free (fixup_graph
->edge_list
);
457 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
460 create_fixup_graph (fixup_graph_type
*fixup_graph
)
462 double sqrt_avg_vertex_weight
= 0;
463 double total_vertex_weight
= 0;
466 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
467 gcov_type
*diff_out_in
= NULL
;
468 gcov_type supply_value
= 1, demand_value
= 0;
470 int new_entry_index
= 0, new_exit_index
= 0;
476 fixup_edge_p pfedge
, r_pfedge
;
477 fixup_edge_p fedge_list
;
480 /* Each basic_block will be split into 2 during vertex transformation. */
481 int fnum_vertices_after_transform
= 2 * n_basic_blocks_for_fn (cfun
);
482 int fnum_edges_after_transform
=
483 n_edges_for_fn (cfun
) + n_basic_blocks_for_fn (cfun
);
485 /* Count the new SOURCE and EXIT vertices to be added. */
486 int fmax_num_vertices
=
487 (fnum_vertices_after_transform
+ n_edges_for_fn (cfun
)
488 + n_basic_blocks_for_fn (cfun
) + 2);
490 /* In create_fixup_graph: Each basic block and edge can be split into 3
491 edges. Number of balance edges = n_basic_blocks. So after
493 max_edges = 4 * n_basic_blocks + 3 * n_edges
494 Accounting for residual flow edges
495 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
496 = 8 * n_basic_blocks + 6 * n_edges
497 < 8 * n_basic_blocks + 8 * n_edges. */
498 int fmax_num_edges
= 8 * (n_basic_blocks_for_fn (cfun
) +
499 n_edges_for_fn (cfun
));
501 /* Initial num of vertices in the fixup graph. */
502 fixup_graph
->num_vertices
= n_basic_blocks_for_fn (cfun
);
504 /* Fixup graph vertex list. */
505 fixup_graph
->vertex_list
=
506 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
508 /* Fixup graph edge list. */
509 fixup_graph
->edge_list
=
510 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
513 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
516 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
517 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
518 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
519 total_vertex_weight
+= bb
->count
;
521 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/
522 n_basic_blocks_for_fn (cfun
));
524 k_pos
= K_POS (sqrt_avg_vertex_weight
);
525 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
527 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
528 connected by an edge e from v' to v''. w(e) = w(v). */
531 fprintf (dump_file
, "\nVertex transformation:\n");
533 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
535 /* v'->v'': index1->(index1+1). */
537 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
538 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
539 fcost
, CAP_INFINITY
);
540 fixup_graph
->num_vertices
++;
542 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
544 /* Edges with ignore attribute set should be treated like they don't
546 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
548 j
= 2 * e
->dest
->index
;
549 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
550 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
555 /* After vertex transformation. */
556 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
557 /* Redirect edges are not added for edges with ignore attribute. */
558 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
560 fnum_edges_after_transform
= fixup_graph
->num_edges
;
562 /* 2. Initialize D(v). */
563 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
565 pfedge
= fixup_graph
->edge_list
+ i
;
566 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
567 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
570 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
571 for (i
= 0; i
<= 3; i
++)
574 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
576 fprintf (dump_file
, "\nReverse edges:\n");
577 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
579 pfedge
= fixup_graph
->edge_list
+ i
;
580 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
582 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
583 if (!r_pfedge
&& pfedge
->weight
)
585 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
587 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
588 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
589 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
593 /* 4. Create single source and sink. Connect new source vertex s' to function
594 entry block. Connect sink vertex t' to function exit. */
596 fprintf (dump_file
, "\ns'->S, T->t':\n");
598 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
599 fixup_graph
->num_vertices
++;
600 /* Set supply_value to 1 to avoid zero count function ENTRY. */
601 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
602 1 /* supply_value */, 0, 1 /* supply_value */);
604 /* Create new exit with EXIT_BLOCK as single pred. */
605 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
606 fixup_graph
->num_vertices
++;
607 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
609 0 /* demand_value */, 0, 0 /* demand_value */);
611 /* Connect vertices with unbalanced D(v) to source/sink. */
613 fprintf (dump_file
, "\nD(v) balance:\n");
614 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
615 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
616 for (i
= 4; i
< new_entry_index
; i
+= 2)
618 if (diff_out_in
[i
] > 0)
620 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
622 demand_value
+= diff_out_in
[i
];
624 else if (diff_out_in
[i
] < 0)
626 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
628 supply_value
-= diff_out_in
[i
];
632 /* Set supply = demand. */
635 fprintf (dump_file
, "\nAdjust supply and demand:\n");
636 fprintf (dump_file
, "supply_value=%" PRId64
"\n",
638 fprintf (dump_file
, "demand_value=%" PRId64
"\n",
642 if (demand_value
> supply_value
)
644 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
645 pfedge
->max_capacity
+= (demand_value
- supply_value
);
649 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
650 pfedge
->max_capacity
+= (supply_value
- demand_value
);
653 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
654 created by the vertex transformation step from self-edges in the original
655 CFG and by the reverse edges added earlier. */
657 fprintf (dump_file
, "\nNormalize edges:\n");
659 fnum_edges
= fixup_graph
->num_edges
;
660 fedge_list
= fixup_graph
->edge_list
;
662 for (i
= 0; i
< fnum_edges
; i
++)
664 pfedge
= fedge_list
+ i
;
665 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
666 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
667 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
669 new_index
= fixup_graph
->num_vertices
;
670 fixup_graph
->num_vertices
++;
674 fprintf (dump_file
, "\nAnti-parallel edge:\n");
675 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
676 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
677 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
678 fprintf (dump_file
, "------------------\n");
682 pfedge
->norm_vertex_index
= new_index
;
685 fprintf (dump_file
, "After normalization:\n");
686 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
689 /* Add a new fixup edge: new_index->src. */
690 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
691 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
692 r_pfedge
->max_capacity
);
693 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
695 /* Edge: r_pfedge->src -> r_pfedge->dest
696 ==> r_pfedge->src -> new_index. */
697 r_pfedge
->dest
= new_index
;
698 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
699 r_pfedge
->cost
= pfedge
->cost
;
700 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
702 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
707 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
714 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
715 proportional to the number of nodes in the graph, which is given by
719 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
721 augmenting_path
->queue_list
.queue
= (int *)
722 xcalloc (graph_size
+ 2, sizeof (int));
723 augmenting_path
->queue_list
.size
= graph_size
+ 2;
724 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
725 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
728 /* Free the structures in AUGMENTING_PATH. */
730 free_augmenting_path (augmenting_path_type
*augmenting_path
)
732 free (augmenting_path
->queue_list
.queue
);
733 free (augmenting_path
->bb_pred
);
734 free (augmenting_path
->is_visited
);
738 /* Queue routines. Assumes queue will never overflow. */
741 init_queue (queue_type
*queue_list
)
743 gcc_assert (queue_list
);
744 queue_list
->head
= 0;
745 queue_list
->tail
= 0;
748 /* Return true if QUEUE_LIST is empty. */
750 is_empty (queue_type
*queue_list
)
752 return (queue_list
->head
== queue_list
->tail
);
755 /* Insert element X into QUEUE_LIST. */
757 enqueue (queue_type
*queue_list
, int x
)
759 gcc_assert (queue_list
->tail
< queue_list
->size
);
760 queue_list
->queue
[queue_list
->tail
] = x
;
761 (queue_list
->tail
)++;
764 /* Return the first element in QUEUE_LIST. */
766 dequeue (queue_type
*queue_list
)
769 gcc_assert (queue_list
->head
>= 0);
770 x
= queue_list
->queue
[queue_list
->head
];
771 (queue_list
->head
)++;
776 /* Finds a negative cycle in the residual network using
777 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
778 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
782 FIXUP_GRAPH - Residual graph (input/output)
783 The following are allocated/freed by the caller:
784 PI - Vector to hold predecessors in path (pi = pred index)
785 D - D[I] holds minimum cost of path from i to sink
786 CYCLE - Vector to hold the minimum cost cycle
789 true if a negative cycle was found, false otherwise. */
792 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
793 int *pi
, gcov_type
*d
, int *cycle
)
796 int fnum_vertices
, fnum_edges
;
797 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
798 bool found_cycle
= false;
799 int cycle_start
= 0, cycle_end
= 0;
800 gcov_type sum_cost
= 0, cycle_flow
= 0;
802 bool propagated
= false;
804 gcc_assert (fixup_graph
);
805 fnum_vertices
= fixup_graph
->num_vertices
;
806 fnum_edges
= fixup_graph
->num_edges
;
807 fedge_list
= fixup_graph
->edge_list
;
808 new_entry_index
= fixup_graph
->new_entry_index
;
812 for (i
= 1; i
< fnum_vertices
; i
++)
821 for (k
= 1; k
< fnum_vertices
; k
++)
824 for (i
= 0; i
< fnum_edges
; i
++)
826 pfedge
= fedge_list
+ i
;
827 if (pfedge
->src
== new_entry_index
)
829 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
830 && d
[pfedge
->src
] != CAP_INFINITY
831 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
833 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
834 pi
[pfedge
->dest
] = pfedge
->src
;
843 /* No negative cycles exist. */
847 for (i
= 0; i
< fnum_edges
; i
++)
849 pfedge
= fedge_list
+ i
;
850 if (pfedge
->src
== new_entry_index
)
852 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
853 && d
[pfedge
->src
] != CAP_INFINITY
854 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
864 /* Augment the cycle with the cycle's minimum residual capacity. */
866 cycle
[0] = pfedge
->dest
;
869 for (i
= 1; i
< fnum_vertices
; i
++)
873 for (k
= 0; k
< i
; k
++)
877 /* cycle[k] -> ... -> cycle[i]. */
888 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
890 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
891 cycle_end
- cycle_start
);
894 cycle_flow
= CAP_INFINITY
;
895 for (k
= cycle_start
; k
< cycle_end
; k
++)
897 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
898 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
899 sum_cost
+= pfedge
->cost
;
901 fprintf (dump_file
, "%d ", cycle
[k
]);
906 fprintf (dump_file
, "%d", cycle
[k
]);
908 ": (%" PRId64
", %" PRId64
909 ")\n", sum_cost
, cycle_flow
);
911 "Augment cycle with %" PRId64
"\n",
915 for (k
= cycle_start
; k
< cycle_end
; k
++)
917 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
918 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
919 pfedge
->rflow
-= cycle_flow
;
921 pfedge
->flow
+= cycle_flow
;
922 r_pfedge
->rflow
+= cycle_flow
;
924 r_pfedge
->flow
-= cycle_flow
;
931 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
932 the edges. ENTRY and EXIT vertices should not be considered. */
935 compute_residual_flow (fixup_graph_type
*fixup_graph
)
939 fixup_edge_p fedge_list
, pfedge
;
941 gcc_assert (fixup_graph
);
944 fputs ("\ncompute_residual_flow():\n", dump_file
);
946 fnum_edges
= fixup_graph
->num_edges
;
947 fedge_list
= fixup_graph
->edge_list
;
949 for (i
= 0; i
< fnum_edges
; i
++)
951 pfedge
= fedge_list
+ i
;
952 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
953 pfedge
->is_rflow_valid
= true;
954 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
960 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
961 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
962 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
963 to reflect the path found.
964 Returns: 0 if no augmenting path is found, 1 otherwise. */
967 find_augmenting_path (fixup_graph_type
*fixup_graph
,
968 augmenting_path_type
*augmenting_path
, int source
,
973 fixup_vertex_p fvertex_list
, pfvertex
;
975 int *bb_pred
, *is_visited
;
976 queue_type
*queue_list
;
978 gcc_assert (augmenting_path
);
979 bb_pred
= augmenting_path
->bb_pred
;
980 gcc_assert (bb_pred
);
981 is_visited
= augmenting_path
->is_visited
;
982 gcc_assert (is_visited
);
983 queue_list
= &(augmenting_path
->queue_list
);
985 gcc_assert (fixup_graph
);
987 fvertex_list
= fixup_graph
->vertex_list
;
989 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
992 init_queue (queue_list
);
993 enqueue (queue_list
, source
);
994 bb_pred
[source
] = -1;
996 while (!is_empty (queue_list
))
998 u
= dequeue (queue_list
);
1000 pfvertex
= fvertex_list
+ u
;
1001 for (i
= 0; pfvertex
->succ_edges
.iterate (i
, &pfedge
);
1004 int dest
= pfedge
->dest
;
1005 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
1007 enqueue (queue_list
, dest
);
1009 is_visited
[dest
] = 1;
1020 /* Routine to find the maximal flow:
1022 1. Initialize flow to 0
1023 2. Find an augmenting path form source to sink.
1024 3. Send flow equal to the path's residual capacity along the edges of this path.
1025 4. Repeat steps 2 and 3 until no new augmenting path is found.
1028 SOURCE: index of source vertex (input)
1029 SINK: index of sink vertex (input)
1030 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1031 set to have a valid maximal flow by this routine. (input)
1032 Return: Maximum flow possible. */
1035 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1038 augmenting_path_type augmenting_path
;
1040 gcov_type max_flow
= 0;
1042 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1044 gcc_assert (fixup_graph
);
1046 fnum_edges
= fixup_graph
->num_edges
;
1047 fedge_list
= fixup_graph
->edge_list
;
1049 /* Initialize flow to 0. */
1050 for (i
= 0; i
< fnum_edges
; i
++)
1052 pfedge
= fedge_list
+ i
;
1056 compute_residual_flow (fixup_graph
);
1058 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1060 bb_pred
= augmenting_path
.bb_pred
;
1061 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1063 /* Determine the amount by which we can increment the flow. */
1064 gcov_type increment
= CAP_INFINITY
;
1065 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1067 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1068 increment
= MIN (increment
, pfedge
->rflow
);
1070 max_flow
+= increment
;
1072 /* Now increment the flow. EXIT vertex index is 1. */
1073 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1075 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1076 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1080 pfedge
->flow
+= increment
;
1081 pfedge
->rflow
-= increment
;
1082 r_pfedge
->rflow
+= increment
;
1086 /* backward edge. */
1087 gcc_assert (r_pfedge
->type
);
1088 r_pfedge
->rflow
+= increment
;
1089 r_pfedge
->flow
-= increment
;
1090 pfedge
->rflow
-= increment
;
1096 fprintf (dump_file
, "\nDump augmenting path:\n");
1097 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1099 print_basic_block (dump_file
, fixup_graph
, u
);
1100 fprintf (dump_file
, "<-");
1103 "ENTRY (path_capacity=%" PRId64
")\n",
1106 "Network flow is %" PRId64
".\n",
1111 free_augmenting_path (&augmenting_path
);
1113 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1118 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1119 after applying the find_minimum_cost_flow() routine. */
1122 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1128 fixup_edge_p pfedge
, pfedge_n
;
1130 gcc_assert (fixup_graph
);
1133 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1135 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
),
1136 EXIT_BLOCK_PTR_FOR_FN (cfun
), next_bb
)
1143 "BB%d: %" PRId64
"", bb
->index
, bb
->count
);
1145 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1148 bb
->count
+= pfedge
->flow
;
1151 fprintf (dump_file
, " + %" PRId64
"(",
1153 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1154 fprintf (dump_file
, ")");
1159 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1160 /* Deduct flow from normalized reverse edge. */
1161 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1163 bb
->count
-= pfedge_n
->flow
;
1166 fprintf (dump_file
, " - %" PRId64
"(",
1168 print_edge (dump_file
, fixup_graph
, i
+ 1,
1169 pfedge
->norm_vertex_index
);
1170 fprintf (dump_file
, ")");
1174 fprintf (dump_file
, " = %" PRId64
"\n", bb
->count
);
1177 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1179 /* Treat edges with ignore attribute set as if they don't exist. */
1180 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1183 j
= 2 * e
->dest
->index
;
1185 fprintf (dump_file
, "%d->%d: %" PRId64
"",
1186 bb
->index
, e
->dest
->index
, e
->count
);
1188 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1190 if (bb
->index
!= e
->dest
->index
)
1192 /* Non-self edge. */
1195 e
->count
+= pfedge
->flow
;
1198 fprintf (dump_file
, " + %" PRId64
"(",
1200 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1201 fprintf (dump_file
, ")");
1206 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1207 /* Deduct flow from normalized reverse edge. */
1208 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1210 e
->count
-= pfedge_n
->flow
;
1213 fprintf (dump_file
, " - %" PRId64
"(",
1215 print_edge (dump_file
, fixup_graph
, j
,
1216 pfedge
->norm_vertex_index
);
1217 fprintf (dump_file
, ")");
1223 /* Handle self edges. Self edge is split with a normalization
1224 vertex. Here i=j. */
1225 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1227 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1228 e
->count
+= pfedge_n
->flow
;
1229 bb
->count
+= pfedge_n
->flow
;
1232 fprintf (dump_file
, "(self edge)");
1233 fprintf (dump_file
, " + %" PRId64
"(",
1235 print_edge (dump_file
, fixup_graph
, i
+ 1,
1236 pfedge
->norm_vertex_index
);
1237 fprintf (dump_file
, ")");
1242 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1244 fprintf (dump_file
, " = %" PRId64
"\t(%.1f%%)\n",
1245 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1249 ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
=
1250 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun
)->succs
);
1251 EXIT_BLOCK_PTR_FOR_FN (cfun
)->count
=
1252 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
);
1254 /* Compute edge probabilities. */
1255 FOR_ALL_BB_FN (bb
, cfun
)
1259 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1260 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1265 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1266 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1270 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1272 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1273 e
->probability
= REG_BR_PROB_BASE
/ total
;
1280 total
+= EDGE_COUNT (bb
->succs
);
1281 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1282 e
->probability
= REG_BR_PROB_BASE
/ total
;
1289 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1290 current_function_name ());
1291 FOR_EACH_BB_FN (bb
, cfun
)
1293 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1294 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1297 "BB%d(%" PRId64
") **INVALID**: ",
1298 bb
->index
, bb
->count
);
1300 "******** BB%d(%" PRId64
1301 ") **INVALID**: \n", bb
->index
, bb
->count
);
1302 fprintf (dump_file
, "in_edges=%" PRId64
" ",
1303 sum_edge_counts (bb
->preds
));
1304 fprintf (dump_file
, "out_edges=%" PRId64
"\n",
1305 sum_edge_counts (bb
->succs
));
1312 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1315 1. Find maximal flow.
1316 2. Form residual network
1318 While G contains a negative cost cycle C, reverse the flow on the found cycle
1319 by the minimum residual capacity in that cycle.
1320 4. Form the minimal cost flow
1323 FIXUP_GRAPH - Initial fixup graph.
1324 The flow field is modified to represent the minimum cost flow. */
1327 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1329 /* Holds the index of predecessor in path. */
1331 /* Used to hold the minimum cost cycle. */
1333 /* Used to record the number of iterations of cancel_negative_cycle. */
1335 /* Vector d[i] holds the minimum cost of path from i to sink. */
1339 int new_entry_index
;
1341 gcc_assert (fixup_graph
);
1342 fnum_vertices
= fixup_graph
->num_vertices
;
1343 new_exit_index
= fixup_graph
->new_exit_index
;
1344 new_entry_index
= fixup_graph
->new_entry_index
;
1346 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1348 /* Initialize the structures for find_negative_cycle(). */
1349 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1350 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1351 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1353 /* Repeatedly find and cancel negative cost cycles, until
1354 no more negative cycles exist. This also updates the flow field
1355 to represent the minimum cost flow so far. */
1357 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1360 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1361 fixup_graph
->num_edges
))
1366 dump_fixup_graph (dump_file
, fixup_graph
,
1367 "After find_minimum_cost_flow()");
1369 /* Cleanup structures. */
1376 /* Compute the sum of the edge counts in TO_EDGES. */
1379 sum_edge_counts (vec
<edge
, va_gc
> *to_edges
)
1385 FOR_EACH_EDGE (e
, ei
, to_edges
)
1387 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1395 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1396 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1397 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1401 mcf_smooth_cfg (void)
1403 fixup_graph_type fixup_graph
;
1404 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1405 create_fixup_graph (&fixup_graph
);
1406 find_minimum_cost_flow (&fixup_graph
);
1407 adjust_cfg_counts (&fixup_graph
);
1408 delete_fixup_graph (&fixup_graph
);