- don't call it Schn... it's a symbol table
[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_iro,
58         tt_tpo,
59         tt_align,
60         tt_allocation,
61         tt_peculiarity,
62         tt_pin_state,
63         tt_type_state,
64         tt_variability,
65         tt_visibility,
66         tt_volatility
67 } typetag_t;
68
69 typedef struct symbol_t
70 {
71         const char *str;      /**< The name of this symbol. */
72         typetag_t   typetag;  /**< The type tag of this symbol. */
73         unsigned    code;     /**< The value of this symbol. */
74 } symbol_t;
75
76 typedef struct id_entry
77 {
78         long id;
79         void *elem;
80 } id_entry;
81
82 /** The symbol table, a set of symbol_t elements. */
83 static set *symtbl;
84
85
86 /**
87  * Calculate a hash value for a string.
88  */
89 static unsigned string_hash(const char *str, int len)
90 {
91         return str[0] * 27893 ^ str[len-1] * 81 ^ str[len >> 1];
92 }
93
94 /**
95  * Compare two symbol table entries.
96  */
97 static int symbol_cmp(const void *elt, const void *key, size_t size)
98 {
99         const symbol_t *entry = (const symbol_t *) elt;
100         const symbol_t *keyentry = (const symbol_t *) key;
101         (void) size;
102         return strcmp(entry->str, keyentry->str);
103 }
104
105 static int id_cmp(const void *elt, const void *key, size_t size)
106 {
107         const id_entry *entry = (const id_entry *) elt;
108         const id_entry *keyentry = (const id_entry *) key;
109         (void) size;
110         return entry->id - keyentry->id;
111 }
112
113 /** Initializes the symbol table. May be called more than once without problems. */
114 static void symtbl_init(void)
115 {
116         symbol_t key;
117
118         /* Only initialize once */
119         if(symtbl != NULL)
120                 return;
121
122         symtbl = new_set(symbol_cmp, 32);
123
124 #define INSERT(s, tt, cod)                                       \
125         key.str = (s);                                               \
126         key.typetag = (tt);                                          \
127         key.code = (cod);                                            \
128         set_insert(symtbl, &key, sizeof(key), string_hash(s, sizeof(s)-1))
129
130 #define INSERTENUM(tt, e) INSERT(#e, tt, e)
131
132         INSERT("primitive", tt_tpo, tpo_primitive);
133         INSERT("method", tt_tpo, tpo_method);
134         INSERT("array", tt_tpo, tpo_array);
135         INSERT("struct", tt_tpo, tpo_struct);
136         INSERT("Unknown", tt_tpo, tpo_unknown);
137
138 #include "gen_irio_lex.inl"
139
140         INSERTENUM(tt_align, align_non_aligned);
141         INSERTENUM(tt_align, align_is_aligned);
142
143         INSERTENUM(tt_allocation, allocation_automatic);
144         INSERTENUM(tt_allocation, allocation_parameter);
145         INSERTENUM(tt_allocation, allocation_dynamic);
146         INSERTENUM(tt_allocation, allocation_static);
147
148         INSERTENUM(tt_pin_state, op_pin_state_floats);
149         INSERTENUM(tt_pin_state, op_pin_state_pinned);
150         INSERTENUM(tt_pin_state, op_pin_state_exc_pinned);
151         INSERTENUM(tt_pin_state, op_pin_state_mem_pinned);
152
153         INSERTENUM(tt_type_state, layout_undefined);
154         INSERTENUM(tt_type_state, layout_fixed);
155
156         INSERTENUM(tt_variability, variability_uninitialized);
157         INSERTENUM(tt_variability, variability_initialized);
158         INSERTENUM(tt_variability, variability_part_constant);
159         INSERTENUM(tt_variability, variability_constant);
160
161         INSERTENUM(tt_visibility, visibility_local);
162         INSERTENUM(tt_visibility, visibility_external_visible);
163         INSERTENUM(tt_visibility, visibility_external_allocated);
164
165         INSERTENUM(tt_volatility, volatility_non_volatile);
166         INSERTENUM(tt_volatility, volatility_is_volatile);
167
168         INSERTENUM(tt_peculiarity, peculiarity_description);
169         INSERTENUM(tt_peculiarity, peculiarity_inherited);
170         INSERTENUM(tt_peculiarity, peculiarity_existent);
171
172 #undef INSERTENUM
173 #undef INSERT
174 }
175
176 /** Returns the according symbol value for the given string and tag, or SYMERROR if none was found. */
177 static unsigned symbol(const char *str, typetag_t typetag)
178 {
179         symbol_t key, *entry;
180
181         key.str = str;
182
183         entry = set_find(symtbl, &key, sizeof(key), string_hash(str, strlen(str)));
184         if (entry && entry->typetag == typetag) {
185                 return entry->code;
186         }
187         return SYMERROR;
188 }
189
190 static void *get_id(io_env_t *env, long id)
191 {
192         id_entry key, *entry;
193         key.id = id;
194
195         entry = set_find(env->idset, &key, sizeof(key), (unsigned) id);
196         return entry ? entry->elem : NULL;
197 }
198
199 static void set_id(io_env_t *env, long id, void *elem)
200 {
201         id_entry key;
202         key.id = id;
203         key.elem = elem;
204         set_insert(env->idset, &key, sizeof(key), (unsigned) id);
205 }
206
207 static void write_mode(io_env_t *env, ir_mode *mode)
208 {
209         fputs(get_mode_name(mode), env->file);
210         fputc(' ', env->file);
211 }
212
213 static void write_pinned(io_env_t *env, ir_node *irn)
214 {
215         fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
216         fputc(' ', env->file);
217 }
218
219 static void write_volatility(io_env_t *env, ir_node *irn)
220 {
221         ir_volatility vol;
222
223         if(is_Load(irn)) vol = get_Load_volatility(irn);
224         else if(is_Store(irn)) vol = get_Store_volatility(irn);
225         else assert(0 && "Invalid optype for write_volatility");
226
227         fputs(get_volatility_name(vol), env->file);
228         fputc(' ', env->file);
229 }
230
231 static void write_align(io_env_t *env, ir_node *irn)
232 {
233         ir_align align;
234
235         if(is_Load(irn)) align = get_Load_align(irn);
236         else if(is_Store(irn)) align = get_Store_align(irn);
237         else assert(0 && "Invalid optype for write_align");
238
239         fputs(get_align_name(align), env->file);
240         fputc(' ', env->file);
241 }
242
243 static void export_type(io_env_t *env, ir_type *tp)
244 {
245         FILE *f = env->file;
246         int i;
247         fprintf(f, "\ttype %ld %s \"%s\" %u %u %s %s ",
248                         get_type_nr(tp),
249                         get_type_tpop_name(tp),
250                         get_type_name(tp),
251                         get_type_size_bytes(tp),
252                         get_type_alignment_bytes(tp),
253                         get_type_state_name(get_type_state(tp)),
254                         get_visibility_name(get_type_visibility(tp)));
255
256         switch(get_type_tpop_code(tp))
257         {
258                 case tpo_array:
259                 {
260                         int n = get_array_n_dimensions(tp);
261                         fprintf(f, "%i %ld ", n, get_type_nr(get_array_element_type(tp)));
262                         for(i = 0; i < n; i++)
263                         {
264                                 ir_node *lower = get_array_lower_bound(tp, i);
265                                 ir_node *upper = get_array_upper_bound(tp, i);
266
267                                 if(is_Const(lower)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(lower)));
268                                 else panic("Lower array bound is not constant");
269
270                                 if(is_Const(upper)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(upper)));
271                                 else panic("Upper array bound is not constant");
272                         }
273                         break;
274                 }
275
276                 case tpo_method:
277                 {
278                         int nparams = get_method_n_params(tp);
279                         int nresults = get_method_n_ress(tp);
280                         fprintf(f, "%i %i ", nparams, nresults);
281                         for(i = 0; i < nparams; i++)
282                                 fprintf(f, "%ld ", get_type_nr(get_method_param_type(tp, i)));
283                         for(i = 0; i < nresults; i++)
284                                 fprintf(f, "%ld ", get_type_nr(get_method_res_type(tp, i)));
285                         break;
286                 }
287
288                 case tpo_primitive:
289                 {
290                         write_mode(env, get_type_mode(tp));
291                         break;
292                 }
293
294                 case tpo_struct:
295                         break;
296
297                 case tpo_class:
298                         /* TODO: inheritance stuff not supported yet */
299                         printf("Inheritance of classes not supported yet!\n");
300                         break;
301
302                 case tpo_unknown:
303                         break;
304
305                 default:
306                         printf("export_type: Unknown type code \"%s\".\n", get_type_tpop_name(tp));
307                         break;
308         }
309         fputc('\n', f);
310 }
311
312 static void export_entity(io_env_t *env, ir_entity *ent)
313 {
314         ir_type *owner = get_entity_owner(ent);
315         fprintf(env->file, "\tentity %ld \"%s\" %ld %ld %d %u %s %s %s %s %s\n",
316                         get_entity_nr(ent),
317                         get_entity_name(ent),
318                         get_type_nr(get_entity_type(ent)),
319                         get_type_nr(owner),
320                         get_entity_offset(ent),
321                         (unsigned) get_entity_offset_bits_remainder(ent),
322                         get_allocation_name(get_entity_allocation(ent)),
323                         get_visibility_name(get_entity_visibility(ent)),
324                         get_variability_name(get_entity_variability(ent)),
325                         get_peculiarity_name(get_entity_peculiarity(ent)),
326                         get_volatility_name(get_entity_volatility(ent)));
327
328         // TODO: inheritance stuff for class entities not supported yet
329         if(is_Class_type(owner) && owner != get_glob_type())
330                 printf("Inheritance of class entities not supported yet!\n");
331 }
332
333 static void export_type_or_ent(type_or_ent tore, void *ctx)
334 {
335         io_env_t *env = (io_env_t *) ctx;
336
337         switch(get_kind(tore.ent))
338         {
339                 case k_entity:
340                         export_entity(env, tore.ent);
341                         break;
342
343                 case k_type:
344                         export_type(env, tore.typ);
345                         break;
346
347                 default:
348                         printf("export_type_or_ent: Unknown type or entity.\n");
349                         break;
350         }
351 }
352
353 static void export_node(ir_node *irn, void *ctx)
354 {
355         io_env_t *env = (io_env_t *) ctx;
356         int i, n;
357         unsigned opcode = get_irn_opcode(irn);
358         char buf[1024];
359
360         if(env->ignoreblocks && opcode == iro_Block)
361                 return;
362
363         n = get_irn_arity(irn);
364
365         fprintf(env->file, "\n\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
366
367         for(i = -1; i < n; i++)
368         {
369                 ir_node *pred = get_irn_n(irn, i);
370                 if(pred == NULL) {
371                         /* Anchor node may ave NULL predecessors */
372                         assert(is_Anchor(irn));
373                         fputs("-1 ", env->file);
374                 } else {
375                         fprintf(env->file, "%ld ", get_irn_node_nr(pred));
376                 }
377         }
378
379         fprintf(env->file, "] { ");
380
381         switch(opcode)
382         {
383                 #include "gen_irio_export.inl"
384         }
385         fputc('}', env->file);
386 }
387
388 /** Exports the given irg to the given file. */
389 void ir_export_irg(ir_graph *irg, const char *filename)
390 {
391         io_env_t env;
392
393         env.file = fopen(filename, "wt");
394         if(!env.file)
395         {
396                 perror(filename);
397                 return;
398         }
399
400         fputs("typegraph {\n", env.file);
401
402         type_walk_irg(irg, NULL, export_type_or_ent, &env);
403
404         fprintf(env.file, "}\n\nirg %ld {", get_entity_nr(get_irg_entity(irg)));
405
406         env.ignoreblocks = 0;
407         irg_block_walk_graph(irg, NULL, export_node, &env);
408
409         env.ignoreblocks = 1;
410         irg_walk_anchors(irg, NULL, export_node, &env);
411
412         fputs("\n}\n", env.file);
413
414         fclose(env.file);
415 }
416
417 static int read_c(io_env_t *env)
418 {
419         int ch = fgetc(env->file);
420         switch(ch)
421         {
422                 case '\t':
423                         env->col += 4;
424                         break;
425
426                 case '\n':
427                         env->col = 0;
428                         env->line++;
429                         break;
430
431                 default:
432                         env->col++;
433                         break;
434         }
435         return ch;
436 }
437
438 /** Returns the first non-whitespace character or EOF. **/
439 static int skip_ws(io_env_t *env)
440 {
441         while(1)
442         {
443                 int ch = read_c(env);
444                 switch(ch)
445                 {
446                         case ' ':
447                         case '\t':
448                         case '\n':
449                         case '\r':
450                                 break;
451
452                         default:
453                                 return ch;
454                 }
455         }
456 }
457
458 static void skip_to(io_env_t *env, char to_ch)
459 {
460         int ch;
461         do
462         {
463                 ch = read_c(env);
464         }
465         while(ch != to_ch && ch != EOF);
466 }
467
468 static int expect_char(io_env_t *env, char ch)
469 {
470         int curch = skip_ws(env);
471         if(curch != ch)
472         {
473                 printf("Unexpected char '%c', expected '%c' in line %i:%i\n", curch, ch, env->line, env->col);
474                 return 0;
475         }
476         return 1;
477 }
478
479 #define EXPECT(c) if(expect_char(env, (c))) {} else return 0
480 #define EXPECT_OR_EXIT(c) if(expect_char(env, (c))) {} else exit(1)
481
482 inline static const char *read_str_to(io_env_t *env, char *buf, size_t bufsize)
483 {
484         size_t i;
485         for(i = 0; i < bufsize - 1; i++)
486         {
487                 int ch = read_c(env);
488                 if(ch == EOF) break;
489                 switch(ch)
490                 {
491                         case ' ':
492                         case '\t':
493                         case '\n':
494                         case '\r':
495                                 if(i != 0)
496                                         goto endofword;
497                                 i--;    // skip whitespace
498                                 break;
499
500                         default:
501                                 buf[i] = ch;
502                                 break;
503                 }
504         }
505 endofword:
506         buf[i] = 0;
507         return buf;
508 }
509
510 static const char *read_str(io_env_t *env)
511 {
512         static char buf[1024];
513         return read_str_to(env, buf, sizeof(buf));
514 }
515
516 static const char *read_qstr_to(io_env_t *env, char *buf, size_t bufsize)
517 {
518         size_t i;
519         EXPECT_OR_EXIT('\"');
520         for(i = 0; i < bufsize - 1; i++)
521         {
522                 int ch = read_c(env);
523                 if(ch == EOF)
524                 {
525                         printf("Unexpected end of quoted string!\n");
526                         exit(1);
527                 }
528                 if(ch == '\"') break;
529
530                 buf[i] = ch;
531         }
532         if(i == bufsize - 1)
533         {
534                 printf("Quoted string too long!\n");
535                 exit(1);
536         }
537         buf[i] = 0;
538         return buf;
539 }
540
541 static long read_long2(io_env_t *env, char **endptr)
542 {
543         static char buf[1024];
544         return strtol(read_str_to(env, buf, sizeof(buf)), endptr, 0);
545 }
546
547 static long read_long(io_env_t *env)
548 {
549         return read_long2(env, NULL);
550 }
551
552 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
553 {
554         ir_node *node = (ir_node *) get_id(env, nodenr);
555         if(node && node->kind != k_ir_node)
556         {
557                 panic("Irn ID %ld collides with something else in line %i:%i\n", nodenr, env->line, env->col);
558         }
559         return node;
560 }
561
562 static ir_node *get_node(io_env_t *env, long nodenr)
563 {
564         ir_node *node = get_node_or_null(env, nodenr);
565         if(!node)
566                 panic("Unknown node: %ld in line %i:%i\n", nodenr, env->line, env->col);
567
568         return node;
569 }
570
571 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
572 {
573         ir_node *node = get_node_or_null(env, nodenr);
574         if(!node)
575         {
576                 node = new_Dummy(mode_X);
577                 set_id(env, nodenr, node);
578         }
579         return node;
580 }
581
582 static ir_type *get_type(io_env_t *env, long typenr)
583 {
584         ir_type *type = (ir_type *) get_id(env, typenr);
585         if(!type)
586         {
587                 panic("Unknown type: %ld in line %i:%i\n", typenr, env->line, env->col);
588         }
589         else if(type->kind != k_type)
590         {
591                 panic("Type ID %ld collides with something else in line %i:%i\n", typenr, env->line, env->col);
592         }
593         return type;
594 }
595
596 static ir_type *read_type(io_env_t *env)
597 {
598         return get_type(env, read_long(env));
599 }
600
601 static ir_entity *get_entity(io_env_t *env, long entnr)
602 {
603         ir_entity *entity = (ir_entity *) get_id(env, entnr);
604         if(!entity)
605         {
606                 printf("Unknown entity: %ld in line %i:%i\n", entnr, env->line, env->col);
607                 exit(1);
608         }
609         else if(entity->kind != k_entity)
610         {
611                 panic("Entity ID %ld collides with something else in line %i:%i\n", entnr, env->line, env->col);
612         }
613         return entity;
614 }
615
616 static ir_entity *read_entity(io_env_t *env)
617 {
618         return get_entity(env, read_long(env));
619 }
620
621 static ir_mode *read_mode(io_env_t *env)
622 {
623         static char buf[128];
624         int i, n;
625
626         read_str_to(env, buf, sizeof(buf));
627
628         n = get_irp_n_modes();
629         for(i = 0; i < n; i++)
630         {
631                 ir_mode *mode = get_irp_mode(i);
632                 if(!strcmp(buf, get_mode_name(mode)))
633                         return mode;
634         }
635
636         printf("Unknown mode \"%s\" in line %i:%i\n", buf, env->line, env->col);
637         return mode_ANY;
638 }
639
640 static const char *get_typetag_name(typetag_t typetag)
641 {
642         switch(typetag)
643         {
644                 case tt_iro:         return "opcode";
645                 case tt_tpo:         return "type";
646                 case tt_align:       return "align";
647                 case tt_allocation:  return "allocation";
648                 case tt_peculiarity: return "peculiarity";
649                 case tt_pin_state:   return "pin state";
650                 case tt_type_state:  return "type state";
651                 case tt_variability: return "variability";
652                 case tt_visibility:  return "visibility";
653                 case tt_volatility:  return "volatility";
654                 default: return "<UNKNOWN>";
655         }
656 }
657
658 /**
659  * Read and decode an enum constant.
660  */
661 static unsigned read_enum(io_env_t *env, typetag_t typetag)
662 {
663         static char buf[128];
664         unsigned code = symbol(read_str_to(env, buf, sizeof(buf)), typetag);
665         if(code != SYMERROR)
666                 return code;
667
668         printf("Invalid %s: \"%s\" in %i:%i\n", get_typetag_name(typetag), buf, env->line, env->col);
669         return 0;
670 }
671
672 #define read_align(env)       ((ir_align)       read_enum(env, tt_align))
673 #define read_allocation(env)  ((ir_allocation)  read_enum(env, tt_allocation))
674 #define read_peculiarity(env) ((ir_peculiarity) read_enum(env, tt_peculiarity))
675 #define read_pinned(env)      ((op_pin_state)   read_enum(env, tt_pin_state))
676 #define read_type_state(env)  ((ir_type_state)  read_enum(env, tt_type_state))
677 #define read_variability(env) ((ir_variability) read_enum(env, tt_variability))
678 #define read_visibility(env)  ((ir_visibility)  read_enum(env, tt_visibility))
679 #define read_volatility(env)  ((ir_volatility)  read_enum(env, tt_volatility))
680
681 static tarval *read_tv(io_env_t *env)
682 {
683         static char buf[128];
684         ir_mode *tvmode = read_mode(env);
685         read_str_to(env, buf, sizeof(buf));
686         return new_tarval_from_str(buf, strlen(buf), tvmode);
687 }
688
689 /** Reads a type description and remembers it by its id. */
690 static void import_type(io_env_t *env)
691 {
692         char           buf[1024];
693         int            i;
694         ir_type       *type;
695         long           typenr = read_long(env);
696         const char    *tpop   = read_str(env);
697         const char    *name   = read_qstr_to(env, buf, sizeof(buf));
698         unsigned       size   = (unsigned) read_long(env);
699         unsigned       align  = (unsigned) read_long(env);
700         ir_type_state  state  = read_type_state(env);
701         ir_visibility  vis    = read_visibility(env);
702
703         ident         *id     = new_id_from_str(name);
704
705         switch(symbol(tpop, tt_tpo))
706         {
707                 case tpo_primitive:
708                 {
709                         ir_mode *mode = read_mode(env);
710                         type = new_type_primitive(id, mode);
711                         break;
712                 }
713
714                 case tpo_method:
715                 {
716                         int nparams  = (int) read_long(env);
717                         int nresults = (int) read_long(env);
718
719                         type = new_type_method(id, nparams, nresults);
720
721                         for(i = 0; i < nparams; i++)
722                         {
723                                 long     typenr = read_long(env);
724                                 ir_type *paramtype = get_type(env, typenr);
725
726                                 set_method_param_type(type, i, paramtype);
727                         }
728                         for(i = 0; i < nresults; i++)
729                         {
730                                 long typenr = read_long(env);
731                                 ir_type *restype = get_type(env, typenr);
732
733                                 set_method_res_type(type, i, restype);
734                         }
735                         break;
736                 }
737
738                 case tpo_array:
739                 {
740                         int ndims = (int) read_long(env);
741                         long elemtypenr = read_long(env);
742                         ir_type *elemtype = get_type(env, elemtypenr);
743
744                         type = new_type_array(id, ndims, elemtype);
745                         for(i = 0; i < ndims; i++)
746                         {
747                                 long lowerbound = read_long(env);
748                                 long upperbound = read_long(env);
749                                 set_array_bounds_int(type, i, lowerbound, upperbound);
750                         }
751                         set_type_size_bytes(type, size);
752                         break;
753                 }
754
755                 case tpo_class:
756                         type = new_type_class(id);
757                         set_type_size_bytes(type, size);
758                         break;
759
760                 case tpo_struct:
761                         type = new_type_struct(id);
762                         set_type_size_bytes(type, size);
763                         break;
764
765                 case tpo_union:
766                         type = new_type_union(id);
767                         set_type_size_bytes(type, size);
768                         break;
769
770                 case tpo_unknown:
771                         return;   // ignore unknown type
772
773                 default:
774                         if(typenr != 0)  // ignore global type
775                                 printf("Unknown type kind: \"%s\" in line %i:%i\n", tpop, env->line, env->col);
776                         skip_to(env, '\n');
777                         return;
778         }
779
780         set_type_alignment_bytes(type, align);
781         set_type_visibility(type, vis);
782
783         if(state == layout_fixed)
784                 ARR_APP1(ir_type *, env->fixedtypes, type);
785
786         set_id(env, typenr, type);
787         printf("Insert type %s %ld\n", name, typenr);
788 }
789
790 /** Reads an entity description and remembers it by its id. */
791 static void import_entity(io_env_t *env)
792 {
793         char          buf[1024];
794         long          entnr       = read_long(env);
795         const char   *name        = read_qstr_to(env, buf, sizeof(buf));
796         long          typenr      = read_long(env);
797         long          ownertypenr = read_long(env);
798
799         ir_type   *type      = get_type(env, typenr);
800         ir_type   *ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
801         ir_entity *entity    = new_entity(ownertype, new_id_from_str(name), type);
802
803         set_entity_offset     (entity, (int) read_long(env));
804         set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
805         set_entity_allocation (entity, read_allocation(env));
806         set_entity_visibility (entity, read_visibility(env));
807         set_entity_variability(entity, read_variability(env));
808         set_entity_peculiarity(entity, read_peculiarity(env));
809         set_entity_volatility (entity, read_volatility(env));
810
811         set_id(env, entnr, entity);
812         printf("Insert entity %s %ld\n", name, entnr);
813 }
814
815 /** Parses the whole type graph. */
816 static int parse_typegraph(io_env_t *env)
817 {
818         const char *kind;
819         long curfpos;
820
821         EXPECT('{');
822
823         curfpos = ftell(env->file);
824
825         // parse all types first
826         while(1)
827         {
828                 kind = read_str(env);
829                 if(kind[0] == '}' && !kind[1]) break;
830
831                 if(!strcmp(kind, "type"))
832                         import_type(env);
833                 else
834                         skip_to(env, '\n');
835         }
836
837         // now parse rest
838         fseek(env->file, curfpos, SEEK_SET);
839         while(1)
840         {
841                 kind = read_str(env);
842                 if(kind[0] == '}' && !kind[1]) break;
843
844                 if(!strcmp(kind, "type"))
845                         skip_to(env, '\n');
846                 else if(!strcmp(kind, "entity"))
847                         import_entity(env);
848                 else
849                 {
850                         printf("Type graph element not supported yet: \"%s\"\n", kind);
851                         skip_to(env, '\n');
852                 }
853         }
854         return 1;
855 }
856
857 static int read_node_header(io_env_t *env, long *nodenr, long **preds, const char **nodename)
858 {
859         int numpreds;
860         *nodename = read_str(env);
861         if((*nodename)[0] == '}' && !(*nodename)[1]) return -1;  // end-of-graph
862
863         *nodenr = read_long(env);
864
865         ARR_RESIZE(ir_node *, *preds, 0);
866
867         EXPECT('[');
868         for(numpreds = 0; !feof(env->file); numpreds++)
869         {
870                 char *endptr;
871                 ARR_APP1(long, *preds, read_long2(env, &endptr));
872                 if(*endptr == ']') break;
873         }
874         return numpreds;
875 }
876
877 /** Parses an IRG. */
878 static int parse_graph(io_env_t *env)
879 {
880         long       *preds = NEW_ARR_F(long, 16);
881         ir_node   **prednodes = NEW_ARR_F(ir_node *, 16);
882         int         i, numpreds, ret = 1;
883         long        nodenr;
884         const char *nodename;
885         ir_node    *node, *newnode;
886
887         current_ir_graph = new_ir_graph(get_entity(env, read_long(env)), 0);
888
889         EXPECT('{');
890
891         while(1)
892         {
893                 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
894                 if(numpreds == -1) break;  // end-of-graph
895                 if(!numpreds)
896                 {
897                         printf("Node %s %ld is missing predecessors!", nodename, nodenr);
898                         ret = 0;
899                         break;
900                 }
901
902                 ARR_RESIZE(ir_node *, prednodes, numpreds);
903                 for(i = 0; i < numpreds - 1; i++)
904                         prednodes[i] = get_node_or_dummy(env, preds[i + 1]);
905
906                 node = get_node_or_null(env, nodenr);
907                 newnode = NULL;
908
909                 EXPECT('{');
910
911                 switch(symbol(nodename, tt_iro))
912                 {
913                         case iro_End:
914                         {
915                                 ir_node *newendblock = get_node(env, preds[0]);
916                                 newnode = get_irg_end(current_ir_graph);
917                                 exchange(get_nodes_block(newnode), newendblock);
918                                 break;
919                         }
920
921                         case iro_Start:
922                         {
923                                 ir_node *newstartblock = get_node(env, preds[0]);
924                                 newnode = get_irg_start(current_ir_graph);
925                                 exchange(get_nodes_block(newnode), newstartblock);
926                                 break;
927                         }
928
929                         case iro_Block:
930                         {
931                                 if(preds[0] != nodenr)
932                                 {
933                                         printf("Invalid block: preds[0] != nodenr (%ld != %ld)\n",
934                                                 preds[0], nodenr);
935                                         ret = 0;
936                                         goto endloop;
937                                 }
938
939                                 newnode = new_Block(numpreds - 1, prednodes);
940                                 break;
941                         }
942
943                         case iro_Anchor:
944                                 newnode = current_ir_graph->anchor;
945                                 for(i = 0; i < numpreds - 1; i++)
946                                         set_irn_n(newnode, i, prednodes[i]);
947                                 set_irn_n(newnode, -1, get_node(env, preds[0]));
948                                 break;
949
950                         case iro_SymConst:
951                         {
952                                 long entnr = read_long(env);
953                                 union symconst_symbol sym;
954                                 sym.entity_p = get_entity(env, entnr);
955                                 newnode = new_SymConst(mode_P, sym, symconst_addr_ent);
956                                 break;
957                         }
958
959                         #include "gen_irio_import.inl"
960
961                         default:
962                                 goto notsupported;
963                 }
964
965                 EXPECT('}');
966
967                 if(!newnode)
968                 {
969 notsupported:
970                         panic("Node type not supported yet: %s in line %i:%i\n", nodename, env->line, env->col);
971                 }
972
973                 if(node)
974                         exchange(node, newnode);
975                 /* Always update hash entry to avoid more uses of id nodes */
976                 set_id(env, nodenr, newnode);
977                 printf("Insert %s %ld\n", nodename, nodenr);
978         }
979
980 endloop:
981         DEL_ARR_F(preds);
982         DEL_ARR_F(prednodes);
983
984         return ret;
985 }
986
987 /** Imports an previously exported textual representation of an (maybe partial) irp */
988 void ir_import(const char *filename)
989 {
990         int oldoptimize = get_optimize();
991         firm_verification_t oldver = get_node_verification_mode();
992         io_env_t ioenv;
993         io_env_t *env = &ioenv;
994         int i, n;
995
996         symtbl_init();
997
998         memset(env, 0, sizeof(*env));
999         env->idset = new_set(id_cmp, 128);
1000         env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1001
1002         env->file = fopen(filename, "rt");
1003         if(!env->file)
1004         {
1005                 perror(filename);
1006                 exit(1);
1007         }
1008
1009         set_optimize(0);
1010         do_node_verification(FIRM_VERIFICATION_OFF);
1011
1012         while(1)
1013         {
1014                 const char *str = read_str(env);
1015                 if(!*str) break;
1016                 if(!strcmp(str, "typegraph"))
1017                 {
1018                         if(!parse_typegraph(env)) break;
1019                 }
1020                 else if(!strcmp(str, "irg"))
1021                 {
1022                         if(!parse_graph(env)) break;
1023                 }
1024         }
1025
1026         n = ARR_LEN(env->fixedtypes);
1027         for(i = 0; i < n; i++)
1028                 set_type_state(env->fixedtypes[i], layout_fixed);
1029
1030         DEL_ARR_F(env->fixedtypes);
1031
1032         del_set(env->idset);
1033
1034         irp_finalize_cons();
1035
1036         do_node_verification(oldver);
1037         set_optimize(oldoptimize);
1038
1039         fclose(env->file);
1040 }