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