you can specify in the spec now for which nodes no standard import/export code is...
[libfirm] / ir / ir / irio.c
1 /*
2  * Copyright (C) 1995-2009 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   Write textual representation of firm to file.
23  * @author  Moritz Kroll
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include <string.h>
29 #include <ctype.h>
30 #include <stdbool.h>
31 #include <stdarg.h>
32
33 #include "irio.h"
34
35 #include "irnode_t.h"
36 #include "irprog.h"
37 #include "irgraph_t.h"
38 #include "ircons.h"
39 #include "irgmod.h"
40 #include "irflag_t.h"
41 #include "irgwalk.h"
42 #include "tv.h"
43 #include "array.h"
44 #include "error.h"
45 #include "typerep.h"
46 #include "adt/set.h"
47 #include "adt/obst.h"
48
49 #define SYMERROR ((unsigned) ~0)
50
51 typedef struct io_env_t
52 {
53         int c;                /**< currently read char */
54         FILE *file;
55         set *idset;           /**< id_entry set, which maps from file ids to new Firm elements */
56         int ignoreblocks;
57         const char *inputname;
58         int line;
59         ir_type **fixedtypes;
60         struct obstack obst;
61         ir_graph *irg;
62 } io_env_t;
63
64 typedef enum typetag_t
65 {
66         tt_align,
67         tt_allocation,
68         tt_builtin,
69         tt_cond_jmp_predicate,
70         tt_initializer,
71         tt_iro,
72         tt_keyword,
73         tt_mode_sort,
74         tt_mode_arithmetic,
75         tt_pin_state,
76         tt_tpo,
77         tt_type_state,
78         tt_volatility,
79         tt_linkage,
80         tt_segment,
81         tt_visibility
82 } typetag_t;
83
84 typedef enum keyword_t
85 {
86         kw_constirg,
87         kw_entity,
88         kw_irg,
89         kw_mode,
90         kw_modes,
91         kw_type,
92         kw_typegraph,
93         kw_program,
94         kw_segment_type
95 } keyword_t;
96
97 typedef struct symbol_t
98 {
99         const char *str;      /**< The name of this symbol. */
100         typetag_t   typetag;  /**< The type tag of this symbol. */
101         unsigned    code;     /**< The value of this symbol. */
102 } symbol_t;
103
104 typedef struct id_entry
105 {
106         long id;
107         void *elem;
108 } id_entry;
109
110 /** The symbol table, a set of symbol_t elements. */
111 static set *symtbl;
112
113 /**
114  * Compare two symbol table entries.
115  */
116 static int symbol_cmp(const void *elt, const void *key, size_t size)
117 {
118         int res;
119         const symbol_t *entry = (const symbol_t *) elt;
120         const symbol_t *keyentry = (const symbol_t *) key;
121         (void) size;
122         res = entry->typetag - keyentry->typetag;
123         if (res) return res;
124         return strcmp(entry->str, keyentry->str);
125 }
126
127 static int id_cmp(const void *elt, const void *key, size_t size)
128 {
129         const id_entry *entry = (const id_entry *) elt;
130         const id_entry *keyentry = (const id_entry *) key;
131         (void) size;
132         return entry->id - keyentry->id;
133 }
134
135 static void __attribute__((format(printf, 2, 3)))
136 parse_error(io_env_t *env, const char *fmt, ...)
137 {
138         va_list ap;
139         int     line = env->line;
140
141         /* workaround read_c "feature" that a '\n' triggers the line++
142          * instead of the character after the '\n' */
143         if (env->c == '\n') {
144                 line--;
145         }
146
147         fprintf(stderr, "%s:%d: error ", env->inputname, line);
148
149         va_start(ap, fmt);
150         vfprintf(stderr, fmt, ap);
151         va_end(ap);
152 }
153
154 /** Initializes the symbol table. May be called more than once without problems. */
155 static void symtbl_init(void)
156 {
157         symbol_t key;
158
159         /* Only initialize once */
160         if (symtbl != NULL)
161                 return;
162
163         symtbl = new_set(symbol_cmp, 256);
164
165 #define INSERT(tt, s, cod)                                       \
166         key.str = (s);                                               \
167         key.typetag = (tt);                                          \
168         key.code = (cod);                                            \
169         set_insert(symtbl, &key, sizeof(key), firm_fnv_hash_str(s) + tt * 17)
170
171 #define INSERTENUM(tt, e) INSERT(tt, #e, e)
172 #define INSERTKEYWORD(k) INSERT(tt_keyword, #k, kw_##k)
173
174         INSERT(tt_tpo, "array", tpo_array);
175         INSERT(tt_tpo, "class", tpo_class);
176         INSERT(tt_tpo, "method", tpo_method);
177         INSERT(tt_tpo, "pointer", tpo_pointer);
178         INSERT(tt_tpo, "primitive", tpo_primitive);
179         INSERT(tt_tpo, "struct", tpo_struct);
180         INSERT(tt_tpo, "union", tpo_union);
181         INSERT(tt_tpo, "Unknown", tpo_unknown);
182
183         INSERT(tt_mode_sort, "auxiliary", irms_auxiliary);
184         INSERT(tt_mode_sort, "control_flow", irms_control_flow);
185         INSERT(tt_mode_sort, "memory", irms_memory);
186         INSERT(tt_mode_sort, "internal_boolean", irms_internal_boolean);
187         INSERT(tt_mode_sort, "reference", irms_reference);
188         INSERT(tt_mode_sort, "int_number", irms_int_number);
189         INSERT(tt_mode_sort, "float_number", irms_float_number);
190
191         INSERT(tt_segment, "global", IR_SEGMENT_GLOBAL);
192         INSERT(tt_segment, "thread_local", IR_SEGMENT_THREAD_LOCAL);
193         INSERT(tt_segment, "constructors", IR_SEGMENT_CONSTRUCTORS);
194         INSERT(tt_segment, "destructors", IR_SEGMENT_DESTRUCTORS);
195
196         INSERT(tt_linkage, "constant", IR_LINKAGE_CONSTANT);
197         INSERT(tt_linkage, "weak", IR_LINKAGE_WEAK);
198         INSERT(tt_linkage, "garbage_collect", IR_LINKAGE_GARBAGE_COLLECT);
199         INSERT(tt_linkage, "merge", IR_LINKAGE_MERGE);
200         INSERT(tt_linkage, "hidden_user", IR_LINKAGE_HIDDEN_USER);
201
202         INSERT(tt_visibility, "local", ir_visibility_local);
203         INSERT(tt_visibility, "external", ir_visibility_external);
204         INSERT(tt_visibility, "default", ir_visibility_default);
205         INSERT(tt_visibility, "private", ir_visibility_private);
206
207         INSERTKEYWORD(constirg);
208         INSERTKEYWORD(entity);
209         INSERTKEYWORD(irg);
210         INSERTKEYWORD(mode);
211         INSERTKEYWORD(modes);
212         INSERTKEYWORD(type);
213         INSERTKEYWORD(typegraph);
214         INSERTKEYWORD(program);
215         INSERTKEYWORD(segment_type);
216
217 #include "gen_irio_lex.inl"
218
219         INSERTENUM(tt_align, align_non_aligned);
220         INSERTENUM(tt_align, align_is_aligned);
221
222         INSERTENUM(tt_builtin, ir_bk_trap);
223         INSERTENUM(tt_builtin, ir_bk_debugbreak);
224         INSERTENUM(tt_builtin, ir_bk_return_address);
225         INSERTENUM(tt_builtin, ir_bk_frame_address);
226         INSERTENUM(tt_builtin, ir_bk_prefetch);
227         INSERTENUM(tt_builtin, ir_bk_ffs);
228         INSERTENUM(tt_builtin, ir_bk_clz);
229         INSERTENUM(tt_builtin, ir_bk_ctz);
230         INSERTENUM(tt_builtin, ir_bk_popcount);
231         INSERTENUM(tt_builtin, ir_bk_parity);
232         INSERTENUM(tt_builtin, ir_bk_bswap);
233         INSERTENUM(tt_builtin, ir_bk_inport);
234         INSERTENUM(tt_builtin, ir_bk_outport);
235         INSERTENUM(tt_builtin, ir_bk_inner_trampoline);
236
237         INSERTENUM(tt_cond_jmp_predicate, COND_JMP_PRED_NONE);
238         INSERTENUM(tt_cond_jmp_predicate, COND_JMP_PRED_TRUE);
239         INSERTENUM(tt_cond_jmp_predicate, COND_JMP_PRED_FALSE);
240
241         INSERTENUM(tt_initializer, IR_INITIALIZER_CONST);
242         INSERTENUM(tt_initializer, IR_INITIALIZER_TARVAL);
243         INSERTENUM(tt_initializer, IR_INITIALIZER_NULL);
244         INSERTENUM(tt_initializer, IR_INITIALIZER_COMPOUND);
245
246         INSERTENUM(tt_mode_arithmetic, irma_uninitialized);
247         INSERTENUM(tt_mode_arithmetic, irma_none);
248         INSERTENUM(tt_mode_arithmetic, irma_twos_complement);
249         INSERTENUM(tt_mode_arithmetic, irma_ones_complement);
250         INSERTENUM(tt_mode_arithmetic, irma_int_BCD);
251         INSERTENUM(tt_mode_arithmetic, irma_ieee754);
252         INSERTENUM(tt_mode_arithmetic, irma_float_BCD);
253
254         INSERTENUM(tt_pin_state, op_pin_state_floats);
255         INSERTENUM(tt_pin_state, op_pin_state_pinned);
256         INSERTENUM(tt_pin_state, op_pin_state_exc_pinned);
257         INSERTENUM(tt_pin_state, op_pin_state_mem_pinned);
258
259         INSERTENUM(tt_type_state, layout_undefined);
260         INSERTENUM(tt_type_state, layout_fixed);
261
262         INSERTENUM(tt_volatility, volatility_non_volatile);
263         INSERTENUM(tt_volatility, volatility_is_volatile);
264
265 #undef INSERTKEYWORD
266 #undef INSERTENUM
267 #undef INSERT
268 }
269
270 static const char *get_segment_name(ir_segment_t segment)
271 {
272         switch (segment) {
273         case IR_SEGMENT_GLOBAL:       return "global";
274         case IR_SEGMENT_THREAD_LOCAL: return "thread_local";
275         case IR_SEGMENT_CONSTRUCTORS: return "constructors";
276         case IR_SEGMENT_DESTRUCTORS:  return "destructors";
277         }
278         return "INVALID_SEGMENT";
279 }
280
281 static const char *get_visibility_name(ir_visibility visibility)
282 {
283         switch (visibility) {
284         case ir_visibility_local:    return "local";
285         case ir_visibility_external: return "external";
286         case ir_visibility_default:  return "default";
287         case ir_visibility_private:  return "private";
288         }
289         return "INVALID_VISIBILITY";
290 }
291
292 /** Returns the according symbol value for the given string and tag, or SYMERROR if none was found. */
293 static unsigned symbol(const char *str, typetag_t typetag)
294 {
295         symbol_t key, *entry;
296
297         key.str = str;
298         key.typetag = typetag;
299
300         entry = (symbol_t*)set_find(symtbl, &key, sizeof(key), firm_fnv_hash_str(str) + typetag * 17);
301         return entry ? entry->code : SYMERROR;
302 }
303
304 static void *get_id(io_env_t *env, long id)
305 {
306         id_entry key, *entry;
307         key.id = id;
308
309         entry = (id_entry*)set_find(env->idset, &key, sizeof(key), (unsigned) id);
310         return entry ? entry->elem : NULL;
311 }
312
313 static void set_id(io_env_t *env, long id, void *elem)
314 {
315         id_entry key;
316         key.id = id;
317         key.elem = elem;
318         set_insert(env->idset, &key, sizeof(key), (unsigned) id);
319 }
320
321 static void write_mode(io_env_t *env, ir_mode *mode)
322 {
323         fputs(get_mode_name(mode), env->file);
324         fputc(' ', env->file);
325 }
326
327 static void write_tarval(io_env_t *env, ir_tarval *tv)
328 {
329         char buf[1024];
330         write_mode(env, get_tarval_mode(tv));
331         tarval_snprintf(buf, sizeof(buf), tv);
332         fputs(buf, env->file);
333         fputc(' ', env->file);
334 }
335
336 static void write_align(io_env_t *env, ir_node *irn)
337 {
338         ir_align align;
339
340         if (is_Load(irn))
341                 align = get_Load_align(irn);
342         else if (is_Store(irn))
343                 align = get_Store_align(irn);
344         else
345                 panic("Invalid optype for write_align");
346
347         fputs(get_align_name(align), env->file);
348         fputc(' ', env->file);
349 }
350
351 static void write_builtin_kind(io_env_t *env, ir_node *irn)
352 {
353         fputs(get_builtin_kind_name(get_Builtin_kind(irn)), env->file);
354         fputc(' ', env->file);
355 }
356
357 static void write_cond_jmp_predicate(io_env_t *env, ir_node *irn)
358 {
359         fputs(get_cond_jmp_predicate_name(get_Cond_jmp_pred(irn)), env->file);
360         fputc(' ', env->file);
361 }
362
363 static void write_initializer(io_env_t *env, ir_initializer_t *ini)
364 {
365         FILE *f = env->file;
366         ir_initializer_kind_t ini_kind = get_initializer_kind(ini);
367
368         fputs(get_initializer_kind_name(ini_kind), f);
369         fputc(' ', f);
370
371         switch (ini_kind) {
372         case IR_INITIALIZER_CONST:
373                 fprintf(f, "%ld ", get_irn_node_nr(get_initializer_const_value(ini)));
374                 break;
375
376         case IR_INITIALIZER_TARVAL:
377                 write_tarval(env, get_initializer_tarval_value(ini));
378                 break;
379
380         case IR_INITIALIZER_NULL:
381                 break;
382
383         case IR_INITIALIZER_COMPOUND: {
384                 unsigned i, n = get_initializer_compound_n_entries(ini);
385                 fprintf(f, "%u ", n);
386                 for (i = 0; i < n; i++)
387                         write_initializer(env, get_initializer_compound_value(ini, i));
388                 break;
389         }
390
391         default:
392                 panic("Unknown initializer kind");
393         }
394 }
395
396 static void write_pin_state(io_env_t *env, ir_node *irn)
397 {
398         fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
399         fputc(' ', env->file);
400 }
401
402 static void write_volatility(io_env_t *env, ir_node *irn)
403 {
404         ir_volatility vol;
405
406         if (is_Load(irn))
407                 vol = get_Load_volatility(irn);
408         else if (is_Store(irn))
409                 vol = get_Store_volatility(irn);
410         else
411                 panic("Invalid optype for write_volatility");
412
413         fputs(get_volatility_name(vol), env->file);
414         fputc(' ', env->file);
415 }
416
417 static void export_type_common(io_env_t *env, ir_type *tp)
418 {
419         fprintf(env->file, "\ttype %ld %s %u %u %s %u ",
420                 get_type_nr(tp),
421                 get_type_tpop_name(tp),
422                 get_type_size_bytes(tp),
423                 get_type_alignment_bytes(tp),
424                 get_type_state_name(get_type_state(tp)),
425                 tp->flags);
426 }
427
428 static void export_compound_name(FILE *f, const ir_type *tp)
429 {
430         ident *name = get_compound_ident(tp);
431         if (name == NULL) {
432                 fputs("NULL ", f);
433         } else {
434                 fprintf(f, "\"%s\" ", get_id_str(name));
435         }
436 }
437
438 static void export_type_pre(io_env_t *env, ir_type *tp)
439 {
440         FILE *f = env->file;
441
442         /* skip types to be handled by post walker */
443         switch (get_type_tpop_code(tp)) {
444         case tpo_array:
445         case tpo_method:
446         case tpo_pointer:
447                 return;
448         default:
449                 break;
450         }
451
452         export_type_common(env, tp);
453
454         switch (get_type_tpop_code(tp)) {
455         case tpo_uninitialized:
456                 panic("invalid type found");
457
458         case tpo_class:
459                 export_compound_name(f, tp);
460                 break;
461
462         case tpo_primitive:
463                 write_mode(env, get_type_mode(tp));
464                 break;
465
466         case tpo_union:
467         case tpo_struct:
468         case tpo_enumeration:
469                 export_compound_name(f, tp);
470                 break;
471
472         case tpo_array:
473         case tpo_method:
474         case tpo_pointer:
475         case tpo_code:
476         case tpo_none:
477         case tpo_unknown:
478                 break;
479         }
480         fputc('\n', f);
481 }
482
483 static void export_type_post(io_env_t *env, ir_type *tp)
484 {
485         FILE *f = env->file;
486         int i;
487
488         /* skip types already handled by pre walker */
489         switch (get_type_tpop_code(tp)) {
490         case tpo_class:
491         case tpo_primitive:
492         case tpo_struct:
493         case tpo_union:
494         case tpo_unknown:
495         case tpo_uninitialized:
496         case tpo_code:
497         case tpo_none:
498                 return;
499         case tpo_array:
500         case tpo_method:
501         case tpo_pointer:
502         case tpo_enumeration:
503                 break;
504         }
505
506         export_type_common(env, tp);
507
508         switch (get_type_tpop_code(tp)) {
509         case tpo_array: {
510                 int n = get_array_n_dimensions(tp);
511                 fprintf(f, "%d %ld ", n, get_type_nr(get_array_element_type(tp)));
512                 for (i = 0; i < n; i++) {
513                         ir_node *lower = get_array_lower_bound(tp, i);
514                         ir_node *upper = get_array_upper_bound(tp, i);
515
516                         if (is_Const(lower))
517                                 fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(lower)));
518                         else
519                                 panic("Lower array bound is not constant");
520
521                         if (is_Const(upper))
522                                 fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(upper)));
523                         else if (is_Unknown(upper))
524                                 fputs("unknown ", f);
525                         else
526                                 panic("Upper array bound is not constant");
527                 }
528                 break;
529         }
530
531         case tpo_method: {
532                 int nparams  = get_method_n_params(tp);
533                 int nresults = get_method_n_ress(tp);
534                 fprintf(f, "%u %u %d %d ", get_method_calling_convention(tp),
535                         get_method_additional_properties(tp), nparams, nresults);
536                 for (i = 0; i < nparams; i++)
537                         fprintf(f, "%ld ", get_type_nr(get_method_param_type(tp, i)));
538                 for (i = 0; i < nresults; i++)
539                         fprintf(f, "%ld ", get_type_nr(get_method_res_type(tp, i)));
540                 fprintf(f, "%d ", get_method_first_variadic_param_index(tp));
541                 break;
542         }
543
544         case tpo_pointer:
545                 write_mode(env, get_type_mode(tp));
546                 fprintf(f, "%ld ", get_type_nr(get_pointer_points_to_type(tp)));
547                 break;
548
549         case tpo_enumeration:
550                 fprintf(stderr, "Enumeration type not handled yet by exporter\n");
551                 break;
552
553         default:
554                 printf("export_type: Unknown type code \"%s\".\n",
555                        get_type_tpop_name(tp));
556                 break;
557         }
558         fputc('\n', f);
559 }
560
561 static void export_entity(io_env_t *env, ir_entity *ent)
562 {
563         FILE          *file       = env->file;
564         ir_type       *owner      = get_entity_owner(ent);
565         ir_visibility  visibility = get_entity_visibility(ent);
566         ir_linkage     linkage    = get_entity_linkage(ent);
567
568         /* we don't dump array_element_ent entities. They're a strange concept
569          * and lead to cycles in type_graph.
570          */
571         if (is_Array_type(owner))
572                 return;
573
574         fprintf(env->file, "\tentity %ld \"%s\" ",
575                 get_entity_nr(ent), get_entity_name(ent));
576         if (ent->ld_name != NULL) {
577                 fprintf(env->file, "\"%s\" ", get_entity_ld_name(ent));
578         } else {
579                 fprintf(env->file, "NULL ");
580         }
581
582         /* visibility + linkage */
583         if (visibility != ir_visibility_default) {
584                 fprintf(file, "%s ", get_visibility_name(visibility));
585         }
586         if (linkage & IR_LINKAGE_CONSTANT)
587                 fputs("constant ", file);
588         if (linkage & IR_LINKAGE_WEAK)
589                 fputs("weak ", file);
590         if (linkage & IR_LINKAGE_GARBAGE_COLLECT)
591                 fputs("garbage_collect ", file);
592         if (linkage & IR_LINKAGE_MERGE)
593                 fputs("merge ", file);
594         if (linkage & IR_LINKAGE_HIDDEN_USER)
595                 fputs("hidden_user ", file);
596
597         fprintf(file, "%ld %ld %d %u %d %s ",
598                         get_type_nr(get_entity_type(ent)),
599                         get_type_nr(owner),
600                         get_entity_offset(ent),
601                         (unsigned) get_entity_offset_bits_remainder(ent),
602                         is_entity_compiler_generated(ent),
603                         get_volatility_name(get_entity_volatility(ent)));
604
605         if (ent->initializer != NULL) {
606                 fputs("initializer ", env->file);
607                 write_initializer(env, get_entity_initializer(ent));
608         } else if (entity_has_compound_ent_values(ent)) {
609                 int i, n = get_compound_ent_n_values(ent);
610                 fputs("compoundgraph ", env->file);
611                 fprintf(env->file, "%d ", n);
612                 for (i = 0; i < n; i++) {
613                         ir_entity *member = get_compound_ent_value_member(ent, i);
614                         ir_node   *irn    = get_compound_ent_value(ent, i);
615                         fprintf(env->file, "%ld %ld ", get_entity_nr(member), get_irn_node_nr(irn));
616                 }
617         } else {
618                 fputs("none", env->file);
619         }
620
621         fputc('\n', env->file);
622 }
623
624 static void export_type_or_ent_pre(type_or_ent tore, void *ctx)
625 {
626         io_env_t *env = (io_env_t *) ctx;
627         if (get_kind(tore.typ) == k_type)
628                 export_type_pre(env, tore.typ);
629 }
630
631 static void export_type_or_ent_post(type_or_ent tore, void *ctx)
632 {
633         io_env_t *env = (io_env_t *) ctx;
634
635         switch (get_kind(tore.ent)) {
636         case k_entity:
637                 export_entity(env, tore.ent);
638                 break;
639
640         case k_type:
641                 export_type_post(env, tore.typ);
642                 break;
643
644         default:
645                 panic("export_type_or_ent_post: Unknown type or entity.");
646                 break;
647         }
648 }
649
650 /**
651  * Walker: exports every node.
652  */
653 static void export_node(ir_node *irn, void *ctx)
654 {
655         io_env_t *env = (io_env_t *) ctx;
656         int i, n;
657         unsigned opcode = get_irn_opcode(irn);
658
659         if (env->ignoreblocks && opcode == iro_Block)
660                 return;
661
662         fprintf(env->file, "\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
663
664         n = get_irn_arity(irn);
665         if (!is_Block(irn)) {
666                 fprintf(env->file, "%ld ", get_irn_node_nr(get_nodes_block(irn)));
667         }
668
669         for (i = 0; i < n; i++) {
670                 ir_node *pred = get_irn_n(irn, i);
671                 if (pred == NULL) {
672                         /* Anchor node may have NULL predecessors */
673                         assert(is_Anchor(irn));
674                         fputs("-1 ", env->file);
675                 } else {
676                         fprintf(env->file, "%ld ", get_irn_node_nr(pred));
677                 }
678         }
679
680         fprintf(env->file, "] { ");
681
682         switch (opcode) {
683         case iro_Start:
684         case iro_End:
685         case iro_Block:
686         case iro_Anchor:
687                 break;
688         case iro_SymConst:
689                 /* TODO: only symconst_addr_ent implemented yet */
690                 assert(get_SymConst_kind(irn) == symconst_addr_ent);
691                 fprintf(env->file, "%ld ", get_entity_nr(get_SymConst_entity(irn)));
692                 break;
693         case iro_Proj:
694                 write_mode(env, get_irn_mode(irn));
695                 fprintf(env->file, "%ld ", get_Proj_proj(irn));
696                 break;
697 #include "gen_irio_export.inl"
698         default:
699                 panic("no export code for node %+F\n", irn);
700         }
701         fputs("}\n", env->file);
702 }
703
704 static const char *get_mode_sort_name(ir_mode_sort sort)
705 {
706         switch (sort) {
707         case irms_auxiliary:        return "auxiliary";
708         case irms_control_flow:     return "control_flow";
709         case irms_memory:           return "memory";
710         case irms_internal_boolean: return "internal_boolean";
711         case irms_reference:        return "reference";
712         case irms_int_number:       return "int_number";
713         case irms_float_number:     return "float_number";
714         }
715         panic("invalid mode sort found");
716 }
717
718 static void export_modes(io_env_t *env)
719 {
720         int i, n_modes = get_irp_n_modes();
721
722         fputs("modes {\n", env->file);
723
724         for (i = 0; i < n_modes; i++) {
725                 ir_mode *mode = get_irp_mode(i);
726                 switch (get_mode_sort(mode)) {
727                 case irms_auxiliary:
728                 case irms_control_flow:
729                 case irms_memory:
730                 case irms_internal_boolean:
731                         /* skip "internal" modes, which may not be user defined */
732                         continue;
733                 default:
734                         break;
735                 }
736
737                 fprintf(env->file, "\tmode \"%s\" %s %u %d %s %u %u ",
738                         get_mode_name(mode), get_mode_sort_name(get_mode_sort(mode)),
739                         get_mode_size_bits(mode), get_mode_sign(mode),
740                         get_mode_arithmetic_name(get_mode_arithmetic(mode)),
741                         get_mode_modulo_shift(mode),
742                         get_mode_n_vector_elems(mode));
743                 if (mode_is_reference(mode)) {
744                         write_mode(env, get_reference_mode_signed_eq(mode));
745                         write_mode(env, get_reference_mode_unsigned_eq(mode));
746                 }
747                 fputc('\n', env->file);
748         }
749
750         fputs("}\n", env->file);
751 }
752
753 static void export_program(io_env_t *env)
754 {
755         FILE         *f = env->file;
756         ir_segment_t  s;
757
758         fputs("\nprogram {\n", f);
759         if (irp_prog_name_is_set()) {
760                 fprintf(f, "\tname \"%s\"\n", get_irp_name());
761         }
762         /* We need numbers for irgs... */
763 #if 0
764         if (get_irp_main_irg() != NULL) {
765                 fprintf(f, "\tmain_irg %d\n", get_irp_main_irg
766 #endif
767
768         for (s = IR_SEGMENT_FIRST; s <= IR_SEGMENT_LAST; ++s) {
769                 ir_type *segment_type = get_segment_type(s);
770                 fprintf(f, "\tsegment_type %s", get_segment_name(s));
771                 if (segment_type == NULL) {
772                         fputs(" NULL\n", f);
773                 } else {
774                         fprintf(f, " %ld\n", get_type_nr(segment_type));
775                 }
776         }
777         fputs("}\n", f);
778 }
779
780 void ir_export(const char *filename)
781 {
782         FILE *file = fopen(filename, "wt");
783         if (file == NULL) {
784                 perror(filename);
785                 return;
786         }
787
788         ir_export_file(file, filename);
789         fclose(file);
790 }
791
792 /* Exports the whole irp to the given file in a textual form. */
793 void ir_export_file(FILE *file, const char *outputname)
794 {
795         io_env_t env;
796         int i, n_irgs = get_irp_n_irgs();
797
798         (void) outputname;
799         env.file = file;
800
801         export_modes(&env);
802
803         fputs("\ntypegraph {\n", env.file);
804         type_walk_prog(export_type_or_ent_pre, export_type_or_ent_post, &env);
805         fputs("}\n", env.file);
806
807         for (i = 0; i < n_irgs; i++) {
808                 ir_graph *irg       = get_irp_irg(i);
809                 ir_type  *valuetype = get_irg_value_param_type(irg);
810
811                 fprintf(env.file, "\nirg %ld %ld %ld {\n",
812                         get_entity_nr(get_irg_entity(irg)),
813                         get_type_nr(get_irg_frame_type(irg)),
814                         valuetype == NULL ? -1 : get_type_nr(valuetype));
815
816                 env.ignoreblocks = 0;
817                 irg_block_walk_graph(irg, NULL, export_node, &env);
818
819                 env.ignoreblocks = 1;
820                 irg_walk_anchors(irg, NULL, export_node, &env);
821
822                 fputs("}\n", env.file);
823         }
824
825         fprintf(env.file, "\nconstirg %ld {\n", get_irn_node_nr(get_const_code_irg()->current_block));
826
827         walk_const_code(NULL, export_node, &env);
828         fputs("}\n", env.file);
829
830         export_program(&env);
831 }
832
833 /* Exports the given irg to the given file. */
834 void ir_export_irg(ir_graph *irg, FILE *file, const char *outputname)
835 {
836         io_env_t env;
837
838         (void) outputname;
839         env.file = file;
840
841         export_modes(&env);
842
843         fputs("typegraph {\n", env.file);
844
845         type_walk_irg(irg, export_type_or_ent_pre, export_type_or_ent_post, &env);
846
847         fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
848
849         env.ignoreblocks = 0;
850         irg_block_walk_graph(irg, NULL, export_node, &env);
851
852         env.ignoreblocks = 1;
853         irg_walk_anchors(irg, NULL, export_node, &env);
854
855         /* TODO: Only output needed constants */
856         fprintf(env.file, "}\n\nconstirg %ld {\n", get_irn_node_nr(get_const_code_irg()->current_block));
857         walk_const_code(NULL, export_node, &env);
858         fputs("}\n", env.file);
859 }
860
861 static void read_c(io_env_t *env)
862 {
863         int c = fgetc(env->file);
864         env->c = c;
865         if (c == '\n')
866                 env->line++;
867 }
868
869 /** Returns the first non-whitespace character or EOF. **/
870 static void skip_ws(io_env_t *env)
871 {
872         while (true) {
873                 switch (env->c) {
874                 case ' ':
875                 case '\t':
876                 case '\n':
877                 case '\r':
878                         read_c(env);
879                         continue;
880
881                 default:
882                         return;
883                 }
884         }
885 }
886
887 static void skip_to(io_env_t *env, char to_ch)
888 {
889         while (env->c != to_ch && env->c != EOF) {
890                 read_c(env);
891         }
892 }
893
894 static int expect_char(io_env_t *env, char ch)
895 {
896         skip_ws(env);
897         if (env->c != ch) {
898                 parse_error(env, "Unexpected char '%c', expected '%c'\n",
899                             env->c, ch);
900                 return 0;
901         }
902         read_c(env);
903         return 1;
904 }
905
906 #define EXPECT(c) if (expect_char(env, (c))) {} else return 0
907
908 static char *read_word(io_env_t *env)
909 {
910         skip_ws(env);
911
912         assert(obstack_object_size(&env->obst) == 0);
913         while (true) {
914                 int c = env->c;
915                 switch (c) {
916                 case EOF:
917                 case ' ':
918                 case '\t':
919                 case '\n':
920                 case '\r':
921                         goto endofword;
922
923                 default:
924                         obstack_1grow(&env->obst, c);
925                         break;
926                 }
927                 read_c(env);
928         }
929
930 endofword:
931         obstack_1grow(&env->obst, '\0');
932         return (char*)obstack_finish(&env->obst);
933 }
934
935 static char *read_quoted_string(io_env_t *env)
936 {
937         skip_ws(env);
938         if (env->c != '\"') {
939                 parse_error(env, "Expected '\"', found '%c'\n", env->c);
940                 exit(1);
941         }
942         read_c(env);
943
944         assert(obstack_object_size(&env->obst) == 0);
945         while (true) {
946                 int ch = env->c;
947                 if (ch == EOF) {
948                         parse_error(env, "Unexpected end of quoted string!\n");
949                         exit(1);
950                 }
951                 if (ch == '\"') {
952                         read_c(env);
953                         break;
954                 }
955                 obstack_1grow(&env->obst, ch);
956                 read_c(env);
957         }
958         obstack_1grow(&env->obst, '\0');
959
960         return (char*)obstack_finish(&env->obst);
961 }
962
963 static ident *read_ident(io_env_t *env)
964 {
965         char  *str = read_quoted_string(env);
966         ident *res = new_id_from_str(str);
967         obstack_free(&env->obst, str);
968
969         return res;
970 }
971
972 /*
973  * reads a "quoted string" or alternatively the token NULL
974  */
975 static char *read_quoted_string_null(io_env_t *env)
976 {
977         skip_ws(env);
978         if (env->c == 'N') {
979                 char *str = read_word(env);
980                 if (strcmp(str, "NULL") == 0) {
981                         obstack_free(&env->obst, str);
982                         return NULL;
983                 }
984         } else if (env->c == '"') {
985                 return read_quoted_string(env);
986         }
987
988         parse_error(env, "Expected \"string\" or NULL\n");
989         exit(1);
990 }
991
992 static ident *read_ident_null(io_env_t *env)
993 {
994         ident *res;
995         char  *str = read_quoted_string_null(env);
996         if (str == NULL)
997                 return NULL;
998
999         res = new_id_from_str(str);
1000         obstack_free(&env->obst, str);
1001         return res;
1002 }
1003
1004 static long read_long(io_env_t *env)
1005 {
1006         long  result;
1007         char *str;
1008
1009         skip_ws(env);
1010         if (!isdigit(env->c) && env->c != '-') {
1011                 parse_error(env, "Expected number, got '%c'\n", env->c);
1012                 exit(1);
1013         }
1014
1015         assert(obstack_object_size(&env->obst) == 0);
1016         do {
1017                 obstack_1grow(&env->obst, env->c);
1018                 read_c(env);
1019         } while (isdigit(env->c));
1020         obstack_1grow(&env->obst, 0);
1021
1022         str = (char*)obstack_finish(&env->obst);
1023         result = atol(str);
1024         obstack_free(&env->obst, str);
1025
1026         return result;
1027 }
1028
1029 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
1030 {
1031         ir_node *node = (ir_node *) get_id(env, nodenr);
1032         if (node && node->kind != k_ir_node) {
1033                 panic("Irn ID %ld collides with something else in line %d\n",
1034                       nodenr, env->line);
1035         }
1036         return node;
1037 }
1038
1039 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
1040 {
1041         ir_node *node = get_node_or_null(env, nodenr);
1042         if (node == NULL) {
1043                 node = new_r_Dummy(env->irg, mode_X);
1044                 set_id(env, nodenr, node);
1045         }
1046         return node;
1047 }
1048
1049 static ir_type *get_type(io_env_t *env, long typenr)
1050 {
1051         ir_type *type = (ir_type *) get_id(env, typenr);
1052         if (type == NULL)
1053                 panic("unknown type: %ld in line %d\n", typenr, env->line);
1054         else if (type->kind != k_type)
1055                 panic("type ID %ld collides with something else in line %d\n",
1056                       typenr, env->line);
1057         return type;
1058 }
1059
1060 static ir_type *read_type(io_env_t *env)
1061 {
1062         return get_type(env, read_long(env));
1063 }
1064
1065 static ir_entity *get_entity(io_env_t *env, long entnr)
1066 {
1067         ir_entity *entity = (ir_entity *) get_id(env, entnr);
1068         if (entity == NULL) {
1069                 parse_error(env, "unknown entity: %ld\n", entnr);
1070                 exit(1);
1071         } else if (entity->kind != k_entity) {
1072                 panic("Entity ID %ld collides with something else in line %d\n",
1073                       entnr, env->line);
1074         }
1075
1076         return entity;
1077 }
1078
1079 static ir_entity *read_entity(io_env_t *env)
1080 {
1081         return get_entity(env, read_long(env));
1082 }
1083
1084 static ir_mode *read_mode(io_env_t *env)
1085 {
1086         char *str = read_word(env);
1087         int i, n;
1088
1089         n = get_irp_n_modes();
1090         for (i = 0; i < n; i++) {
1091                 ir_mode *mode = get_irp_mode(i);
1092                 if (strcmp(str, get_mode_name(mode)) == 0) {
1093                         obstack_free(&env->obst, str);
1094                         return mode;
1095                 }
1096         }
1097
1098         parse_error(env, "unknown mode \"%s\"\n", str);
1099         exit(1);
1100 }
1101
1102 static const char *get_typetag_name(typetag_t typetag)
1103 {
1104         switch (typetag) {
1105         case tt_align:              return "align";
1106         case tt_allocation:         return "allocation";
1107         case tt_builtin:            return "builtin kind";
1108         case tt_cond_jmp_predicate: return "cond_jmp_predicate";
1109         case tt_initializer:        return "initializer kind";
1110         case tt_iro:                return "opcode";
1111         case tt_keyword:            return "keyword";
1112         case tt_linkage:            return "linkage";
1113         case tt_mode_arithmetic:    return "mode_arithmetic";
1114         case tt_mode_sort:          return "mode_sort";
1115         case tt_pin_state:          return "pin state";
1116         case tt_segment:            return "segment";
1117         case tt_tpo:                return "type";
1118         case tt_type_state:         return "type state";
1119         case tt_volatility:         return "volatility";
1120         case tt_visibility:         return "visibility";
1121         }
1122         return "<UNKNOWN>";
1123 }
1124
1125 /**
1126  * Read and decode an enum constant.
1127  */
1128 static unsigned read_enum(io_env_t *env, typetag_t typetag)
1129 {
1130         char     *str  = read_word(env);
1131         unsigned  code = symbol(str, typetag);
1132
1133         if (code != SYMERROR) {
1134                 obstack_free(&env->obst, str);
1135                 return code;
1136         }
1137
1138         parse_error(env, "invalid %s: \"%s\"\n", get_typetag_name(typetag), str);
1139         return 0;
1140 }
1141
1142 #define read_align(env)              ((ir_align)              read_enum(env, tt_align))
1143 #define read_allocation(env)         ((ir_allocation)         read_enum(env, tt_allocation))
1144 #define read_builtin_kind(env)       ((ir_builtin_kind)       read_enum(env, tt_builtin))
1145 #define read_cond_jmp_predicate(env) ((cond_jmp_predicate)    read_enum(env, tt_cond_jmp_predicate))
1146 #define read_initializer_kind(env)   ((ir_initializer_kind_t) read_enum(env, tt_initializer))
1147 #define read_mode_arithmetic(env)    ((ir_mode_arithmetic)    read_enum(env, tt_mode_arithmetic))
1148 #define read_peculiarity(env)        ((ir_peculiarity)        read_enum(env, tt_peculiarity))
1149 #define read_pin_state(env)          ((op_pin_state)          read_enum(env, tt_pin_state))
1150 #define read_type_state(env)         ((ir_type_state)         read_enum(env, tt_type_state))
1151 #define read_variability(env)        ((ir_variability)        read_enum(env, tt_variability))
1152 #define read_volatility(env)         ((ir_volatility)         read_enum(env, tt_volatility))
1153
1154 static ir_cons_flags get_cons_flags(io_env_t *env)
1155 {
1156         ir_cons_flags flags = cons_none;
1157
1158         op_pin_state pinstate = read_pin_state(env);
1159         switch (pinstate) {
1160         case op_pin_state_floats: flags |= cons_floats; break;
1161         case op_pin_state_pinned: break;
1162         default:
1163                 panic("Error in %d: Invalid pinstate: %s", env->line,
1164                       get_op_pin_state_name(pinstate));
1165         }
1166
1167         if (read_volatility(env) == volatility_is_volatile)
1168                 flags |= cons_volatile;
1169         if (read_align(env) == align_non_aligned)
1170                 flags |= cons_unaligned;
1171
1172         return flags;
1173 }
1174
1175 static ir_tarval *read_tv(io_env_t *env)
1176 {
1177         ir_mode   *tvmode = read_mode(env);
1178         char      *str    = read_word(env);
1179         ir_tarval *tv     = new_tarval_from_str(str, strlen(str), tvmode);
1180         obstack_free(&env->obst, str);
1181
1182         return tv;
1183 }
1184
1185 static ir_initializer_t *read_initializer(io_env_t *env)
1186 {
1187         ir_initializer_kind_t ini_kind = read_initializer_kind(env);
1188
1189         switch (ini_kind) {
1190         case IR_INITIALIZER_CONST: {
1191                 ir_node *irn = get_node_or_dummy(env, read_long(env));
1192                 return create_initializer_const(irn);
1193         }
1194
1195         case IR_INITIALIZER_TARVAL:
1196                 return create_initializer_tarval(read_tv(env));
1197
1198         case IR_INITIALIZER_NULL:
1199                 return get_initializer_null();
1200
1201         case IR_INITIALIZER_COMPOUND: {
1202                 unsigned i, n = (unsigned) read_long(env);
1203                 ir_initializer_t *ini = create_initializer_compound(n);
1204                 for (i = 0; i < n; i++) {
1205                         ir_initializer_t *curini = read_initializer(env);
1206                         set_initializer_compound_value(ini, i, curini);
1207                 }
1208                 return ini;
1209         }
1210
1211         default:
1212                 panic("Unknown initializer kind");
1213         }
1214 }
1215
1216
1217 /** Reads a type description and remembers it by its id. */
1218 static void import_type(io_env_t *env)
1219 {
1220         int            i;
1221         ir_type       *type;
1222         long           typenr = read_long(env);
1223         tp_opcode      tpop   = (tp_opcode) read_enum(env, tt_tpo);
1224         unsigned       size   = (unsigned) read_long(env);
1225         unsigned       align  = (unsigned) read_long(env);
1226         ir_type_state  state  = read_type_state(env);
1227         unsigned       flags  = (unsigned) read_long(env);
1228
1229         switch (tpop) {
1230         case tpo_array: {
1231                 int ndims = (int) read_long(env);
1232                 long elemtypenr = read_long(env);
1233                 ir_type *elemtype = get_type(env, elemtypenr);
1234
1235                 type = new_type_array(ndims, elemtype);
1236                 for (i = 0; i < ndims; i++) {
1237                         char *str = read_word(env);
1238                         if (strcmp(str, "unknown") != 0) {
1239                                 long lowerbound = atol(str);
1240                                 set_array_lower_bound_int(type, i, lowerbound);
1241                         }
1242                         obstack_free(&env->obst, str);
1243
1244                         str = read_word(env);
1245                         if (strcmp(str, "unknown") != 0) {
1246                                 long upperbound = atol(str);
1247                                 set_array_upper_bound_int(type, i, upperbound);
1248                         }
1249                         obstack_free(&env->obst, str);
1250                 }
1251                 set_type_size_bytes(type, size);
1252                 break;
1253         }
1254
1255         case tpo_class: {
1256                 const char *name = read_quoted_string_null(env);
1257                 ident      *id   = name != NULL ? new_id_from_str(name) : NULL;
1258
1259                 if (typenr == (long) IR_SEGMENT_GLOBAL)
1260                         type = get_glob_type();
1261                 else
1262                         type = new_type_class(id);
1263                 set_type_size_bytes(type, size);
1264                 break;
1265         }
1266
1267         case tpo_method: {
1268                 unsigned                  callingconv = (unsigned) read_long(env);
1269                 mtp_additional_properties addprops    = (mtp_additional_properties) read_long(env);
1270                 int nparams          = (int)      read_long(env);
1271                 int nresults         = (int)      read_long(env);
1272                 int variaindex;
1273
1274                 type = new_type_method(nparams, nresults);
1275
1276                 for (i = 0; i < nparams; i++) {
1277                         long     typenr = read_long(env);
1278                         ir_type *paramtype = get_type(env, typenr);
1279
1280                         set_method_param_type(type, i, paramtype);
1281                 }
1282                 for (i = 0; i < nresults; i++) {
1283                         long typenr = read_long(env);
1284                         ir_type *restype = get_type(env, typenr);
1285
1286                         set_method_res_type(type, i, restype);
1287                 }
1288
1289                 variaindex = (int) read_long(env);
1290                 if (variaindex != -1) {
1291                         set_method_variadicity(type, variadicity_variadic);
1292                         if (variaindex != nparams)
1293                                 set_method_first_variadic_param_index(type, variaindex);
1294                 }
1295
1296                 set_method_calling_convention(type, callingconv);
1297                 set_method_additional_properties(type, addprops);
1298                 break;
1299         }
1300
1301         case tpo_pointer: {
1302                 ir_mode *mode     = read_mode(env);
1303                 ir_type *pointsto = get_type(env, read_long(env));
1304                 type = new_type_pointer(pointsto);
1305                 set_type_mode(type, mode);
1306                 break;
1307         }
1308
1309         case tpo_primitive: {
1310                 ir_mode *mode = read_mode(env);
1311                 type = new_type_primitive(mode);
1312                 break;
1313         }
1314
1315         case tpo_struct: {
1316                 const char *name = read_quoted_string_null(env);
1317                 ident      *id   = name != NULL ? new_id_from_str(name) : NULL;
1318                 type = new_type_struct(id);
1319                 set_type_size_bytes(type, size);
1320                 break;
1321         }
1322
1323         case tpo_union: {
1324                 const char *name = read_quoted_string_null(env);
1325                 ident      *id   = name != NULL ? new_id_from_str(name) : NULL;
1326
1327                 type = new_type_union(id);
1328                 set_type_size_bytes(type, size);
1329                 break;
1330         }
1331
1332         case tpo_unknown:
1333                 return;   /* ignore unknown type */
1334
1335         default:
1336                 parse_error(env, "unknown type kind: \"%d\"\n", tpop);
1337                 skip_to(env, '\n');
1338                 return;
1339         }
1340
1341         set_type_alignment_bytes(type, align);
1342         type->flags = flags;
1343
1344         if (state == layout_fixed)
1345                 ARR_APP1(ir_type *, env->fixedtypes, type);
1346
1347         set_id(env, typenr, type);
1348 }
1349
1350 /** Reads an entity description and remembers it by its id. */
1351 static void import_entity(io_env_t *env)
1352 {
1353         long           entnr      = read_long(env);
1354         ident         *name       = read_ident(env);
1355         ident         *ld_name    = read_ident_null(env);
1356         ir_visibility  visibility = ir_visibility_default;
1357         ir_linkage     linkage    = IR_LINKAGE_DEFAULT;
1358         long           typenr;
1359         long           ownertypenr;
1360         const char    *str;
1361         ir_type       *type;
1362         ir_type       *ownertype;
1363         ir_entity     *entity;
1364
1365         skip_ws(env);
1366         while (!isdigit(env->c)) {
1367                 char     *str = read_word(env);
1368                 unsigned  v;
1369
1370                 skip_ws(env);
1371
1372                 v = symbol(str, tt_visibility);
1373                 if (v != SYMERROR) {
1374                         visibility = (ir_visibility)v;
1375                         continue;
1376                 }
1377                 v = symbol(str, tt_linkage);
1378                 if (v != SYMERROR) {
1379                         linkage |= (ir_linkage)v;
1380                         continue;
1381                 }
1382                 printf("Parser error, expected visibility or linkage, got '%s'\n",
1383                        str);
1384                 break;
1385         }
1386
1387         typenr      = read_long(env);
1388         ownertypenr = read_long(env);
1389
1390         type      = get_type(env, typenr);
1391         ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
1392         entity    = new_entity(ownertype, name, type);
1393
1394         if (ld_name != NULL)
1395                 set_entity_ld_ident(entity, ld_name);
1396         set_entity_offset(entity, (int) read_long(env));
1397         set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
1398         set_entity_compiler_generated(entity, (int) read_long(env));
1399         set_entity_volatility(entity, read_volatility(env));
1400         set_entity_visibility(entity, visibility);
1401         set_entity_linkage(entity, linkage);
1402
1403         str = read_word(env);
1404         if (strcmp(str, "initializer") == 0) {
1405                 set_entity_initializer(entity, read_initializer(env));
1406         } else if (strcmp(str, "compoundgraph") == 0) {
1407                 int n = (int) read_long(env);
1408                 int i;
1409                 for (i = 0; i < n; i++) {
1410                         ir_entity *member = get_entity(env, read_long(env));
1411                         ir_node   *irn    = get_node_or_dummy(env, read_long(env));
1412                         add_compound_ent_value(entity, irn, member);
1413                 }
1414         } else if (strcmp(str, "none") == 0) {
1415                 /* do nothing */
1416         } else {
1417                 parse_error(env, "expected 'initializer', 'compoundgraph' or 'none' got '%s'\n", str);
1418                 exit(1);
1419         }
1420
1421         set_id(env, entnr, entity);
1422 }
1423
1424 /** Parses the whole type graph. */
1425 static int parse_typegraph(io_env_t *env)
1426 {
1427         ir_graph *old_irg = env->irg;
1428         keyword_t kwkind;
1429
1430         EXPECT('{');
1431
1432         env->irg = get_const_code_irg();
1433
1434         /* parse all types first */
1435         while (true) {
1436                 skip_ws(env);
1437                 if (env->c == '}') {
1438                         read_c(env);
1439                         break;
1440                 }
1441
1442                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1443                 switch (kwkind) {
1444                 case kw_type:
1445                         import_type(env);
1446                         break;
1447
1448                 case kw_entity:
1449                         import_entity(env);
1450                         break;
1451
1452                 default:
1453                         parse_error(env, "type graph element not supported yet: %d\n", kwkind);
1454                         skip_to(env, '\n');
1455                         break;
1456                 }
1457         }
1458         env->irg = old_irg;
1459         return 1;
1460 }
1461
1462 static int read_node_header(io_env_t *env, long *nodenr, ir_node ***preds,
1463                             const char **nodename)
1464 {
1465         int numpreds;
1466
1467         *nodename = read_word(env);
1468         *nodenr   = read_long(env);
1469
1470         ARR_RESIZE(ir_node*, *preds, 0);
1471
1472         EXPECT('[');
1473         for (numpreds = 0; !feof(env->file); numpreds++) {
1474                 long val;
1475                 ir_node *pred;
1476
1477                 skip_ws(env);
1478                 if (env->c == ']') {
1479                         read_c(env);
1480                         break;
1481                 }
1482                 val = read_long(env);
1483                 pred = get_node_or_dummy(env, val);
1484                 ARR_APP1(ir_node*, *preds, pred);
1485         }
1486
1487         return numpreds;
1488 }
1489
1490 /** Parses an IRG. */
1491 static int parse_graph(io_env_t *env, ir_graph *irg)
1492 {
1493         ir_node   **preds = NEW_ARR_F(ir_node*,0);
1494         int         i, numpreds, ret = 1;
1495         long        nodenr;
1496         const char *nodename;
1497         ir_node    *node, *newnode;
1498
1499         env->irg = irg;
1500
1501         EXPECT('{');
1502
1503         while (true) {
1504                 skip_ws(env);
1505                 if (env->c == '}') {
1506                         read_c(env);
1507                         break;
1508                 }
1509
1510                 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
1511
1512                 node = get_node_or_null(env, nodenr);
1513                 newnode = NULL;
1514
1515                 EXPECT('{');
1516
1517                 switch (symbol(nodename, tt_iro)) {
1518                 case iro_End: {
1519                         ir_node *newendblock = preds[0];
1520                         newnode = get_irg_end(irg);
1521                         exchange(get_nodes_block(newnode), newendblock);
1522                         for (i = 1; i < numpreds; i++)
1523                                 add_irn_n(newnode, preds[i]);
1524                         break;
1525                 }
1526
1527                 case iro_Start: {
1528                         ir_node *newstartblock = preds[0];
1529                         newnode = get_irg_start(irg);
1530                         exchange(get_nodes_block(newnode), newstartblock);
1531                         break;
1532                 }
1533
1534                 case iro_Block:
1535                         newnode = new_r_Block(irg, numpreds, preds);
1536                         break;
1537
1538                 case iro_Anchor:
1539                         newnode = irg->anchor;
1540                         for (i = 1; i < numpreds; i++)
1541                                 set_irn_n(newnode, i-1, preds[i]);
1542                         set_nodes_block(newnode, preds[0]);
1543                         break;
1544
1545                 case iro_SymConst: {
1546                         long entnr = read_long(env);
1547                         union symconst_symbol sym;
1548                         sym.entity_p = get_entity(env, entnr);
1549                         newnode = new_r_SymConst(irg, mode_P, sym, symconst_addr_ent);
1550                         break;
1551                 }
1552
1553                 case iro_Proj: {
1554                         ir_mode *mode = read_mode(env);
1555                         long     pn   = read_long(env);
1556                         newnode = new_r_Proj(preds[1], mode, pn);
1557                         /* explicitely set block, since preds[1] might be a dummy node
1558                          * which is always in the startblock */
1559                         set_nodes_block(newnode, preds[0]);
1560                         break;
1561                 }
1562
1563                 #include "gen_irio_import.inl"
1564
1565                 default:
1566                         goto notsupported;
1567                 }
1568
1569                 EXPECT('}');
1570
1571                 if (!newnode) {
1572 notsupported:
1573                         parse_error(env, "node type not supported yet: %s\n", nodename);
1574                         abort();
1575                 }
1576
1577                 if (node)
1578                         exchange(node, newnode);
1579                 /* Always update hash entry to avoid more uses of id nodes */
1580                 set_id(env, nodenr, newnode);
1581         }
1582
1583         DEL_ARR_F(preds);
1584
1585         return ret;
1586 }
1587
1588 static int parse_modes(io_env_t *env)
1589 {
1590         EXPECT('{');
1591
1592         while (true) {
1593                 keyword_t kwkind;
1594
1595                 skip_ws(env);
1596                 if (env->c == '}') {
1597                         read_c(env);
1598                         break;
1599                 }
1600
1601                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1602                 switch (kwkind) {
1603                 case kw_mode: {
1604                         const char *name = read_quoted_string(env);
1605                         ir_mode_sort sort = (ir_mode_sort)read_enum(env, tt_mode_sort);
1606                         int size = read_long(env);
1607                         int sign = read_long(env);
1608                         ir_mode_arithmetic arith = read_mode_arithmetic(env);
1609                         unsigned modulo_shift = read_long(env);
1610                         int vector_elems = read_long(env);
1611                         ir_mode *mode;
1612
1613                         if (vector_elems != 1) {
1614                                 panic("no support for import of vector modes yes");
1615                         }
1616
1617                         mode = new_ir_mode(name, sort, size, sign, arith, modulo_shift);
1618                         if (mode_is_reference(mode)) {
1619                                 set_reference_mode_signed_eq(mode, read_mode(env));
1620                                 set_reference_mode_unsigned_eq(mode, read_mode(env));
1621                         }
1622                         break;
1623                 }
1624
1625                 default:
1626                         skip_to(env, '\n');
1627                         break;
1628                 }
1629         }
1630         return 1;
1631 }
1632
1633 static int parse_program(io_env_t *env)
1634 {
1635         EXPECT('{');
1636
1637         while (true) {
1638                 keyword_t kwkind;
1639
1640                 skip_ws(env);
1641                 if (env->c == '}') {
1642                         read_c(env);
1643                         break;
1644                 }
1645
1646                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1647                 switch (kwkind) {
1648                 case kw_segment_type: {
1649                         ir_segment_t  segment = (ir_segment_t) read_enum(env, tt_segment);
1650                         ir_type      *type    = read_type(env);
1651                         set_segment_type(segment, type);
1652                         break;
1653                 }
1654                 default:
1655                         parse_error(env, "unexpected keyword %d\n", kwkind);
1656                         skip_to(env, '\n');
1657                 }
1658         }
1659         return 1;
1660 }
1661
1662 void ir_import(const char *filename)
1663 {
1664         FILE *file = fopen(filename, "rt");
1665         if (file == NULL) {
1666                 perror(filename);
1667                 exit(1);
1668         }
1669
1670         ir_import_file(file, filename);
1671
1672         fclose(file);
1673 }
1674
1675 void ir_import_file(FILE *input, const char *inputname)
1676 {
1677         int oldoptimize = get_optimize();
1678         firm_verification_t oldver = get_node_verification_mode();
1679         io_env_t ioenv;
1680         io_env_t *env = &ioenv;
1681         int i, n;
1682
1683         symtbl_init();
1684
1685         memset(env, 0, sizeof(*env));
1686         obstack_init(&env->obst);
1687         env->idset      = new_set(id_cmp, 128);
1688         env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1689         env->inputname  = inputname;
1690         env->file       = input;
1691         env->line       = 1;
1692
1693         /* read first character */
1694         read_c(env);
1695
1696         set_optimize(0);
1697         do_node_verification(FIRM_VERIFICATION_OFF);
1698
1699         while (true) {
1700                 keyword_t kw;
1701
1702                 skip_ws(env);
1703                 if (env->c == EOF)
1704                         break;
1705
1706                 kw = (keyword_t)read_enum(env, tt_keyword);
1707                 switch (kw) {
1708                 case kw_modes:
1709                         if (!parse_modes(env)) goto end;
1710                         break;
1711
1712                 case kw_typegraph:
1713                         if (!parse_typegraph(env)) goto end;
1714                         break;
1715
1716                 case kw_irg:
1717                 {
1718                         ir_entity *irgent = get_entity(env, read_long(env));
1719                         long valuetypeid;
1720                         ir_graph *irg = new_ir_graph(irgent, 0);
1721                         set_irg_frame_type(irg, get_type(env, read_long(env)));
1722                         valuetypeid = read_long(env);
1723                         if (valuetypeid != -1)
1724                                 set_method_value_param_type(get_entity_type(irgent),
1725                                                 get_type(env, valuetypeid));
1726
1727                         if (!parse_graph(env, irg)) goto end;
1728                         break;
1729                 }
1730
1731                 case kw_constirg: {
1732                         ir_graph *constirg = get_const_code_irg();
1733                         long bodyblockid = read_long(env);
1734                         set_id(env, bodyblockid, constirg->current_block);
1735                         if (!parse_graph(env, constirg)) goto end;
1736                         break;
1737                 }
1738
1739                 case kw_program:
1740                         parse_program(env);
1741                         break;
1742
1743                 default: {
1744                         parse_error(env, "Unexpected keyword %d at toplevel\n", kw);
1745                         exit(1);
1746                 }
1747                 }
1748         }
1749
1750 end:
1751         n = ARR_LEN(env->fixedtypes);
1752         for (i = 0; i < n; i++)
1753                 set_type_state(env->fixedtypes[i], layout_fixed);
1754
1755         DEL_ARR_F(env->fixedtypes);
1756
1757         del_set(env->idset);
1758
1759         irp_finalize_cons();
1760
1761         do_node_verification(oldver);
1762         set_optimize(oldoptimize);
1763
1764         obstack_free(&env->obst, NULL);
1765 }