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