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