1 /* Routines to implement minimum-cost maximal flow algorithm used to smooth
2 basic block and edge frequency counts.
3 Copyright (C) 2008, 2009
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
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
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/>. */
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;
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.
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
40 5. Form the minimal cost flow
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). */
48 #include "coretypes.h"
49 #include "basic-block.h"
54 /* CAP_INFINITY: Constant to represent infinite capacity. */
55 #define CAP_INFINITY INTTYPE_MAXIMUM (HOST_WIDEST_INT)
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)))
67 VERTEX_SPLIT_EDGE
, /* Edge to represent vertex with w(e) = w(v). */
68 REDIRECT_EDGE
, /* Edge after vertex transformation. */
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. */
77 /* Structure to represent an edge in the fixup graph. */
78 typedef struct fixup_edge_d
82 /* Flag denoting type of edge and attributes for the flow field. */
85 /* Index to the normalization vertex added for this edge. */
86 int norm_vertex_index
;
87 /* Flow for this edge. */
89 /* Residual flow for this edge - used during negative cycle canceling. */
93 gcov_type max_capacity
;
96 typedef fixup_edge_type
*fixup_edge_p
;
98 DEF_VEC_P (fixup_edge_p
);
99 DEF_VEC_ALLOC_P (fixup_edge_p
, heap
);
101 /* Structure to represent a vertex in the fixup graph. */
102 typedef struct fixup_vertex_d
104 VEC (fixup_edge_p
, heap
) *succ_edges
;
107 typedef fixup_vertex_type
*fixup_vertex_p
;
109 /* Fixup graph used in the MCF algorithm. */
110 typedef struct fixup_graph_d
112 /* Current number of vertices for the graph. */
114 /* Current number of edges for the graph. */
116 /* Index of new entry vertex. */
118 /* Index of new exit vertex. */
120 /* Fixup vertex list. Adjacency list for fixup graph. */
121 fixup_vertex_p vertex_list
;
122 /* Fixup edge list. */
123 fixup_edge_p edge_list
;
126 typedef struct queue_d
134 /* Structure used in the maximal flow routines to find augmenting path. */
135 typedef struct augmenting_path_d
137 /* Queue used to hold vertex indices. */
138 queue_type queue_list
;
139 /* Vector to hold chain of pred vertex indices in augmenting path. */
141 /* Vector that indicates if basic block i has been visited. */
143 } augmenting_path_type
;
146 /* Function definitions. */
148 /* Dump routines to aid debugging. */
150 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
153 print_basic_block (FILE *file
, fixup_graph_type
*fixup_graph
, int n
)
155 if (n
== ENTRY_BLOCK
)
156 fputs ("ENTRY", file
);
157 else if (n
== ENTRY_BLOCK
+ 1)
158 fputs ("ENTRY''", file
);
159 else if (n
== 2 * EXIT_BLOCK
)
160 fputs ("EXIT", file
);
161 else if (n
== 2 * EXIT_BLOCK
+ 1)
162 fputs ("EXIT''", file
);
163 else if (n
== fixup_graph
->new_exit_index
)
164 fputs ("NEW_EXIT", file
);
165 else if (n
== fixup_graph
->new_entry_index
)
166 fputs ("NEW_ENTRY", file
);
169 fprintf (file
, "%d", n
/ 2);
178 /* Print edge S->D for given fixup_graph with n' and n'' format.
180 S is the index of the source vertex of the edge (input) and
181 D is the index of the destination vertex of the edge (input) for the given
182 fixup_graph (input). */
185 print_edge (FILE *file
, fixup_graph_type
*fixup_graph
, int s
, int d
)
187 print_basic_block (file
, fixup_graph
, s
);
189 print_basic_block (file
, fixup_graph
, d
);
193 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
196 dump_fixup_edge (FILE *file
, fixup_graph_type
*fixup_graph
, fixup_edge_p fedge
)
200 fputs ("NULL fixup graph edge.\n", file
);
204 print_edge (file
, fixup_graph
, fedge
->src
, fedge
->dest
);
209 fprintf (file
, "flow/capacity=" HOST_WIDEST_INT_PRINT_DEC
"/",
211 if (fedge
->max_capacity
== CAP_INFINITY
)
212 fputs ("+oo,", file
);
214 fprintf (file
, "" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->max_capacity
);
217 if (fedge
->is_rflow_valid
)
219 if (fedge
->rflow
== CAP_INFINITY
)
220 fputs (" rflow=+oo.", file
);
222 fprintf (file
, " rflow=" HOST_WIDEST_INT_PRINT_DEC
",", fedge
->rflow
);
225 fprintf (file
, " cost=" HOST_WIDEST_INT_PRINT_DEC
".", fedge
->cost
);
227 fprintf (file
, "\t(%d->%d)", fedge
->src
, fedge
->dest
);
233 case VERTEX_SPLIT_EDGE
:
234 fputs (" @VERTEX_SPLIT_EDGE", file
);
238 fputs (" @REDIRECT_EDGE", file
);
241 case SOURCE_CONNECT_EDGE
:
242 fputs (" @SOURCE_CONNECT_EDGE", file
);
245 case SINK_CONNECT_EDGE
:
246 fputs (" @SINK_CONNECT_EDGE", file
);
250 fputs (" @REVERSE_EDGE", file
);
254 fputs (" @BALANCE_EDGE", file
);
257 case REDIRECT_NORMALIZED_EDGE
:
258 case REVERSE_NORMALIZED_EDGE
:
259 fputs (" @NORMALIZED_EDGE", file
);
263 fputs (" @INVALID_EDGE", file
);
271 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
272 file. The input string MSG is printed out as a heading. */
275 dump_fixup_graph (FILE *file
, fixup_graph_type
*fixup_graph
, const char *msg
)
278 int fnum_vertices
, fnum_edges
;
280 fixup_vertex_p fvertex_list
, pfvertex
;
283 gcc_assert (fixup_graph
);
284 fvertex_list
= fixup_graph
->vertex_list
;
285 fnum_vertices
= fixup_graph
->num_vertices
;
286 fnum_edges
= fixup_graph
->num_edges
;
288 fprintf (file
, "\nDump fixup graph for %s(): %s.\n",
289 current_function_name (), msg
);
291 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
292 fnum_vertices
, fnum_edges
, fixup_graph
->new_exit_index
);
294 for (i
= 0; i
< fnum_vertices
; i
++)
296 pfvertex
= fvertex_list
+ i
;
297 fprintf (file
, "vertex_list[%d]: %d succ fixup edges.\n",
298 i
, VEC_length (fixup_edge_p
, pfvertex
->succ_edges
));
300 for (j
= 0; VEC_iterate (fixup_edge_p
, pfvertex
->succ_edges
, j
, pfedge
);
303 /* Distinguish forward edges and backward edges in the residual flow
306 fputs ("(f) ", file
);
307 else if (pfedge
->is_rflow_valid
)
308 fputs ("(b) ", file
);
309 dump_fixup_edge (file
, fixup_graph
, pfedge
);
317 /* Utility routines. */
318 /* ln() implementation: approximate calculation. Returns ln of X. */
339 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
340 implementation) by John Carmack. Returns sqrt of X. */
345 #define MAGIC_CONST1 0x1fbcf800
346 #define MAGIC_CONST2 0x5f3759df
350 } convertor
, convertor2
;
354 convertor
.floatPart
= x
;
355 convertor2
.floatPart
= x
;
356 convertor
.intPart
= MAGIC_CONST1
+ (convertor
.intPart
>> 1);
357 convertor2
.intPart
= MAGIC_CONST2
- (convertor2
.intPart
>> 1);
359 return 0.5f
* (convertor
.floatPart
+ (x
* convertor2
.floatPart
));
363 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
364 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
365 added set to COST. */
368 add_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, gcov_type cost
)
370 fixup_vertex_p curr_vertex
= fixup_graph
->vertex_list
+ src
;
371 fixup_edge_p curr_edge
= fixup_graph
->edge_list
+ fixup_graph
->num_edges
;
372 curr_edge
->src
= src
;
373 curr_edge
->dest
= dest
;
374 curr_edge
->cost
= cost
;
375 fixup_graph
->num_edges
++;
377 dump_fixup_edge (dump_file
, fixup_graph
, curr_edge
);
378 VEC_safe_push (fixup_edge_p
, heap
, curr_vertex
->succ_edges
, curr_edge
);
383 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
384 MAX_CAPACITY to the edge_list in the fixup graph. */
387 add_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
388 edge_type type
, gcov_type weight
, gcov_type cost
,
389 gcov_type max_capacity
)
391 fixup_edge_p curr_edge
= add_edge(fixup_graph
, src
, dest
, cost
);
392 curr_edge
->type
= type
;
393 curr_edge
->weight
= weight
;
394 curr_edge
->max_capacity
= max_capacity
;
398 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
399 to the fixup graph. */
402 add_rfixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
403 gcov_type rflow
, gcov_type cost
)
405 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
406 curr_edge
->rflow
= rflow
;
407 curr_edge
->is_rflow_valid
= true;
408 /* This edge is not a valid edge - merely used to hold residual flow. */
409 curr_edge
->type
= INVALID_EDGE
;
413 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
414 exist in the FIXUP_GRAPH. */
417 find_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
)
421 fixup_vertex_p pfvertex
;
423 gcc_assert (src
< fixup_graph
->num_vertices
);
425 pfvertex
= fixup_graph
->vertex_list
+ src
;
427 for (j
= 0; VEC_iterate (fixup_edge_p
, pfvertex
->succ_edges
, j
, pfedge
);
429 if (pfedge
->dest
== dest
)
436 /* Cleanup routine to free structures in FIXUP_GRAPH. */
439 delete_fixup_graph (fixup_graph_type
*fixup_graph
)
442 int fnum_vertices
= fixup_graph
->num_vertices
;
443 fixup_vertex_p pfvertex
= fixup_graph
->vertex_list
;
445 for (i
= 0; i
< fnum_vertices
; i
++, pfvertex
++)
446 VEC_free (fixup_edge_p
, heap
, pfvertex
->succ_edges
);
448 free (fixup_graph
->vertex_list
);
449 free (fixup_graph
->edge_list
);
453 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
456 create_fixup_graph (fixup_graph_type
*fixup_graph
)
458 double sqrt_avg_vertex_weight
= 0;
459 double total_vertex_weight
= 0;
462 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
463 gcov_type
*diff_out_in
= NULL
;
464 gcov_type supply_value
= 1, demand_value
= 0;
466 int new_entry_index
= 0, new_exit_index
= 0;
472 fixup_edge_p pfedge
, r_pfedge
;
473 fixup_edge_p fedge_list
;
476 /* Each basic_block will be split into 2 during vertex transformation. */
477 int fnum_vertices_after_transform
= 2 * n_basic_blocks
;
478 int fnum_edges_after_transform
= n_edges
+ n_basic_blocks
;
480 /* Count the new SOURCE and EXIT vertices to be added. */
481 int fmax_num_vertices
=
482 fnum_vertices_after_transform
+ n_edges
+ n_basic_blocks
+ 2;
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
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. */
492 int fmax_num_edges
= 8 * (n_basic_blocks
+ n_edges
);
494 /* Initial num of vertices in the fixup graph. */
495 fixup_graph
->num_vertices
= n_basic_blocks
;
497 /* Fixup graph vertex list. */
498 fixup_graph
->vertex_list
=
499 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
501 /* Fixup graph edge list. */
502 fixup_graph
->edge_list
=
503 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
506 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
509 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
510 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
511 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
512 total_vertex_weight
+= bb
->count
;
514 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/ n_basic_blocks
);
516 k_pos
= K_POS (sqrt_avg_vertex_weight
);
517 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
519 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
520 connected by an edge e from v' to v''. w(e) = w(v). */
523 fprintf (dump_file
, "\nVertex transformation:\n");
525 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
527 /* v'->v'': index1->(index1+1). */
529 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
530 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
531 fcost
, CAP_INFINITY
);
532 fixup_graph
->num_vertices
++;
534 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
536 /* Edges with ignore attribute set should be treated like they don't
538 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
540 j
= 2 * e
->dest
->index
;
541 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
542 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
547 /* After vertex transformation. */
548 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
549 /* Redirect edges are not added for edges with ignore attribute. */
550 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
552 fnum_edges_after_transform
= fixup_graph
->num_edges
;
554 /* 2. Initialize D(v). */
555 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
557 pfedge
= fixup_graph
->edge_list
+ i
;
558 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
559 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
562 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
563 for (i
= 0; i
<= 3; i
++)
566 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
568 fprintf (dump_file
, "\nReverse edges:\n");
569 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
571 pfedge
= fixup_graph
->edge_list
+ i
;
572 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
574 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
575 if (!r_pfedge
&& pfedge
->weight
)
577 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
579 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
580 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
581 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
585 /* 4. Create single source and sink. Connect new source vertex s' to function
586 entry block. Connect sink vertex t' to function exit. */
588 fprintf (dump_file
, "\ns'->S, T->t':\n");
590 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
591 fixup_graph
->num_vertices
++;
592 /* Set supply_value to 1 to avoid zero count function ENTRY. */
593 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
594 1 /* supply_value */, 0, 1 /* supply_value */);
596 /* Create new exit with EXIT_BLOCK as single pred. */
597 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
598 fixup_graph
->num_vertices
++;
599 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
601 0 /* demand_value */, 0, 0 /* demand_value */);
603 /* Connect vertices with unbalanced D(v) to source/sink. */
605 fprintf (dump_file
, "\nD(v) balance:\n");
606 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
607 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
608 for (i
= 4; i
< new_entry_index
; i
+= 2)
610 if (diff_out_in
[i
] > 0)
612 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
614 demand_value
+= diff_out_in
[i
];
616 else if (diff_out_in
[i
] < 0)
618 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
620 supply_value
-= diff_out_in
[i
];
624 /* Set supply = demand. */
627 fprintf (dump_file
, "\nAdjust supply and demand:\n");
628 fprintf (dump_file
, "supply_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
630 fprintf (dump_file
, "demand_value=" HOST_WIDEST_INT_PRINT_DEC
"\n",
634 if (demand_value
> supply_value
)
636 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
637 pfedge
->max_capacity
+= (demand_value
- supply_value
);
641 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
642 pfedge
->max_capacity
+= (supply_value
- demand_value
);
645 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
646 created by the vertex transformation step from self-edges in the original
647 CFG and by the reverse edges added earlier. */
649 fprintf (dump_file
, "\nNormalize edges:\n");
651 fnum_edges
= fixup_graph
->num_edges
;
652 fedge_list
= fixup_graph
->edge_list
;
654 for (i
= 0; i
< fnum_edges
; i
++)
656 pfedge
= fedge_list
+ i
;
657 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
658 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
659 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
661 new_index
= fixup_graph
->num_vertices
;
662 fixup_graph
->num_vertices
++;
666 fprintf (dump_file
, "\nAnti-parallel edge:\n");
667 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
668 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
669 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
670 fprintf (dump_file
, "------------------\n");
674 pfedge
->norm_vertex_index
= new_index
;
677 fprintf (dump_file
, "After normalization:\n");
678 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
681 /* Add a new fixup edge: new_index->src. */
682 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
683 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
684 r_pfedge
->max_capacity
);
685 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
687 /* Edge: r_pfedge->src -> r_pfedge->dest
688 ==> r_pfedge->src -> new_index. */
689 r_pfedge
->dest
= new_index
;
690 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
691 r_pfedge
->cost
= pfedge
->cost
;
692 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
694 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
699 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
706 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
707 proportional to the number of nodes in the graph, which is given by
711 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
713 augmenting_path
->queue_list
.queue
= (int *)
714 xcalloc (graph_size
+ 2, sizeof (int));
715 augmenting_path
->queue_list
.size
= graph_size
+ 2;
716 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
717 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
720 /* Free the structures in AUGMENTING_PATH. */
722 free_augmenting_path (augmenting_path_type
*augmenting_path
)
724 free (augmenting_path
->queue_list
.queue
);
725 free (augmenting_path
->bb_pred
);
726 free (augmenting_path
->is_visited
);
730 /* Queue routines. Assumes queue will never overflow. */
733 init_queue (queue_type
*queue_list
)
735 gcc_assert (queue_list
);
736 queue_list
->head
= 0;
737 queue_list
->tail
= 0;
740 /* Return true if QUEUE_LIST is empty. */
742 is_empty (queue_type
*queue_list
)
744 return (queue_list
->head
== queue_list
->tail
);
747 /* Insert element X into QUEUE_LIST. */
749 enqueue (queue_type
*queue_list
, int x
)
751 gcc_assert (queue_list
->tail
< queue_list
->size
);
752 queue_list
->queue
[queue_list
->tail
] = x
;
753 (queue_list
->tail
)++;
756 /* Return the first element in QUEUE_LIST. */
758 dequeue (queue_type
*queue_list
)
761 gcc_assert (queue_list
->head
>= 0);
762 x
= queue_list
->queue
[queue_list
->head
];
763 (queue_list
->head
)++;
768 /* Finds a negative cycle in the residual network using
769 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
770 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
774 FIXUP_GRAPH - Residual graph (input/output)
775 The following are allocated/freed by the caller:
776 PI - Vector to hold predecessors in path (pi = pred index)
777 D - D[I] holds minimum cost of path from i to sink
778 CYCLE - Vector to hold the minimum cost cycle
781 true if a negative cycle was found, false otherwise. */
784 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
785 int *pi
, gcov_type
*d
, int *cycle
)
788 int fnum_vertices
, fnum_edges
;
789 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
790 bool found_cycle
= false;
791 int cycle_start
= 0, cycle_end
= 0;
792 gcov_type sum_cost
= 0, cycle_flow
= 0;
794 bool propagated
= false;
796 gcc_assert (fixup_graph
);
797 fnum_vertices
= fixup_graph
->num_vertices
;
798 fnum_edges
= fixup_graph
->num_edges
;
799 fedge_list
= fixup_graph
->edge_list
;
800 new_entry_index
= fixup_graph
->new_entry_index
;
804 for (i
= 1; i
< fnum_vertices
; i
++)
813 for (k
= 1; k
< fnum_vertices
; k
++)
816 for (i
= 0; i
< fnum_edges
; i
++)
818 pfedge
= fedge_list
+ i
;
819 if (pfedge
->src
== new_entry_index
)
821 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
822 && d
[pfedge
->src
] != CAP_INFINITY
823 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
825 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
826 pi
[pfedge
->dest
] = pfedge
->src
;
835 /* No negative cycles exist. */
839 for (i
= 0; i
< fnum_edges
; i
++)
841 pfedge
= fedge_list
+ i
;
842 if (pfedge
->src
== new_entry_index
)
844 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
845 && d
[pfedge
->src
] != CAP_INFINITY
846 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
856 /* Augment the cycle with the cycle's minimum residual capacity. */
858 cycle
[0] = pfedge
->dest
;
861 for (i
= 1; i
< fnum_vertices
; i
++)
865 for (k
= 0; k
< i
; k
++)
869 /* cycle[k] -> ... -> cycle[i]. */
880 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
882 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
883 cycle_end
- cycle_start
);
886 cycle_flow
= CAP_INFINITY
;
887 for (k
= cycle_start
; k
< cycle_end
; k
++)
889 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
890 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
891 sum_cost
+= pfedge
->cost
;
893 fprintf (dump_file
, "%d ", cycle
[k
]);
898 fprintf (dump_file
, "%d", cycle
[k
]);
900 ": (" HOST_WIDEST_INT_PRINT_DEC
", " HOST_WIDEST_INT_PRINT_DEC
901 ")\n", sum_cost
, cycle_flow
);
903 "Augment cycle with " HOST_WIDEST_INT_PRINT_DEC
"\n",
907 for (k
= cycle_start
; k
< cycle_end
; k
++)
909 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
910 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
911 pfedge
->rflow
-= cycle_flow
;
913 pfedge
->flow
+= cycle_flow
;
914 r_pfedge
->rflow
+= cycle_flow
;
916 r_pfedge
->flow
-= cycle_flow
;
923 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
924 the edges. ENTRY and EXIT vertices should not be considered. */
927 compute_residual_flow (fixup_graph_type
*fixup_graph
)
931 fixup_edge_p fedge_list
, pfedge
;
933 gcc_assert (fixup_graph
);
936 fputs ("\ncompute_residual_flow():\n", dump_file
);
938 fnum_edges
= fixup_graph
->num_edges
;
939 fedge_list
= fixup_graph
->edge_list
;
941 for (i
= 0; i
< fnum_edges
; i
++)
943 pfedge
= fedge_list
+ i
;
944 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
945 pfedge
->is_rflow_valid
= true;
946 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
952 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
953 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
954 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
955 to reflect the path found.
956 Returns: 0 if no augmenting path is found, 1 otherwise. */
959 find_augmenting_path (fixup_graph_type
*fixup_graph
,
960 augmenting_path_type
*augmenting_path
, int source
,
965 fixup_vertex_p fvertex_list
, pfvertex
;
967 int *bb_pred
, *is_visited
;
968 queue_type
*queue_list
;
970 gcc_assert (augmenting_path
);
971 bb_pred
= augmenting_path
->bb_pred
;
972 gcc_assert (bb_pred
);
973 is_visited
= augmenting_path
->is_visited
;
974 gcc_assert (is_visited
);
975 queue_list
= &(augmenting_path
->queue_list
);
977 gcc_assert (fixup_graph
);
979 fvertex_list
= fixup_graph
->vertex_list
;
981 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
984 init_queue (queue_list
);
985 enqueue (queue_list
, source
);
986 bb_pred
[source
] = -1;
988 while (!is_empty (queue_list
))
990 u
= dequeue (queue_list
);
992 pfvertex
= fvertex_list
+ u
;
993 for (i
= 0; VEC_iterate (fixup_edge_p
, pfvertex
->succ_edges
, i
, pfedge
);
996 int dest
= pfedge
->dest
;
997 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
999 enqueue (queue_list
, dest
);
1001 is_visited
[dest
] = 1;
1012 /* Routine to find the maximal flow:
1014 1. Initialize flow to 0
1015 2. Find an augmenting path form source to sink.
1016 3. Send flow equal to the path's residual capacity along the edges of this path.
1017 4. Repeat steps 2 and 3 until no new augmenting path is found.
1020 SOURCE: index of source vertex (input)
1021 SINK: index of sink vertex (input)
1022 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1023 set to have a valid maximal flow by this routine. (input)
1024 Return: Maximum flow possible. */
1027 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1030 augmenting_path_type augmenting_path
;
1032 gcov_type max_flow
= 0;
1034 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1036 gcc_assert (fixup_graph
);
1038 fnum_edges
= fixup_graph
->num_edges
;
1039 fedge_list
= fixup_graph
->edge_list
;
1041 /* Initialize flow to 0. */
1042 for (i
= 0; i
< fnum_edges
; i
++)
1044 pfedge
= fedge_list
+ i
;
1048 compute_residual_flow (fixup_graph
);
1050 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1052 bb_pred
= augmenting_path
.bb_pred
;
1053 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1055 /* Determine the amount by which we can increment the flow. */
1056 gcov_type increment
= CAP_INFINITY
;
1057 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1059 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1060 increment
= MIN (increment
, pfedge
->rflow
);
1062 max_flow
+= increment
;
1064 /* Now increment the flow. EXIT vertex index is 1. */
1065 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1067 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1068 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1072 pfedge
->flow
+= increment
;
1073 pfedge
->rflow
-= increment
;
1074 r_pfedge
->rflow
+= increment
;
1078 /* backward edge. */
1079 gcc_assert (r_pfedge
->type
);
1080 r_pfedge
->rflow
+= increment
;
1081 r_pfedge
->flow
-= increment
;
1082 pfedge
->rflow
-= increment
;
1088 fprintf (dump_file
, "\nDump augmenting path:\n");
1089 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1091 print_basic_block (dump_file
, fixup_graph
, u
);
1092 fprintf (dump_file
, "<-");
1095 "ENTRY (path_capacity=" HOST_WIDEST_INT_PRINT_DEC
")\n",
1098 "Network flow is " HOST_WIDEST_INT_PRINT_DEC
".\n",
1103 free_augmenting_path (&augmenting_path
);
1105 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1110 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1111 after applying the find_minimum_cost_flow() routine. */
1114 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1120 fixup_edge_p pfedge
, pfedge_n
;
1122 gcc_assert (fixup_graph
);
1125 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1127 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, EXIT_BLOCK_PTR
, next_bb
)
1134 "BB%d: " HOST_WIDEST_INT_PRINT_DEC
"", bb
->index
, bb
->count
);
1136 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1139 bb
->count
+= pfedge
->flow
;
1142 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1144 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1145 fprintf (dump_file
, ")");
1150 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1151 /* Deduct flow from normalized reverse edge. */
1152 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1154 bb
->count
-= pfedge_n
->flow
;
1157 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1159 print_edge (dump_file
, fixup_graph
, i
+ 1,
1160 pfedge
->norm_vertex_index
);
1161 fprintf (dump_file
, ")");
1165 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\n", bb
->count
);
1168 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1170 /* Treat edges with ignore attribute set as if they don't exist. */
1171 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1174 j
= 2 * e
->dest
->index
;
1176 fprintf (dump_file
, "%d->%d: " HOST_WIDEST_INT_PRINT_DEC
"",
1177 bb
->index
, e
->dest
->index
, e
->count
);
1179 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1181 if (bb
->index
!= e
->dest
->index
)
1183 /* Non-self edge. */
1186 e
->count
+= pfedge
->flow
;
1189 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1191 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1192 fprintf (dump_file
, ")");
1197 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1198 /* Deduct flow from normalized reverse edge. */
1199 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1201 e
->count
-= pfedge_n
->flow
;
1204 fprintf (dump_file
, " - " HOST_WIDEST_INT_PRINT_DEC
"(",
1206 print_edge (dump_file
, fixup_graph
, j
,
1207 pfedge
->norm_vertex_index
);
1208 fprintf (dump_file
, ")");
1214 /* Handle self edges. Self edge is split with a normalization
1215 vertex. Here i=j. */
1216 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1218 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1219 e
->count
+= pfedge_n
->flow
;
1220 bb
->count
+= pfedge_n
->flow
;
1223 fprintf (dump_file
, "(self edge)");
1224 fprintf (dump_file
, " + " HOST_WIDEST_INT_PRINT_DEC
"(",
1226 print_edge (dump_file
, fixup_graph
, i
+ 1,
1227 pfedge
->norm_vertex_index
);
1228 fprintf (dump_file
, ")");
1233 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1235 fprintf (dump_file
, " = " HOST_WIDEST_INT_PRINT_DEC
"\t(%.1f%%)\n",
1236 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1240 ENTRY_BLOCK_PTR
->count
= sum_edge_counts (ENTRY_BLOCK_PTR
->succs
);
1241 EXIT_BLOCK_PTR
->count
= sum_edge_counts (EXIT_BLOCK_PTR
->preds
);
1243 /* Compute edge probabilities. */
1248 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1249 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1254 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1255 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1259 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1261 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1262 e
->probability
= REG_BR_PROB_BASE
/ total
;
1269 total
+= EDGE_COUNT (bb
->succs
);
1270 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1271 e
->probability
= REG_BR_PROB_BASE
/ total
;
1278 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1279 current_function_name ());
1282 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1283 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1286 "BB%d(" HOST_WIDEST_INT_PRINT_DEC
") **INVALID**: ",
1287 bb
->index
, bb
->count
);
1289 "******** BB%d(" HOST_WIDEST_INT_PRINT_DEC
1290 ") **INVALID**: \n", bb
->index
, bb
->count
);
1291 fprintf (dump_file
, "in_edges=" HOST_WIDEST_INT_PRINT_DEC
" ",
1292 sum_edge_counts (bb
->preds
));
1293 fprintf (dump_file
, "out_edges=" HOST_WIDEST_INT_PRINT_DEC
"\n",
1294 sum_edge_counts (bb
->succs
));
1301 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1304 1. Find maximal flow.
1305 2. Form residual network
1307 While G contains a negative cost cycle C, reverse the flow on the found cycle
1308 by the minimum residual capacity in that cycle.
1309 4. Form the minimal cost flow
1312 FIXUP_GRAPH - Initial fixup graph.
1313 The flow field is modified to represent the minimum cost flow. */
1316 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1318 /* Holds the index of predecessor in path. */
1320 /* Used to hold the minimum cost cycle. */
1322 /* Used to record the number of iterations of cancel_negative_cycle. */
1324 /* Vector d[i] holds the minimum cost of path from i to sink. */
1328 int new_entry_index
;
1330 gcc_assert (fixup_graph
);
1331 fnum_vertices
= fixup_graph
->num_vertices
;
1332 new_exit_index
= fixup_graph
->new_exit_index
;
1333 new_entry_index
= fixup_graph
->new_entry_index
;
1335 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1337 /* Initialize the structures for find_negative_cycle(). */
1338 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1339 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1340 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1342 /* Repeatedly find and cancel negative cost cycles, until
1343 no more negative cycles exist. This also updates the flow field
1344 to represent the minimum cost flow so far. */
1346 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1349 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1350 fixup_graph
->num_edges
))
1355 dump_fixup_graph (dump_file
, fixup_graph
,
1356 "After find_minimum_cost_flow()");
1358 /* Cleanup structures. */
1365 /* Compute the sum of the edge counts in TO_EDGES. */
1368 sum_edge_counts (VEC (edge
, gc
) *to_edges
)
1374 FOR_EACH_EDGE (e
, ei
, to_edges
)
1376 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1384 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1385 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1386 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1390 mcf_smooth_cfg (void)
1392 fixup_graph_type fixup_graph
;
1393 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1394 create_fixup_graph (&fixup_graph
);
1395 find_minimum_cost_flow (&fixup_graph
);
1396 adjust_cfg_counts (&fixup_graph
);
1397 delete_fixup_graph (&fixup_graph
);