2 * Copyright (C) 1995-2011 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @brief Statistics for Firm. Pattern history.
23 * @author Michael Beck
39 #include "pattern_dmp.h"
42 #include "lc_printf.h"
45 * just be make some things clear :-), the
48 #define HASH_MAP(type) pset_##type
50 typedef pset pset_pattern_entry_t;
52 typedef unsigned char BYTE;
54 /** Maximum size of the pattern store. */
55 #define PATTERN_STORE_SIZE 2048
61 typedef struct code_buf_t {
62 BYTE *next; /**< Next byte address to be written. */
63 BYTE *end; /**< End address of the buffer. */
64 BYTE *start; /**< Start address of the buffer. */
65 unsigned hash; /**< The hash value for the buffer content. */
66 unsigned overrun; /**< flag set if the buffer was overrun */
73 VLC_7BIT = 0x00, /**< 8 bit code, carrying 7 bits payload */
74 VLC_14BIT = 0x80, /**< 16 bit code, carrying 14 bits payload */
75 VLC_21BIT = 0xC0, /**< 24 bit code, carrying 21 bits payload */
76 VLC_28BIT = 0xE0, /**< 32 bit code, carrying 28 bits payload */
77 VLC_32BIT = 0xF0, /**< 40 bit code, carrying 32 bits payload */
79 VLC_TAG_FIRST = 0xF1, /**< First possible tag value. */
80 VLC_TAG_ICONST = 0xFB, /**< Encodes an integer constant. */
81 VLC_TAG_EMPTY = 0xFC, /**< Encodes an empty entity. */
82 VLC_TAG_OPTION = 0xFD, /**< Options exists. */
83 VLC_TAG_REF = 0xFE, /**< Special tag, next code is an ID. */
84 VLC_TAG_END = 0xFF, /**< End tag. */
88 * An entry for holding one pattern.
90 typedef struct pattern_entry_t {
91 counter_t count; /**< Amount of pattern occurance. */
92 size_t len; /**< The length of the VLC encoded buffer. */
93 BYTE buf[1]; /**< The buffer containing the VLC encoded pattern. */
97 * Current options for the pattern matcher.
100 OPT_WITH_MODE = 0x00000001, /**< use modes */
101 OPT_ENC_DAG = 0x00000002, /**< encode DAGs, not terms */
102 OPT_WITH_ICONST = 0x00000004, /**< encode integer constants */
103 OPT_PERSIST_PATTERN = 0x00000008, /**< persistent pattern hash */
110 typedef struct pattern_info_t {
111 int enable; /**< If non-zero, this module is enabled. */
112 struct obstack obst; /**< An obstack containing the counters. */
113 HASH_MAP(pattern_entry_t) *pattern_hash; /**< A hash map containing the pattern. */
114 unsigned bound; /**< Lowest value for pattern output. */
115 unsigned options; /**< Current option mask. */
116 unsigned min_depth; /**< Minimum pattern depth. */
117 unsigned max_depth; /**< Maximum pattern depth. */
123 static pattern_info_t _status, *status = &_status;
126 * Compare two pattern for its occurance counter.
128 static int pattern_count_cmp(const void *elt, const void *key)
132 pattern_entry_t **e1 = (pattern_entry_t **)elt;
133 pattern_entry_t **e2 = (pattern_entry_t **)key;
135 /* we want it sorted in descending order */
136 cmp = cnt_cmp(&(*e2)->count, &(*e1)->count);
139 } /* pattern_count_cmp */
142 * Compare two pattern for its pattern hash.
144 static int pattern_cmp(const void *elt, const void *key)
146 const pattern_entry_t *e1 = (const pattern_entry_t*)elt;
147 const pattern_entry_t *e2 = (const pattern_entry_t*)key;
149 if (e1->len == e2->len)
150 return memcmp(e1->buf, e2->buf, e1->len);
152 return e1->len < e2->len ? -1 : +1;
156 * Initialize a code buffer.
158 * @param buf the code buffer
159 * @param data a buffer address
160 * @param len the length of the data buffer
162 static void init_buf(CODE_BUFFER *buf, BYTE *data, size_t len)
166 buf->end = data + len;
167 buf->hash = 0x2BAD4; /* An arbitrary seed. */
172 * Put a byte into the buffer.
174 * @param buf the code buffer
175 * @param byte the byte to write
177 * The hash value for the buffer content is updated.
179 static inline void put_byte(CODE_BUFFER *buf, BYTE byte)
181 if (buf->next < buf->end) {
183 buf->hash = (buf->hash * 9) ^ byte;
190 * Returns the current length of a buffer.
192 * @param buf the code buffer
194 * @return the length of the buffer content
196 static size_t buf_lenght(const CODE_BUFFER *buf)
198 return buf->next - buf->start;
202 * Returns the current content of a buffer.
204 * @param buf the code buffer
206 * @return the start address of the buffer content
208 static const BYTE *buf_content(const CODE_BUFFER *buf)
214 * Returns the hash value of a buffer.
216 * @param buf the code buffer
218 * @return the hash value of the buffer content
220 static unsigned buf_hash(const CODE_BUFFER *buf)
226 * Returns non-zero if a buffer overrun has occurred.
228 * @param buf the code buffer
230 static unsigned buf_overrun(const CODE_BUFFER *buf)
236 * Returns the next byte from the buffer WITHOUT dropping.
238 * @param buf the code buffer
240 * @return the next byte from the code buffer
242 static inline BYTE look_byte(CODE_BUFFER *buf)
244 if (buf->next < buf->end)
250 * Returns the next byte from the buffer WITH dropping.
252 * @param buf the code buffer
254 * @return the next byte from the code buffer
256 static inline BYTE get_byte(CODE_BUFFER *buf)
258 if (buf->next < buf->end)
263 #define BITS(n) (1 << (n))
266 * Put a 32bit value into the buffer.
268 * @param buf the code buffer
269 * @param code the code to be written into the buffer
271 static void put_code(CODE_BUFFER *buf, unsigned code)
273 if (code < BITS(7)) {
274 put_byte(buf, VLC_7BIT | code);
275 } else if (code < BITS(6 + 8)) {
276 put_byte(buf, VLC_14BIT | (code >> 8));
278 } else if (code < BITS(5 + 8 + 8)) {
279 put_byte(buf, VLC_21BIT | (code >> 16));
280 put_byte(buf, code >> 8);
282 } else if (code < BITS(4 + 8 + 8 + 8)) {
283 put_byte(buf, VLC_28BIT | (code >> 24));
284 put_byte(buf, code >> 16);
285 put_byte(buf, code >> 8);
288 put_byte(buf, VLC_32BIT);
289 put_byte(buf, code >> 24);
290 put_byte(buf, code >> 16);
291 put_byte(buf, code >> 8);
296 #define BIT_MASK(n) ((1 << (n)) - 1)
299 * Get 32 bit from the buffer.
301 * @param buf the code buffer
303 * @return next 32bit value from the code buffer
305 static unsigned get_code(CODE_BUFFER *buf)
307 unsigned code = get_byte(buf);
309 if (code < VLC_14BIT)
311 if (code < VLC_21BIT)
312 return ((code & BIT_MASK(6)) << 8) | get_byte(buf);
313 if (code < VLC_28BIT) {
314 code = ((code & BIT_MASK(5)) << 16) | (get_byte(buf) << 8);
315 code |= get_byte(buf);
318 if (code < VLC_32BIT) {
319 code = ((code & BIT_MASK(4)) << 24) | (get_byte(buf) << 16);
320 code |= get_byte(buf) << 8;
321 code |= get_byte(buf);
324 if (code == VLC_32BIT) {
325 code = get_byte(buf) << 24;
326 code |= get_byte(buf) << 16;
327 code |= get_byte(buf) << 8;
328 code |= get_byte(buf);
331 /* should not happen */
332 panic("Wrong code in buffer");
336 * Put a tag into the buffer.
338 * @param buf the code buffer
339 * @param tag the tag to write to the code buffer
341 static void put_tag(CODE_BUFFER *buf, BYTE tag)
343 assert(tag >= VLC_TAG_FIRST && "invalid tag");
349 * Returns the next tag or zero if the next code isn't a tag.
351 * @param buf the code buffer
353 * @return the next tag in the code buffer
355 static BYTE next_tag(CODE_BUFFER *buf)
357 BYTE b = look_byte(buf);
359 if (b >= VLC_TAG_FIRST)
360 return get_byte(buf);
365 * An Environment for the pattern encoder.
367 typedef struct codec_enc_t {
368 CODE_BUFFER *buf; /**< The current code buffer. */
369 set *id_set; /**< A set containing all already seen Firm nodes. */
370 unsigned curr_id; /**< The current node id. */
371 unsigned options; /**< The encoding options. */
372 pattern_dumper_t *dmp; /**< The dumper for the decoder. */
378 typedef struct addr_entry_t {
379 void *addr; /**< the address */
380 unsigned id; /**< associated ID */
384 * Compare two addresses.
386 static int addr_cmp(const void *p1, const void *p2, size_t size)
388 const addr_entry_t *e1 = (const addr_entry_t*)p1;
389 const addr_entry_t *e2 = (const addr_entry_t*)p2;
392 return e1->addr != e2->addr;
396 * Return the index of a (existing) mode.
398 static size_t find_mode_index(const ir_mode *mode)
400 size_t i, n = get_irp_n_modes();
402 for (i = 0; i < n; ++i) {
403 if (get_irp_mode(i) == mode)
406 /* should really not happen */
407 assert(!"Cound not find index of mode in find_mode_index()");
412 * Encodes an IR-node, recursive worker.
414 * @return reached depth
416 static int _encode_node(ir_node *node, int max_depth, codec_env_t *env)
418 addr_entry_t entry, *r_entry;
423 unsigned code = get_irn_opcode(node);
425 /* insert the node into our ID map */
427 entry.id = env->curr_id;
429 s_entry = set_hinsert(env->id_set, &entry, sizeof(entry), HASH_PTR(node));
430 r_entry = (addr_entry_t *)s_entry->dptr;
432 if (r_entry->id != env->curr_id) {
433 /* already in the map, add an REF */
434 put_tag(env->buf, VLC_TAG_REF);
435 put_code(env->buf, r_entry->id);
439 /* a new entry, proceed */
443 put_code(env->buf, (unsigned)code);
445 /* do we need the mode ? */
446 if (env->options & OPT_WITH_MODE) {
447 ir_mode *mode = get_irn_mode(node);
450 put_code(env->buf, find_mode_index(mode));
452 put_tag(env->buf, VLC_TAG_EMPTY);
455 /* do we need integer constants */
456 if (env->options & OPT_WITH_ICONST) {
457 if (code == iro_Const) {
458 ir_tarval *tv = get_Const_tarval(node);
460 if (tarval_is_long(tv)) {
461 long v = get_tarval_long(tv);
463 put_tag(env->buf, VLC_TAG_ICONST);
464 put_code(env->buf, v);
471 if (max_depth <= 0) {
472 put_code(env->buf, 0);
476 preds = get_irn_arity(node);
477 put_code(env->buf, preds);
480 if (is_op_commutative(get_irn_op(node))) {
481 ir_node *l = get_binop_left(node);
482 ir_node *r = get_binop_right(node);
483 int opcode_diff = (int)get_irn_opcode(l) - (int)get_irn_opcode(r);
485 if (opcode_diff > 0) {
489 } else if (opcode_diff == 0 && l != r) {
490 /* Both nodes have the same opcode, but are different.
491 Need a better method here to decide which goes to the left side. */
494 /* special handling for commutative operators */
495 depth = _encode_node(l, max_depth, env);
498 depth = _encode_node(r, max_depth, env);
502 for (i = 0; i < preds; ++i) {
503 ir_node *n = get_irn_n(node, i);
505 depth = _encode_node(n, max_depth, env);
514 * Encode a DAG starting by the IR-node node.
516 * @param node The root node of the graph
517 * @param buf The code buffer to store the bitstring in
518 * @param max_depth The maximum depth for descending
520 * @return The depth of the encoded graph (without cycles)
522 static int encode_node(ir_node *node, CODE_BUFFER *buf, int max_depth)
527 /* initialize the encoder environment */
529 env.curr_id = 1; /* 0 is used for special purpose */
530 env.options = status->options;
533 if (env.options & OPT_ENC_DAG)
534 env.id_set = new_set(addr_cmp, 32);
538 /* encode options if any for the decoder */
540 put_tag(buf, VLC_TAG_OPTION);
541 put_code(buf, env.options);
544 res = _encode_node(node, max_depth, &env);
546 if (env.id_set != NULL)
549 return max_depth - res;
553 * Decode an IR-node, recursive walker.
555 static void _decode_node(unsigned parent, int position, codec_env_t *env)
559 unsigned mode_code = 0;
563 code = next_tag(env->buf);
564 if (code == VLC_TAG_REF) { /* it's a REF */
565 code = get_code(env->buf);
571 * the mode of a Firm edge can be either computed from its target or
572 * from its source and position. We must take the second approach because
573 * we don't know the target here, it's a ref.
575 pattern_dump_edge(env->dmp, code, parent, position, edge_mode);
578 /* dump the node ref */
579 pattern_dump_ref(env->dmp, code);
585 op_code = get_code(env->buf);
587 /* get the mode if encoded */
588 if (env->options & OPT_WITH_MODE) {
589 if (next_tag(env->buf) != VLC_TAG_EMPTY) {
590 mode_code = get_code(env->buf);
594 /* check, if a ICONST attribute is given */
595 if (next_tag(env->buf) == VLC_TAG_ICONST) {
596 iconst = get_code(env->buf);
605 * the mode of a Firm edge can be either computed from its target or
606 * from its source and position. We take the second approach because
607 * we need it anyway for ref's.
609 pattern_dump_edge(env->dmp, env->curr_id, parent, position, edge_mode);
613 parent = env->curr_id;
614 pattern_dump_node(env->dmp, parent, op_code, mode_code, attr);
616 /* ok, we have a new ID */
619 code = next_tag(env->buf);
620 if (code != VLC_TAG_END) {
621 /* more info, do recursion */
624 preds = get_code(env->buf);
626 pattern_start_children(env->dmp, parent);
627 for (i = 0; i < preds; ++i) {
628 _decode_node(parent, i, env);
630 pattern_finish_children(env->dmp, parent);
638 static void decode_node(BYTE *b, size_t len, pattern_dumper_t *dump)
642 unsigned code, options = 0;
644 init_buf(&buf, b, len);
647 env.curr_id = 1; /* 0 is used for special purpose */
651 code = next_tag(&buf);
652 if (code == VLC_TAG_OPTION) {
653 options = get_code(&buf);
655 env.options = options;
657 _decode_node(0, 0, &env);
661 * The environment for the pattern calculation.
663 typedef struct pattern_env {
664 int max_depth; /**< maximum depth for pattern generation. */
668 * Returns the associates pattern_entry_t for a CODE_BUF.
670 * @param buf the code buffer
671 * @param set the hash table containing all pattern entries
673 * @return the associated pattern_entry_t for the given code buffer
675 * If the code content was never seen before, a new pattern_entry is created
678 static pattern_entry_t *pattern_get_entry(CODE_BUFFER *buf, pset *set)
680 pattern_entry_t *key, *elem;
681 size_t len = buf_lenght(buf);
684 key = OALLOCF(&status->obst, pattern_entry_t, buf, len);
686 memcpy(key->buf, buf_content(buf), len);
688 hash = buf_hash(buf);
690 elem = (pattern_entry_t*)pset_find(set, key, hash);
692 obstack_free(&status->obst, key);
696 cnt_clr(&key->count);
697 return (pattern_entry_t*)pset_insert(set, key, hash);
698 } /* pattern_get_entry */
701 * Increase the count for a pattern.
703 * @param buf the code buffer containing the pattern
704 * @param depth the pattern depth
706 * @note Single node patterns are ignored
708 static void count_pattern(CODE_BUFFER *buf, int depth)
710 pattern_entry_t *entry;
712 /* ignore single node pattern (i.e. constants) */
714 entry = pattern_get_entry(buf, status->pattern_hash);
717 cnt_inc(&entry->count);
719 } /* count_pattern */
722 * Pre-walker for nodes pattern calculation.
724 static void calc_nodes_pattern(ir_node *node, void *ctx)
726 pattern_env_t *env = (pattern_env_t*)ctx;
727 BYTE buffer[PATTERN_STORE_SIZE];
731 init_buf(&buf, buffer, sizeof(buffer));
732 depth = encode_node(node, &buf, env->max_depth);
734 if (buf_overrun(&buf)) {
735 lc_fprintf(stderr, "Pattern store: buffer overrun at size %zu. Pattern ignored.\n", sizeof(buffer));
737 count_pattern(&buf, depth);
738 } /* calc_nodes_pattern */
741 * Store all collected patterns.
743 * @param fname filename for storage
745 static void store_pattern(const char *fname)
748 pattern_entry_t *entry;
749 size_t i, count = pset_count(status->pattern_hash);
754 f = fopen(fname, "wb");
760 fwrite("FPS1", 4, 1, f);
761 fwrite(&count, sizeof(count), 1, f);
763 for (i = 0, entry = (pattern_entry_t*)pset_first(status->pattern_hash);
765 entry = (pattern_entry_t*)pset_next(status->pattern_hash), ++i) {
766 fwrite(entry, offsetof(pattern_entry_t, buf) + entry->len, 1, f);
769 } /* store_pattern */
772 * Read collected patterns from a file.
774 * @param fname filename
776 static HASH_MAP(pattern_entry_t) *read_pattern(const char *fname)
779 pattern_entry_t *entry, tmp;
783 HASH_MAP(pattern_entry_t) *pattern_hash = new_pset(pattern_cmp, 8);
784 BYTE buffer[PATTERN_STORE_SIZE];
787 f = fopen(fname, "rb");
793 fread(magic, 4, 1, f);
795 fread(&count, sizeof(count), 1, f);
796 if (memcmp(magic, "FPS1", 4) != 0 || count <= 0) {
797 fprintf(stderr, "Error: %s is not a Firm pattern store. Ignored.\n", fname);
802 /* read all pattern entries and put them into the hash table. */
803 for (i = 0; i < count; ++i) {
804 init_buf(&buf, buffer, sizeof(buffer));
805 fread(&tmp, offsetof(pattern_entry_t, buf), 1, f);
806 for (j = 0; j < tmp.len; ++j)
807 put_byte(&buf, fgetc(f));
808 entry = pattern_get_entry(&buf, pattern_hash);
809 entry->count = tmp.count;
813 lc_printf("Read %zu pattern from %s\n", count, fname);
814 assert(pset_count(pattern_hash) == count);
820 * Write the collected patterns to a VCG file for inspection.
822 * @param fname name of the VCG file to create
824 static void pattern_output(const char *fname)
826 pattern_entry_t *entry;
827 pattern_entry_t **pattern_arr;
828 pattern_dumper_t *dump;
829 size_t i, count = pset_count(status->pattern_hash);
831 lc_printf("\n%zu pattern detected\n", count);
836 /* creates a dumper */
837 dump = new_vcg_dumper(fname, 100);
839 pattern_arr = XMALLOCN(pattern_entry_t*, count);
840 for (i = 0, entry = (pattern_entry_t*)pset_first(status->pattern_hash);
842 entry = (pattern_entry_t*)pset_next(status->pattern_hash), ++i) {
843 pattern_arr[i] = entry;
849 qsort(pattern_arr, count, sizeof(*pattern_arr), pattern_count_cmp);
851 for (i = 0; i < count; ++i) {
852 entry = pattern_arr[i];
853 if (cnt_to_uint(&entry->count) < status->bound)
857 pattern_dump_new_pattern(dump, &entry->count);
858 decode_node(entry->buf, entry->len, dump);
859 pattern_dump_finish_pattern(dump);
864 } /* pattern_output */
867 * Calculates the pattern history.
869 void stat_calc_pattern_history(ir_graph *irg)
874 if (! status->enable)
877 /* do NOT count the const code IRG */
878 if (irg == get_const_code_irg())
881 for (i = status->min_depth; i <= status->max_depth; ++i) {
883 irg_walk_graph(irg, calc_nodes_pattern, NULL, &env);
885 } /* stat_calc_pattern_history */
888 * Initializes the pattern history.
890 void stat_init_pattern_history(int enable)
892 HASH_MAP(pattern_entry_t) *pattern_hash = NULL;
894 status->enable = enable;
899 status->options = /* OPT_WITH_MODE | */ OPT_ENC_DAG | OPT_WITH_ICONST | OPT_PERSIST_PATTERN;
900 status->min_depth = 3;
901 status->max_depth = 5;
903 obstack_init(&status->obst);
905 /* create the hash-table */
906 if (status->options & OPT_PERSIST_PATTERN)
907 pattern_hash = read_pattern("pattern.fps");
908 if (pattern_hash == NULL)
909 pattern_hash = new_pset(pattern_cmp, 8);
910 status->pattern_hash = pattern_hash;
911 } /* stat_init_pattern_history */
914 * Finish the pattern history.
916 void stat_finish_pattern_history(const char *fname)
919 if (! status->enable)
922 store_pattern("pattern.fps");
923 pattern_output("pattern.vcg");
925 del_pset(status->pattern_hash);
926 obstack_free(&status->obst, NULL);
929 } /* stat_finish_pattern_history */