fix weak external functions
[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,i) for((i)=set_first((s)); (i); (i)=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 *set;
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
88 cmp_freq(const void *a, const void *b, size_t size)
89 {
90         const freq_t *p = a;
91         const freq_t *q = b;
92         (void) size;
93
94         return !(p->irn == q->irn);
95 }
96
97 static freq_t *
98 set_find_freq(set * set, const ir_node * irn)
99 {
100         freq_t     query;
101
102         query.irn = irn;
103         return set_find(set, &query, sizeof(query), HASH_PTR(irn));
104 }
105
106 static freq_t *
107 set_insert_freq(set * set, const ir_node * irn)
108 {
109         freq_t query;
110
111         query.irn = irn;
112         query.freq = 0.0;
113         query.idx  = -1;
114         return set_insert(set, &query, sizeof(query), HASH_PTR(irn));
115 }
116
117 double
118 get_block_execfreq(const ir_exec_freq *ef, const ir_node * irn)
119 {
120         if(!ef->infeasible) {
121                 set *freqs = ef->set;
122                 freq_t *freq;
123                 assert(is_Block(irn));
124                 freq = set_find_freq(freqs, irn);
125                 assert(freq);
126
127                 assert(freq->freq >= 0);
128                 return freq->freq;
129         }
130
131         return 1.0;
132 }
133
134 unsigned long
135 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
136 {
137         double f       = get_block_execfreq(ef, bb);
138         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
139         return res;
140 }
141
142 static double *
143 solve_lgs(gs_matrix_t *mat, double *x, int size)
144 {
145         double init = 1.0 / size;
146         double dev;
147         int i, iter = 0;
148
149         /* better convergence. */
150         for (i = 0; i < size; ++i)
151                 x[i] = init;
152
153         stat_ev_dbl("execfreq_matrix_size", size);
154         stat_ev_tim_push();
155         do {
156                 ++iter;
157                 dev = gs_matrix_gauss_seidel(mat, x, size);
158         } while(fabs(dev) > SEIDEL_TOLERANCE);
159         stat_ev_tim_pop("execfreq_seidel_time");
160         stat_ev_dbl("execfreq_seidel_iter", iter);
161
162 #ifdef COMPARE_AGAINST_GAUSSJORDAN
163         {
164                 double *nw = XMALLOCN(double, size * size);
165                 double *nx = XMALLOCNZ(double, size);
166
167                 gs_matrix_export(mat, nw, size);
168
169                 stat_ev_tim_push();
170                 firm_gaussjordansolve(nw, nx, size);
171                 stat_ev_tim_pop("execfreq_jordan_time");
172
173                 xfree(nw);
174                 xfree(nx);
175         }
176 #endif
177
178         return x;
179 }
180
181 /*
182  * Determine probability that predecessor pos takes this cf edge.
183  */
184 static double
185 get_cf_probability(ir_node *bb, int pos, double loop_weight)
186 {
187         double           sum = 0.0;
188         double           cur = 1.0;
189         double           inv_loop_weight = 1./loop_weight;
190         const ir_node   *pred = get_Block_cfgpred_block(bb, pos);
191         const ir_loop   *pred_loop;
192         int              pred_depth;
193         const ir_edge_t *edge;
194         const ir_loop   *loop;
195         int              depth;
196         int              d;
197
198         if (is_Bad(pred))
199                 return 0;
200
201         loop       = get_irn_loop(bb);
202         depth      = get_loop_depth(loop);
203         pred_loop  = get_irn_loop(pred);
204         pred_depth = get_loop_depth(pred_loop);
205
206         for (d = depth; d < pred_depth; ++d) {
207                 cur *= inv_loop_weight;
208         }
209
210         foreach_block_succ(pred, edge) {
211                 const ir_node *succ       = get_edge_src_irn(edge);
212                 const ir_loop *succ_loop  = get_irn_loop(succ);
213                 int            succ_depth = get_loop_depth(succ_loop);
214
215                 double         fac = 1.0;
216                 for (d = succ_depth; d < pred_depth; ++d) {
217                         fac *= inv_loop_weight;
218                 }
219                 sum += fac;
220         }
221
222         return cur/sum;
223 }
224
225 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
226 {
227         if(is_Block(irn)) {
228                 ir_exec_freq *ef = ctx;
229                 fprintf(f, "execution frequency: %g/%lu\n", get_block_execfreq(ef, irn), get_block_execfreq_ulong(ef, irn));
230         }
231 }
232
233 ir_exec_freq *create_execfreq(ir_graph *irg)
234 {
235         ir_exec_freq *execfreq = XMALLOCZ(ir_exec_freq);
236         execfreq->set = new_set(cmp_freq, 32);
237
238         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
239
240         // set reasonable values to convert double execfreq to ulong execfreq
241         execfreq->m = 1.0;
242
243         execfreq->hook.context = execfreq;
244         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
245         register_hook(hook_node_info, &execfreq->hook);
246         (void) irg;
247
248         return execfreq;
249 }
250
251 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
252 {
253         freq_t *f = set_insert_freq(execfreq->set, block);
254         f->freq = freq;
255 }
256
257 static void collect_blocks(ir_node *bl, void *data)
258 {
259         set *freqs = data;
260         set_insert_freq(freqs, bl);
261 }
262
263 ir_exec_freq *
264 compute_execfreq(ir_graph * irg, double loop_weight)
265 {
266         gs_matrix_t  *mat;
267         int           size;
268         int           n_keepalives;
269         int           idx;
270         freq_t       *freq, *s, *e;
271         ir_exec_freq *ef;
272         ir_node      *end = get_irg_end(irg);
273         set          *freqs;
274         dfs_t        *dfs;
275         double       *x;
276         double        norm;
277
278         /*
279          * compute a DFS.
280          * using a toposort on the CFG (without back edges) will propagate
281          * the values better for the gauss/seidel iteration.
282          * => they can "flow" from start to end.
283          */
284         dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
285         ef = XMALLOCZ(ir_exec_freq);
286         ef->min_non_zero = HUGE_VAL; /* initialize with a reasonable large number. */
287         freqs = ef->set = new_set(cmp_freq, dfs_get_n_nodes(dfs));
288
289         /*
290          * Populate the exec freq set.
291          * The DFS cannot be used alone, since the CFG might not be connected
292          * due to unreachable code.
293          */
294         irg_block_walk_graph(irg, collect_blocks, NULL, freqs);
295
296         construct_cf_backedges(irg);
297         edges_assure(irg);
298
299         size = dfs_get_n_nodes(dfs);
300         mat  = gs_new_matrix(size, size);
301         x    = XMALLOCN(double, size);
302
303         for (idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
304                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
305                 freq_t *freq;
306                 int i;
307
308                 freq = set_insert_freq(freqs, bb);
309                 freq->idx = idx;
310
311                 /* Sum of (execution frequency of predecessor * probability of cf edge) ... */
312                 for(i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
313                         ir_node *pred = get_Block_cfgpred_block(bb, i);
314                         int pred_idx  = size - dfs_get_post_num(dfs, pred) - 1;
315
316                         gs_matrix_set(mat, idx, pred_idx, get_cf_probability(bb, i, loop_weight));
317                 }
318                 /* ... equals my execution frequency */
319                 gs_matrix_set(mat, idx, idx, -1.0);
320         }
321
322         dfs_free(dfs);
323
324         /*
325          * Add an edge from end to start.
326          * The problem is then an eigenvalue problem:
327          * Solve A*x = 1*x => (A-I)x = 0
328          */
329         s = set_find_freq(freqs, get_irg_start_block(irg));
330
331         e = set_find_freq(freqs, get_irg_end_block(irg));
332         if (e->idx >= 0)
333                 gs_matrix_set(mat, s->idx, e->idx, 1.0);
334
335         /*
336          * Also add an edge for each kept block to start.
337          *
338          * This avoid strange results for e.g. an irg containing a exit()-call
339          * which block has no cfg successor.
340          */
341         n_keepalives = get_End_n_keepalives(end);
342         for (idx = n_keepalives - 1; idx >= 0; --idx) {
343                 ir_node *keep = get_End_keepalive(end, idx);
344
345                 if (is_Block(keep) && get_Block_n_cfg_outs(keep) == 0) {
346                         freq_t *k = set_find_freq(freqs, keep);
347                         if (k->idx >= 0)
348                                 gs_matrix_set(mat, s->idx, k->idx, 1.0);
349                 }
350         }
351
352         /* solve the system and delete the matrix */
353         solve_lgs(mat, x, size);
354         gs_delete_matrix(mat);
355
356         /*
357          * compute the normalization factor.
358          * 1.0 / exec freq of start block.
359          */
360         norm = x[s->idx] != 0.0 ? 1.0 / x[s->idx] : 1.0;
361
362         ef->max = 0.0;
363         set_foreach(freqs, freq) {
364                 int idx = freq->idx;
365
366                 /* take abs because it sometimes can be -0 in case of endless loops */
367                 freq->freq = fabs(x[idx]) * norm;
368
369                 /* get the maximum exec freq */
370                 ef->max = MAX(ef->max, freq->freq);
371
372                 /* Get the minimum non-zero execution frequency. */
373                 if(freq->freq > 0.0)
374                         ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
375         }
376
377         /* compute m and b of the transformation used to convert the doubles into scaled ints */
378         {
379                 double smallest_diff = 1.0;
380
381                 double l2 = ef->min_non_zero;
382                 double h2 = ef->max;
383                 double l1 = 1.0;
384                 double h1 = MAX_INT_FREQ;
385
386                 double *fs = malloc(set_count(freqs) * sizeof(fs[0]));
387                 int i, j, n = 0;
388
389                 set_foreach(freqs, freq)
390                         fs[n++] = freq->freq;
391
392                 /*
393                  * find the smallest difference of the execution frequencies
394                  * we try to ressolve it with 1 integer.
395                  */
396                 for(i = 0; i < n; ++i) {
397                         if(fs[i] <= 0.0)
398                                 continue;
399
400                         for(j = i + 1; j < n; ++j) {
401                                 double diff = fabs(fs[i] - fs[j]);
402
403                                 if(!UNDEF(diff))
404                                         smallest_diff = MIN(diff, smallest_diff);
405                         }
406                 }
407
408                 /* according to that the slope of the translation function is 1.0 / smallest diff */
409                 ef->m = 1.0 / smallest_diff;
410
411                 /* the abscissa is then given by */
412                 ef->b = l1 - ef->m * l2;
413
414                 /*
415                  * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
416                  * set the largest int freq to that upper limit and recompute the translation function
417                  */
418                 if(ef->m * h2 + ef->b > MAX_INT_FREQ) {
419                         ef->m = (h1 - l1) / (h2 - l2);
420                         ef->b = l1 - ef->m * l2;
421                 }
422
423                 free(fs);
424         }
425
426         memset(&ef->hook, 0, sizeof(ef->hook));
427         ef->hook.context = ef;
428         ef->hook.hook._hook_node_info = exec_freq_node_info;
429         register_hook(hook_node_info, &ef->hook);
430
431         xfree(x);
432
433         return ef;
434 }
435
436 void
437 free_execfreq(ir_exec_freq *ef)
438 {
439         del_set(ef->set);
440         unregister_hook(hook_node_info, &ef->hook);
441         free(ef);
442 }