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"
52 #include "dominance.h"
54 #include "basic-block.h"
59 /* CAP_INFINITY: Constant to represent infinite capacity. */
60 #define CAP_INFINITY INTTYPE_MAXIMUM (int64_t)
63 #define K_POS(b) ((b))
64 #define K_NEG(b) (50 * (b))
65 #define COST(k, w) ((k) / mcf_ln ((w) + 2))
66 /* Limit the number of iterations for cancel_negative_cycles() to ensure
67 reasonable compile time. */
68 #define MAX_ITER(n, e) 10 + (1000000 / ((n) * (e)))
72 VERTEX_SPLIT_EDGE
, /* Edge to represent vertex with w(e) = w(v). */
73 REDIRECT_EDGE
, /* Edge after vertex transformation. */
75 SOURCE_CONNECT_EDGE
, /* Single edge connecting to single source. */
76 SINK_CONNECT_EDGE
, /* Single edge connecting to single sink. */
77 BALANCE_EDGE
, /* Edge connecting with source/sink: cp(e) = 0. */
78 REDIRECT_NORMALIZED_EDGE
, /* Normalized edge for a redirect edge. */
79 REVERSE_NORMALIZED_EDGE
/* Normalized edge for a reverse edge. */
82 /* Structure to represent an edge in the fixup graph. */
83 typedef struct fixup_edge_d
87 /* Flag denoting type of edge and attributes for the flow field. */
90 /* Index to the normalization vertex added for this edge. */
91 int norm_vertex_index
;
92 /* Flow for this edge. */
94 /* Residual flow for this edge - used during negative cycle canceling. */
98 gcov_type max_capacity
;
101 typedef fixup_edge_type
*fixup_edge_p
;
104 /* Structure to represent a vertex in the fixup graph. */
105 typedef struct fixup_vertex_d
107 vec
<fixup_edge_p
> succ_edges
;
110 typedef fixup_vertex_type
*fixup_vertex_p
;
112 /* Fixup graph used in the MCF algorithm. */
113 typedef struct fixup_graph_d
115 /* Current number of vertices for the graph. */
117 /* Current number of edges for the graph. */
119 /* Index of new entry vertex. */
121 /* Index of new exit vertex. */
123 /* Fixup vertex list. Adjacency list for fixup graph. */
124 fixup_vertex_p vertex_list
;
125 /* Fixup edge list. */
126 fixup_edge_p edge_list
;
129 typedef struct queue_d
137 /* Structure used in the maximal flow routines to find augmenting path. */
138 typedef struct augmenting_path_d
140 /* Queue used to hold vertex indices. */
141 queue_type queue_list
;
142 /* Vector to hold chain of pred vertex indices in augmenting path. */
144 /* Vector that indicates if basic block i has been visited. */
146 } augmenting_path_type
;
149 /* Function definitions. */
151 /* Dump routines to aid debugging. */
153 /* Print basic block with index N for FIXUP_GRAPH in n' and n'' format. */
156 print_basic_block (FILE *file
, fixup_graph_type
*fixup_graph
, int n
)
158 if (n
== ENTRY_BLOCK
)
159 fputs ("ENTRY", file
);
160 else if (n
== ENTRY_BLOCK
+ 1)
161 fputs ("ENTRY''", file
);
162 else if (n
== 2 * EXIT_BLOCK
)
163 fputs ("EXIT", file
);
164 else if (n
== 2 * EXIT_BLOCK
+ 1)
165 fputs ("EXIT''", file
);
166 else if (n
== fixup_graph
->new_exit_index
)
167 fputs ("NEW_EXIT", file
);
168 else if (n
== fixup_graph
->new_entry_index
)
169 fputs ("NEW_ENTRY", file
);
172 fprintf (file
, "%d", n
/ 2);
181 /* Print edge S->D for given fixup_graph with n' and n'' format.
183 S is the index of the source vertex of the edge (input) and
184 D is the index of the destination vertex of the edge (input) for the given
185 fixup_graph (input). */
188 print_edge (FILE *file
, fixup_graph_type
*fixup_graph
, int s
, int d
)
190 print_basic_block (file
, fixup_graph
, s
);
192 print_basic_block (file
, fixup_graph
, d
);
196 /* Dump out the attributes of a given edge FEDGE in the fixup_graph to a
199 dump_fixup_edge (FILE *file
, fixup_graph_type
*fixup_graph
, fixup_edge_p fedge
)
203 fputs ("NULL fixup graph edge.\n", file
);
207 print_edge (file
, fixup_graph
, fedge
->src
, fedge
->dest
);
212 fprintf (file
, "flow/capacity=%" PRId64
"/",
214 if (fedge
->max_capacity
== CAP_INFINITY
)
215 fputs ("+oo,", file
);
217 fprintf (file
, "%" PRId64
",", fedge
->max_capacity
);
220 if (fedge
->is_rflow_valid
)
222 if (fedge
->rflow
== CAP_INFINITY
)
223 fputs (" rflow=+oo.", file
);
225 fprintf (file
, " rflow=%" PRId64
",", fedge
->rflow
);
228 fprintf (file
, " cost=%" PRId64
".", fedge
->cost
);
230 fprintf (file
, "\t(%d->%d)", fedge
->src
, fedge
->dest
);
236 case VERTEX_SPLIT_EDGE
:
237 fputs (" @VERTEX_SPLIT_EDGE", file
);
241 fputs (" @REDIRECT_EDGE", file
);
244 case SOURCE_CONNECT_EDGE
:
245 fputs (" @SOURCE_CONNECT_EDGE", file
);
248 case SINK_CONNECT_EDGE
:
249 fputs (" @SINK_CONNECT_EDGE", file
);
253 fputs (" @REVERSE_EDGE", file
);
257 fputs (" @BALANCE_EDGE", file
);
260 case REDIRECT_NORMALIZED_EDGE
:
261 case REVERSE_NORMALIZED_EDGE
:
262 fputs (" @NORMALIZED_EDGE", file
);
266 fputs (" @INVALID_EDGE", file
);
274 /* Print out the edges and vertices of the given FIXUP_GRAPH, into the dump
275 file. The input string MSG is printed out as a heading. */
278 dump_fixup_graph (FILE *file
, fixup_graph_type
*fixup_graph
, const char *msg
)
281 int fnum_vertices
, fnum_edges
;
283 fixup_vertex_p fvertex_list
, pfvertex
;
286 gcc_assert (fixup_graph
);
287 fvertex_list
= fixup_graph
->vertex_list
;
288 fnum_vertices
= fixup_graph
->num_vertices
;
289 fnum_edges
= fixup_graph
->num_edges
;
291 fprintf (file
, "\nDump fixup graph for %s(): %s.\n",
292 current_function_name (), msg
);
294 "There are %d vertices and %d edges. new_exit_index is %d.\n\n",
295 fnum_vertices
, fnum_edges
, fixup_graph
->new_exit_index
);
297 for (i
= 0; i
< fnum_vertices
; i
++)
299 pfvertex
= fvertex_list
+ i
;
300 fprintf (file
, "vertex_list[%d]: %d succ fixup edges.\n",
301 i
, pfvertex
->succ_edges
.length ());
303 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
306 /* Distinguish forward edges and backward edges in the residual flow
309 fputs ("(f) ", file
);
310 else if (pfedge
->is_rflow_valid
)
311 fputs ("(b) ", file
);
312 dump_fixup_edge (file
, fixup_graph
, pfedge
);
320 /* Utility routines. */
321 /* ln() implementation: approximate calculation. Returns ln of X. */
342 /* sqrt() implementation: based on open source QUAKE3 code (magic sqrt
343 implementation) by John Carmack. Returns sqrt of X. */
348 #define MAGIC_CONST1 0x1fbcf800
349 #define MAGIC_CONST2 0x5f3759df
353 } convertor
, convertor2
;
357 convertor
.floatPart
= x
;
358 convertor2
.floatPart
= x
;
359 convertor
.intPart
= MAGIC_CONST1
+ (convertor
.intPart
>> 1);
360 convertor2
.intPart
= MAGIC_CONST2
- (convertor2
.intPart
>> 1);
362 return 0.5f
* (convertor
.floatPart
+ (x
* convertor2
.floatPart
));
366 /* Common code shared between add_fixup_edge and add_rfixup_edge. Adds an edge
367 (SRC->DEST) to the edge_list maintained in FIXUP_GRAPH with cost of the edge
368 added set to COST. */
371 add_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
, gcov_type cost
)
373 fixup_vertex_p curr_vertex
= fixup_graph
->vertex_list
+ src
;
374 fixup_edge_p curr_edge
= fixup_graph
->edge_list
+ fixup_graph
->num_edges
;
375 curr_edge
->src
= src
;
376 curr_edge
->dest
= dest
;
377 curr_edge
->cost
= cost
;
378 fixup_graph
->num_edges
++;
380 dump_fixup_edge (dump_file
, fixup_graph
, curr_edge
);
381 curr_vertex
->succ_edges
.safe_push (curr_edge
);
386 /* Add a fixup edge (src->dest) with attributes TYPE, WEIGHT, COST and
387 MAX_CAPACITY to the edge_list in the fixup graph. */
390 add_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
391 edge_type type
, gcov_type weight
, gcov_type cost
,
392 gcov_type max_capacity
)
394 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
395 curr_edge
->type
= type
;
396 curr_edge
->weight
= weight
;
397 curr_edge
->max_capacity
= max_capacity
;
401 /* Add a residual edge (SRC->DEST) with attributes RFLOW and COST
402 to the fixup graph. */
405 add_rfixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
,
406 gcov_type rflow
, gcov_type cost
)
408 fixup_edge_p curr_edge
= add_edge (fixup_graph
, src
, dest
, cost
);
409 curr_edge
->rflow
= rflow
;
410 curr_edge
->is_rflow_valid
= true;
411 /* This edge is not a valid edge - merely used to hold residual flow. */
412 curr_edge
->type
= INVALID_EDGE
;
416 /* Return the pointer to fixup edge SRC->DEST or NULL if edge does not
417 exist in the FIXUP_GRAPH. */
420 find_fixup_edge (fixup_graph_type
*fixup_graph
, int src
, int dest
)
424 fixup_vertex_p pfvertex
;
426 gcc_assert (src
< fixup_graph
->num_vertices
);
428 pfvertex
= fixup_graph
->vertex_list
+ src
;
430 for (j
= 0; pfvertex
->succ_edges
.iterate (j
, &pfedge
);
432 if (pfedge
->dest
== dest
)
439 /* Cleanup routine to free structures in FIXUP_GRAPH. */
442 delete_fixup_graph (fixup_graph_type
*fixup_graph
)
445 int fnum_vertices
= fixup_graph
->num_vertices
;
446 fixup_vertex_p pfvertex
= fixup_graph
->vertex_list
;
448 for (i
= 0; i
< fnum_vertices
; i
++, pfvertex
++)
449 pfvertex
->succ_edges
.release ();
451 free (fixup_graph
->vertex_list
);
452 free (fixup_graph
->edge_list
);
456 /* Creates a fixup graph FIXUP_GRAPH from the function CFG. */
459 create_fixup_graph (fixup_graph_type
*fixup_graph
)
461 double sqrt_avg_vertex_weight
= 0;
462 double total_vertex_weight
= 0;
465 /* Vector to hold D(v) = sum_out_edges(v) - sum_in_edges(v). */
466 gcov_type
*diff_out_in
= NULL
;
467 gcov_type supply_value
= 1, demand_value
= 0;
469 int new_entry_index
= 0, new_exit_index
= 0;
475 fixup_edge_p pfedge
, r_pfedge
;
476 fixup_edge_p fedge_list
;
479 /* Each basic_block will be split into 2 during vertex transformation. */
480 int fnum_vertices_after_transform
= 2 * n_basic_blocks_for_fn (cfun
);
481 int fnum_edges_after_transform
=
482 n_edges_for_fn (cfun
) + n_basic_blocks_for_fn (cfun
);
484 /* Count the new SOURCE and EXIT vertices to be added. */
485 int fmax_num_vertices
=
486 (fnum_vertices_after_transform
+ n_edges_for_fn (cfun
)
487 + n_basic_blocks_for_fn (cfun
) + 2);
489 /* In create_fixup_graph: Each basic block and edge can be split into 3
490 edges. Number of balance edges = n_basic_blocks. So after
492 max_edges = 4 * n_basic_blocks + 3 * n_edges
493 Accounting for residual flow edges
494 max_edges = 2 * (4 * n_basic_blocks + 3 * n_edges)
495 = 8 * n_basic_blocks + 6 * n_edges
496 < 8 * n_basic_blocks + 8 * n_edges. */
497 int fmax_num_edges
= 8 * (n_basic_blocks_for_fn (cfun
) +
498 n_edges_for_fn (cfun
));
500 /* Initial num of vertices in the fixup graph. */
501 fixup_graph
->num_vertices
= n_basic_blocks_for_fn (cfun
);
503 /* Fixup graph vertex list. */
504 fixup_graph
->vertex_list
=
505 (fixup_vertex_p
) xcalloc (fmax_num_vertices
, sizeof (fixup_vertex_type
));
507 /* Fixup graph edge list. */
508 fixup_graph
->edge_list
=
509 (fixup_edge_p
) xcalloc (fmax_num_edges
, sizeof (fixup_edge_type
));
512 (gcov_type
*) xcalloc (1 + fnum_vertices_after_transform
,
515 /* Compute constants b, k_pos, k_neg used in the cost function calculation.
516 b = sqrt(avg_vertex_weight(cfg)); k_pos = b; k_neg = 50b. */
517 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
518 total_vertex_weight
+= bb
->count
;
520 sqrt_avg_vertex_weight
= mcf_sqrt (total_vertex_weight
/
521 n_basic_blocks_for_fn (cfun
));
523 k_pos
= K_POS (sqrt_avg_vertex_weight
);
524 k_neg
= K_NEG (sqrt_avg_vertex_weight
);
526 /* 1. Vertex Transformation: Split each vertex v into two vertices v' and v'',
527 connected by an edge e from v' to v''. w(e) = w(v). */
530 fprintf (dump_file
, "\nVertex transformation:\n");
532 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
534 /* v'->v'': index1->(index1+1). */
536 fcost
= (gcov_type
) COST (k_pos
, bb
->count
);
537 add_fixup_edge (fixup_graph
, i
, i
+ 1, VERTEX_SPLIT_EDGE
, bb
->count
,
538 fcost
, CAP_INFINITY
);
539 fixup_graph
->num_vertices
++;
541 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
543 /* Edges with ignore attribute set should be treated like they don't
545 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
547 j
= 2 * e
->dest
->index
;
548 fcost
= (gcov_type
) COST (k_pos
, e
->count
);
549 add_fixup_edge (fixup_graph
, i
+ 1, j
, REDIRECT_EDGE
, e
->count
, fcost
,
554 /* After vertex transformation. */
555 gcc_assert (fixup_graph
->num_vertices
== fnum_vertices_after_transform
);
556 /* Redirect edges are not added for edges with ignore attribute. */
557 gcc_assert (fixup_graph
->num_edges
<= fnum_edges_after_transform
);
559 fnum_edges_after_transform
= fixup_graph
->num_edges
;
561 /* 2. Initialize D(v). */
562 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
564 pfedge
= fixup_graph
->edge_list
+ i
;
565 diff_out_in
[pfedge
->src
] += pfedge
->weight
;
566 diff_out_in
[pfedge
->dest
] -= pfedge
->weight
;
569 /* Entry block - vertex indices 0, 1; EXIT block - vertex indices 2, 3. */
570 for (i
= 0; i
<= 3; i
++)
573 /* 3. Add reverse edges: needed to decrease counts during smoothing. */
575 fprintf (dump_file
, "\nReverse edges:\n");
576 for (i
= 0; i
< fnum_edges_after_transform
; i
++)
578 pfedge
= fixup_graph
->edge_list
+ i
;
579 if ((pfedge
->src
== 0) || (pfedge
->src
== 2))
581 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
582 if (!r_pfedge
&& pfedge
->weight
)
584 /* Skip adding reverse edges for edges with w(e) = 0, as its maximum
586 fcost
= (gcov_type
) COST (k_neg
, pfedge
->weight
);
587 add_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
,
588 REVERSE_EDGE
, 0, fcost
, pfedge
->weight
);
592 /* 4. Create single source and sink. Connect new source vertex s' to function
593 entry block. Connect sink vertex t' to function exit. */
595 fprintf (dump_file
, "\ns'->S, T->t':\n");
597 new_entry_index
= fixup_graph
->new_entry_index
= fixup_graph
->num_vertices
;
598 fixup_graph
->num_vertices
++;
599 /* Set supply_value to 1 to avoid zero count function ENTRY. */
600 add_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
, SOURCE_CONNECT_EDGE
,
601 1 /* supply_value */, 0, 1 /* supply_value */);
603 /* Create new exit with EXIT_BLOCK as single pred. */
604 new_exit_index
= fixup_graph
->new_exit_index
= fixup_graph
->num_vertices
;
605 fixup_graph
->num_vertices
++;
606 add_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
,
608 0 /* demand_value */, 0, 0 /* demand_value */);
610 /* Connect vertices with unbalanced D(v) to source/sink. */
612 fprintf (dump_file
, "\nD(v) balance:\n");
613 /* Skip vertices for ENTRY (0, 1) and EXIT (2,3) blocks, so start with i = 4.
614 diff_out_in[v''] will be 0, so skip v'' vertices, hence i += 2. */
615 for (i
= 4; i
< new_entry_index
; i
+= 2)
617 if (diff_out_in
[i
] > 0)
619 add_fixup_edge (fixup_graph
, i
, new_exit_index
, BALANCE_EDGE
, 0, 0,
621 demand_value
+= diff_out_in
[i
];
623 else if (diff_out_in
[i
] < 0)
625 add_fixup_edge (fixup_graph
, new_entry_index
, i
, BALANCE_EDGE
, 0, 0,
627 supply_value
-= diff_out_in
[i
];
631 /* Set supply = demand. */
634 fprintf (dump_file
, "\nAdjust supply and demand:\n");
635 fprintf (dump_file
, "supply_value=%" PRId64
"\n",
637 fprintf (dump_file
, "demand_value=%" PRId64
"\n",
641 if (demand_value
> supply_value
)
643 pfedge
= find_fixup_edge (fixup_graph
, new_entry_index
, ENTRY_BLOCK
);
644 pfedge
->max_capacity
+= (demand_value
- supply_value
);
648 pfedge
= find_fixup_edge (fixup_graph
, 2 * EXIT_BLOCK
+ 1, new_exit_index
);
649 pfedge
->max_capacity
+= (supply_value
- demand_value
);
652 /* 6. Normalize edges: remove anti-parallel edges. Anti-parallel edges are
653 created by the vertex transformation step from self-edges in the original
654 CFG and by the reverse edges added earlier. */
656 fprintf (dump_file
, "\nNormalize edges:\n");
658 fnum_edges
= fixup_graph
->num_edges
;
659 fedge_list
= fixup_graph
->edge_list
;
661 for (i
= 0; i
< fnum_edges
; i
++)
663 pfedge
= fedge_list
+ i
;
664 r_pfedge
= find_fixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
);
665 if (((pfedge
->type
== VERTEX_SPLIT_EDGE
)
666 || (pfedge
->type
== REDIRECT_EDGE
)) && r_pfedge
)
668 new_index
= fixup_graph
->num_vertices
;
669 fixup_graph
->num_vertices
++;
673 fprintf (dump_file
, "\nAnti-parallel edge:\n");
674 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
675 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
676 fprintf (dump_file
, "New vertex is %d.\n", new_index
);
677 fprintf (dump_file
, "------------------\n");
681 pfedge
->norm_vertex_index
= new_index
;
684 fprintf (dump_file
, "After normalization:\n");
685 dump_fixup_edge (dump_file
, fixup_graph
, pfedge
);
688 /* Add a new fixup edge: new_index->src. */
689 add_fixup_edge (fixup_graph
, new_index
, pfedge
->src
,
690 REVERSE_NORMALIZED_EDGE
, 0, r_pfedge
->cost
,
691 r_pfedge
->max_capacity
);
692 gcc_assert (fixup_graph
->num_vertices
<= fmax_num_vertices
);
694 /* Edge: r_pfedge->src -> r_pfedge->dest
695 ==> r_pfedge->src -> new_index. */
696 r_pfedge
->dest
= new_index
;
697 r_pfedge
->type
= REVERSE_NORMALIZED_EDGE
;
698 r_pfedge
->cost
= pfedge
->cost
;
699 r_pfedge
->max_capacity
= pfedge
->max_capacity
;
701 dump_fixup_edge (dump_file
, fixup_graph
, r_pfedge
);
706 dump_fixup_graph (dump_file
, fixup_graph
, "After create_fixup_graph()");
713 /* Allocates space for the structures in AUGMENTING_PATH. The space needed is
714 proportional to the number of nodes in the graph, which is given by
718 init_augmenting_path (augmenting_path_type
*augmenting_path
, int graph_size
)
720 augmenting_path
->queue_list
.queue
= (int *)
721 xcalloc (graph_size
+ 2, sizeof (int));
722 augmenting_path
->queue_list
.size
= graph_size
+ 2;
723 augmenting_path
->bb_pred
= (int *) xcalloc (graph_size
, sizeof (int));
724 augmenting_path
->is_visited
= (int *) xcalloc (graph_size
, sizeof (int));
727 /* Free the structures in AUGMENTING_PATH. */
729 free_augmenting_path (augmenting_path_type
*augmenting_path
)
731 free (augmenting_path
->queue_list
.queue
);
732 free (augmenting_path
->bb_pred
);
733 free (augmenting_path
->is_visited
);
737 /* Queue routines. Assumes queue will never overflow. */
740 init_queue (queue_type
*queue_list
)
742 gcc_assert (queue_list
);
743 queue_list
->head
= 0;
744 queue_list
->tail
= 0;
747 /* Return true if QUEUE_LIST is empty. */
749 is_empty (queue_type
*queue_list
)
751 return (queue_list
->head
== queue_list
->tail
);
754 /* Insert element X into QUEUE_LIST. */
756 enqueue (queue_type
*queue_list
, int x
)
758 gcc_assert (queue_list
->tail
< queue_list
->size
);
759 queue_list
->queue
[queue_list
->tail
] = x
;
760 (queue_list
->tail
)++;
763 /* Return the first element in QUEUE_LIST. */
765 dequeue (queue_type
*queue_list
)
768 gcc_assert (queue_list
->head
>= 0);
769 x
= queue_list
->queue
[queue_list
->head
];
770 (queue_list
->head
)++;
775 /* Finds a negative cycle in the residual network using
776 the Bellman-Ford algorithm. The flow on the found cycle is reversed by the
777 minimum residual capacity of that cycle. ENTRY and EXIT vertices are not
781 FIXUP_GRAPH - Residual graph (input/output)
782 The following are allocated/freed by the caller:
783 PI - Vector to hold predecessors in path (pi = pred index)
784 D - D[I] holds minimum cost of path from i to sink
785 CYCLE - Vector to hold the minimum cost cycle
788 true if a negative cycle was found, false otherwise. */
791 cancel_negative_cycle (fixup_graph_type
*fixup_graph
,
792 int *pi
, gcov_type
*d
, int *cycle
)
795 int fnum_vertices
, fnum_edges
;
796 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
797 bool found_cycle
= false;
798 int cycle_start
= 0, cycle_end
= 0;
799 gcov_type sum_cost
= 0, cycle_flow
= 0;
801 bool propagated
= false;
803 gcc_assert (fixup_graph
);
804 fnum_vertices
= fixup_graph
->num_vertices
;
805 fnum_edges
= fixup_graph
->num_edges
;
806 fedge_list
= fixup_graph
->edge_list
;
807 new_entry_index
= fixup_graph
->new_entry_index
;
811 for (i
= 1; i
< fnum_vertices
; i
++)
820 for (k
= 1; k
< fnum_vertices
; k
++)
823 for (i
= 0; i
< fnum_edges
; i
++)
825 pfedge
= fedge_list
+ i
;
826 if (pfedge
->src
== new_entry_index
)
828 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
829 && d
[pfedge
->src
] != CAP_INFINITY
830 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
832 d
[pfedge
->dest
] = d
[pfedge
->src
] + pfedge
->cost
;
833 pi
[pfedge
->dest
] = pfedge
->src
;
842 /* No negative cycles exist. */
846 for (i
= 0; i
< fnum_edges
; i
++)
848 pfedge
= fedge_list
+ i
;
849 if (pfedge
->src
== new_entry_index
)
851 if (pfedge
->is_rflow_valid
&& pfedge
->rflow
852 && d
[pfedge
->src
] != CAP_INFINITY
853 && (d
[pfedge
->dest
] > d
[pfedge
->src
] + pfedge
->cost
))
863 /* Augment the cycle with the cycle's minimum residual capacity. */
865 cycle
[0] = pfedge
->dest
;
868 for (i
= 1; i
< fnum_vertices
; i
++)
872 for (k
= 0; k
< i
; k
++)
876 /* cycle[k] -> ... -> cycle[i]. */
887 gcc_assert (cycle
[cycle_start
] == cycle
[cycle_end
]);
889 fprintf (dump_file
, "\nNegative cycle length is %d:\n",
890 cycle_end
- cycle_start
);
893 cycle_flow
= CAP_INFINITY
;
894 for (k
= cycle_start
; k
< cycle_end
; k
++)
896 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
897 cycle_flow
= MIN (cycle_flow
, pfedge
->rflow
);
898 sum_cost
+= pfedge
->cost
;
900 fprintf (dump_file
, "%d ", cycle
[k
]);
905 fprintf (dump_file
, "%d", cycle
[k
]);
907 ": (%" PRId64
", %" PRId64
908 ")\n", sum_cost
, cycle_flow
);
910 "Augment cycle with %" PRId64
"\n",
914 for (k
= cycle_start
; k
< cycle_end
; k
++)
916 pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
+ 1], cycle
[k
]);
917 r_pfedge
= find_fixup_edge (fixup_graph
, cycle
[k
], cycle
[k
+ 1]);
918 pfedge
->rflow
-= cycle_flow
;
920 pfedge
->flow
+= cycle_flow
;
921 r_pfedge
->rflow
+= cycle_flow
;
923 r_pfedge
->flow
-= cycle_flow
;
930 /* Computes the residual flow for FIXUP_GRAPH by setting the rflow field of
931 the edges. ENTRY and EXIT vertices should not be considered. */
934 compute_residual_flow (fixup_graph_type
*fixup_graph
)
938 fixup_edge_p fedge_list
, pfedge
;
940 gcc_assert (fixup_graph
);
943 fputs ("\ncompute_residual_flow():\n", dump_file
);
945 fnum_edges
= fixup_graph
->num_edges
;
946 fedge_list
= fixup_graph
->edge_list
;
948 for (i
= 0; i
< fnum_edges
; i
++)
950 pfedge
= fedge_list
+ i
;
951 pfedge
->rflow
= pfedge
->max_capacity
- pfedge
->flow
;
952 pfedge
->is_rflow_valid
= true;
953 add_rfixup_edge (fixup_graph
, pfedge
->dest
, pfedge
->src
, pfedge
->flow
,
959 /* Uses Edmonds-Karp algorithm - BFS to find augmenting path from SOURCE to
960 SINK. The fields in the edge vector in the FIXUP_GRAPH are not modified by
961 this routine. The vector bb_pred in the AUGMENTING_PATH structure is updated
962 to reflect the path found.
963 Returns: 0 if no augmenting path is found, 1 otherwise. */
966 find_augmenting_path (fixup_graph_type
*fixup_graph
,
967 augmenting_path_type
*augmenting_path
, int source
,
972 fixup_vertex_p fvertex_list
, pfvertex
;
974 int *bb_pred
, *is_visited
;
975 queue_type
*queue_list
;
977 gcc_assert (augmenting_path
);
978 bb_pred
= augmenting_path
->bb_pred
;
979 gcc_assert (bb_pred
);
980 is_visited
= augmenting_path
->is_visited
;
981 gcc_assert (is_visited
);
982 queue_list
= &(augmenting_path
->queue_list
);
984 gcc_assert (fixup_graph
);
986 fvertex_list
= fixup_graph
->vertex_list
;
988 for (u
= 0; u
< fixup_graph
->num_vertices
; u
++)
991 init_queue (queue_list
);
992 enqueue (queue_list
, source
);
993 bb_pred
[source
] = -1;
995 while (!is_empty (queue_list
))
997 u
= dequeue (queue_list
);
999 pfvertex
= fvertex_list
+ u
;
1000 for (i
= 0; pfvertex
->succ_edges
.iterate (i
, &pfedge
);
1003 int dest
= pfedge
->dest
;
1004 if ((pfedge
->rflow
> 0) && (is_visited
[dest
] == 0))
1006 enqueue (queue_list
, dest
);
1008 is_visited
[dest
] = 1;
1019 /* Routine to find the maximal flow:
1021 1. Initialize flow to 0
1022 2. Find an augmenting path form source to sink.
1023 3. Send flow equal to the path's residual capacity along the edges of this path.
1024 4. Repeat steps 2 and 3 until no new augmenting path is found.
1027 SOURCE: index of source vertex (input)
1028 SINK: index of sink vertex (input)
1029 FIXUP_GRAPH: adjacency matrix representing the graph. The flow of the edges will be
1030 set to have a valid maximal flow by this routine. (input)
1031 Return: Maximum flow possible. */
1034 find_max_flow (fixup_graph_type
*fixup_graph
, int source
, int sink
)
1037 augmenting_path_type augmenting_path
;
1039 gcov_type max_flow
= 0;
1041 fixup_edge_p fedge_list
, pfedge
, r_pfedge
;
1043 gcc_assert (fixup_graph
);
1045 fnum_edges
= fixup_graph
->num_edges
;
1046 fedge_list
= fixup_graph
->edge_list
;
1048 /* Initialize flow to 0. */
1049 for (i
= 0; i
< fnum_edges
; i
++)
1051 pfedge
= fedge_list
+ i
;
1055 compute_residual_flow (fixup_graph
);
1057 init_augmenting_path (&augmenting_path
, fixup_graph
->num_vertices
);
1059 bb_pred
= augmenting_path
.bb_pred
;
1060 while (find_augmenting_path (fixup_graph
, &augmenting_path
, source
, sink
))
1062 /* Determine the amount by which we can increment the flow. */
1063 gcov_type increment
= CAP_INFINITY
;
1064 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1066 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1067 increment
= MIN (increment
, pfedge
->rflow
);
1069 max_flow
+= increment
;
1071 /* Now increment the flow. EXIT vertex index is 1. */
1072 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1074 pfedge
= find_fixup_edge (fixup_graph
, bb_pred
[u
], u
);
1075 r_pfedge
= find_fixup_edge (fixup_graph
, u
, bb_pred
[u
]);
1079 pfedge
->flow
+= increment
;
1080 pfedge
->rflow
-= increment
;
1081 r_pfedge
->rflow
+= increment
;
1085 /* backward edge. */
1086 gcc_assert (r_pfedge
->type
);
1087 r_pfedge
->rflow
+= increment
;
1088 r_pfedge
->flow
-= increment
;
1089 pfedge
->rflow
-= increment
;
1095 fprintf (dump_file
, "\nDump augmenting path:\n");
1096 for (u
= sink
; u
!= source
; u
= bb_pred
[u
])
1098 print_basic_block (dump_file
, fixup_graph
, u
);
1099 fprintf (dump_file
, "<-");
1102 "ENTRY (path_capacity=%" PRId64
")\n",
1105 "Network flow is %" PRId64
".\n",
1110 free_augmenting_path (&augmenting_path
);
1112 dump_fixup_graph (dump_file
, fixup_graph
, "After find_max_flow()");
1117 /* Computes the corrected edge and basic block weights using FIXUP_GRAPH
1118 after applying the find_minimum_cost_flow() routine. */
1121 adjust_cfg_counts (fixup_graph_type
*fixup_graph
)
1127 fixup_edge_p pfedge
, pfedge_n
;
1129 gcc_assert (fixup_graph
);
1132 fprintf (dump_file
, "\nadjust_cfg_counts():\n");
1134 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
),
1135 EXIT_BLOCK_PTR_FOR_FN (cfun
), next_bb
)
1142 "BB%d: %" PRId64
"", bb
->index
, bb
->count
);
1144 pfedge
= find_fixup_edge (fixup_graph
, i
, i
+ 1);
1147 bb
->count
+= pfedge
->flow
;
1150 fprintf (dump_file
, " + %" PRId64
"(",
1152 print_edge (dump_file
, fixup_graph
, i
, i
+ 1);
1153 fprintf (dump_file
, ")");
1158 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1159 /* Deduct flow from normalized reverse edge. */
1160 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1162 bb
->count
-= pfedge_n
->flow
;
1165 fprintf (dump_file
, " - %" PRId64
"(",
1167 print_edge (dump_file
, fixup_graph
, i
+ 1,
1168 pfedge
->norm_vertex_index
);
1169 fprintf (dump_file
, ")");
1173 fprintf (dump_file
, " = %" PRId64
"\n", bb
->count
);
1176 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1178 /* Treat edges with ignore attribute set as if they don't exist. */
1179 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1182 j
= 2 * e
->dest
->index
;
1184 fprintf (dump_file
, "%d->%d: %" PRId64
"",
1185 bb
->index
, e
->dest
->index
, e
->count
);
1187 pfedge
= find_fixup_edge (fixup_graph
, i
+ 1, j
);
1189 if (bb
->index
!= e
->dest
->index
)
1191 /* Non-self edge. */
1194 e
->count
+= pfedge
->flow
;
1197 fprintf (dump_file
, " + %" PRId64
"(",
1199 print_edge (dump_file
, fixup_graph
, i
+ 1, j
);
1200 fprintf (dump_file
, ")");
1205 find_fixup_edge (fixup_graph
, j
, pfedge
->norm_vertex_index
);
1206 /* Deduct flow from normalized reverse edge. */
1207 if (pfedge
->norm_vertex_index
&& pfedge_n
->flow
)
1209 e
->count
-= pfedge_n
->flow
;
1212 fprintf (dump_file
, " - %" PRId64
"(",
1214 print_edge (dump_file
, fixup_graph
, j
,
1215 pfedge
->norm_vertex_index
);
1216 fprintf (dump_file
, ")");
1222 /* Handle self edges. Self edge is split with a normalization
1223 vertex. Here i=j. */
1224 pfedge
= find_fixup_edge (fixup_graph
, j
, i
+ 1);
1226 find_fixup_edge (fixup_graph
, i
+ 1, pfedge
->norm_vertex_index
);
1227 e
->count
+= pfedge_n
->flow
;
1228 bb
->count
+= pfedge_n
->flow
;
1231 fprintf (dump_file
, "(self edge)");
1232 fprintf (dump_file
, " + %" PRId64
"(",
1234 print_edge (dump_file
, fixup_graph
, i
+ 1,
1235 pfedge
->norm_vertex_index
);
1236 fprintf (dump_file
, ")");
1241 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1243 fprintf (dump_file
, " = %" PRId64
"\t(%.1f%%)\n",
1244 e
->count
, e
->probability
* 100.0 / REG_BR_PROB_BASE
);
1248 ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
=
1249 sum_edge_counts (ENTRY_BLOCK_PTR_FOR_FN (cfun
)->succs
);
1250 EXIT_BLOCK_PTR_FOR_FN (cfun
)->count
=
1251 sum_edge_counts (EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
);
1253 /* Compute edge probabilities. */
1254 FOR_ALL_BB_FN (bb
, cfun
)
1258 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1259 e
->probability
= REG_BR_PROB_BASE
* e
->count
/ bb
->count
;
1264 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1265 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1269 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1271 if (!(e
->flags
& (EDGE_COMPLEX
| EDGE_FAKE
)))
1272 e
->probability
= REG_BR_PROB_BASE
/ total
;
1279 total
+= EDGE_COUNT (bb
->succs
);
1280 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1281 e
->probability
= REG_BR_PROB_BASE
/ total
;
1288 fprintf (dump_file
, "\nCheck %s() CFG flow conservation:\n",
1289 current_function_name ());
1290 FOR_EACH_BB_FN (bb
, cfun
)
1292 if ((bb
->count
!= sum_edge_counts (bb
->preds
))
1293 || (bb
->count
!= sum_edge_counts (bb
->succs
)))
1296 "BB%d(%" PRId64
") **INVALID**: ",
1297 bb
->index
, bb
->count
);
1299 "******** BB%d(%" PRId64
1300 ") **INVALID**: \n", bb
->index
, bb
->count
);
1301 fprintf (dump_file
, "in_edges=%" PRId64
" ",
1302 sum_edge_counts (bb
->preds
));
1303 fprintf (dump_file
, "out_edges=%" PRId64
"\n",
1304 sum_edge_counts (bb
->succs
));
1311 /* Implements the negative cycle canceling algorithm to compute a minimum cost
1314 1. Find maximal flow.
1315 2. Form residual network
1317 While G contains a negative cost cycle C, reverse the flow on the found cycle
1318 by the minimum residual capacity in that cycle.
1319 4. Form the minimal cost flow
1322 FIXUP_GRAPH - Initial fixup graph.
1323 The flow field is modified to represent the minimum cost flow. */
1326 find_minimum_cost_flow (fixup_graph_type
*fixup_graph
)
1328 /* Holds the index of predecessor in path. */
1330 /* Used to hold the minimum cost cycle. */
1332 /* Used to record the number of iterations of cancel_negative_cycle. */
1334 /* Vector d[i] holds the minimum cost of path from i to sink. */
1338 int new_entry_index
;
1340 gcc_assert (fixup_graph
);
1341 fnum_vertices
= fixup_graph
->num_vertices
;
1342 new_exit_index
= fixup_graph
->new_exit_index
;
1343 new_entry_index
= fixup_graph
->new_entry_index
;
1345 find_max_flow (fixup_graph
, new_entry_index
, new_exit_index
);
1347 /* Initialize the structures for find_negative_cycle(). */
1348 pred
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1349 d
= (gcov_type
*) xcalloc (fnum_vertices
, sizeof (gcov_type
));
1350 cycle
= (int *) xcalloc (fnum_vertices
, sizeof (int));
1352 /* Repeatedly find and cancel negative cost cycles, until
1353 no more negative cycles exist. This also updates the flow field
1354 to represent the minimum cost flow so far. */
1356 while (cancel_negative_cycle (fixup_graph
, pred
, d
, cycle
))
1359 if (iteration
> MAX_ITER (fixup_graph
->num_vertices
,
1360 fixup_graph
->num_edges
))
1365 dump_fixup_graph (dump_file
, fixup_graph
,
1366 "After find_minimum_cost_flow()");
1368 /* Cleanup structures. */
1375 /* Compute the sum of the edge counts in TO_EDGES. */
1378 sum_edge_counts (vec
<edge
, va_gc
> *to_edges
)
1384 FOR_EACH_EDGE (e
, ei
, to_edges
)
1386 if (EDGE_INFO (e
) && EDGE_INFO (e
)->ignore
)
1394 /* Main routine. Smoothes the initial assigned basic block and edge counts using
1395 a minimum cost flow algorithm, to ensure that the flow consistency rule is
1396 obeyed: sum of outgoing edges = sum of incoming edges for each basic
1400 mcf_smooth_cfg (void)
1402 fixup_graph_type fixup_graph
;
1403 memset (&fixup_graph
, 0, sizeof (fixup_graph
));
1404 create_fixup_graph (&fixup_graph
);
1405 find_minimum_cost_flow (&fixup_graph
);
1406 adjust_cfg_counts (&fixup_graph
);
1407 delete_fixup_graph (&fixup_graph
);