irio: Added support for Builtin nodes
[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
30 #include "irio.h"
31
32 #include "irnode_t.h"
33 #include "irprog.h"
34 #include "irgraph_t.h"
35 #include "ircons.h"
36 #include "irgmod.h"
37 #include "irflag_t.h"
38 #include "irgwalk.h"
39 #include "tv.h"
40 #include "array.h"
41 #include "error.h"
42 #include "adt/set.h"
43
44 #define SYMERROR ((unsigned) ~0)
45
46 typedef struct io_env
47 {
48         FILE *file;
49         set *idset;               /**< id_entry set, which maps from file ids to new Firm elements */
50         int ignoreblocks;
51         int line, col;
52         ir_type **fixedtypes;
53 } io_env_t;
54
55 typedef enum typetag_t
56 {
57         tt_align,
58         tt_allocation,
59         tt_builtin,
60         tt_initializer,
61         tt_iro,
62         tt_peculiarity,
63         tt_pin_state,
64         tt_tpo,
65         tt_type_state,
66         tt_variability,
67         tt_visibility,
68         tt_volatility
69 } typetag_t;
70
71 typedef struct symbol_t
72 {
73         const char *str;      /**< The name of this symbol. */
74         typetag_t   typetag;  /**< The type tag of this symbol. */
75         unsigned    code;     /**< The value of this symbol. */
76 } symbol_t;
77
78 typedef struct id_entry
79 {
80         long id;
81         void *elem;
82 } id_entry;
83
84 /** The symbol table, a set of symbol_t elements. */
85 static set *symtbl;
86
87
88 /**
89  * Calculate a hash value for a string.
90  */
91 static unsigned string_hash(const char *str, int len)
92 {
93         return str[0] * 27893 ^ str[len-1] * 81 ^ str[len >> 1];
94 }
95
96 /**
97  * Compare two symbol table entries.
98  */
99 static int symbol_cmp(const void *elt, const void *key, size_t size)
100 {
101         const symbol_t *entry = (const symbol_t *) elt;
102         const symbol_t *keyentry = (const symbol_t *) key;
103         (void) size;
104         return strcmp(entry->str, keyentry->str);
105 }
106
107 static int id_cmp(const void *elt, const void *key, size_t size)
108 {
109         const id_entry *entry = (const id_entry *) elt;
110         const id_entry *keyentry = (const id_entry *) key;
111         (void) size;
112         return entry->id - keyentry->id;
113 }
114
115 /** Initializes the symbol table. May be called more than once without problems. */
116 static void symtbl_init(void)
117 {
118         symbol_t key;
119
120         /* Only initialize once */
121         if(symtbl != NULL)
122                 return;
123
124         symtbl = new_set(symbol_cmp, 256);
125
126 #define INSERT(s, tt, cod)                                       \
127         key.str = (s);                                               \
128         key.typetag = (tt);                                          \
129         key.code = (cod);                                            \
130         set_insert(symtbl, &key, sizeof(key), string_hash(s, sizeof(s)-1))
131
132 #define INSERTENUM(tt, e) INSERT(#e, tt, e)
133
134         INSERT("array", tt_tpo, tpo_array);
135         INSERT("class", tt_tpo, tpo_class);
136         INSERT("method", tt_tpo, tpo_method);
137         INSERT("pointer", tt_tpo, tpo_pointer);
138         INSERT("primitive", tt_tpo, tpo_primitive);
139         INSERT("struct", tt_tpo, tpo_struct);
140         INSERT("Unknown", tt_tpo, tpo_unknown);
141
142 #include "gen_irio_lex.inl"
143
144         INSERTENUM(tt_align, align_non_aligned);
145         INSERTENUM(tt_align, align_is_aligned);
146
147         INSERTENUM(tt_allocation, allocation_automatic);
148         INSERTENUM(tt_allocation, allocation_parameter);
149         INSERTENUM(tt_allocation, allocation_dynamic);
150         INSERTENUM(tt_allocation, allocation_static);
151
152         INSERTENUM(tt_pin_state, op_pin_state_floats);
153         INSERTENUM(tt_pin_state, op_pin_state_pinned);
154         INSERTENUM(tt_pin_state, op_pin_state_exc_pinned);
155         INSERTENUM(tt_pin_state, op_pin_state_mem_pinned);
156
157         INSERTENUM(tt_type_state, layout_undefined);
158         INSERTENUM(tt_type_state, layout_fixed);
159
160         INSERTENUM(tt_variability, variability_uninitialized);
161         INSERTENUM(tt_variability, variability_initialized);
162         INSERTENUM(tt_variability, variability_part_constant);
163         INSERTENUM(tt_variability, variability_constant);
164
165         INSERTENUM(tt_visibility, visibility_local);
166         INSERTENUM(tt_visibility, visibility_external_visible);
167         INSERTENUM(tt_visibility, visibility_external_allocated);
168
169         INSERTENUM(tt_volatility, volatility_non_volatile);
170         INSERTENUM(tt_volatility, volatility_is_volatile);
171
172         INSERTENUM(tt_peculiarity, peculiarity_description);
173         INSERTENUM(tt_peculiarity, peculiarity_inherited);
174         INSERTENUM(tt_peculiarity, peculiarity_existent);
175
176         INSERTENUM(tt_initializer, IR_INITIALIZER_CONST);
177         INSERTENUM(tt_initializer, IR_INITIALIZER_TARVAL);
178         INSERTENUM(tt_initializer, IR_INITIALIZER_NULL);
179         INSERTENUM(tt_initializer, IR_INITIALIZER_COMPOUND);
180
181         INSERTENUM(tt_builtin, ir_bk_trap);
182         INSERTENUM(tt_builtin, ir_bk_debugbreak);
183         INSERTENUM(tt_builtin, ir_bk_return_address);
184         INSERTENUM(tt_builtin, ir_bk_frame_addess);
185         INSERTENUM(tt_builtin, ir_bk_prefetch);
186         INSERTENUM(tt_builtin, ir_bk_ffs);
187         INSERTENUM(tt_builtin, ir_bk_clz);
188         INSERTENUM(tt_builtin, ir_bk_ctz);
189         INSERTENUM(tt_builtin, ir_bk_popcount);
190         INSERTENUM(tt_builtin, ir_bk_parity);
191         INSERTENUM(tt_builtin, ir_bk_bswap);
192         INSERTENUM(tt_builtin, ir_bk_inport);
193         INSERTENUM(tt_builtin, ir_bk_outport);
194         INSERTENUM(tt_builtin, ir_bk_inner_trampoline);
195
196 #undef INSERTENUM
197 #undef INSERT
198 }
199
200 /** Returns the according symbol value for the given string and tag, or SYMERROR if none was found. */
201 static unsigned symbol(const char *str, typetag_t typetag)
202 {
203         symbol_t key, *entry;
204
205         key.str = str;
206
207         entry = set_find(symtbl, &key, sizeof(key), string_hash(str, strlen(str)));
208         if (entry && entry->typetag == typetag) {
209                 return entry->code;
210         }
211         return SYMERROR;
212 }
213
214 static void *get_id(io_env_t *env, long id)
215 {
216         id_entry key, *entry;
217         key.id = id;
218
219         entry = set_find(env->idset, &key, sizeof(key), (unsigned) id);
220         return entry ? entry->elem : NULL;
221 }
222
223 static void set_id(io_env_t *env, long id, void *elem)
224 {
225         id_entry key;
226         key.id = id;
227         key.elem = elem;
228         set_insert(env->idset, &key, sizeof(key), (unsigned) id);
229 }
230
231 static void write_mode(io_env_t *env, ir_mode *mode)
232 {
233         fputs(get_mode_name(mode), env->file);
234         fputc(' ', env->file);
235 }
236
237 static void write_tarval(io_env_t *env, tarval *tv)
238 {
239         char buf[1024];
240         write_mode(env, get_tarval_mode(tv));
241         tarval_snprintf(buf, sizeof(buf), tv);
242         fputs(buf, env->file);
243         fputc(' ', env->file);
244 }
245
246 static void write_pin_state(io_env_t *env, ir_node *irn)
247 {
248         fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
249         fputc(' ', env->file);
250 }
251
252 static void write_volatility(io_env_t *env, ir_node *irn)
253 {
254         ir_volatility vol;
255
256         if(is_Load(irn)) vol = get_Load_volatility(irn);
257         else if(is_Store(irn)) vol = get_Store_volatility(irn);
258         else assert(0 && "Invalid optype for write_volatility");
259
260         fputs(get_volatility_name(vol), env->file);
261         fputc(' ', env->file);
262 }
263
264 static void write_align(io_env_t *env, ir_node *irn)
265 {
266         ir_align align;
267
268         if(is_Load(irn)) align = get_Load_align(irn);
269         else if(is_Store(irn)) align = get_Store_align(irn);
270         else assert(0 && "Invalid optype for write_align");
271
272         fputs(get_align_name(align), env->file);
273         fputc(' ', env->file);
274 }
275
276 static void write_builtin_kind(io_env_t *env, ir_node *irn)
277 {
278         fputs(get_builtin_kind_name(get_Builtin_kind(irn)), env->file);
279         fputc(' ', env->file);
280 }
281
282 static void write_initializer(io_env_t *env, ir_initializer_t *ini)
283 {
284         FILE *f = env->file;
285         ir_initializer_kind_t ini_kind = get_initializer_kind(ini);
286
287         fputs(get_initializer_kind_name(ini_kind), f);
288         fputc(' ', f);
289
290         switch(ini_kind)
291         {
292                 case IR_INITIALIZER_CONST:
293                         fprintf(f, "%ld ", get_irn_node_nr(get_initializer_const_value(ini)));
294                         break;
295
296                 case IR_INITIALIZER_TARVAL:
297                         write_tarval(env, get_initializer_tarval_value(ini));
298                         break;
299
300                 case IR_INITIALIZER_NULL:
301                         break;
302
303                 case IR_INITIALIZER_COMPOUND:
304                 {
305                         unsigned i, n = get_initializer_compound_n_entries(ini);
306                         fprintf(f, "%d ", n);
307                         for(i = 0; i < n; i++)
308                                 write_initializer(env, get_initializer_compound_value(ini, i));
309                         break;
310                 }
311
312                 default:
313                         panic("Unknown initializer kind");
314         }
315 }
316
317 static void export_type(io_env_t *env, ir_type *tp)
318 {
319         FILE *f = env->file;
320         int i;
321         fprintf(f, "\ttype %ld %s \"%s\" %u %u %s %s ",
322                         get_type_nr(tp),
323                         get_type_tpop_name(tp),
324                         get_type_name(tp),
325                         get_type_size_bytes(tp),
326                         get_type_alignment_bytes(tp),
327                         get_type_state_name(get_type_state(tp)),
328                         get_visibility_name(get_type_visibility(tp)));
329
330         switch(get_type_tpop_code(tp))
331         {
332                 case tpo_array:
333                 {
334                         int n = get_array_n_dimensions(tp);
335                         fprintf(f, "%i %ld ", n, get_type_nr(get_array_element_type(tp)));
336                         for(i = 0; i < n; i++)
337                         {
338                                 ir_node *lower = get_array_lower_bound(tp, i);
339                                 ir_node *upper = get_array_upper_bound(tp, i);
340
341                                 if(is_Const(lower)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(lower)));
342                                 else panic("Lower array bound is not constant");
343
344                                 if(is_Const(upper)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(upper)));
345                                 else if(is_Unknown(upper)) fputs("unknown ", f);
346                                 else panic("Upper array bound is not constant");
347                         }
348                         break;
349                 }
350
351                 case tpo_class:
352                         /* TODO: inheritance stuff not supported yet */
353                         printf("Inheritance of classes not supported yet!\n");
354                         break;
355
356                 case tpo_method:
357                 {
358                         int nparams = get_method_n_params(tp);
359                         int nresults = get_method_n_ress(tp);
360                         fprintf(f, "%i %i ", nparams, nresults);
361                         for(i = 0; i < nparams; i++)
362                                 fprintf(f, "%ld ", get_type_nr(get_method_param_type(tp, i)));
363                         for(i = 0; i < nresults; i++)
364                                 fprintf(f, "%ld ", get_type_nr(get_method_res_type(tp, i)));
365                         break;
366                 }
367
368                 case tpo_pointer:
369                         write_mode(env, get_type_mode(tp));
370                         fprintf(f, "%ld ", get_type_nr(get_pointer_points_to_type(tp)));
371                         break;
372
373                 case tpo_primitive:
374                         write_mode(env, get_type_mode(tp));
375                         break;
376
377                 case tpo_struct:
378                         break;
379
380                 case tpo_unknown:
381                         break;
382
383                 default:
384                         printf("export_type: Unknown type code \"%s\".\n", get_type_tpop_name(tp));
385                         break;
386         }
387         fputc('\n', f);
388 }
389
390 static void export_entity(io_env_t *env, ir_entity *ent)
391 {
392         ir_type *owner = get_entity_owner(ent);
393         fprintf(env->file, "\tentity %ld \"%s\" \"%s\" %ld %ld %d %u %s %s %s %s %s ",
394                         get_entity_nr(ent),
395                         get_entity_name(ent),
396                         ent->ld_name ? get_id_str(ent->ld_name) : "",
397                         get_type_nr(get_entity_type(ent)),
398                         get_type_nr(owner),
399                         get_entity_offset(ent),
400                         (unsigned) get_entity_offset_bits_remainder(ent),
401                         get_allocation_name(get_entity_allocation(ent)),
402                         get_visibility_name(get_entity_visibility(ent)),
403                         get_variability_name(get_entity_variability(ent)),
404                         get_peculiarity_name(get_entity_peculiarity(ent)),
405                         get_volatility_name(get_entity_volatility(ent)));
406
407         // TODO: inheritance stuff for class entities not supported yet
408         if(is_Class_type(owner) && owner != get_glob_type())
409                 printf("Inheritance of class entities not supported yet!\n");
410
411         if(get_entity_variability(ent) != variability_uninitialized
412                 && get_entity_visibility(ent) != visibility_external_allocated)
413         {
414                 if(is_compound_entity(ent))
415                 {
416                         if(has_entity_initializer(ent))
417                         {
418                                 fputs("initializer ", env->file);
419                                 write_initializer(env, get_entity_initializer(ent));
420                         }
421                         else
422                         {
423                                 int i, n = get_compound_ent_n_values(ent);
424                                 fputs("noninitializer ", env->file);
425                                 fprintf(env->file, "%d ", n);
426                                 for(i = 0; i < n; i++)
427                                 {
428                                         ir_entity *member = get_compound_ent_value_member(ent, i);
429                                         ir_node   *irn    = get_compound_ent_value(ent, i);
430                                         fprintf(env->file, "%ld %ld ", get_entity_nr(member), get_irn_node_nr(irn));
431                                 }
432                         }
433                 }
434                 else
435                 {
436                         ir_node *irn = get_atomic_ent_value(ent);
437                         fprintf(env->file, "%ld ", get_irn_node_nr(irn));
438                 }
439         }
440
441         fputc('\n', env->file);
442 }
443
444 static void export_type_or_ent(type_or_ent tore, void *ctx)
445 {
446         io_env_t *env = (io_env_t *) ctx;
447
448         switch(get_kind(tore.ent))
449         {
450                 case k_entity:
451                         export_entity(env, tore.ent);
452                         break;
453
454                 case k_type:
455                         export_type(env, tore.typ);
456                         break;
457
458                 default:
459                         printf("export_type_or_ent: Unknown type or entity.\n");
460                         break;
461         }
462 }
463
464 static void export_node(ir_node *irn, void *ctx)
465 {
466         io_env_t *env = (io_env_t *) ctx;
467         int i, n;
468         unsigned opcode = get_irn_opcode(irn);
469
470         if(env->ignoreblocks && opcode == iro_Block)
471                 return;
472
473         n = get_irn_arity(irn);
474
475         fprintf(env->file, "\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
476
477         for(i = -1; i < n; i++)
478         {
479                 ir_node *pred = get_irn_n(irn, i);
480                 if(pred == NULL) {
481                         /* Anchor node may have NULL predecessors */
482                         assert(is_Anchor(irn));
483                         fputs("-1 ", env->file);
484                 } else {
485                         fprintf(env->file, "%ld ", get_irn_node_nr(pred));
486                 }
487         }
488
489         fprintf(env->file, "] { ");
490
491         switch(opcode)
492         {
493                 #include "gen_irio_export.inl"
494         }
495         fputs("}\n", env->file);
496 }
497
498 /** Exports the whole irp to the given file in a textual form. */
499 void ir_export(const char *filename)
500 {
501         io_env_t env;
502         int i, n_irgs = get_irp_n_irgs(), n_pseudoirgs = get_irp_n_pseudo_irgs();
503
504         env.file = fopen(filename, "wt");
505         if(!env.file)
506         {
507                 perror(filename);
508                 return;
509         }
510
511         fputs("typegraph {\n", env.file);
512
513         type_walk_plus_frames(NULL, export_type_or_ent, &env);
514         /* TODO: Visit frame types and "types for value params"? */
515
516         for(i = 0; i < n_irgs; i++)
517         {
518                 ir_graph *irg = get_irp_irg(i);
519
520                 fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
521
522                 env.ignoreblocks = 0;
523                 irg_block_walk_graph(irg, NULL, export_node, &env);
524
525                 env.ignoreblocks = 1;
526                 irg_walk_anchors(irg, NULL, export_node, &env);
527         }
528
529         fputs("}\n\nconstirg {\n", env.file);
530         walk_const_code(NULL, export_node, &env);
531         fputs("}\n", env.file);
532
533         fclose(env.file);
534 }
535
536 /** Exports the given irg to the given file. */
537 void ir_export_irg(ir_graph *irg, const char *filename)
538 {
539         io_env_t env;
540
541         env.file = fopen(filename, "wt");
542         if(!env.file)
543         {
544                 perror(filename);
545                 return;
546         }
547
548         fputs("typegraph {\n", env.file);
549
550         type_walk_irg(irg, NULL, export_type_or_ent, &env);
551
552         fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
553
554         env.ignoreblocks = 0;
555         irg_block_walk_graph(irg, NULL, export_node, &env);
556
557         env.ignoreblocks = 1;
558         irg_walk_anchors(irg, NULL, export_node, &env);
559
560         /* TODO: Only output needed constants */
561         fputs("}\n\nconstirg {\n", env.file);
562         walk_const_code(NULL, export_node, &env);
563         fputs("}\n", env.file);
564
565         fclose(env.file);
566 }
567
568 static int read_c(io_env_t *env)
569 {
570         int ch = fgetc(env->file);
571         switch(ch)
572         {
573                 case '\t':
574                         env->col += 4;
575                         break;
576
577                 case '\n':
578                         env->col = 0;
579                         env->line++;
580                         break;
581
582                 default:
583                         env->col++;
584                         break;
585         }
586         return ch;
587 }
588
589 /** Returns the first non-whitespace character or EOF. **/
590 static int skip_ws(io_env_t *env)
591 {
592         while(1)
593         {
594                 int ch = read_c(env);
595                 switch(ch)
596                 {
597                         case ' ':
598                         case '\t':
599                         case '\n':
600                         case '\r':
601                                 break;
602
603                         default:
604                                 return ch;
605                 }
606         }
607 }
608
609 static void skip_to(io_env_t *env, char to_ch)
610 {
611         int ch;
612         do
613         {
614                 ch = read_c(env);
615         }
616         while(ch != to_ch && ch != EOF);
617 }
618
619 static int expect_char(io_env_t *env, char ch)
620 {
621         int curch = skip_ws(env);
622         if(curch != ch)
623         {
624                 printf("Unexpected char '%c', expected '%c' in line %i:%i\n", curch, ch, env->line, env->col);
625                 return 0;
626         }
627         return 1;
628 }
629
630 #define EXPECT(c) if(expect_char(env, (c))) {} else return 0
631 #define EXPECT_OR_EXIT(c) if(expect_char(env, (c))) {} else exit(1)
632
633 inline static const char *read_str_to(io_env_t *env, char *buf, size_t bufsize)
634 {
635         size_t i;
636         for(i = 0; i < bufsize - 1; i++)
637         {
638                 int ch = read_c(env);
639                 if(ch == EOF) break;
640                 switch(ch)
641                 {
642                         case ' ':
643                         case '\t':
644                         case '\n':
645                         case '\r':
646                                 if(i != 0)
647                                         goto endofword;
648                                 i--;    // skip whitespace
649                                 break;
650
651                         default:
652                                 buf[i] = ch;
653                                 break;
654                 }
655         }
656 endofword:
657         buf[i] = 0;
658         return buf;
659 }
660
661 static const char *read_str(io_env_t *env)
662 {
663         static char buf[1024];
664         return read_str_to(env, buf, sizeof(buf));
665 }
666
667 static const char *read_qstr_to(io_env_t *env, char *buf, size_t bufsize)
668 {
669         size_t i;
670         EXPECT_OR_EXIT('\"');
671         for(i = 0; i < bufsize - 1; i++)
672         {
673                 int ch = read_c(env);
674                 if(ch == EOF)
675                 {
676                         printf("Unexpected end of quoted string!\n");
677                         exit(1);
678                 }
679                 if(ch == '\"') break;
680
681                 buf[i] = ch;
682         }
683         if(i == bufsize - 1)
684         {
685                 printf("Quoted string too long!\n");
686                 exit(1);
687         }
688         buf[i] = 0;
689         return buf;
690 }
691
692 static long read_long2(io_env_t *env, char **endptr)
693 {
694         static char buf[1024];
695         return strtol(read_str_to(env, buf, sizeof(buf)), endptr, 0);
696 }
697
698 static long read_long(io_env_t *env)
699 {
700         return read_long2(env, NULL);
701 }
702
703 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
704 {
705         ir_node *node = (ir_node *) get_id(env, nodenr);
706         if(node && node->kind != k_ir_node)
707         {
708                 panic("Irn ID %ld collides with something else in line %i:%i\n", nodenr, env->line, env->col);
709         }
710         return node;
711 }
712
713 static ir_node *get_node(io_env_t *env, long nodenr)
714 {
715         ir_node *node = get_node_or_null(env, nodenr);
716         if(!node)
717                 panic("Unknown node: %ld in line %i:%i\n", nodenr, env->line, env->col);
718
719         return node;
720 }
721
722 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
723 {
724         ir_node *node = get_node_or_null(env, nodenr);
725         if(!node)
726         {
727                 node = new_Dummy(mode_X);
728                 set_id(env, nodenr, node);
729         }
730         return node;
731 }
732
733 static ir_type *get_type(io_env_t *env, long typenr)
734 {
735         ir_type *type = (ir_type *) get_id(env, typenr);
736         if(!type)
737         {
738                 panic("Unknown type: %ld in line %i:%i\n", typenr, env->line, env->col);
739         }
740         else if(type->kind != k_type)
741         {
742                 panic("Type ID %ld collides with something else in line %i:%i\n", typenr, env->line, env->col);
743         }
744         return type;
745 }
746
747 static ir_type *read_type(io_env_t *env)
748 {
749         return get_type(env, read_long(env));
750 }
751
752 static ir_entity *get_entity(io_env_t *env, long entnr)
753 {
754         ir_entity *entity = (ir_entity *) get_id(env, entnr);
755         if(!entity)
756         {
757                 printf("Unknown entity: %ld in line %i:%i\n", entnr, env->line, env->col);
758                 exit(1);
759         }
760         else if(entity->kind != k_entity)
761         {
762                 panic("Entity ID %ld collides with something else in line %i:%i\n", entnr, env->line, env->col);
763         }
764         return entity;
765 }
766
767 static ir_entity *read_entity(io_env_t *env)
768 {
769         return get_entity(env, read_long(env));
770 }
771
772 static ir_mode *read_mode(io_env_t *env)
773 {
774         static char buf[128];
775         int i, n;
776
777         read_str_to(env, buf, sizeof(buf));
778
779         n = get_irp_n_modes();
780         for(i = 0; i < n; i++)
781         {
782                 ir_mode *mode = get_irp_mode(i);
783                 if(!strcmp(buf, get_mode_name(mode)))
784                         return mode;
785         }
786
787         printf("Unknown mode \"%s\" in line %i:%i\n", buf, env->line, env->col);
788         return mode_ANY;
789 }
790
791 static const char *get_typetag_name(typetag_t typetag)
792 {
793         switch(typetag)
794         {
795                 case tt_align:       return "align";
796                 case tt_allocation:  return "allocation";
797                 case tt_builtin:     return "builtin kind";
798                 case tt_initializer: return "initializer kind";
799                 case tt_iro:         return "opcode";
800                 case tt_peculiarity: return "peculiarity";
801                 case tt_pin_state:   return "pin state";
802                 case tt_tpo:         return "type";
803                 case tt_type_state:  return "type state";
804                 case tt_variability: return "variability";
805                 case tt_visibility:  return "visibility";
806                 case tt_volatility:  return "volatility";
807                 default: return "<UNKNOWN>";
808         }
809 }
810
811 /**
812  * Read and decode an enum constant.
813  */
814 static unsigned read_enum(io_env_t *env, typetag_t typetag)
815 {
816         static char buf[128];
817         unsigned code = symbol(read_str_to(env, buf, sizeof(buf)), typetag);
818         if(code != SYMERROR)
819                 return code;
820
821         printf("Invalid %s: \"%s\" in %i:%i\n", get_typetag_name(typetag), buf, env->line, env->col);
822         return 0;
823 }
824
825 #define read_align(env)            ((ir_align)              read_enum(env, tt_align))
826 #define read_allocation(env)       ((ir_allocation)         read_enum(env, tt_allocation))
827 #define read_peculiarity(env)      ((ir_peculiarity)        read_enum(env, tt_peculiarity))
828 #define read_pin_state(env)        ((op_pin_state)          read_enum(env, tt_pin_state))
829 #define read_type_state(env)       ((ir_type_state)         read_enum(env, tt_type_state))
830 #define read_variability(env)      ((ir_variability)        read_enum(env, tt_variability))
831 #define read_visibility(env)       ((ir_visibility)         read_enum(env, tt_visibility))
832 #define read_volatility(env)       ((ir_volatility)         read_enum(env, tt_volatility))
833 #define read_initializer_kind(env) ((ir_initializer_kind_t) read_enum(env, tt_initializer))
834 #define read_builtin_kind(env)     ((ir_builtin_kind)       read_enum(env, tt_builtin))
835
836 static ir_cons_flags get_cons_flags(io_env_t *env)
837 {
838         ir_cons_flags flags = cons_none;
839
840         op_pin_state pinstate = read_pin_state(env);
841         switch(pinstate)
842         {
843                 case op_pin_state_floats: flags |= cons_floats; break;
844                 case op_pin_state_pinned: break;
845                 default:
846                         panic("Error in %i:%i: Invalid pinstate: %s", env->line, env->col, get_op_pin_state_name(pinstate));
847         }
848
849         if(read_volatility(env) == volatility_is_volatile) flags |= cons_volatile;
850         if(read_align(env) == align_non_aligned) flags |= cons_unaligned;
851
852         return flags;
853 }
854
855 static tarval *read_tv(io_env_t *env)
856 {
857         static char buf[128];
858         ir_mode *tvmode = read_mode(env);
859         read_str_to(env, buf, sizeof(buf));
860         return new_tarval_from_str(buf, strlen(buf), tvmode);
861 }
862
863 static ir_initializer_t *read_initializer(io_env_t *env)
864 {
865         FILE *f = env->file;
866         ir_initializer_kind_t ini_kind = read_initializer_kind(env);
867
868         switch(ini_kind)
869         {
870                 case IR_INITIALIZER_CONST:
871                 {
872                         ir_node *irn = get_node_or_dummy(env, read_long(env));
873                         return create_initializer_const(irn);
874                 }
875
876                 case IR_INITIALIZER_TARVAL:
877                         return create_initializer_tarval(read_tv(env));
878
879                 case IR_INITIALIZER_NULL:
880                         return get_initializer_null();
881
882                 case IR_INITIALIZER_COMPOUND:
883                 {
884                         unsigned i, n = (unsigned) read_long(env);
885                         ir_initializer_t *ini = create_initializer_compound(n);
886                         for(i = 0; i < n; i++)
887                         {
888                                 ir_initializer_t *curini = read_initializer(env);
889                                 set_initializer_compound_value(ini, i, curini);
890                         }
891                         return ini;
892                 }
893
894                 default:
895                         panic("Unknown initializer kind");
896         }
897 }
898
899
900 /** Reads a type description and remembers it by its id. */
901 static void import_type(io_env_t *env)
902 {
903         char           buf[1024];
904         int            i;
905         ir_type       *type;
906         long           typenr = read_long(env);
907         const char    *tpop   = read_str(env);
908         const char    *name   = read_qstr_to(env, buf, sizeof(buf));
909         unsigned       size   = (unsigned) read_long(env);
910         unsigned       align  = (unsigned) read_long(env);
911         ir_type_state  state  = read_type_state(env);
912         ir_visibility  vis    = read_visibility(env);
913
914         ident         *id     = new_id_from_str(name);
915
916         switch(symbol(tpop, tt_tpo))
917         {
918                 case tpo_array:
919                 {
920                         int ndims = (int) read_long(env);
921                         long elemtypenr = read_long(env);
922                         ir_type *elemtype = get_type(env, elemtypenr);
923
924                         type = new_type_array(id, ndims, elemtype);
925                         for(i = 0; i < ndims; i++)
926                         {
927                                 const char *str = read_str(env);
928                                 if(strcmp(str, "unknown"))
929                                 {
930                                         long lowerbound = strtol(str, NULL, 0);
931                                         set_array_lower_bound_int(type, i, lowerbound);
932                                 }
933                                 str = read_str(env);
934                                 if(strcmp(str, "unknown"))
935                                 {
936                                         long upperbound = strtol(str, NULL, 0);
937                                         set_array_upper_bound_int(type, i, upperbound);
938                                 }
939                         }
940                         set_type_size_bytes(type, size);
941                         break;
942                 }
943
944                 case tpo_class:
945                         type = new_type_class(id);
946                         set_type_size_bytes(type, size);
947                         break;
948
949                 case tpo_method:
950                 {
951                         int nparams  = (int) read_long(env);
952                         int nresults = (int) read_long(env);
953
954                         type = new_type_method(id, nparams, nresults);
955
956                         for(i = 0; i < nparams; i++)
957                         {
958                                 long     typenr = read_long(env);
959                                 ir_type *paramtype = get_type(env, typenr);
960
961                                 set_method_param_type(type, i, paramtype);
962                         }
963                         for(i = 0; i < nresults; i++)
964                         {
965                                 long typenr = read_long(env);
966                                 ir_type *restype = get_type(env, typenr);
967
968                                 set_method_res_type(type, i, restype);
969                         }
970                         break;
971                 }
972
973                 case tpo_pointer:
974                 {
975                         ir_mode *mode = read_mode(env);
976                         ir_type *pointsto = get_type(env, read_long(env));
977                         type = new_type_pointer(id, pointsto, mode);
978                         break;
979                 }
980
981                 case tpo_primitive:
982                 {
983                         ir_mode *mode = read_mode(env);
984                         type = new_type_primitive(id, mode);
985                         break;
986                 }
987
988                 case tpo_struct:
989                         type = new_type_struct(id);
990                         set_type_size_bytes(type, size);
991                         break;
992
993                 case tpo_union:
994                         type = new_type_union(id);
995                         set_type_size_bytes(type, size);
996                         break;
997
998                 case tpo_unknown:
999                         return;   // ignore unknown type
1000
1001                 default:
1002                         if(typenr != 0)  // ignore global type
1003                                 printf("Unknown type kind: \"%s\" in line %i:%i\n", tpop, env->line, env->col);
1004                         skip_to(env, '\n');
1005                         return;
1006         }
1007
1008         set_type_alignment_bytes(type, align);
1009         set_type_visibility(type, vis);
1010
1011         if(state == layout_fixed)
1012                 ARR_APP1(ir_type *, env->fixedtypes, type);
1013
1014         set_id(env, typenr, type);
1015         printf("Insert type %s %ld\n", name, typenr);
1016 }
1017
1018 /** Reads an entity description and remembers it by its id. */
1019 static void import_entity(io_env_t *env)
1020 {
1021         char          buf[1024], buf2[1024];
1022         long          entnr       = read_long(env);
1023         const char   *name        = read_qstr_to(env, buf, sizeof(buf));
1024         const char   *ld_name     = read_qstr_to(env, buf2, sizeof(buf2));
1025         long          typenr      = read_long(env);
1026         long          ownertypenr = read_long(env);
1027
1028         ir_type   *type      = get_type(env, typenr);
1029         ir_type   *ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
1030         ir_entity *entity    = new_entity(ownertype, new_id_from_str(name), type);
1031
1032         if(*ld_name) set_entity_ld_ident(entity, new_id_from_str(ld_name));
1033         set_entity_offset     (entity, (int) read_long(env));
1034         set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
1035         set_entity_allocation (entity, read_allocation(env));
1036         set_entity_visibility (entity, read_visibility(env));
1037         set_entity_variability(entity, read_variability(env));
1038         set_entity_peculiarity(entity, read_peculiarity(env));
1039         set_entity_volatility (entity, read_volatility(env));
1040
1041         if(get_entity_variability(entity) != variability_uninitialized
1042                 && get_entity_visibility(entity) != visibility_external_allocated)
1043         {
1044                 if(is_compound_entity(entity))
1045                 {
1046                         if(!strcmp(read_str_to(env, buf2, sizeof(buf2)), "initializer"))
1047                         {
1048                                 set_entity_initializer(entity, read_initializer(env));
1049                         }
1050                         else
1051                         {
1052                                 int i, n = (int) read_long(env);
1053                                 for(i = 0; i < n; i++)
1054                                 {
1055                                         ir_entity *member = get_entity(env, read_long(env));
1056                                         ir_node   *irn    = get_node_or_dummy(env, read_long(env));
1057                                         add_compound_ent_value(entity, irn, member);
1058                                 }
1059                         }
1060                 }
1061                 else
1062                 {
1063                         ir_node *irn = get_node_or_dummy(env, read_long(env));
1064                         set_atomic_ent_value(entity, irn);
1065                 }
1066         }
1067
1068         set_id(env, entnr, entity);
1069         printf("Insert entity %s %ld\n", name, entnr);
1070 }
1071
1072 /** Parses the whole type graph. */
1073 static int parse_typegraph(io_env_t *env)
1074 {
1075         const char *kind;
1076         long curfpos;
1077
1078         EXPECT('{');
1079
1080         curfpos = ftell(env->file);
1081
1082         current_ir_graph = get_const_code_irg();
1083
1084         // parse all types first
1085         while(1)
1086         {
1087                 kind = read_str(env);
1088                 if(kind[0] == '}' && !kind[1]) break;
1089
1090                 if(!strcmp(kind, "type"))
1091                         import_type(env);
1092                 else
1093                         skip_to(env, '\n');
1094         }
1095
1096         // now parse rest
1097         fseek(env->file, curfpos, SEEK_SET);
1098         while(1)
1099         {
1100                 kind = read_str(env);
1101                 if(kind[0] == '}' && !kind[1]) break;
1102
1103                 if(!strcmp(kind, "type"))
1104                         skip_to(env, '\n');
1105                 else if(!strcmp(kind, "entity"))
1106                         import_entity(env);
1107                 else
1108                 {
1109                         printf("Type graph element not supported yet: \"%s\"\n", kind);
1110                         skip_to(env, '\n');
1111                 }
1112         }
1113         return 1;
1114 }
1115
1116 static int read_node_header(io_env_t *env, long *nodenr, long **preds, const char **nodename)
1117 {
1118         int numpreds;
1119         *nodename = read_str(env);
1120         if((*nodename)[0] == '}' && !(*nodename)[1]) return -1;  // end-of-graph
1121
1122         *nodenr = read_long(env);
1123
1124         ARR_RESIZE(ir_node *, *preds, 0);
1125
1126         EXPECT('[');
1127         for(numpreds = 0; !feof(env->file); numpreds++)
1128         {
1129                 char *endptr;
1130                 ARR_APP1(long, *preds, read_long2(env, &endptr));
1131                 if(*endptr == ']') break;
1132         }
1133         return numpreds;
1134 }
1135
1136 /** Parses an IRG. */
1137 static int parse_graph(io_env_t *env, ir_graph *irg)
1138 {
1139         long       *preds = NEW_ARR_F(long, 16);
1140         ir_node   **prednodes = NEW_ARR_F(ir_node *, 16);
1141         int         i, numpreds, ret = 1;
1142         long        nodenr;
1143         const char *nodename;
1144         ir_node    *node, *newnode;
1145
1146         current_ir_graph = irg;
1147
1148         EXPECT('{');
1149
1150         while(1)
1151         {
1152                 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
1153                 if(numpreds == -1) break;  // end-of-graph
1154                 if(!numpreds)
1155                 {
1156                         printf("Node %s %ld is missing predecessors!", nodename, nodenr);
1157                         ret = 0;
1158                         break;
1159                 }
1160
1161                 ARR_RESIZE(ir_node *, prednodes, numpreds);
1162                 for(i = 0; i < numpreds - 1; i++)
1163                         prednodes[i] = get_node_or_dummy(env, preds[i + 1]);
1164
1165                 node = get_node_or_null(env, nodenr);
1166                 newnode = NULL;
1167
1168                 EXPECT('{');
1169
1170                 switch(symbol(nodename, tt_iro))
1171                 {
1172                         case iro_End:
1173                         {
1174                                 ir_node *newendblock = get_node(env, preds[0]);
1175                                 newnode = get_irg_end(current_ir_graph);
1176                                 exchange(get_nodes_block(newnode), newendblock);
1177                                 for(i = 0; i < numpreds - 1; i++)
1178                                         add_irn_n(newnode, prednodes[i]);
1179                                 break;
1180                         }
1181
1182                         case iro_Start:
1183                         {
1184                                 ir_node *newstartblock = get_node(env, preds[0]);
1185                                 newnode = get_irg_start(current_ir_graph);
1186                                 exchange(get_nodes_block(newnode), newstartblock);
1187                                 break;
1188                         }
1189
1190                         case iro_Block:
1191                         {
1192                                 if(preds[0] != nodenr)
1193                                 {
1194                                         printf("Invalid block: preds[0] != nodenr (%ld != %ld)\n",
1195                                                 preds[0], nodenr);
1196                                         ret = 0;
1197                                         goto endloop;
1198                                 }
1199
1200                                 newnode = new_Block(numpreds - 1, prednodes);
1201                                 break;
1202                         }
1203
1204                         case iro_Anchor:
1205                                 newnode = current_ir_graph->anchor;
1206                                 for(i = 0; i < numpreds - 1; i++)
1207                                         set_irn_n(newnode, i, prednodes[i]);
1208                                 set_irn_n(newnode, -1, get_node(env, preds[0]));
1209                                 break;
1210
1211                         case iro_SymConst:
1212                         {
1213                                 long entnr = read_long(env);
1214                                 union symconst_symbol sym;
1215                                 sym.entity_p = get_entity(env, entnr);
1216                                 newnode = new_SymConst(mode_P, sym, symconst_addr_ent);
1217                                 break;
1218                         }
1219
1220                         #include "gen_irio_import.inl"
1221
1222                         default:
1223                                 goto notsupported;
1224                 }
1225
1226                 EXPECT('}');
1227
1228                 if(!newnode)
1229                 {
1230 notsupported:
1231                         panic("Node type not supported yet: %s in line %i:%i\n", nodename, env->line, env->col);
1232                 }
1233
1234                 if(node)
1235                         exchange(node, newnode);
1236                 /* Always update hash entry to avoid more uses of id nodes */
1237                 set_id(env, nodenr, newnode);
1238                 //printf("Insert %s %ld\n", nodename, nodenr);
1239         }
1240
1241 endloop:
1242         DEL_ARR_F(preds);
1243         DEL_ARR_F(prednodes);
1244
1245         return ret;
1246 }
1247
1248 /** Imports an previously exported textual representation of an (maybe partial) irp */
1249 void ir_import(const char *filename)
1250 {
1251         int oldoptimize = get_optimize();
1252         firm_verification_t oldver = get_node_verification_mode();
1253         io_env_t ioenv;
1254         io_env_t *env = &ioenv;
1255         int i, n;
1256
1257         symtbl_init();
1258
1259         memset(env, 0, sizeof(*env));
1260         env->idset = new_set(id_cmp, 128);
1261         env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1262
1263         env->file = fopen(filename, "rt");
1264         if(!env->file)
1265         {
1266                 perror(filename);
1267                 exit(1);
1268         }
1269
1270         set_optimize(0);
1271         do_node_verification(FIRM_VERIFICATION_OFF);
1272
1273         while(1)
1274         {
1275                 const char *str = read_str(env);
1276                 if(!*str) break;
1277                 if(!strcmp(str, "typegraph"))
1278                 {
1279                         if(!parse_typegraph(env)) break;
1280                 }
1281                 else if(!strcmp(str, "irg"))
1282                 {
1283                         ir_graph *irg = new_ir_graph(get_entity(env, read_long(env)), 0);
1284                         if(!parse_graph(env, irg)) break;
1285                 }
1286                 else if(!strcmp(str, "constirg"))
1287                 {
1288                         if(!parse_graph(env, get_const_code_irg())) break;
1289                 }
1290         }
1291
1292         n = ARR_LEN(env->fixedtypes);
1293         for(i = 0; i < n; i++)
1294                 set_type_state(env->fixedtypes[i], layout_fixed);
1295
1296         DEL_ARR_F(env->fixedtypes);
1297
1298         del_set(env->idset);
1299
1300         irp_finalize_cons();
1301
1302         do_node_verification(oldver);
1303         set_optimize(oldoptimize);
1304
1305         fclose(env->file);
1306 }