Fixed some warning about unused variables.
[libfirm] / ir / ana / execfreq.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Compute an estimate of basic block executions.
23  * @author      Adam M. Szalkowski
24  * @date        28.05.2006
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <math.h>
33
34 #include "gaussseidel.h"
35
36 #include "set.h"
37 #include "hashptr.h"
38 #include "debug.h"
39 #include "statev.h"
40 #include "dfs_t.h"
41 #include "absgraph.h"
42
43 #include "irprog_t.h"
44 #include "irgraph_t.h"
45 #include "irnode_t.h"
46 #include "irloop.h"
47 #include "irgwalk.h"
48 #include "iredges.h"
49 #include "irouts.h"
50 #include "irprintf.h"
51 #include "irtools.h"
52 #include "irhooks.h"
53
54 #include "execfreq.h"
55
56 /* enable to also solve the equations with Gauss-Jordan */
57 #undef COMPARE_AGAINST_GAUSSJORDAN
58
59 #ifdef COMPARE_AGAINST_GAUSSJORDAN
60 #include "gaussjordan.h"
61 #endif
62
63
64 #define EPSILON          1e-5
65 #define UNDEF(x)         (fabs(x) < EPSILON)
66 #define SEIDEL_TOLERANCE 1e-7
67
68 #define MAX_INT_FREQ 1000000
69
70 #define set_foreach(s,type,i) for ((i)=(type)set_first((s)); (i); (i)=(type)set_next((s)))
71
72 typedef struct freq_t {
73         const ir_node    *irn;
74         int               idx;
75         double            freq;
76 } freq_t;
77
78 struct ir_exec_freq {
79         set *freqs;
80         hook_entry_t hook;
81         double max;
82         double min_non_zero;
83         double m, b;
84         unsigned infeasible : 1;
85 };
86
87 static int cmp_freq(const void *a, const void *b, size_t size)
88 {
89         const freq_t *p = (const freq_t*) a;
90         const freq_t *q = (const freq_t*) b;
91         (void) size;
92
93         return !(p->irn == q->irn);
94 }
95
96 static freq_t *set_find_freq(set *freqs, const ir_node *irn)
97 {
98         freq_t query;
99         query.irn = irn;
100         return (freq_t*) set_find(freqs, &query, sizeof(query), HASH_PTR(irn));
101 }
102
103 static freq_t *set_insert_freq(set *freqs, const ir_node *irn)
104 {
105         freq_t query;
106
107         query.irn = irn;
108         query.freq = 0.0;
109         query.idx  = -1;
110         return (freq_t*) set_insert(freqs, &query, sizeof(query), HASH_PTR(irn));
111 }
112
113 double get_block_execfreq(const ir_exec_freq *ef, const ir_node *irn)
114 {
115         if (!ef->infeasible) {
116                 set *freqs = ef->freqs;
117                 freq_t *freq;
118                 assert(is_Block(irn));
119                 freq = set_find_freq(freqs, irn);
120                 assert(freq);
121
122                 assert(freq->freq >= 0);
123                 return freq->freq;
124         }
125
126         return 1.0;
127 }
128
129 unsigned long
130 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
131 {
132         double f       = get_block_execfreq(ef, bb);
133         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
134         return res;
135 }
136
137 static double *solve_lgs(gs_matrix_t *mat, double *x, int size)
138 {
139         double init = 1.0 / size;
140         double dev;
141         int i, iter = 0;
142
143         /* better convergence. */
144         for (i = 0; i < size; ++i)
145                 x[i] = init;
146
147         stat_ev_dbl("execfreq_matrix_size", size);
148         stat_ev_tim_push();
149         do {
150                 ++iter;
151                 dev = gs_matrix_gauss_seidel(mat, x, size);
152         } while (fabs(dev) > SEIDEL_TOLERANCE);
153         stat_ev_tim_pop("execfreq_seidel_time");
154         stat_ev_dbl("execfreq_seidel_iter", iter);
155
156 #ifdef COMPARE_AGAINST_GAUSSJORDAN
157         {
158                 double *nw = XMALLOCN(double, size * size);
159                 double *nx = XMALLOCNZ(double, size);
160
161                 gs_matrix_export(mat, nw, size);
162
163                 stat_ev_tim_push();
164                 firm_gaussjordansolve(nw, nx, size);
165                 stat_ev_tim_pop("execfreq_jordan_time");
166
167                 xfree(nw);
168                 xfree(nx);
169         }
170 #endif
171
172         return x;
173 }
174
175 /*
176  * Determine probability that predecessor pos takes this cf edge.
177  */
178 static double get_cf_probability(ir_node *bb, int pos, double loop_weight)
179 {
180         double           sum = 0.0;
181         double           cur = 1.0;
182         double           inv_loop_weight = 1./loop_weight;
183         const ir_node   *pred = get_Block_cfgpred_block(bb, pos);
184         const ir_loop   *pred_loop;
185         int              pred_depth;
186         const ir_edge_t *edge;
187         const ir_loop   *loop;
188         int              depth;
189         int              d;
190
191         if (is_Bad(pred))
192                 return 0;
193
194         loop       = get_irn_loop(bb);
195         depth      = get_loop_depth(loop);
196         pred_loop  = get_irn_loop(pred);
197         pred_depth = get_loop_depth(pred_loop);
198
199         for (d = depth; d < pred_depth; ++d) {
200                 cur *= inv_loop_weight;
201         }
202
203         foreach_block_succ(pred, edge) {
204                 const ir_node *succ       = get_edge_src_irn(edge);
205                 const ir_loop *succ_loop  = get_irn_loop(succ);
206                 int            succ_depth = get_loop_depth(succ_loop);
207
208                 double         fac = 1.0;
209                 for (d = succ_depth; d < pred_depth; ++d) {
210                         fac *= inv_loop_weight;
211                 }
212                 sum += fac;
213         }
214
215         return cur/sum;
216 }
217
218 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
219 {
220         ir_exec_freq *ef = (ir_exec_freq*) ctx;
221         if (!is_Block(irn))
222                 return;
223
224         fprintf(f, "execution frequency: %g/%lu\n", get_block_execfreq(ef, irn), get_block_execfreq_ulong(ef, irn));
225 }
226
227 ir_exec_freq *create_execfreq(ir_graph *irg)
228 {
229         ir_exec_freq *execfreq = XMALLOCZ(ir_exec_freq);
230         execfreq->freqs = new_set(cmp_freq, 32);
231
232         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
233
234         // set reasonable values to convert double execfreq to ulong execfreq
235         execfreq->m = 1.0;
236
237         execfreq->hook.context = execfreq;
238         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
239         register_hook(hook_node_info, &execfreq->hook);
240         (void) irg;
241
242         return execfreq;
243 }
244
245 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
246 {
247         freq_t *f = set_insert_freq(execfreq->freqs, block);
248         f->freq = freq;
249 }
250
251 static void collect_blocks(ir_node *bl, void *data)
252 {
253         set *freqs = (set*) data;
254         set_insert_freq(freqs, bl);
255 }
256
257 ir_exec_freq *compute_execfreq(ir_graph *irg, double loop_weight)
258 {
259         gs_matrix_t  *mat;
260         int           size;
261         int           n_keepalives;
262         int           idx;
263         freq_t       *freq, *s, *e;
264         ir_exec_freq *ef;
265         ir_node      *end = get_irg_end(irg);
266         set          *freqs;
267         dfs_t        *dfs;
268         double       *x;
269         double        norm;
270
271         /*
272          * compute a DFS.
273          * using a toposort on the CFG (without back edges) will propagate
274          * the values better for the gauss/seidel iteration.
275          * => they can "flow" from start to end.
276          */
277         dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
278         ef = XMALLOCZ(ir_exec_freq);
279         ef->min_non_zero = HUGE_VAL; /* initialize with a reasonable large number. */
280         freqs = ef->freqs = new_set(cmp_freq, dfs_get_n_nodes(dfs));
281
282         /*
283          * Populate the exec freq set.
284          * The DFS cannot be used alone, since the CFG might not be connected
285          * due to unreachable code.
286          */
287         irg_block_walk_graph(irg, collect_blocks, NULL, freqs);
288
289         construct_cf_backedges(irg);
290         edges_assure(irg);
291
292         size = dfs_get_n_nodes(dfs);
293         mat  = gs_new_matrix(size, size);
294         x    = XMALLOCN(double, size);
295
296         for (idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
297                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
298                 freq_t *freq;
299                 int i;
300
301                 freq = set_insert_freq(freqs, bb);
302                 freq->idx = idx;
303
304                 /* Sum of (execution frequency of predecessor * probability of cf edge) ... */
305                 for (i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
306                         ir_node *pred = get_Block_cfgpred_block(bb, i);
307                         int pred_idx  = size - dfs_get_post_num(dfs, pred) - 1;
308
309                         gs_matrix_set(mat, idx, pred_idx, get_cf_probability(bb, i, loop_weight));
310                 }
311                 /* ... equals my execution frequency */
312                 gs_matrix_set(mat, idx, idx, -1.0);
313         }
314
315         dfs_free(dfs);
316
317         /*
318          * Add an edge from end to start.
319          * The problem is then an eigenvalue problem:
320          * Solve A*x = 1*x => (A-I)x = 0
321          */
322         s = set_find_freq(freqs, get_irg_start_block(irg));
323
324         e = set_find_freq(freqs, get_irg_end_block(irg));
325         if (e->idx >= 0)
326                 gs_matrix_set(mat, s->idx, e->idx, 1.0);
327
328         /*
329          * Also add an edge for each kept block to start.
330          *
331          * This avoid strange results for e.g. an irg containing a exit()-call
332          * which block has no cfg successor.
333          */
334         n_keepalives = get_End_n_keepalives(end);
335         for (idx = n_keepalives - 1; idx >= 0; --idx) {
336                 ir_node *keep = get_End_keepalive(end, idx);
337
338                 if (is_Block(keep) && get_Block_n_cfg_outs(keep) == 0) {
339                         freq_t *k = set_find_freq(freqs, keep);
340                         if (k->idx >= 0)
341                                 gs_matrix_set(mat, s->idx, k->idx, 1.0);
342                 }
343         }
344
345         /* solve the system and delete the matrix */
346         solve_lgs(mat, x, size);
347         gs_delete_matrix(mat);
348
349         /*
350          * compute the normalization factor.
351          * 1.0 / exec freq of start block.
352          */
353         norm = x[s->idx] != 0.0 ? 1.0 / x[s->idx] : 1.0;
354
355         ef->max = 0.0;
356         set_foreach(freqs, freq_t*, freq) {
357                 int idx = freq->idx;
358
359                 /* take abs because it sometimes can be -0 in case of endless loops */
360                 freq->freq = fabs(x[idx]) * norm;
361
362                 /* get the maximum exec freq */
363                 ef->max = MAX(ef->max, freq->freq);
364
365                 /* Get the minimum non-zero execution frequency. */
366                 if (freq->freq > 0.0)
367                         ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
368         }
369
370         /* compute m and b of the transformation used to convert the doubles into scaled ints */
371         {
372                 double smallest_diff = 1.0;
373
374                 double l2 = ef->min_non_zero;
375                 double h2 = ef->max;
376                 double l1 = 1.0;
377                 double h1 = MAX_INT_FREQ;
378
379                 double *fs = (double*) malloc(set_count(freqs) * sizeof(fs[0]));
380                 int i, j, n = 0;
381
382                 set_foreach(freqs, freq_t*, freq)
383                         fs[n++] = freq->freq;
384
385                 /*
386                  * find the smallest difference of the execution frequencies
387                  * we try to ressolve it with 1 integer.
388                  */
389                 for (i = 0; i < n; ++i) {
390                         if (fs[i] <= 0.0)
391                                 continue;
392
393                         for (j = i + 1; j < n; ++j) {
394                                 double diff = fabs(fs[i] - fs[j]);
395
396                                 if (!UNDEF(diff))
397                                         smallest_diff = MIN(diff, smallest_diff);
398                         }
399                 }
400
401                 /* according to that the slope of the translation function is 1.0 / smallest diff */
402                 ef->m = 1.0 / smallest_diff;
403
404                 /* the abscissa is then given by */
405                 ef->b = l1 - ef->m * l2;
406
407                 /*
408                  * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
409                  * set the largest int freq to that upper limit and recompute the translation function
410                  */
411                 if (ef->m * h2 + ef->b > MAX_INT_FREQ) {
412                         ef->m = (h1 - l1) / (h2 - l2);
413                         ef->b = l1 - ef->m * l2;
414                 }
415
416                 free(fs);
417         }
418
419         memset(&ef->hook, 0, sizeof(ef->hook));
420         ef->hook.context = ef;
421         ef->hook.hook._hook_node_info = exec_freq_node_info;
422         register_hook(hook_node_info, &ef->hook);
423
424         xfree(x);
425
426         return ef;
427 }
428
429 void free_execfreq(ir_exec_freq *ef)
430 {
431         del_set(ef->freqs);
432         unregister_hook(hook_node_info, &ef->hook);
433         free(ef);
434 }