ia32_Minus64Bit needs no contraint copies.
[libfirm] / ir / ir / irprofile.c
1 /*
2  * Copyright (C) 1995-2011 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       Code instrumentation and execution count profiling.
23  * @author      Adam M. Szalkowski, Steven Schaefer
24  * @date        06.04.2006, 11.11.2010
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include <math.h>
30 #include <stdio.h>
31
32 #include "hashptr.h"
33 #include "debug.h"
34 #include "obst.h"
35 #include "xmalloc.h"
36 #include "set.h"
37 #include "irtools.h"
38
39 #include "irgwalk.h"
40 #include "irdump_t.h"
41 #include "irnode_t.h"
42 #include "ircons_t.h"
43 #include "execfreq.h"
44 #include "typerep.h"
45
46 #include "irprofile.h"
47
48 /* Instrument blocks walker. */
49 typedef struct block_id_walker_data_t {
50         unsigned int id;   /**< current block id number */
51         ir_node *symconst; /**< the SymConst representing the counter array */
52 } block_id_walker_data_t;
53
54 /* Associate counters with blocks. */
55 typedef struct block_assoc_t {
56         unsigned int i;          /**< current block id number */
57         unsigned int *counters;  /**< block execution counts */
58 } block_assoc_t;
59
60 typedef struct intialize_execfreq_env_t {
61         ir_graph *irg;
62         ir_exec_freq *execfreqs;
63         double freq_factor;
64 } initialize_execfreq_env_t;
65
66 /* minimal execution frequency (an execfreq of 0 confuses algos) */
67 #define MIN_EXECFREQ 0.00001
68
69 /* keep the execcounts here because they are only read once per compiler run */
70 static set *profile = NULL;
71
72 /* Hook for vcg output. */
73 static void *hook;
74
75 /* The debug module handle. */
76 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
77
78 /* Since the backend creates a new firm graph we cannot associate counts with
79  * blocks directly. Instead we associate them with the block ids, which are
80  * maintained.
81  */
82 typedef struct execcount_t {
83         unsigned long block; /**< block id */
84         unsigned int  count; /**< execution count */
85 } execcount_t;
86
87 /**
88  * Compare two execcount_t entries.
89  */
90 static int cmp_execcount(const void *a, const void *b, size_t size)
91 {
92         const execcount_t *ea = (const execcount_t*)a;
93         const execcount_t *eb = (const execcount_t*)b;
94         (void) size;
95         return ea->block != eb->block;
96 }
97
98 /**
99  * Block walker, count number of blocks.
100  */
101 static void block_counter(ir_node *bb, void *data)
102 {
103         unsigned *count = (unsigned*) data;
104         (void) bb;
105         ++(*count);
106 }
107
108 /**
109  * Returns the number of blocks the given graph.
110  */
111 static unsigned int get_irg_n_blocks(ir_graph *irg)
112 {
113         unsigned int count = 0;
114         irg_block_walk_graph(irg, block_counter, NULL, &count);
115         return count;
116 }
117
118 /**
119  * Returns the number of basic blocks in the current ir program.
120  */
121 static unsigned int get_irp_n_blocks(void)
122 {
123         int i, n = get_irp_n_irgs();
124         unsigned int count = 0;
125
126         for (i = 0; i < n; i++) {
127                 ir_graph *irg = get_irp_irg(i);
128                 count += get_irg_n_blocks(irg);
129         }
130
131         return count;
132 }
133
134 /* vcg helper */
135 static void dump_profile_node_info(void *ctx, FILE *f, const ir_node *irn)
136 {
137         (void) ctx;
138         if (is_Block(irn)) {
139                 unsigned int execcount = ir_profile_get_block_execcount(irn);
140                 fprintf(f, "profiled execution count: %u\n", execcount);
141         }
142 }
143
144 /**
145  * Add the given method entity as a constructor.
146  */
147 static void add_constructor(ir_entity *method)
148 {
149     ir_type   *method_type  = get_entity_type(method);
150     ir_type   *ptr_type     = new_type_pointer(method_type);
151
152     ir_type   *constructors = get_segment_type(IR_SEGMENT_CONSTRUCTORS);
153         /* Mach-O does not like labels in the constructor segment, but with ELF
154          * the linker dies horribly if there is no label. */
155         ident     *ide = id_unique("constructor_ptr.%u");
156     ir_entity *ptr = new_entity(constructors, ide, ptr_type);
157     ir_graph  *irg = get_const_code_irg();
158     ir_node   *val = new_rd_SymConst_addr_ent(NULL, irg, mode_P_code, method);
159
160         set_entity_ld_ident(ptr, new_id_from_chars("", 0));
161     set_entity_compiler_generated(ptr, 1);
162     set_entity_linkage(ptr, IR_LINKAGE_CONSTANT | IR_LINKAGE_HIDDEN_USER);
163     set_entity_visibility(ptr, ir_visibility_private);
164     set_atomic_ent_value(ptr, val);
165 }
166
167 /**
168  * Returns an entity representing the __init_firmprof function from libfirmprof
169  * This is the equivalent of:
170  * extern void __init_firmprof(char *filename, uint *counters, uint size)
171  */
172 static ir_entity *get_init_firmprof_ref(void)
173 {
174         ident   *init_name = new_id_from_str("__init_firmprof");
175         ir_type *init_type = new_type_method(3, 0);
176         ir_type *uint      = new_type_primitive(mode_Iu);
177         ir_type *uintptr   = new_type_pointer(uint);
178         ir_type *string    = new_type_pointer(new_type_primitive(mode_Bs));
179         ir_entity *result;
180
181         set_method_param_type(init_type, 0, string);
182         set_method_param_type(init_type, 1, uintptr);
183         set_method_param_type(init_type, 2, uint);
184
185         result = new_entity(get_glob_type(), init_name, init_type);
186         set_entity_visibility(result, ir_visibility_external);
187
188         return result;
189 }
190
191 /**
192  * Generates a new irg which calls the initializer
193  *
194  * Pseudocode:
195  *    static void __firmprof_initializer(void) __attribute__ ((constructor))
196  *    {
197  *        __init_firmprof(ent_filename, bblock_counts, n_blocks);
198  *    }
199  */
200 static ir_graph *gen_initializer_irg(ir_entity *ent_filename,
201                                      ir_entity *bblock_counts, int n_blocks)
202 {
203         ir_graph *irg;
204         ir_node  *ins[3];
205         ir_node  *bb, *ret, *call, *symconst;
206         ir_type  *empty_frame_type;
207         symconst_symbol sym;
208
209         ir_entity *init_ent = get_init_firmprof_ref();
210
211         ident     *name = new_id_from_str("__firmprof_initializer");
212         ir_entity *ent  = new_entity(get_glob_type(), name, new_type_method(0, 0));
213         set_entity_visibility(ent, ir_visibility_local);
214         set_entity_ld_ident(ent, name);
215
216         /* create the new ir_graph */
217         irg = new_ir_graph(ent, 0);
218         set_current_ir_graph(irg);
219         empty_frame_type = get_irg_frame_type(irg);
220         set_type_size_bytes(empty_frame_type, 0);
221         set_type_state(empty_frame_type, layout_fixed);
222
223         bb = get_r_cur_block(irg);
224
225         sym.entity_p = init_ent;
226         symconst     = new_r_SymConst(irg, mode_P_data, sym, symconst_addr_ent);
227
228         sym.entity_p = ent_filename;
229         ins[0] = new_r_SymConst(irg, mode_P_data, sym, symconst_addr_ent);
230         sym.entity_p = bblock_counts;
231         ins[1] = new_r_SymConst(irg, mode_P_data, sym, symconst_addr_ent);
232         ins[2] = new_r_Const_long(irg, mode_Iu, n_blocks);
233
234         call = new_r_Call(bb, get_irg_initial_mem(irg), symconst, 3, ins,
235                 get_entity_type(init_ent));
236         ret  = new_r_Return(bb, new_r_Proj(call, mode_M, pn_Call_M), 0, NULL);
237         mature_immBlock(bb);
238
239         add_immBlock_pred(get_irg_end_block(irg), ret);
240         mature_immBlock(get_irg_end_block(irg));
241
242         irg_finalize_cons(irg);
243
244         /* add a pointer to the new function in the constructor section */
245         add_constructor(ent);
246
247         return irg;
248 }
249
250 /**
251  * Instrument a block with code needed for profiling.
252  * This just inserts the instruction nodes, it doesn't connect the memory
253  * nodes in a meaningful way.
254  */
255 static void instrument_block(ir_node *bb, ir_node *address, unsigned int id)
256 {
257         ir_graph *irg = get_irn_irg(bb);
258         ir_node  *load, *store, *offset, *add, *projm, *proji, *unknown, *cnst;
259
260         /* We can't instrument the end block */
261         if (bb == get_irg_end_block(irg))
262                 return;
263
264         unknown = new_r_Unknown(irg, mode_M);
265         cnst    = new_r_Const_long(irg, mode_Iu, get_mode_size_bytes(mode_Iu) * id);
266         offset  = new_r_Add(bb, address, cnst, get_modeP_data());
267         load    = new_r_Load(bb, unknown, offset, mode_Iu, cons_none);
268         projm   = new_r_Proj(load, mode_M, pn_Load_M);
269         proji   = new_r_Proj(load, mode_Iu, pn_Load_res);
270         cnst    = new_r_Const_long(irg, mode_Iu, 1);
271         add     = new_r_Add(bb, proji, cnst, mode_Iu);
272         store   = new_r_Store(bb, projm, offset, add, cons_none);
273         projm   = new_r_Proj(store, mode_M, pn_Store_M);
274
275         set_irn_link(bb, projm);
276         set_irn_link(projm, load);
277 }
278
279 /**
280  * SSA Construction for instrumentation code memory.
281  *
282  * This introduces a new memory node and connects it to the instrumentation
283  * codes, inserting phiM nodes as necessary. Note that afterwards, the new
284  * memory is not connected to any return nodes and thus still dead.
285  */
286 static void fix_ssa(ir_node *bb, void *data)
287 {
288         ir_graph *irg = get_irn_irg(bb);
289         ir_node *mem, *proj, *load;
290         int n, arity = get_Block_n_cfgpreds(bb);
291
292         (void) data;
293
294         /* end blocks are not instrumented, skip! */
295         if (bb == get_irg_end_block(irg))
296                 return;
297
298         if (bb == get_irg_start_block(irg)) {
299                 mem = get_irg_initial_mem(irg);
300         } else if (arity == 1) {
301                 ir_node *pred = get_Block_cfgpred_block(bb, 0);
302                 if (!is_Bad(pred))
303                         mem = (ir_node*) get_irn_link(pred);
304                 else
305                         mem = new_r_NoMem(irg);
306         } else {
307                 ir_node **ins = ALLOCAN(ir_node*, arity);
308                 for (n = arity - 1; n >= 0; --n) {
309                         ir_node *pred = get_Block_cfgpred_block(bb, n);
310                         if (!is_Bad(pred))
311                                 ins[n] = (ir_node*) get_irn_link(pred);
312                         else
313                                 ins[n] = new_r_NoMem(irg);
314                 }
315                 mem = new_r_Phi(bb, arity, ins, mode_M);
316         }
317
318         /* The block link fields point to the projm from the instrumentation code,
319          * the projm in turn links to the initial load which lacks a memory
320          * argument at this point. */
321         proj = (ir_node*) get_irn_link(bb);
322         load = (ir_node*) get_irn_link(proj);
323         set_Load_mem(load, mem);
324 }
325
326 /**
327  * Instrument a single block.
328  */
329 static void block_instrument_walker(ir_node *bb, void *data)
330 {
331         block_id_walker_data_t *wd = (block_id_walker_data_t*)data;
332         instrument_block(bb, wd->symconst, wd->id);
333         ++wd->id;
334 }
335
336 /**
337  * Synchronize the original memory input of node with the additional operand
338  * from the profiling code.
339  */
340 static ir_node *sync_mem(ir_node *bb, ir_node *mem)
341 {
342         ir_node *ins[2];
343         ins[0] = (ir_node*) get_irn_link(bb);
344         ins[1] = mem;
345         return new_r_Sync(bb, 2, ins);
346 }
347
348 /**
349  * Instrument a single ir_graph, counters should point to the bblock
350  * counters array.
351  */
352 static void instrument_irg(ir_graph *irg, ir_entity *counters,
353                            block_id_walker_data_t *wd)
354 {
355         ir_node *end   = get_irg_end(irg);
356         ir_node *endbb = get_irg_end_block(irg);
357         int i;
358
359         /* generate a symbolic constant pointing to the count array */
360         symconst_symbol sym;
361         sym.entity_p = counters;
362         wd->symconst = new_r_SymConst(irg, mode_P_data, sym, symconst_addr_ent);
363
364         /* instrument each block in the current irg */
365         irg_block_walk_graph(irg, block_instrument_walker, NULL, wd);
366         irg_block_walk_graph(irg, fix_ssa, NULL, NULL);
367
368         /* connect the new memory nodes to the return nodes */
369         for (i = get_Block_n_cfgpreds(endbb) - 1; i >= 0; --i) {
370                 ir_node *node = skip_Proj(get_Block_cfgpred(endbb, i));
371                 ir_node *bb   = get_Block_cfgpred_block(endbb, i);
372                 ir_node *mem;
373
374                 switch (get_irn_opcode(node)) {
375                 case iro_Return:
376                         mem = get_Return_mem(node);
377                         set_Return_mem(node, sync_mem(bb, mem));
378                         break;
379                 case iro_Raise:
380                         mem = get_Raise_mem(node);
381                         set_Raise_mem(node, sync_mem(bb, mem));
382                         break;
383                 case iro_Bad:
384                         break;
385                 default:
386                         /* A fragile's op exception. There should be another path to End,
387                          * so ignore it.
388                          */
389                         assert(is_fragile_op(node) && \
390                                 "unexpected End control flow predecessor");
391                 }
392         }
393
394         /* as well as calls with attribute noreturn */
395         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i) {
396                 ir_node *node = get_End_keepalive(end, i);
397                 if (is_Call(node)) {
398                         ir_node *bb  = get_nodes_block(node);
399                         ir_node *mem = get_Call_mem(node);
400                         set_Call_mem(node, sync_mem(bb, mem));
401                 }
402         }
403 }
404
405 /**
406  * Creates a new entity representing the equivalent of
407  * static unsigned int name[size]
408  */
409 static ir_entity *new_array_entity(ident *name, int size)
410 {
411         ir_entity *result;
412         ir_type *uint_type, *array_type;
413
414         uint_type = new_type_primitive(mode_Iu);
415         set_type_alignment_bytes(uint_type, get_type_size_bytes(uint_type));
416
417         array_type = new_type_array(1, uint_type);
418         set_array_bounds_int(array_type, 0, 0, size);
419         set_type_size_bytes(array_type, size * get_mode_size_bytes(mode_Iu));
420         set_type_alignment_bytes(array_type, get_mode_size_bytes(mode_Iu));
421         set_type_state(array_type, layout_fixed);
422
423         result = new_entity(get_glob_type(), name, array_type);
424         set_entity_visibility(result, ir_visibility_local);
425         set_entity_compiler_generated(result, 1);
426
427         return result;
428 }
429
430 /**
431  * Creates a new entity representing the equivalent of
432  * static const char name[strlen(string)+1] = string
433  */
434 static ir_entity *new_static_string_entity(ident *name, const char *string)
435 {
436         ir_entity *result;
437
438         ir_type *char_type   = new_type_primitive(mode_Bs);
439         ir_type *string_type = new_type_array(1, char_type);
440
441         ir_initializer_t *contents;
442
443         size_t i, length = strlen(string)+1;
444
445         /* Create the type for a fixed-length string */
446         set_array_bounds_int(string_type, 0, 0, length);
447         set_type_size_bytes(string_type, length);
448         set_type_alignment_bytes(string_type, 1);
449         set_type_state(string_type, layout_fixed);
450
451         result = new_entity(get_glob_type(), name, string_type);
452         set_entity_visibility(result, ir_visibility_local);
453         set_entity_linkage(result, IR_LINKAGE_CONSTANT);
454         set_entity_compiler_generated(result, 1);
455
456         /* There seems to be no simpler way to do this. Or at least, cparser
457          * does exactly the same thing... */
458         contents = create_initializer_compound(length);
459         for (i = 0; i < length; i++) {
460                 ir_tarval *c = new_tarval_from_long(string[i], mode_Bs);
461                 ir_initializer_t *init = create_initializer_tarval(c);
462                 set_initializer_compound_value(contents, i, init);
463         }
464         set_entity_initializer(result, contents);
465
466         return result;
467 }
468
469 /**
470  * Instrument all ir_graphs in the current ir_program. Currently this only
471  * works for graphs in the backend. Additionally, the resulting program
472  * has to be linked with libfirmprof.
473  *
474  * @param filename the name of the profile file (usually module_name.prof)
475  * @returns the module initializer, may be NULL
476  */
477 ir_graph *ir_profile_instrument(const char *filename)
478 {
479         int n, n_blocks = 0;
480         ident *counter_id, *filename_id;
481         ir_entity *bblock_counts, *ent_filename;
482         block_id_walker_data_t wd;
483         FIRM_DBG_REGISTER(dbg, "firm.ir.profile");
484
485         /* Don't do anything for modules without code. Else the linker will
486          * complain. */
487         if (get_irp_n_irgs() == 0)
488                 return NULL;
489
490         /* count the number of block first */
491         n_blocks = get_irp_n_blocks();
492
493         /* create all the necessary types and entities. Note that the
494          * types must have a fixed layout, because we are already running in the
495          * backend */
496         counter_id    = new_id_from_str("__FIRMPROF__BLOCK_COUNTS");
497         bblock_counts = new_array_entity(counter_id, n_blocks);
498
499         filename_id  = new_id_from_str("__FIRMPROF__FILE_NAME");
500         ent_filename = new_static_string_entity(filename_id, filename);
501
502         /* initialize block id array and instrument blocks */
503         wd.id  = 0;
504         for (n = get_irp_n_irgs() - 1; n >= 0; --n) {
505                 ir_graph *irg = get_irp_irg(n);
506                 instrument_irg(irg, bblock_counts, &wd);
507         }
508
509         return gen_initializer_irg(ent_filename, bblock_counts, n_blocks);
510 }
511
512 static unsigned int *
513 parse_profile(const char *filename, unsigned int num_blocks)
514 {
515         unsigned int *result = NULL;
516         char buf[8];
517         size_t ret;
518
519         FILE *f = fopen(filename, "rb");
520         if (!f) {
521                 DBG((dbg, LEVEL_2, "Failed to open profile file (%s)\n", filename));
522                 return NULL;
523         }
524
525         /* check header */
526         ret = fread(buf, 8, 1, f);
527         if (ret == 0 || strncmp(buf, "firmprof", 8) != 0) {
528                 DBG((dbg, LEVEL_2, "Broken fileheader in profile\n"));
529                 goto end;
530         }
531
532         result = XMALLOCN(unsigned int, num_blocks);
533         if (fread(result, sizeof(unsigned int) * num_blocks, 1, f) < 1) {
534                 DBG((dbg, LEVEL_4, "Failed to read counters... (size: %u)\n",
535                     sizeof(unsigned int) * num_blocks));
536                 xfree(result);
537                 result = NULL;
538         }
539
540 end:
541         fclose(f);
542         return result;
543 }
544
545 /**
546  * Reads the corresponding profile info file if it exists.
547  */
548
549 static void block_associate_walker(ir_node *bb, void *env)
550 {
551         block_assoc_t *b = (block_assoc_t*) env;
552         execcount_t query;
553
554         query.block = get_irn_node_nr(bb);
555         query.count = b->counters[(b->i)++];
556         DBG((dbg, LEVEL_4, "execcount(%+F, %u): %u\n", bb, query.block,
557             query.count));
558         set_insert(profile, &query, sizeof(query), query.block);
559 }
560
561 static void irp_associate_blocks(block_assoc_t *env)
562 {
563         int n;
564         for (n = get_irp_n_irgs() - 1; n >= 0; --n) {
565                 ir_graph *irg = get_irp_irg(n);
566                 irg_block_walk_graph(irg, block_associate_walker, NULL, env);
567         }
568 }
569
570 bool ir_profile_read(const char *filename)
571 {
572         block_assoc_t env;
573         FIRM_DBG_REGISTER(dbg, "firm.ir.profile");
574
575         env.i = 0;
576         env.counters = parse_profile(filename, get_irp_n_blocks());
577         if (!env.counters)
578                 return false;
579
580         if (profile)
581                 ir_profile_free();
582         profile = new_set(cmp_execcount, 16);
583
584         irp_associate_blocks(&env);
585         xfree(env.counters);
586
587         /* register the vcg hook */
588         hook = dump_add_node_info_callback(dump_profile_node_info, NULL);
589         return true;
590 }
591
592 /**
593  * Frees the profile info
594  */
595 void ir_profile_free(void)
596 {
597         if (profile) {
598                 del_set(profile);
599                 profile = NULL;
600         }
601
602         if (hook != NULL) {
603                 dump_remove_node_info_callback(hook);
604                 hook = NULL;
605         }
606 }
607
608 /**
609  * Tells whether profile module has acquired data
610  */
611 bool ir_profile_has_data(void)
612 {
613         return profile != NULL;
614 }
615
616 /**
617  * Get block execution count as determined by profiling
618  */
619 unsigned int ir_profile_get_block_execcount(const ir_node *block)
620 {
621         execcount_t *ec, query;
622
623         if (!ir_profile_has_data())
624                 return 1;
625
626         query.block = get_irn_node_nr(block);
627         ec = (execcount_t*)set_find(profile, &query, sizeof(query), query.block);
628
629         if (ec != NULL) {
630                 return ec->count;
631         } else {
632                 DBG((dbg, LEVEL_3,
633                         "Warning: Profile contains no data for %+F\n", block));
634                 return 1;
635         }
636 }
637
638 static void initialize_execfreq(ir_node *block, void *data)
639 {
640         initialize_execfreq_env_t *env = (initialize_execfreq_env_t*)data;
641         double freq;
642
643         if (block == get_irg_start_block(env->irg)
644            || block == get_irg_end_block(env->irg)) {
645                 freq = 1.0;
646         } else {
647                 freq = ir_profile_get_block_execcount(block);
648                 freq *= env->freq_factor;
649                 if (freq < MIN_EXECFREQ)
650                         freq = MIN_EXECFREQ;
651         }
652
653         set_execfreq(env->execfreqs, block, freq);
654 }
655
656 ir_exec_freq *ir_create_execfreqs_from_profile(ir_graph *irg)
657 {
658         ir_node *start_block;
659         initialize_execfreq_env_t env;
660         unsigned count;
661
662         env.irg = irg;
663         env.execfreqs = create_execfreq(irg);
664
665         /* Find the first block containing instructions */
666         start_block = get_irg_start_block(irg);
667         count = ir_profile_get_block_execcount(start_block);
668         if (count == 0) {
669                 /* the function was never executed, so fallback to estimated freqs */
670                 free_execfreq(env.execfreqs);
671                 return compute_execfreq(irg, 10);
672         }
673
674         env.freq_factor = 1.0 / count;
675         irg_block_walk_graph(irg, initialize_execfreq, NULL, &env);
676
677         return env.execfreqs;
678 }