c2d68e17451be5a1cb3fd9c4ca961c1b3e6331cd
[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_long(io_env_t *env, long value)
322 {
323         fprintf(env->file, "%ld ", value);
324 }
325
326 static void write_int(io_env_t *env, int value)
327 {
328         fprintf(env->file, "%d ", value);
329 }
330
331 static void write_unsigned(io_env_t *env, unsigned value)
332 {
333         fprintf(env->file, "%u ", value);
334 }
335
336 static void write_entity_ref(io_env_t *env, ir_entity *entity)
337 {
338         write_long(env, get_entity_nr(entity));
339 }
340
341 static void write_type_ref(io_env_t *env, ir_type *type)
342 {
343         write_long(env, get_type_nr(type));
344 }
345
346 static void write_string(io_env_t *env, const char *string)
347 {
348         const char *c;
349         fputc('"', env->file);
350         for (c = string; *c != '\0'; ++c) {
351                 switch (*c) {
352                 case '\n':
353                         fputc('\\', env->file);
354                         fputc('n', env->file);
355                         break;
356                 case '"':
357                 case '\\':
358                         fputc('\\', env->file);
359                         /* FALLTHROUGH */
360                 default:
361                         fputc(*c, env->file);
362                         break;
363                 }
364         }
365         fputc('"', env->file);
366 }
367
368 static void write_ident(io_env_t *env, ident *id)
369 {
370         write_string(env, get_id_str(id));
371         fputc(' ', env->file);
372 }
373
374 static void write_ident_null(io_env_t *env, ident *id)
375 {
376         if (id == NULL) {
377                 fputs("NULL ", env->file);
378         } else {
379                 write_ident(env, id);
380         }
381 }
382
383 static void write_mode(io_env_t *env, ir_mode *mode)
384 {
385         fputs(get_mode_name(mode), env->file);
386         fputc(' ', env->file);
387 }
388
389 static void write_tarval(io_env_t *env, ir_tarval *tv)
390 {
391         char buf[1024];
392         write_mode(env, get_tarval_mode(tv));
393         tarval_snprintf(buf, sizeof(buf), tv);
394         fputs(buf, env->file);
395         fputc(' ', env->file);
396 }
397
398 static void write_align(io_env_t *env, ir_node *irn)
399 {
400         ir_align align;
401
402         if (is_Load(irn))
403                 align = get_Load_align(irn);
404         else if (is_Store(irn))
405                 align = get_Store_align(irn);
406         else
407                 panic("Invalid optype for write_align");
408
409         fputs(get_align_name(align), env->file);
410         fputc(' ', env->file);
411 }
412
413 static void write_builtin_kind(io_env_t *env, ir_node *irn)
414 {
415         fputs(get_builtin_kind_name(get_Builtin_kind(irn)), env->file);
416         fputc(' ', env->file);
417 }
418
419 static void write_cond_jmp_predicate(io_env_t *env, ir_node *irn)
420 {
421         fputs(get_cond_jmp_predicate_name(get_Cond_jmp_pred(irn)), env->file);
422         fputc(' ', env->file);
423 }
424
425 static void write_initializer(io_env_t *env, ir_initializer_t *ini)
426 {
427         FILE *f = env->file;
428         ir_initializer_kind_t ini_kind = get_initializer_kind(ini);
429
430         fputs(get_initializer_kind_name(ini_kind), f);
431         fputc(' ', f);
432
433         switch (ini_kind) {
434         case IR_INITIALIZER_CONST:
435                 write_long(env, get_irn_node_nr(get_initializer_const_value(ini)));
436                 break;
437
438         case IR_INITIALIZER_TARVAL:
439                 write_tarval(env, get_initializer_tarval_value(ini));
440                 break;
441
442         case IR_INITIALIZER_NULL:
443                 break;
444
445         case IR_INITIALIZER_COMPOUND: {
446                 unsigned i, n = get_initializer_compound_n_entries(ini);
447                 fprintf(f, "%u ", n);
448                 for (i = 0; i < n; i++)
449                         write_initializer(env, get_initializer_compound_value(ini, i));
450                 break;
451         }
452
453         default:
454                 panic("Unknown initializer kind");
455         }
456 }
457
458 static void write_pin_state(io_env_t *env, ir_node *irn)
459 {
460         fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
461         fputc(' ', env->file);
462 }
463
464 static void write_volatility(io_env_t *env, ir_node *irn)
465 {
466         ir_volatility vol;
467
468         if (is_Load(irn))
469                 vol = get_Load_volatility(irn);
470         else if (is_Store(irn))
471                 vol = get_Store_volatility(irn);
472         else
473                 panic("Invalid optype for write_volatility");
474
475         fputs(get_volatility_name(vol), env->file);
476         fputc(' ', env->file);
477 }
478
479 static void export_type_common(io_env_t *env, ir_type *tp)
480 {
481         fprintf(env->file, "\ttype %ld %s %u %u %s %u ",
482                 get_type_nr(tp),
483                 get_type_tpop_name(tp),
484                 get_type_size_bytes(tp),
485                 get_type_alignment_bytes(tp),
486                 get_type_state_name(get_type_state(tp)),
487                 tp->flags);
488 }
489
490 static void export_type_pre(io_env_t *env, ir_type *tp)
491 {
492         FILE *f = env->file;
493
494         /* skip types to be handled by post walker */
495         switch (get_type_tpop_code(tp)) {
496         case tpo_array:
497         case tpo_method:
498         case tpo_pointer:
499                 return;
500         default:
501                 break;
502         }
503
504         export_type_common(env, tp);
505
506         switch (get_type_tpop_code(tp)) {
507         case tpo_uninitialized:
508                 panic("invalid type found");
509
510         case tpo_class:
511                 write_ident_null(env, get_compound_ident(tp));
512                 break;
513
514         case tpo_primitive:
515                 write_mode(env, get_type_mode(tp));
516                 break;
517
518         case tpo_union:
519         case tpo_struct:
520         case tpo_enumeration:
521                 write_ident_null(env, get_compound_ident(tp));
522                 break;
523
524         case tpo_array:
525         case tpo_method:
526         case tpo_pointer:
527         case tpo_code:
528         case tpo_none:
529         case tpo_unknown:
530                 break;
531         }
532         fputc('\n', f);
533 }
534
535 static void export_type_post(io_env_t *env, ir_type *tp)
536 {
537         FILE *f = env->file;
538         int i;
539
540         /* skip types already handled by pre walker */
541         switch (get_type_tpop_code(tp)) {
542         case tpo_class:
543         case tpo_primitive:
544         case tpo_struct:
545         case tpo_union:
546         case tpo_unknown:
547         case tpo_uninitialized:
548         case tpo_code:
549         case tpo_none:
550                 return;
551         case tpo_array:
552         case tpo_method:
553         case tpo_pointer:
554         case tpo_enumeration:
555                 break;
556         }
557
558         export_type_common(env, tp);
559
560         switch (get_type_tpop_code(tp)) {
561         case tpo_array: {
562                 int n = get_array_n_dimensions(tp);
563                 fprintf(f, "%d %ld ", n, get_type_nr(get_array_element_type(tp)));
564                 for (i = 0; i < n; i++) {
565                         ir_node *lower = get_array_lower_bound(tp, i);
566                         ir_node *upper = get_array_upper_bound(tp, i);
567
568                         if (is_Const(lower))
569                                 write_long(env, get_tarval_long(get_Const_tarval(lower)));
570                         else
571                                 panic("Lower array bound is not constant");
572
573                         if (is_Const(upper))
574                                 write_long(env, get_tarval_long(get_Const_tarval(upper)));
575                         else if (is_Unknown(upper))
576                                 fputs("unknown ", f);
577                         else
578                                 panic("Upper array bound is not constant");
579                 }
580                 break;
581         }
582
583         case tpo_method: {
584                 int nparams  = get_method_n_params(tp);
585                 int nresults = get_method_n_ress(tp);
586                 fprintf(f, "%u %u %d %d ", get_method_calling_convention(tp),
587                         get_method_additional_properties(tp), nparams, nresults);
588                 for (i = 0; i < nparams; i++)
589                         write_long(env, get_type_nr(get_method_param_type(tp, i)));
590                 for (i = 0; i < nresults; i++)
591                         write_long(env, get_type_nr(get_method_res_type(tp, i)));
592                 fprintf(f, "%d ", get_method_first_variadic_param_index(tp));
593                 break;
594         }
595
596         case tpo_pointer:
597                 write_mode(env, get_type_mode(tp));
598                 write_long(env, get_type_nr(get_pointer_points_to_type(tp)));
599                 break;
600
601         case tpo_enumeration:
602                 fprintf(stderr, "Enumeration type not handled yet by exporter\n");
603                 break;
604
605         default:
606                 printf("export_type: Unknown type code \"%s\".\n",
607                        get_type_tpop_name(tp));
608                 break;
609         }
610         fputc('\n', f);
611 }
612
613 static void export_entity(io_env_t *env, ir_entity *ent)
614 {
615         FILE          *file       = env->file;
616         ir_type       *owner      = get_entity_owner(ent);
617         ir_visibility  visibility = get_entity_visibility(ent);
618         ir_linkage     linkage    = get_entity_linkage(ent);
619
620         /* we don't dump array_element_ent entities. They're a strange concept
621          * and lead to cycles in type_graph.
622          */
623         if (is_Array_type(owner))
624                 return;
625
626         fprintf(env->file, "\tentity ");
627         write_long(env, get_entity_nr(ent));
628         write_ident_null(env, get_entity_ident(ent));
629         if (!entity_has_ld_ident(ent)) {
630                 write_ident_null(env, NULL);
631         } else {
632                 write_ident_null(env, get_entity_ld_ident(ent));
633         }
634
635         /* visibility + linkage */
636         if (visibility != ir_visibility_default) {
637                 fprintf(file, "%s ", get_visibility_name(visibility));
638         }
639         if (linkage & IR_LINKAGE_CONSTANT)
640                 fputs("constant ", file);
641         if (linkage & IR_LINKAGE_WEAK)
642                 fputs("weak ", file);
643         if (linkage & IR_LINKAGE_GARBAGE_COLLECT)
644                 fputs("garbage_collect ", file);
645         if (linkage & IR_LINKAGE_MERGE)
646                 fputs("merge ", file);
647         if (linkage & IR_LINKAGE_HIDDEN_USER)
648                 fputs("hidden_user ", file);
649
650         fprintf(file, "%ld %ld %d %u %d %s ",
651                         get_type_nr(get_entity_type(ent)),
652                         get_type_nr(owner),
653                         get_entity_offset(ent),
654                         (unsigned) get_entity_offset_bits_remainder(ent),
655                         is_entity_compiler_generated(ent),
656                         get_volatility_name(get_entity_volatility(ent)));
657
658         if (ent->initializer != NULL) {
659                 fputs("initializer ", env->file);
660                 write_initializer(env, get_entity_initializer(ent));
661         } else if (entity_has_compound_ent_values(ent)) {
662                 int i, n = get_compound_ent_n_values(ent);
663                 fputs("compoundgraph ", env->file);
664                 fprintf(env->file, "%d ", n);
665                 for (i = 0; i < n; i++) {
666                         ir_entity *member = get_compound_ent_value_member(ent, i);
667                         ir_node   *irn    = get_compound_ent_value(ent, i);
668                         fprintf(env->file, "%ld %ld ", get_entity_nr(member), get_irn_node_nr(irn));
669                 }
670         } else {
671                 fputs("none", env->file);
672         }
673
674         fputc('\n', env->file);
675 }
676
677 static void export_type_or_ent_pre(type_or_ent tore, void *ctx)
678 {
679         io_env_t *env = (io_env_t *) ctx;
680         if (get_kind(tore.typ) == k_type)
681                 export_type_pre(env, tore.typ);
682 }
683
684 static void export_type_or_ent_post(type_or_ent tore, void *ctx)
685 {
686         io_env_t *env = (io_env_t *) ctx;
687
688         switch (get_kind(tore.ent)) {
689         case k_entity:
690                 export_entity(env, tore.ent);
691                 break;
692
693         case k_type:
694                 export_type_post(env, tore.typ);
695                 break;
696
697         default:
698                 panic("export_type_or_ent_post: Unknown type or entity.");
699                 break;
700         }
701 }
702
703 /**
704  * Walker: exports every node.
705  */
706 static void export_node(ir_node *irn, void *ctx)
707 {
708         io_env_t *env = (io_env_t *) ctx;
709         int i, n;
710         unsigned opcode = get_irn_opcode(irn);
711
712         if (env->ignoreblocks && opcode == iro_Block)
713                 return;
714
715         fprintf(env->file, "\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
716
717         n = get_irn_arity(irn);
718         if (!is_Block(irn)) {
719                 fprintf(env->file, "%ld ", get_irn_node_nr(get_nodes_block(irn)));
720         }
721
722         for (i = 0; i < n; i++) {
723                 ir_node *pred = get_irn_n(irn, i);
724                 if (pred == NULL) {
725                         /* Anchor node may have NULL predecessors */
726                         assert(is_Anchor(irn));
727                         fputs("-1 ", env->file);
728                 } else {
729                         write_long(env, get_irn_node_nr(pred));
730                 }
731         }
732
733         fprintf(env->file, "] { ");
734
735         switch (opcode) {
736         case iro_Start:
737         case iro_End:
738         case iro_Block:
739         case iro_Anchor:
740                 break;
741         case iro_SymConst:
742                 /* TODO: only symconst_addr_ent implemented yet */
743                 assert(get_SymConst_kind(irn) == symconst_addr_ent);
744                 fprintf(env->file, "%ld ", get_entity_nr(get_SymConst_entity(irn)));
745                 break;
746         case iro_Proj:
747                 write_mode(env, get_irn_mode(irn));
748                 fprintf(env->file, "%ld ", get_Proj_proj(irn));
749                 break;
750 #include "gen_irio_export.inl"
751         default:
752                 panic("no export code for node %+F\n", irn);
753         }
754         fputs("}\n", env->file);
755 }
756
757 static const char *get_mode_sort_name(ir_mode_sort sort)
758 {
759         switch (sort) {
760         case irms_auxiliary:        return "auxiliary";
761         case irms_control_flow:     return "control_flow";
762         case irms_memory:           return "memory";
763         case irms_internal_boolean: return "internal_boolean";
764         case irms_reference:        return "reference";
765         case irms_int_number:       return "int_number";
766         case irms_float_number:     return "float_number";
767         }
768         panic("invalid mode sort found");
769 }
770
771 static void export_modes(io_env_t *env)
772 {
773         int i, n_modes = get_irp_n_modes();
774
775         fputs("modes {\n", env->file);
776
777         for (i = 0; i < n_modes; i++) {
778                 ir_mode *mode = get_irp_mode(i);
779                 switch (get_mode_sort(mode)) {
780                 case irms_auxiliary:
781                 case irms_control_flow:
782                 case irms_memory:
783                 case irms_internal_boolean:
784                         /* skip "internal" modes, which may not be user defined */
785                         continue;
786                 default:
787                         break;
788                 }
789
790                 fprintf(env->file, "\tmode ");
791                 write_string(env, get_mode_name(mode));
792                 fprintf(env->file, "%s %u %d %s %u %u ",
793                         get_mode_sort_name(get_mode_sort(mode)),
794                         get_mode_size_bits(mode), get_mode_sign(mode),
795                         get_mode_arithmetic_name(get_mode_arithmetic(mode)),
796                         get_mode_modulo_shift(mode),
797                         get_mode_n_vector_elems(mode));
798                 if (mode_is_reference(mode)) {
799                         write_mode(env, get_reference_mode_signed_eq(mode));
800                         write_mode(env, get_reference_mode_unsigned_eq(mode));
801                 }
802                 fputc('\n', env->file);
803         }
804
805         fputs("}\n", env->file);
806 }
807
808 static void export_program(io_env_t *env)
809 {
810         FILE         *f = env->file;
811         ir_segment_t  s;
812
813         fputs("\nprogram {\n", f);
814         if (irp_prog_name_is_set()) {
815                 fprintf(f, "\tname ");
816                 write_string(env, get_irp_name());
817                 fputc('\n', f);
818         }
819
820         for (s = IR_SEGMENT_FIRST; s <= IR_SEGMENT_LAST; ++s) {
821                 ir_type *segment_type = get_segment_type(s);
822                 fprintf(f, "\tsegment_type %s ", get_segment_name(s));
823                 if (segment_type == NULL) {
824                         fputs(" NULL\n", f);
825                 } else {
826                         write_long(env, get_type_nr(segment_type));
827                         fputc('\n', f);
828                 }
829         }
830         fputs("}\n", f);
831 }
832
833 void ir_export(const char *filename)
834 {
835         FILE *file = fopen(filename, "wt");
836         if (file == NULL) {
837                 perror(filename);
838                 return;
839         }
840
841         ir_export_file(file, filename);
842         fclose(file);
843 }
844
845 /* Exports the whole irp to the given file in a textual form. */
846 void ir_export_file(FILE *file, const char *outputname)
847 {
848         io_env_t env;
849         int i, n_irgs = get_irp_n_irgs();
850
851         (void) outputname;
852         env.file = file;
853
854         export_modes(&env);
855
856         fputs("\ntypegraph {\n", env.file);
857         type_walk_prog(export_type_or_ent_pre, export_type_or_ent_post, &env);
858         fputs("}\n", env.file);
859
860         for (i = 0; i < n_irgs; i++) {
861                 ir_graph *irg       = get_irp_irg(i);
862                 ir_type  *valuetype = get_irg_value_param_type(irg);
863
864                 fprintf(env.file, "\nirg %ld %ld %ld {\n",
865                         get_entity_nr(get_irg_entity(irg)),
866                         get_type_nr(get_irg_frame_type(irg)),
867                         valuetype == NULL ? -1 : get_type_nr(valuetype));
868
869                 env.ignoreblocks = 0;
870                 irg_block_walk_graph(irg, NULL, export_node, &env);
871
872                 env.ignoreblocks = 1;
873                 irg_walk_anchors(irg, NULL, export_node, &env);
874
875                 fputs("}\n", env.file);
876         }
877
878         fprintf(env.file, "\nconstirg %ld {\n", get_irn_node_nr(get_const_code_irg()->current_block));
879
880         walk_const_code(NULL, export_node, &env);
881         fputs("}\n", env.file);
882
883         export_program(&env);
884 }
885
886 /* Exports the given irg to the given file. */
887 void ir_export_irg(ir_graph *irg, FILE *file, const char *outputname)
888 {
889         io_env_t env;
890
891         (void) outputname;
892         env.file = file;
893
894         export_modes(&env);
895
896         fputs("typegraph {\n", env.file);
897
898         type_walk_irg(irg, export_type_or_ent_pre, export_type_or_ent_post, &env);
899
900         fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
901
902         env.ignoreblocks = 0;
903         irg_block_walk_graph(irg, NULL, export_node, &env);
904
905         env.ignoreblocks = 1;
906         irg_walk_anchors(irg, NULL, export_node, &env);
907
908         /* TODO: Only output needed constants */
909         fprintf(env.file, "}\n\nconstirg %ld {\n", get_irn_node_nr(get_const_code_irg()->current_block));
910         walk_const_code(NULL, export_node, &env);
911         fputs("}\n", env.file);
912 }
913
914 static void read_c(io_env_t *env)
915 {
916         int c = fgetc(env->file);
917         env->c = c;
918         if (c == '\n')
919                 env->line++;
920 }
921
922 /** Returns the first non-whitespace character or EOF. **/
923 static void skip_ws(io_env_t *env)
924 {
925         while (true) {
926                 switch (env->c) {
927                 case ' ':
928                 case '\t':
929                 case '\n':
930                 case '\r':
931                         read_c(env);
932                         continue;
933
934                 default:
935                         return;
936                 }
937         }
938 }
939
940 static void skip_to(io_env_t *env, char to_ch)
941 {
942         while (env->c != to_ch && env->c != EOF) {
943                 read_c(env);
944         }
945 }
946
947 static int expect_char(io_env_t *env, char ch)
948 {
949         skip_ws(env);
950         if (env->c != ch) {
951                 parse_error(env, "Unexpected char '%c', expected '%c'\n",
952                             env->c, ch);
953                 return 0;
954         }
955         read_c(env);
956         return 1;
957 }
958
959 #define EXPECT(c) if (expect_char(env, (c))) {} else return 0
960
961 static char *read_word(io_env_t *env)
962 {
963         skip_ws(env);
964
965         assert(obstack_object_size(&env->obst) == 0);
966         while (true) {
967                 int c = env->c;
968                 switch (c) {
969                 case EOF:
970                 case ' ':
971                 case '\t':
972                 case '\n':
973                 case '\r':
974                         goto endofword;
975
976                 default:
977                         obstack_1grow(&env->obst, c);
978                         break;
979                 }
980                 read_c(env);
981         }
982
983 endofword:
984         obstack_1grow(&env->obst, '\0');
985         return (char*)obstack_finish(&env->obst);
986 }
987
988 static char *read_string(io_env_t *env)
989 {
990         skip_ws(env);
991         if (env->c != '"') {
992                 parse_error(env, "Expected string, got '%c'\n", env->c);
993                 exit(1);
994         }
995         read_c(env);
996
997         assert(obstack_object_size(&env->obst) == 0);
998         while (env->c != '"') {
999                 if (env->c == EOF) {
1000                         parse_error(env, "Unexpected EOF while parsing string\n");
1001                         exit(1);
1002                 }
1003
1004                 if (env->c == '\\') {
1005                         read_c(env);
1006                         switch (env->c) {
1007                         case 'n':
1008                                 obstack_1grow(&env->obst, '\n');
1009                                 break;
1010                         case '"':
1011                         case '\\':
1012                                 obstack_1grow(&env->obst, env->c);
1013                                 break;
1014                         default:
1015                                 parse_error(env, "Unknown escape sequence '\\%c'\n", env->c);
1016                                 exit(1);
1017                                 break;
1018                         }
1019                 } else {
1020                         obstack_1grow(&env->obst, env->c);
1021                 }
1022                 read_c(env);
1023         }
1024         read_c(env);
1025         obstack_1grow(&env->obst, 0);
1026
1027         return (char*)obstack_finish(&env->obst);
1028 }
1029
1030 static ident *read_ident(io_env_t *env)
1031 {
1032         char  *str = read_string(env);
1033         ident *res = new_id_from_str(str);
1034         obstack_free(&env->obst, str);
1035         return res;
1036 }
1037
1038 /*
1039  * reads a "quoted string" or alternatively the token NULL
1040  */
1041 static char *read_string_null(io_env_t *env)
1042 {
1043         skip_ws(env);
1044         if (env->c == 'N') {
1045                 char *str = read_word(env);
1046                 if (strcmp(str, "NULL") == 0) {
1047                         obstack_free(&env->obst, str);
1048                         return NULL;
1049                 }
1050         } else if (env->c == '"') {
1051                 return read_string(env);
1052         }
1053
1054         parse_error(env, "Expected \"string\" or NULL\n");
1055         exit(1);
1056 }
1057
1058 static ident *read_ident_null(io_env_t *env)
1059 {
1060         ident *res;
1061         char  *str = read_string_null(env);
1062         if (str == NULL)
1063                 return NULL;
1064
1065         res = new_id_from_str(str);
1066         obstack_free(&env->obst, str);
1067         return res;
1068 }
1069
1070 static long read_long(io_env_t *env)
1071 {
1072         long  result;
1073         char *str;
1074
1075         skip_ws(env);
1076         if (!isdigit(env->c) && env->c != '-') {
1077                 parse_error(env, "Expected number, got '%c'\n", env->c);
1078                 exit(1);
1079         }
1080
1081         assert(obstack_object_size(&env->obst) == 0);
1082         do {
1083                 obstack_1grow(&env->obst, env->c);
1084                 read_c(env);
1085         } while (isdigit(env->c));
1086         obstack_1grow(&env->obst, 0);
1087
1088         str = (char*)obstack_finish(&env->obst);
1089         result = atol(str);
1090         obstack_free(&env->obst, str);
1091
1092         return result;
1093 }
1094
1095 static int read_int(io_env_t *env)
1096 {
1097         return (int) read_long(env);
1098 }
1099
1100 static unsigned read_unsigned(io_env_t *env)
1101 {
1102         return (unsigned) read_long(env);
1103 }
1104
1105 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
1106 {
1107         ir_node *node = (ir_node *) get_id(env, nodenr);
1108         if (node && node->kind != k_ir_node) {
1109                 panic("Irn ID %ld collides with something else in line %d\n",
1110                       nodenr, env->line);
1111         }
1112         return node;
1113 }
1114
1115 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
1116 {
1117         ir_node *node = get_node_or_null(env, nodenr);
1118         if (node == NULL) {
1119                 node = new_r_Dummy(env->irg, mode_X);
1120                 set_id(env, nodenr, node);
1121         }
1122         return node;
1123 }
1124
1125 static ir_type *get_type(io_env_t *env, long typenr)
1126 {
1127         ir_type *type = (ir_type *) get_id(env, typenr);
1128         if (type == NULL)
1129                 panic("unknown type: %ld in line %d\n", typenr, env->line);
1130         else if (type->kind != k_type)
1131                 panic("type ID %ld collides with something else in line %d\n",
1132                       typenr, env->line);
1133         return type;
1134 }
1135
1136 static ir_type *read_type(io_env_t *env)
1137 {
1138         return get_type(env, read_long(env));
1139 }
1140
1141 static ir_entity *get_entity(io_env_t *env, long entnr)
1142 {
1143         ir_entity *entity = (ir_entity *) get_id(env, entnr);
1144         if (entity == NULL) {
1145                 parse_error(env, "unknown entity: %ld\n", entnr);
1146                 exit(1);
1147         } else if (entity->kind != k_entity) {
1148                 panic("Entity ID %ld collides with something else in line %d\n",
1149                       entnr, env->line);
1150         }
1151
1152         return entity;
1153 }
1154
1155 static ir_entity *read_entity(io_env_t *env)
1156 {
1157         return get_entity(env, read_long(env));
1158 }
1159
1160 static ir_mode *read_mode(io_env_t *env)
1161 {
1162         char *str = read_word(env);
1163         int i, n;
1164
1165         n = get_irp_n_modes();
1166         for (i = 0; i < n; i++) {
1167                 ir_mode *mode = get_irp_mode(i);
1168                 if (strcmp(str, get_mode_name(mode)) == 0) {
1169                         obstack_free(&env->obst, str);
1170                         return mode;
1171                 }
1172         }
1173
1174         parse_error(env, "unknown mode \"%s\"\n", str);
1175         exit(1);
1176 }
1177
1178 static const char *get_typetag_name(typetag_t typetag)
1179 {
1180         switch (typetag) {
1181         case tt_align:              return "align";
1182         case tt_allocation:         return "allocation";
1183         case tt_builtin:            return "builtin kind";
1184         case tt_cond_jmp_predicate: return "cond_jmp_predicate";
1185         case tt_initializer:        return "initializer kind";
1186         case tt_iro:                return "opcode";
1187         case tt_keyword:            return "keyword";
1188         case tt_linkage:            return "linkage";
1189         case tt_mode_arithmetic:    return "mode_arithmetic";
1190         case tt_mode_sort:          return "mode_sort";
1191         case tt_pin_state:          return "pin state";
1192         case tt_segment:            return "segment";
1193         case tt_tpo:                return "type";
1194         case tt_type_state:         return "type state";
1195         case tt_volatility:         return "volatility";
1196         case tt_visibility:         return "visibility";
1197         }
1198         return "<UNKNOWN>";
1199 }
1200
1201 /**
1202  * Read and decode an enum constant.
1203  */
1204 static unsigned read_enum(io_env_t *env, typetag_t typetag)
1205 {
1206         char     *str  = read_word(env);
1207         unsigned  code = symbol(str, typetag);
1208
1209         if (code != SYMERROR) {
1210                 obstack_free(&env->obst, str);
1211                 return code;
1212         }
1213
1214         parse_error(env, "invalid %s: \"%s\"\n", get_typetag_name(typetag), str);
1215         return 0;
1216 }
1217
1218 #define read_align(env)              ((ir_align)              read_enum(env, tt_align))
1219 #define read_allocation(env)         ((ir_allocation)         read_enum(env, tt_allocation))
1220 #define read_builtin_kind(env)       ((ir_builtin_kind)       read_enum(env, tt_builtin))
1221 #define read_cond_jmp_predicate(env) ((cond_jmp_predicate)    read_enum(env, tt_cond_jmp_predicate))
1222 #define read_initializer_kind(env)   ((ir_initializer_kind_t) read_enum(env, tt_initializer))
1223 #define read_mode_arithmetic(env)    ((ir_mode_arithmetic)    read_enum(env, tt_mode_arithmetic))
1224 #define read_peculiarity(env)        ((ir_peculiarity)        read_enum(env, tt_peculiarity))
1225 #define read_pin_state(env)          ((op_pin_state)          read_enum(env, tt_pin_state))
1226 #define read_type_state(env)         ((ir_type_state)         read_enum(env, tt_type_state))
1227 #define read_variability(env)        ((ir_variability)        read_enum(env, tt_variability))
1228 #define read_volatility(env)         ((ir_volatility)         read_enum(env, tt_volatility))
1229
1230 static ir_cons_flags get_cons_flags(io_env_t *env)
1231 {
1232         ir_cons_flags flags = cons_none;
1233
1234         op_pin_state pinstate = read_pin_state(env);
1235         switch (pinstate) {
1236         case op_pin_state_floats: flags |= cons_floats; break;
1237         case op_pin_state_pinned: break;
1238         default:
1239                 panic("Error in %d: Invalid pinstate: %s", env->line,
1240                       get_op_pin_state_name(pinstate));
1241         }
1242
1243         if (read_volatility(env) == volatility_is_volatile)
1244                 flags |= cons_volatile;
1245         if (read_align(env) == align_non_aligned)
1246                 flags |= cons_unaligned;
1247
1248         return flags;
1249 }
1250
1251 static ir_tarval *read_tv(io_env_t *env)
1252 {
1253         ir_mode   *tvmode = read_mode(env);
1254         char      *str    = read_word(env);
1255         ir_tarval *tv     = new_tarval_from_str(str, strlen(str), tvmode);
1256         obstack_free(&env->obst, str);
1257
1258         return tv;
1259 }
1260
1261 static ir_initializer_t *read_initializer(io_env_t *env)
1262 {
1263         ir_initializer_kind_t ini_kind = read_initializer_kind(env);
1264
1265         switch (ini_kind) {
1266         case IR_INITIALIZER_CONST: {
1267                 ir_node *irn = get_node_or_dummy(env, read_long(env));
1268                 return create_initializer_const(irn);
1269         }
1270
1271         case IR_INITIALIZER_TARVAL:
1272                 return create_initializer_tarval(read_tv(env));
1273
1274         case IR_INITIALIZER_NULL:
1275                 return get_initializer_null();
1276
1277         case IR_INITIALIZER_COMPOUND: {
1278                 unsigned i, n = (unsigned) read_long(env);
1279                 ir_initializer_t *ini = create_initializer_compound(n);
1280                 for (i = 0; i < n; i++) {
1281                         ir_initializer_t *curini = read_initializer(env);
1282                         set_initializer_compound_value(ini, i, curini);
1283                 }
1284                 return ini;
1285         }
1286
1287         default:
1288                 panic("Unknown initializer kind");
1289         }
1290 }
1291
1292
1293 /** Reads a type description and remembers it by its id. */
1294 static void import_type(io_env_t *env)
1295 {
1296         int            i;
1297         ir_type       *type;
1298         long           typenr = read_long(env);
1299         tp_opcode      tpop   = (tp_opcode) read_enum(env, tt_tpo);
1300         unsigned       size   = (unsigned) read_long(env);
1301         unsigned       align  = (unsigned) read_long(env);
1302         ir_type_state  state  = read_type_state(env);
1303         unsigned       flags  = (unsigned) read_long(env);
1304
1305         switch (tpop) {
1306         case tpo_array: {
1307                 int ndims = (int) read_long(env);
1308                 long elemtypenr = read_long(env);
1309                 ir_type *elemtype = get_type(env, elemtypenr);
1310
1311                 type = new_type_array(ndims, elemtype);
1312                 for (i = 0; i < ndims; i++) {
1313                         char *str = read_word(env);
1314                         if (strcmp(str, "unknown") != 0) {
1315                                 long lowerbound = atol(str);
1316                                 set_array_lower_bound_int(type, i, lowerbound);
1317                         }
1318                         obstack_free(&env->obst, str);
1319
1320                         str = read_word(env);
1321                         if (strcmp(str, "unknown") != 0) {
1322                                 long upperbound = atol(str);
1323                                 set_array_upper_bound_int(type, i, upperbound);
1324                         }
1325                         obstack_free(&env->obst, str);
1326                 }
1327                 set_type_size_bytes(type, size);
1328                 break;
1329         }
1330
1331         case tpo_class: {
1332                 ident *id = read_ident_null(env);
1333
1334                 if (typenr == (long) IR_SEGMENT_GLOBAL)
1335                         type = get_glob_type();
1336                 else
1337                         type = new_type_class(id);
1338                 set_type_size_bytes(type, size);
1339                 break;
1340         }
1341
1342         case tpo_method: {
1343                 unsigned                  callingconv = (unsigned) read_long(env);
1344                 mtp_additional_properties addprops    = (mtp_additional_properties) read_long(env);
1345                 int nparams          = (int)      read_long(env);
1346                 int nresults         = (int)      read_long(env);
1347                 int variaindex;
1348
1349                 type = new_type_method(nparams, nresults);
1350
1351                 for (i = 0; i < nparams; i++) {
1352                         long     typenr = read_long(env);
1353                         ir_type *paramtype = get_type(env, typenr);
1354
1355                         set_method_param_type(type, i, paramtype);
1356                 }
1357                 for (i = 0; i < nresults; i++) {
1358                         long typenr = read_long(env);
1359                         ir_type *restype = get_type(env, typenr);
1360
1361                         set_method_res_type(type, i, restype);
1362                 }
1363
1364                 variaindex = (int) read_long(env);
1365                 if (variaindex != -1) {
1366                         set_method_variadicity(type, variadicity_variadic);
1367                         if (variaindex != nparams)
1368                                 set_method_first_variadic_param_index(type, variaindex);
1369                 }
1370
1371                 set_method_calling_convention(type, callingconv);
1372                 set_method_additional_properties(type, addprops);
1373                 break;
1374         }
1375
1376         case tpo_pointer: {
1377                 ir_mode *mode     = read_mode(env);
1378                 ir_type *pointsto = get_type(env, read_long(env));
1379                 type = new_type_pointer(pointsto);
1380                 set_type_mode(type, mode);
1381                 break;
1382         }
1383
1384         case tpo_primitive: {
1385                 ir_mode *mode = read_mode(env);
1386                 type = new_type_primitive(mode);
1387                 break;
1388         }
1389
1390         case tpo_struct: {
1391                 ident *id = read_ident_null(env);
1392                 type = new_type_struct(id);
1393                 set_type_size_bytes(type, size);
1394                 break;
1395         }
1396
1397         case tpo_union: {
1398                 ident *id = read_ident_null(env);
1399                 type = new_type_union(id);
1400                 set_type_size_bytes(type, size);
1401                 break;
1402         }
1403
1404         case tpo_unknown:
1405                 return;   /* ignore unknown type */
1406
1407         default:
1408                 parse_error(env, "unknown type kind: \"%d\"\n", tpop);
1409                 skip_to(env, '\n');
1410                 return;
1411         }
1412
1413         set_type_alignment_bytes(type, align);
1414         type->flags = flags;
1415
1416         if (state == layout_fixed)
1417                 ARR_APP1(ir_type *, env->fixedtypes, type);
1418
1419         set_id(env, typenr, type);
1420 }
1421
1422 /** Reads an entity description and remembers it by its id. */
1423 static void import_entity(io_env_t *env)
1424 {
1425         long           entnr      = read_long(env);
1426         ident         *name       = read_ident(env);
1427         ident         *ld_name    = read_ident_null(env);
1428         ir_visibility  visibility = ir_visibility_default;
1429         ir_linkage     linkage    = IR_LINKAGE_DEFAULT;
1430         long           typenr;
1431         long           ownertypenr;
1432         const char    *str;
1433         ir_type       *type;
1434         ir_type       *ownertype;
1435         ir_entity     *entity;
1436
1437         skip_ws(env);
1438         while (!isdigit(env->c)) {
1439                 char     *str = read_word(env);
1440                 unsigned  v;
1441
1442                 skip_ws(env);
1443
1444                 v = symbol(str, tt_visibility);
1445                 if (v != SYMERROR) {
1446                         visibility = (ir_visibility)v;
1447                         continue;
1448                 }
1449                 v = symbol(str, tt_linkage);
1450                 if (v != SYMERROR) {
1451                         linkage |= (ir_linkage)v;
1452                         continue;
1453                 }
1454                 printf("Parser error, expected visibility or linkage, got '%s'\n",
1455                        str);
1456                 break;
1457         }
1458
1459         typenr      = read_long(env);
1460         ownertypenr = read_long(env);
1461
1462         type      = get_type(env, typenr);
1463         ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
1464         entity    = new_entity(ownertype, name, type);
1465
1466         if (ld_name != NULL)
1467                 set_entity_ld_ident(entity, ld_name);
1468         set_entity_offset(entity, (int) read_long(env));
1469         set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
1470         set_entity_compiler_generated(entity, (int) read_long(env));
1471         set_entity_volatility(entity, read_volatility(env));
1472         set_entity_visibility(entity, visibility);
1473         set_entity_linkage(entity, linkage);
1474
1475         str = read_word(env);
1476         if (strcmp(str, "initializer") == 0) {
1477                 set_entity_initializer(entity, read_initializer(env));
1478         } else if (strcmp(str, "compoundgraph") == 0) {
1479                 int n = (int) read_long(env);
1480                 int i;
1481                 for (i = 0; i < n; i++) {
1482                         ir_entity *member = get_entity(env, read_long(env));
1483                         ir_node   *irn    = get_node_or_dummy(env, read_long(env));
1484                         add_compound_ent_value(entity, irn, member);
1485                 }
1486         } else if (strcmp(str, "none") == 0) {
1487                 /* do nothing */
1488         } else {
1489                 parse_error(env, "expected 'initializer', 'compoundgraph' or 'none' got '%s'\n", str);
1490                 exit(1);
1491         }
1492
1493         set_id(env, entnr, entity);
1494 }
1495
1496 /** Parses the whole type graph. */
1497 static int parse_typegraph(io_env_t *env)
1498 {
1499         ir_graph *old_irg = env->irg;
1500         keyword_t kwkind;
1501
1502         EXPECT('{');
1503
1504         env->irg = get_const_code_irg();
1505
1506         /* parse all types first */
1507         while (true) {
1508                 skip_ws(env);
1509                 if (env->c == '}') {
1510                         read_c(env);
1511                         break;
1512                 }
1513
1514                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1515                 switch (kwkind) {
1516                 case kw_type:
1517                         import_type(env);
1518                         break;
1519
1520                 case kw_entity:
1521                         import_entity(env);
1522                         break;
1523
1524                 default:
1525                         parse_error(env, "type graph element not supported yet: %d\n", kwkind);
1526                         skip_to(env, '\n');
1527                         break;
1528                 }
1529         }
1530         env->irg = old_irg;
1531         return 1;
1532 }
1533
1534 static int read_node_header(io_env_t *env, long *nodenr, ir_node ***preds,
1535                             const char **nodename)
1536 {
1537         int numpreds;
1538
1539         *nodename = read_word(env);
1540         *nodenr   = read_long(env);
1541
1542         ARR_RESIZE(ir_node*, *preds, 0);
1543
1544         EXPECT('[');
1545         for (numpreds = 0; !feof(env->file); numpreds++) {
1546                 long val;
1547                 ir_node *pred;
1548
1549                 skip_ws(env);
1550                 if (env->c == ']') {
1551                         read_c(env);
1552                         break;
1553                 }
1554                 val = read_long(env);
1555                 pred = get_node_or_dummy(env, val);
1556                 ARR_APP1(ir_node*, *preds, pred);
1557         }
1558
1559         return numpreds;
1560 }
1561
1562 /** Parses an IRG. */
1563 static int parse_graph(io_env_t *env, ir_graph *irg)
1564 {
1565         ir_node   **preds = NEW_ARR_F(ir_node*,0);
1566         int         i, numpreds, ret = 1;
1567         long        nodenr;
1568         const char *nodename;
1569         ir_node    *node, *newnode;
1570
1571         env->irg = irg;
1572
1573         EXPECT('{');
1574
1575         while (true) {
1576                 skip_ws(env);
1577                 if (env->c == '}') {
1578                         read_c(env);
1579                         break;
1580                 }
1581
1582                 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
1583
1584                 node = get_node_or_null(env, nodenr);
1585                 newnode = NULL;
1586
1587                 EXPECT('{');
1588
1589                 switch (symbol(nodename, tt_iro)) {
1590                 case iro_End: {
1591                         ir_node *newendblock = preds[0];
1592                         newnode = get_irg_end(irg);
1593                         exchange(get_nodes_block(newnode), newendblock);
1594                         for (i = 1; i < numpreds; i++)
1595                                 add_irn_n(newnode, preds[i]);
1596                         break;
1597                 }
1598
1599                 case iro_Start: {
1600                         ir_node *newstartblock = preds[0];
1601                         newnode = get_irg_start(irg);
1602                         exchange(get_nodes_block(newnode), newstartblock);
1603                         break;
1604                 }
1605
1606                 case iro_Block:
1607                         newnode = new_r_Block(irg, numpreds, preds);
1608                         break;
1609
1610                 case iro_Anchor:
1611                         newnode = irg->anchor;
1612                         for (i = 1; i < numpreds; i++)
1613                                 set_irn_n(newnode, i-1, preds[i]);
1614                         set_nodes_block(newnode, preds[0]);
1615                         break;
1616
1617                 case iro_SymConst: {
1618                         long entnr = read_long(env);
1619                         union symconst_symbol sym;
1620                         sym.entity_p = get_entity(env, entnr);
1621                         newnode = new_r_SymConst(irg, mode_P, sym, symconst_addr_ent);
1622                         break;
1623                 }
1624
1625                 case iro_Proj: {
1626                         ir_mode *mode = read_mode(env);
1627                         long     pn   = read_long(env);
1628                         newnode = new_r_Proj(preds[1], mode, pn);
1629                         /* explicitely set block, since preds[1] might be a dummy node
1630                          * which is always in the startblock */
1631                         set_nodes_block(newnode, preds[0]);
1632                         break;
1633                 }
1634
1635                 #include "gen_irio_import.inl"
1636
1637                 default:
1638                         goto notsupported;
1639                 }
1640
1641                 EXPECT('}');
1642
1643                 if (!newnode) {
1644 notsupported:
1645                         parse_error(env, "node type not supported yet: %s\n", nodename);
1646                         abort();
1647                 }
1648
1649                 if (node)
1650                         exchange(node, newnode);
1651                 /* Always update hash entry to avoid more uses of id nodes */
1652                 set_id(env, nodenr, newnode);
1653         }
1654
1655         DEL_ARR_F(preds);
1656
1657         return ret;
1658 }
1659
1660 static int parse_modes(io_env_t *env)
1661 {
1662         EXPECT('{');
1663
1664         while (true) {
1665                 keyword_t kwkind;
1666
1667                 skip_ws(env);
1668                 if (env->c == '}') {
1669                         read_c(env);
1670                         break;
1671                 }
1672
1673                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1674                 switch (kwkind) {
1675                 case kw_mode: {
1676                         const char *name = read_string(env);
1677                         ir_mode_sort sort = (ir_mode_sort)read_enum(env, tt_mode_sort);
1678                         int size = read_long(env);
1679                         int sign = read_long(env);
1680                         ir_mode_arithmetic arith = read_mode_arithmetic(env);
1681                         unsigned modulo_shift = read_long(env);
1682                         int vector_elems = read_long(env);
1683                         ir_mode *mode;
1684
1685                         if (vector_elems != 1) {
1686                                 panic("no support for import of vector modes yes");
1687                         }
1688
1689                         mode = new_ir_mode(name, sort, size, sign, arith, modulo_shift);
1690                         if (mode_is_reference(mode)) {
1691                                 set_reference_mode_signed_eq(mode, read_mode(env));
1692                                 set_reference_mode_unsigned_eq(mode, read_mode(env));
1693                         }
1694                         break;
1695                 }
1696
1697                 default:
1698                         skip_to(env, '\n');
1699                         break;
1700                 }
1701         }
1702         return 1;
1703 }
1704
1705 static int parse_program(io_env_t *env)
1706 {
1707         EXPECT('{');
1708
1709         while (true) {
1710                 keyword_t kwkind;
1711
1712                 skip_ws(env);
1713                 if (env->c == '}') {
1714                         read_c(env);
1715                         break;
1716                 }
1717
1718                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1719                 switch (kwkind) {
1720                 case kw_segment_type: {
1721                         ir_segment_t  segment = (ir_segment_t) read_enum(env, tt_segment);
1722                         ir_type      *type    = read_type(env);
1723                         set_segment_type(segment, type);
1724                         break;
1725                 }
1726                 default:
1727                         parse_error(env, "unexpected keyword %d\n", kwkind);
1728                         skip_to(env, '\n');
1729                 }
1730         }
1731         return 1;
1732 }
1733
1734 void ir_import(const char *filename)
1735 {
1736         FILE *file = fopen(filename, "rt");
1737         if (file == NULL) {
1738                 perror(filename);
1739                 exit(1);
1740         }
1741
1742         ir_import_file(file, filename);
1743
1744         fclose(file);
1745 }
1746
1747 void ir_import_file(FILE *input, const char *inputname)
1748 {
1749         int oldoptimize = get_optimize();
1750         firm_verification_t oldver = get_node_verification_mode();
1751         io_env_t ioenv;
1752         io_env_t *env = &ioenv;
1753         int i, n;
1754
1755         symtbl_init();
1756
1757         memset(env, 0, sizeof(*env));
1758         obstack_init(&env->obst);
1759         env->idset      = new_set(id_cmp, 128);
1760         env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1761         env->inputname  = inputname;
1762         env->file       = input;
1763         env->line       = 1;
1764
1765         /* read first character */
1766         read_c(env);
1767
1768         set_optimize(0);
1769         do_node_verification(FIRM_VERIFICATION_OFF);
1770
1771         while (true) {
1772                 keyword_t kw;
1773
1774                 skip_ws(env);
1775                 if (env->c == EOF)
1776                         break;
1777
1778                 kw = (keyword_t)read_enum(env, tt_keyword);
1779                 switch (kw) {
1780                 case kw_modes:
1781                         if (!parse_modes(env)) goto end;
1782                         break;
1783
1784                 case kw_typegraph:
1785                         if (!parse_typegraph(env)) goto end;
1786                         break;
1787
1788                 case kw_irg:
1789                 {
1790                         ir_entity *irgent = get_entity(env, read_long(env));
1791                         long valuetypeid;
1792                         ir_graph *irg = new_ir_graph(irgent, 0);
1793                         set_irg_frame_type(irg, get_type(env, read_long(env)));
1794                         valuetypeid = read_long(env);
1795                         if (valuetypeid != -1)
1796                                 set_method_value_param_type(get_entity_type(irgent),
1797                                                 get_type(env, valuetypeid));
1798
1799                         if (!parse_graph(env, irg)) goto end;
1800                         break;
1801                 }
1802
1803                 case kw_constirg: {
1804                         ir_graph *constirg = get_const_code_irg();
1805                         long bodyblockid = read_long(env);
1806                         set_id(env, bodyblockid, constirg->current_block);
1807                         if (!parse_graph(env, constirg)) goto end;
1808                         break;
1809                 }
1810
1811                 case kw_program:
1812                         parse_program(env);
1813                         break;
1814
1815                 default: {
1816                         parse_error(env, "Unexpected keyword %d at toplevel\n", kw);
1817                         exit(1);
1818                 }
1819                 }
1820         }
1821
1822 end:
1823         n = ARR_LEN(env->fixedtypes);
1824         for (i = 0; i < n; i++)
1825                 set_type_state(env->fixedtypes[i], layout_fixed);
1826
1827         DEL_ARR_F(env->fixedtypes);
1828
1829         del_set(env->idset);
1830
1831         irp_finalize_cons();
1832
1833         do_node_verification(oldver);
1834         set_optimize(oldoptimize);
1835
1836         obstack_free(&env->obst, NULL);
1837 }