move backend into libfirm
[libfirm] / ir / ana / execfreq.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ana/execfreq.c
4  * Purpose:     Compute an estimate of basic block executions.
5  * Author:      Adam M. Szalkowski
6  * Modified by:
7  * Created:     28.05.2006
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 2006 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12 #ifdef HAVE_CONFIG_H
13 #include "config.h"
14 #endif
15
16 #undef USE_GSL
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <limits.h>
21 #include <math.h>
22
23 #ifdef USE_GSL
24 #include <gsl/gsl_linalg.h>
25 #include <gsl/gsl_vector.h>
26 #else
27 #include "gaussjordan.h"
28 #endif
29
30 #include "firm_common_t.h"
31 #include "set.h"
32 #include "hashptr.h"
33
34 #include "irprog_t.h"
35 #include "irgraph_t.h"
36 #include "irnode_t.h"
37 #include "irloop.h"
38 #include "irgwalk.h"
39 #include "iredges.h"
40 #include "irprintf.h"
41 #include "irhooks.h"
42
43 #include "execfreq.h"
44
45 #define set_foreach(s,i) for((i)=set_first((s)); (i); (i)=set_next((s)))
46
47 #define MAX_INT_FREQ 1000000
48
49 typedef struct _freq_t {
50         const ir_node    *irn;
51         double            freq;
52 } freq_t;
53
54
55 typedef struct _walkerdata_t {
56   set    *set;
57   size_t  idx;
58 } walkerdata_t;
59
60 struct ir_exec_freq {
61         set *set;
62         hook_entry_t hook;
63         double max;
64         double min_non_zero;
65         double m, b;
66         unsigned infeasible : 1;
67 };
68
69 static int
70 cmp_freq(const void *a, const void *b, size_t size)
71 {
72         const freq_t *p = a;
73         const freq_t *q = b;
74
75         return !(p->irn == q->irn);
76 }
77
78 static freq_t *
79 set_find_freq(set * set, const ir_node * irn)
80 {
81         freq_t     query;
82
83         query.irn = irn;
84         return set_find(set, &query, sizeof(query), HASH_PTR(irn));
85 }
86
87 static freq_t *
88 set_insert_freq(set * set, const ir_node * irn)
89 {
90         freq_t query;
91
92         query.irn = irn;
93         query.freq = 0.0;
94         return set_insert(set, &query, sizeof(query), HASH_PTR(irn));
95 }
96
97 double
98 get_block_execfreq(const ir_exec_freq *ef, const ir_node * irn)
99 {
100         if(!ef->infeasible) {
101                 set *freqs = ef->set;
102                 freq_t *freq;
103                 assert(is_Block(irn));
104                 freq = set_find_freq(freqs, irn);
105                 assert(freq);
106
107                 assert(freq->freq >= 0);
108                 return freq->freq;
109         }
110
111         return 1.0;
112 }
113
114 unsigned long
115 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
116 {
117         double f       = get_block_execfreq(ef, bb);
118         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
119
120         // printf("%20.6f %10d\n", f, res);
121         return res;
122 }
123
124 #define EPSILON         0.0001
125 #define UNDEF(x)    !(x > EPSILON)
126
127 static void
128 block_walker(ir_node * bb, void * data)
129 {
130   walkerdata_t  *wd = data;
131
132   set_insert_freq(wd->set, bb);
133   set_irn_link(bb, (void*)wd->idx++);
134 }
135
136 #ifdef USE_GSL
137 static gsl_vector *
138 solve_lgs(double * a_data, double * b_data, size_t size)
139 {
140   gsl_matrix_view m
141     = gsl_matrix_view_array (a_data, size, size);
142
143   gsl_vector_view b
144     = gsl_vector_view_array (b_data, size);
145
146   gsl_vector *x = gsl_vector_alloc (size);
147
148   int s;
149
150   gsl_permutation * p = gsl_permutation_alloc (size);
151
152   gsl_linalg_LU_decomp (&m.matrix, p, &s);
153
154   gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x);
155
156   gsl_permutation_free (p);
157
158   return x;
159 }
160 #else
161 static double *
162 solve_lgs(double * A, double * b, size_t size)
163 {
164   if(firm_gaussjordansolve(A,b,size) == 0) {
165     return b;
166   } else {
167     return NULL;
168   }
169 }
170 #endif
171
172 static double
173 get_cf_probability(ir_node *bb, int pos, double loop_weight)
174 {
175         double  sum = 0.0;
176         double  cur = 0.0;
177         const ir_node *pred = get_Block_cfgpred_block(bb, pos);
178         const ir_loop *pred_loop = get_irn_loop(pred);
179         int pred_depth = get_loop_depth(pred_loop);
180         const ir_edge_t *edge;
181
182         cur = get_loop_depth(get_irn_loop(bb)) < get_loop_depth(get_irn_loop(pred)) ? 1.0 : loop_weight;
183
184         foreach_block_succ(pred, edge) {
185                 const ir_node *block = get_edge_src_irn(edge);
186                 const ir_loop *loop = get_irn_loop(block);
187                 int depth = get_loop_depth(loop);
188                 sum += depth < pred_depth ? 1.0 : loop_weight;
189         }
190
191         return cur/sum;
192 }
193
194 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
195 {
196         if(is_Block(irn)) {
197                 ir_exec_freq *ef = ctx;
198                 fprintf(f, "execution frequency: %g/%lu\n", get_block_execfreq(ef, irn), get_block_execfreq_ulong(ef, irn));
199         }
200 }
201
202 ir_exec_freq *create_execfreq(ir_graph *irg)
203 {
204         ir_exec_freq *execfreq = xmalloc(sizeof(execfreq[0]));
205         memset(execfreq, 0, sizeof(execfreq[0]));
206         execfreq->set = new_set(cmp_freq, 32);
207
208         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
209         execfreq->hook.context = execfreq;
210         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
211         register_hook(hook_node_info, &execfreq->hook);
212
213         return execfreq;
214 }
215
216 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
217 {
218         freq_t *f = set_insert_freq(execfreq->set, block);
219         f->freq = freq;
220 }
221
222 ir_exec_freq *
223 compute_execfreq(ir_graph * irg, double loop_weight)
224 {
225         size_t        size;
226         double       *matrix;
227         double       *rhs;
228         int           i;
229         freq_t       *freq;
230         walkerdata_t  wd;
231         ir_exec_freq  *ef;
232         set          *freqs;
233 #ifdef USE_GSL
234         gsl_vector   *x;
235 #else
236         double       *x;
237 #endif
238
239         ef = xmalloc(sizeof(ef[0]));
240         memset(ef, 0, sizeof(ef[0]));
241         ef->min_non_zero = 1e50; /* initialize with a reasonable large number. */
242         freqs = ef->set = new_set(cmp_freq, 32);
243
244         construct_cf_backedges(irg);
245         edges_assure(irg);
246
247         wd.idx = 0;
248         wd.set = freqs;
249
250         irg_block_walk_graph(irg, block_walker, NULL, &wd);
251
252         size = set_count(freqs);
253         matrix = xmalloc(size*size*sizeof(*matrix));
254         memset(matrix, 0, size*size*sizeof(*matrix));
255         rhs = xmalloc(size*sizeof(*rhs));
256         memset(rhs, 0, size*sizeof(*rhs));
257
258         set_foreach(freqs, freq) {
259                 ir_node *bb = (ir_node *)freq->irn;
260                 size_t  idx = (int)get_irn_link(bb);
261
262                 matrix[idx * (size + 1)] = -1.0;
263
264                 if (bb == get_irg_start_block(irg)) {
265                         rhs[(int)get_irn_link(bb)] = -1.0;
266                         continue;
267                 }
268
269                 for(i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
270                         ir_node *pred    = get_Block_cfgpred_block(bb, i);
271                         size_t  pred_idx = (int)get_irn_link(pred);
272
273                         //      matrix[pred_idx + idx*size] += 1.0/(double)get_Block_n_cfg_outs(pred);
274                         matrix[pred_idx + idx * size] += get_cf_probability(bb, i, loop_weight);
275                 }
276         }
277
278         x = solve_lgs(matrix, rhs, size);
279         if(x == NULL) {
280                 ef->infeasible = 1;
281                 return ef;
282         }
283
284         ef->max = 0.0;
285
286         set_foreach(freqs, freq) {
287                 const ir_node *bb = freq->irn;
288                 size_t        idx = PTR_TO_INT(get_irn_link(bb));
289
290 #ifdef USE_GSL
291                 freq->freq = UNDEF(gsl_vector_get(x, idx)) ? EPSILON : gsl_vector_get(x, idx);
292 #else
293                 freq->freq = UNDEF(x[idx]) ? EPSILON : x[idx];
294 #endif
295
296                 /* get the maximum exec freq */
297                 ef->max = MAX(ef->max, freq->freq);
298
299                 /* Get the minimum non-zero execution frequency. */
300                 if(freq->freq > 0.0)
301                         ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
302         }
303
304         /* compute m and b of the transformation used to convert the doubles into scaled ints */
305         {
306                 double smallest_diff = 1.0;
307
308                 double l2 = ef->min_non_zero;
309                 double h2 = ef->max;
310                 double l1 = 1.0;
311                 double h1 = MAX_INT_FREQ;
312
313                 double *fs = malloc(set_count(freqs) * sizeof(fs[0]));
314                 int i, j, n = 0;
315
316                 set_foreach(freqs, freq)
317                         fs[n++] = freq->freq;
318
319                 /*
320                  * find the smallest difference of the execution frequencies
321                  * we try to ressolve it with 1 integer.
322                  */
323                 for(i = 0; i < n; ++i) {
324                         if(fs[i] <= 0.0)
325                                 continue;
326
327                         for(j = i + 1; j < n; ++j) {
328                                 double diff = fabs(fs[i] - fs[j]);
329
330                                 if(!UNDEF(diff))
331                                         smallest_diff = MIN(diff, smallest_diff);
332                         }
333                 }
334
335                 /* according to that the slope of the translation function is 1.0 / smallest diff */
336                 ef->m = 1.0 / smallest_diff;
337
338                 /* the abscissa is then given by */
339                 ef->b = l1 - ef->m * l2;
340
341                 /*
342                  * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
343                  * set the largest int freq to that upper limit and recompute the translation function
344                  */
345                 if(ef->m * h2 + ef->b > MAX_INT_FREQ) {
346                         ef->m = (h1 - l1) / (h2 - l2);
347                         ef->b = l1 - ef->m * l2;
348                 }
349
350                 // printf("smallest_diff: %g, l1: %f, h1: %f, l2: %f, h2: %f, m: %f, b: %f\n", smallest_diff, l1, h1, l2, h2, ef->m, ef->b);
351                 free(fs);
352         }
353
354 #ifdef USE_GSL
355         gsl_vector_free(x);
356 #endif
357         free(matrix);
358
359         memset(&ef->hook, 0, sizeof(ef->hook));
360         ef->hook.context = ef;
361         ef->hook.hook._hook_node_info = exec_freq_node_info;
362         register_hook(hook_node_info, &ef->hook);
363
364         return ef;
365 }
366
367 void
368 free_execfreq(ir_exec_freq *ef)
369 {
370         del_set(ef->set);
371         unregister_hook(hook_node_info, &ef->hook);
372         free(ef);
373 }
374
375 #undef ELEM