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