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