2 * Copyright (C) 1995-2009 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 Write textual representation of firm to file.
23 * @author Moritz Kroll
34 #include "irgraph_t.h"
44 #define SYMERROR ((unsigned) ~0)
49 set *idset; /**< id_entry set, which maps from file ids to new Firm elements */
55 typedef enum typetag_t
69 typedef struct symbol_t
71 const char *str; /**< The name of this symbol. */
72 typetag_t typetag; /**< The type tag of this symbol. */
73 unsigned code; /**< The value of this symbol. */
76 typedef struct id_entry
82 /** The symbol table, a set of symbol_t elements. */
87 * Calculate a hash value for a string.
89 static unsigned string_hash(const char *str, int len)
91 return str[0] * 27893 ^ str[len-1] * 81 ^ str[len >> 1];
95 * Compare two symbol table entries.
97 static int symbol_cmp(const void *elt, const void *key, size_t size)
99 const symbol_t *entry = (const symbol_t *) elt;
100 const symbol_t *keyentry = (const symbol_t *) key;
102 return strcmp(entry->str, keyentry->str);
105 static int id_cmp(const void *elt, const void *key, size_t size)
107 const id_entry *entry = (const id_entry *) elt;
108 const id_entry *keyentry = (const id_entry *) key;
110 return entry->id - keyentry->id;
113 /** Initializes the symbol table. May be called more than once without problems. */
114 static void symtbl_init(void)
118 /* Only initialize once */
122 symtbl = new_set(symbol_cmp, 32);
124 #define INSERT(s, tt, cod) \
126 key.typetag = (tt); \
128 set_insert(symtbl, &key, sizeof(key), string_hash(s, sizeof(s)-1))
130 #define INSERTENUM(tt, e) INSERT(#e, tt, e)
132 INSERT("primitive", tt_tpo, tpo_primitive);
133 INSERT("method", tt_tpo, tpo_method);
134 INSERT("array", tt_tpo, tpo_array);
135 INSERT("struct", tt_tpo, tpo_struct);
136 INSERT("Unknown", tt_tpo, tpo_unknown);
138 #include "gen_irio_lex.inl"
140 INSERTENUM(tt_align, align_non_aligned);
141 INSERTENUM(tt_align, align_is_aligned);
143 INSERTENUM(tt_allocation, allocation_automatic);
144 INSERTENUM(tt_allocation, allocation_parameter);
145 INSERTENUM(tt_allocation, allocation_dynamic);
146 INSERTENUM(tt_allocation, allocation_static);
148 INSERTENUM(tt_pin_state, op_pin_state_floats);
149 INSERTENUM(tt_pin_state, op_pin_state_pinned);
150 INSERTENUM(tt_pin_state, op_pin_state_exc_pinned);
151 INSERTENUM(tt_pin_state, op_pin_state_mem_pinned);
153 INSERTENUM(tt_type_state, layout_undefined);
154 INSERTENUM(tt_type_state, layout_fixed);
156 INSERTENUM(tt_variability, variability_uninitialized);
157 INSERTENUM(tt_variability, variability_initialized);
158 INSERTENUM(tt_variability, variability_part_constant);
159 INSERTENUM(tt_variability, variability_constant);
161 INSERTENUM(tt_visibility, visibility_local);
162 INSERTENUM(tt_visibility, visibility_external_visible);
163 INSERTENUM(tt_visibility, visibility_external_allocated);
165 INSERTENUM(tt_volatility, volatility_non_volatile);
166 INSERTENUM(tt_volatility, volatility_is_volatile);
168 INSERTENUM(tt_peculiarity, peculiarity_description);
169 INSERTENUM(tt_peculiarity, peculiarity_inherited);
170 INSERTENUM(tt_peculiarity, peculiarity_existent);
176 /** Returns the according symbol value for the given string and tag, or SYMERROR if none was found. */
177 static unsigned symbol(const char *str, typetag_t typetag)
179 symbol_t key, *entry;
183 entry = set_find(symtbl, &key, sizeof(key), string_hash(str, strlen(str)));
184 if (entry && entry->typetag == typetag) {
190 static void *get_id(io_env_t *env, long id)
192 id_entry key, *entry;
195 entry = set_find(env->idset, &key, sizeof(key), (unsigned) id);
196 return entry ? entry->elem : NULL;
199 static void set_id(io_env_t *env, long id, void *elem)
204 set_insert(env->idset, &key, sizeof(key), (unsigned) id);
207 static void write_mode(io_env_t *env, ir_mode *mode)
209 fputs(get_mode_name(mode), env->file);
210 fputc(' ', env->file);
213 static void write_pinned(io_env_t *env, ir_node *irn)
215 fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
216 fputc(' ', env->file);
219 static void write_volatility(io_env_t *env, ir_node *irn)
223 if(is_Load(irn)) vol = get_Load_volatility(irn);
224 else if(is_Store(irn)) vol = get_Store_volatility(irn);
225 else assert(0 && "Invalid optype for write_volatility");
227 fputs(get_volatility_name(vol), env->file);
228 fputc(' ', env->file);
231 static void write_align(io_env_t *env, ir_node *irn)
235 if(is_Load(irn)) align = get_Load_align(irn);
236 else if(is_Store(irn)) align = get_Store_align(irn);
237 else assert(0 && "Invalid optype for write_align");
239 fputs(get_align_name(align), env->file);
240 fputc(' ', env->file);
243 static void export_type(io_env_t *env, ir_type *tp)
247 fprintf(f, "\ttype %ld %s \"%s\" %u %u %s %s ",
249 get_type_tpop_name(tp),
251 get_type_size_bytes(tp),
252 get_type_alignment_bytes(tp),
253 get_type_state_name(get_type_state(tp)),
254 get_visibility_name(get_type_visibility(tp)));
256 switch(get_type_tpop_code(tp))
260 int n = get_array_n_dimensions(tp);
261 fprintf(f, "%i %ld ", n, get_type_nr(get_array_element_type(tp)));
262 for(i = 0; i < n; i++)
264 ir_node *lower = get_array_lower_bound(tp, i);
265 ir_node *upper = get_array_upper_bound(tp, i);
267 if(is_Const(lower)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(lower)));
268 else panic("Lower array bound is not constant");
270 if(is_Const(upper)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(upper)));
271 else panic("Upper array bound is not constant");
278 int nparams = get_method_n_params(tp);
279 int nresults = get_method_n_ress(tp);
280 fprintf(f, "%i %i ", nparams, nresults);
281 for(i = 0; i < nparams; i++)
282 fprintf(f, "%ld ", get_type_nr(get_method_param_type(tp, i)));
283 for(i = 0; i < nresults; i++)
284 fprintf(f, "%ld ", get_type_nr(get_method_res_type(tp, i)));
290 write_mode(env, get_type_mode(tp));
298 /* TODO: inheritance stuff not supported yet */
299 printf("Inheritance of classes not supported yet!\n");
306 printf("export_type: Unknown type code \"%s\".\n", get_type_tpop_name(tp));
312 static void export_entity(io_env_t *env, ir_entity *ent)
314 ir_type *owner = get_entity_owner(ent);
315 fprintf(env->file, "\tentity %ld \"%s\" %ld %ld %d %u %s %s %s %s %s\n",
317 get_entity_name(ent),
318 get_type_nr(get_entity_type(ent)),
320 get_entity_offset(ent),
321 (unsigned) get_entity_offset_bits_remainder(ent),
322 get_allocation_name(get_entity_allocation(ent)),
323 get_visibility_name(get_entity_visibility(ent)),
324 get_variability_name(get_entity_variability(ent)),
325 get_peculiarity_name(get_entity_peculiarity(ent)),
326 get_volatility_name(get_entity_volatility(ent)));
328 // TODO: inheritance stuff for class entities not supported yet
329 if(is_Class_type(owner) && owner != get_glob_type())
330 printf("Inheritance of class entities not supported yet!\n");
333 static void export_type_or_ent(type_or_ent tore, void *ctx)
335 io_env_t *env = (io_env_t *) ctx;
337 switch(get_kind(tore.ent))
340 export_entity(env, tore.ent);
344 export_type(env, tore.typ);
348 printf("export_type_or_ent: Unknown type or entity.\n");
353 static void export_node(ir_node *irn, void *ctx)
355 io_env_t *env = (io_env_t *) ctx;
357 unsigned opcode = get_irn_opcode(irn);
360 if(env->ignoreblocks && opcode == iro_Block)
363 n = get_irn_arity(irn);
365 fprintf(env->file, "\n\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
367 for(i = -1; i < n; i++)
369 ir_node *pred = get_irn_n(irn, i);
371 /* Anchor node may ave NULL predecessors */
372 assert(is_Anchor(irn));
373 fputs("-1 ", env->file);
375 fprintf(env->file, "%ld ", get_irn_node_nr(pred));
379 fprintf(env->file, "] { ");
383 #include "gen_irio_export.inl"
385 fputc('}', env->file);
388 /** Exports the given irg to the given file. */
389 void ir_export_irg(ir_graph *irg, const char *filename)
393 env.file = fopen(filename, "wt");
400 fputs("typegraph {\n", env.file);
402 type_walk_irg(irg, NULL, export_type_or_ent, &env);
404 fprintf(env.file, "}\n\nirg %ld {", get_entity_nr(get_irg_entity(irg)));
406 env.ignoreblocks = 0;
407 irg_block_walk_graph(irg, NULL, export_node, &env);
409 env.ignoreblocks = 1;
410 irg_walk_anchors(irg, NULL, export_node, &env);
412 fputs("\n}\n", env.file);
417 static int read_c(io_env_t *env)
419 int ch = fgetc(env->file);
438 /** Returns the first non-whitespace character or EOF. **/
439 static int skip_ws(io_env_t *env)
443 int ch = read_c(env);
458 static void skip_to(io_env_t *env, char to_ch)
465 while(ch != to_ch && ch != EOF);
468 static int expect_char(io_env_t *env, char ch)
470 int curch = skip_ws(env);
473 printf("Unexpected char '%c', expected '%c' in line %i:%i\n", curch, ch, env->line, env->col);
479 #define EXPECT(c) if(expect_char(env, (c))) {} else return 0
480 #define EXPECT_OR_EXIT(c) if(expect_char(env, (c))) {} else exit(1)
482 inline static const char *read_str_to(io_env_t *env, char *buf, size_t bufsize)
485 for(i = 0; i < bufsize - 1; i++)
487 int ch = read_c(env);
497 i--; // skip whitespace
510 static const char *read_str(io_env_t *env)
512 static char buf[1024];
513 return read_str_to(env, buf, sizeof(buf));
516 static const char *read_qstr_to(io_env_t *env, char *buf, size_t bufsize)
519 EXPECT_OR_EXIT('\"');
520 for(i = 0; i < bufsize - 1; i++)
522 int ch = read_c(env);
525 printf("Unexpected end of quoted string!\n");
528 if(ch == '\"') break;
534 printf("Quoted string too long!\n");
541 static long read_long2(io_env_t *env, char **endptr)
543 static char buf[1024];
544 return strtol(read_str_to(env, buf, sizeof(buf)), endptr, 0);
547 static long read_long(io_env_t *env)
549 return read_long2(env, NULL);
552 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
554 ir_node *node = (ir_node *) get_id(env, nodenr);
555 if(node && node->kind != k_ir_node)
557 panic("Irn ID %ld collides with something else in line %i:%i\n", nodenr, env->line, env->col);
562 static ir_node *get_node(io_env_t *env, long nodenr)
564 ir_node *node = get_node_or_null(env, nodenr);
566 panic("Unknown node: %ld in line %i:%i\n", nodenr, env->line, env->col);
571 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
573 ir_node *node = get_node_or_null(env, nodenr);
576 node = new_Dummy(mode_X);
577 set_id(env, nodenr, node);
582 static ir_type *get_type(io_env_t *env, long typenr)
584 ir_type *type = (ir_type *) get_id(env, typenr);
587 panic("Unknown type: %ld in line %i:%i\n", typenr, env->line, env->col);
589 else if(type->kind != k_type)
591 panic("Type ID %ld collides with something else in line %i:%i\n", typenr, env->line, env->col);
596 static ir_type *read_type(io_env_t *env)
598 return get_type(env, read_long(env));
601 static ir_entity *get_entity(io_env_t *env, long entnr)
603 ir_entity *entity = (ir_entity *) get_id(env, entnr);
606 printf("Unknown entity: %ld in line %i:%i\n", entnr, env->line, env->col);
609 else if(entity->kind != k_entity)
611 panic("Entity ID %ld collides with something else in line %i:%i\n", entnr, env->line, env->col);
616 static ir_entity *read_entity(io_env_t *env)
618 return get_entity(env, read_long(env));
621 static ir_mode *read_mode(io_env_t *env)
623 static char buf[128];
626 read_str_to(env, buf, sizeof(buf));
628 n = get_irp_n_modes();
629 for(i = 0; i < n; i++)
631 ir_mode *mode = get_irp_mode(i);
632 if(!strcmp(buf, get_mode_name(mode)))
636 printf("Unknown mode \"%s\" in line %i:%i\n", buf, env->line, env->col);
640 static const char *get_typetag_name(typetag_t typetag)
644 case tt_iro: return "opcode";
645 case tt_tpo: return "type";
646 case tt_align: return "align";
647 case tt_allocation: return "allocation";
648 case tt_peculiarity: return "peculiarity";
649 case tt_pin_state: return "pin state";
650 case tt_type_state: return "type state";
651 case tt_variability: return "variability";
652 case tt_visibility: return "visibility";
653 case tt_volatility: return "volatility";
654 default: return "<UNKNOWN>";
659 * Read and decode an enum constant.
661 static unsigned read_enum(io_env_t *env, typetag_t typetag)
663 static char buf[128];
664 unsigned code = symbol(read_str_to(env, buf, sizeof(buf)), typetag);
668 printf("Invalid %s: \"%s\" in %i:%i\n", get_typetag_name(typetag), buf, env->line, env->col);
672 #define read_align(env) ((ir_align) read_enum(env, tt_align))
673 #define read_allocation(env) ((ir_allocation) read_enum(env, tt_allocation))
674 #define read_peculiarity(env) ((ir_peculiarity) read_enum(env, tt_peculiarity))
675 #define read_pinned(env) ((op_pin_state) read_enum(env, tt_pin_state))
676 #define read_type_state(env) ((ir_type_state) read_enum(env, tt_type_state))
677 #define read_variability(env) ((ir_variability) read_enum(env, tt_variability))
678 #define read_visibility(env) ((ir_visibility) read_enum(env, tt_visibility))
679 #define read_volatility(env) ((ir_volatility) read_enum(env, tt_volatility))
681 static tarval *read_tv(io_env_t *env)
683 static char buf[128];
684 ir_mode *tvmode = read_mode(env);
685 read_str_to(env, buf, sizeof(buf));
686 return new_tarval_from_str(buf, strlen(buf), tvmode);
689 /** Reads a type description and remembers it by its id. */
690 static void import_type(io_env_t *env)
695 long typenr = read_long(env);
696 const char *tpop = read_str(env);
697 const char *name = read_qstr_to(env, buf, sizeof(buf));
698 unsigned size = (unsigned) read_long(env);
699 unsigned align = (unsigned) read_long(env);
700 ir_type_state state = read_type_state(env);
701 ir_visibility vis = read_visibility(env);
703 ident *id = new_id_from_str(name);
705 switch(symbol(tpop, tt_tpo))
709 ir_mode *mode = read_mode(env);
710 type = new_type_primitive(id, mode);
716 int nparams = (int) read_long(env);
717 int nresults = (int) read_long(env);
719 type = new_type_method(id, nparams, nresults);
721 for(i = 0; i < nparams; i++)
723 long typenr = read_long(env);
724 ir_type *paramtype = get_type(env, typenr);
726 set_method_param_type(type, i, paramtype);
728 for(i = 0; i < nresults; i++)
730 long typenr = read_long(env);
731 ir_type *restype = get_type(env, typenr);
733 set_method_res_type(type, i, restype);
740 int ndims = (int) read_long(env);
741 long elemtypenr = read_long(env);
742 ir_type *elemtype = get_type(env, elemtypenr);
744 type = new_type_array(id, ndims, elemtype);
745 for(i = 0; i < ndims; i++)
747 long lowerbound = read_long(env);
748 long upperbound = read_long(env);
749 set_array_bounds_int(type, i, lowerbound, upperbound);
751 set_type_size_bytes(type, size);
756 type = new_type_class(id);
757 set_type_size_bytes(type, size);
761 type = new_type_struct(id);
762 set_type_size_bytes(type, size);
766 type = new_type_union(id);
767 set_type_size_bytes(type, size);
771 return; // ignore unknown type
774 if(typenr != 0) // ignore global type
775 printf("Unknown type kind: \"%s\" in line %i:%i\n", tpop, env->line, env->col);
780 set_type_alignment_bytes(type, align);
781 set_type_visibility(type, vis);
783 if(state == layout_fixed)
784 ARR_APP1(ir_type *, env->fixedtypes, type);
786 set_id(env, typenr, type);
787 printf("Insert type %s %ld\n", name, typenr);
790 /** Reads an entity description and remembers it by its id. */
791 static void import_entity(io_env_t *env)
794 long entnr = read_long(env);
795 const char *name = read_qstr_to(env, buf, sizeof(buf));
796 long typenr = read_long(env);
797 long ownertypenr = read_long(env);
799 ir_type *type = get_type(env, typenr);
800 ir_type *ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
801 ir_entity *entity = new_entity(ownertype, new_id_from_str(name), type);
803 set_entity_offset (entity, (int) read_long(env));
804 set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
805 set_entity_allocation (entity, read_allocation(env));
806 set_entity_visibility (entity, read_visibility(env));
807 set_entity_variability(entity, read_variability(env));
808 set_entity_peculiarity(entity, read_peculiarity(env));
809 set_entity_volatility (entity, read_volatility(env));
811 set_id(env, entnr, entity);
812 printf("Insert entity %s %ld\n", name, entnr);
815 /** Parses the whole type graph. */
816 static int parse_typegraph(io_env_t *env)
823 curfpos = ftell(env->file);
825 // parse all types first
828 kind = read_str(env);
829 if(kind[0] == '}' && !kind[1]) break;
831 if(!strcmp(kind, "type"))
838 fseek(env->file, curfpos, SEEK_SET);
841 kind = read_str(env);
842 if(kind[0] == '}' && !kind[1]) break;
844 if(!strcmp(kind, "type"))
846 else if(!strcmp(kind, "entity"))
850 printf("Type graph element not supported yet: \"%s\"\n", kind);
857 static int read_node_header(io_env_t *env, long *nodenr, long **preds, const char **nodename)
860 *nodename = read_str(env);
861 if((*nodename)[0] == '}' && !(*nodename)[1]) return -1; // end-of-graph
863 *nodenr = read_long(env);
865 ARR_RESIZE(ir_node *, *preds, 0);
868 for(numpreds = 0; !feof(env->file); numpreds++)
871 ARR_APP1(long, *preds, read_long2(env, &endptr));
872 if(*endptr == ']') break;
877 /** Parses an IRG. */
878 static int parse_graph(io_env_t *env)
880 long *preds = NEW_ARR_F(long, 16);
881 ir_node **prednodes = NEW_ARR_F(ir_node *, 16);
882 int i, numpreds, ret = 1;
884 const char *nodename;
885 ir_node *node, *newnode;
887 current_ir_graph = new_ir_graph(get_entity(env, read_long(env)), 0);
893 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
894 if(numpreds == -1) break; // end-of-graph
897 printf("Node %s %ld is missing predecessors!", nodename, nodenr);
902 ARR_RESIZE(ir_node *, prednodes, numpreds);
903 for(i = 0; i < numpreds - 1; i++)
904 prednodes[i] = get_node_or_dummy(env, preds[i + 1]);
906 node = get_node_or_null(env, nodenr);
911 switch(symbol(nodename, tt_iro))
915 ir_node *newendblock = get_node(env, preds[0]);
916 newnode = get_irg_end(current_ir_graph);
917 exchange(get_nodes_block(newnode), newendblock);
923 ir_node *newstartblock = get_node(env, preds[0]);
924 newnode = get_irg_start(current_ir_graph);
925 exchange(get_nodes_block(newnode), newstartblock);
931 if(preds[0] != nodenr)
933 printf("Invalid block: preds[0] != nodenr (%ld != %ld)\n",
939 newnode = new_Block(numpreds - 1, prednodes);
944 newnode = current_ir_graph->anchor;
945 for(i = 0; i < numpreds - 1; i++)
946 set_irn_n(newnode, i, prednodes[i]);
947 set_irn_n(newnode, -1, get_node(env, preds[0]));
952 long entnr = read_long(env);
953 union symconst_symbol sym;
954 sym.entity_p = get_entity(env, entnr);
955 newnode = new_SymConst(mode_P, sym, symconst_addr_ent);
959 #include "gen_irio_import.inl"
970 panic("Node type not supported yet: %s in line %i:%i\n", nodename, env->line, env->col);
974 exchange(node, newnode);
975 /* Always update hash entry to avoid more uses of id nodes */
976 set_id(env, nodenr, newnode);
977 printf("Insert %s %ld\n", nodename, nodenr);
982 DEL_ARR_F(prednodes);
987 /** Imports an previously exported textual representation of an (maybe partial) irp */
988 void ir_import(const char *filename)
990 int oldoptimize = get_optimize();
991 firm_verification_t oldver = get_node_verification_mode();
993 io_env_t *env = &ioenv;
998 memset(env, 0, sizeof(*env));
999 env->idset = new_set(id_cmp, 128);
1000 env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1002 env->file = fopen(filename, "rt");
1010 do_node_verification(FIRM_VERIFICATION_OFF);
1014 const char *str = read_str(env);
1016 if(!strcmp(str, "typegraph"))
1018 if(!parse_typegraph(env)) break;
1020 else if(!strcmp(str, "irg"))
1022 if(!parse_graph(env)) break;
1026 n = ARR_LEN(env->fixedtypes);
1027 for(i = 0; i < n; i++)
1028 set_type_state(env->fixedtypes[i], layout_fixed);
1030 DEL_ARR_F(env->fixedtypes);
1032 del_set(env->idset);
1034 irp_finalize_cons();
1036 do_node_verification(oldver);
1037 set_optimize(oldoptimize);