d4f3a18b465820ae898c89c022854a0b68e546c9
[libfirm] / ir / be / scripts / generate_new_opcodes.pl
1 #!/usr/bin/perl -w
2
3 #
4 # Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
5 #
6 # This file is part of libFirm.
7 #
8 # This file may be distributed and/or modified under the terms of the
9 # GNU General Public License version 2 as published by the Free Software
10 # Foundation and appearing in the file LICENSE.GPL included in the
11 # packaging of this file.
12 #
13 # Licensees holding valid libFirm Professional Edition licenses may use
14 # this file in accordance with the libFirm Commercial License.
15 # Agreement provided with the Software.
16 #
17 # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
18 # WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE.
20 #
21
22 # This script generates the C code which creates the irop's and
23 # their coresponding node constructors for all operations in a given spec
24 # so they can be used as normal firm nodes.
25 # Creation: 2005/10/19
26
27 use strict;
28 use Data::Dumper;
29
30 my $specfile   = $ARGV[0];
31 my $target_dir = $ARGV[1];
32
33 our $arch;
34 our %nodes;
35 our $default_attr_type;
36 our $default_cmp_attr;
37 our $default_copy_attr;
38 our %init_attr;
39 our $custom_init_attr_func;
40 our %compare_attr;
41 our %copy_attr;
42 our %reg_classes;
43 our %custom_irn_flags;
44
45 # include spec file
46
47 my $return;
48
49 no strict "subs";
50 unless ($return = do $specfile) {
51         die "Fatal error: couldn't parse $specfile: $@" if $@;
52         die "Fatal error: couldn't do $specfile: $!"    unless defined $return;
53         die "Fatal error: couldn't run $specfile"       unless $return;
54 }
55 use strict "subs";
56
57 my $target_c = $target_dir."/gen_".$arch."_new_nodes.c.inl";
58 my $target_h = $target_dir."/gen_".$arch."_new_nodes.h";
59
60 if(!defined($default_attr_type)) {
61         $default_attr_type = "${arch}_attr_t";
62 }
63 if(! %init_attr) {
64         %init_attr = (
65                 "$default_attr_type" => "\tinit_${arch}_attributes(res, irn_flags_, in_reqs, n_res);",
66         );
67 }
68 if(!defined($default_cmp_attr)) {
69         $default_cmp_attr = "${arch}_compare_attr";
70 }
71 if(! %compare_attr) {
72         %compare_attr = (
73                 "${default_attr_type}" => "${default_cmp_attr}",
74         );
75 }
76
77 # create c code file from specs
78
79 my $obst_limit_func  = ""; #
80 my $obst_reg_reqs    = ""; #
81 my $obst_opvar       = ""; # buffer for the "ir_op *op_<arch>_<op-name> = NULL;" statements
82 my $obst_get_opvar   = ""; # buffer for the get_op_<arch>_<op-name>() functions
83 my $obst_constructor = ""; # buffer for node constructor functions
84 my $obst_new_irop    = ""; # buffer for the new_ir_op calls
85 my $obst_free_irop   = ""; # buffer for free_ir_op calls
86 my $obst_enum_op     = ""; # buffer for creating the <arch>_opcode enum
87 my $obst_header      = ""; # buffer for function prototypes
88 my $obst_cmp_attr    = ""; # buffer for the compare attribute functions
89 my $obst_proj        = ""; # buffer for the pn_ numbers
90 my $orig_op;
91 my $arity;
92 my $cmp_attr_func;
93 my $temp;
94 my $n_opcodes = 0;    # number of opcodes
95 my $ARITY_VARIABLE = -1;
96 my $ARITY_DYNAMIC  = -2;
97 my %requirements = ();
98 my %limit_bitsets = ();
99 my %reg2class = ();
100 my %regclass2len = ();
101
102 # build register->class hashes
103 foreach my $class_name (keys(%reg_classes)) {
104         my @class         = @{ $reg_classes{"$class_name"} };
105         my $old_classname = $class_name;
106
107         pop(@class);
108
109         $class_name = $arch."_".$class_name;
110
111         my $idx = 0;
112         foreach (@class) {
113                 $reg2class{$_->{name}} = {
114                         "class" => $old_classname,
115                         "index" => $idx
116                 };
117                 $idx++;
118         }
119
120         $regclass2len{$old_classname} = $idx;
121 }
122
123
124 $obst_header .= "void ${arch}_create_opcodes(const arch_irn_ops_t *be_ops);\n";
125 $obst_header .= "void ${arch}_free_opcodes(void);\n";
126
127 sub create_constructor {
128         my $op   = shift;
129         my $name = shift;
130         my $n    = shift;
131         my $on   = shift;
132         my $known_mode;
133
134         my $suffix = "";
135         if ($name ne "") {
136                 $suffix = "_${name}";
137         }
138
139         # determine mode
140         if (exists($n->{mode})) {
141                 $known_mode = $n->{mode};
142         }
143
144         # determine arity
145         my $arity = 0;
146         if(exists($n->{"arity"})) {
147                 $arity = $n->{"arity"};
148         } elsif (exists($n->{"reg_req"}) && exists($n->{"reg_req"}{"in"})) {
149                 $arity = scalar(@{ $n->{"reg_req"}{"in"} });
150         } elsif (exists($n->{"ins"})) {
151                 $arity = scalar(@{ $n->{"ins"} });
152         }
153         if($arity eq "variable") {
154                 $arity = $ARITY_VARIABLE;
155         } elsif($arity eq "dynamic") {
156                 $arity = $ARITY_DYNAMIC;
157         }
158
159         # determine out arity
160         my $out_arity = 0;
161         if(exists($n->{"out_arity"})) {
162                 $out_arity = $n->{"out_arity"};
163         } elsif (exists($n->{"reg_req"}) && exists($n->{"reg_req"}{"out"})) {
164                 $out_arity = scalar(@{ $n->{"reg_req"}{"out"} });
165         } elsif (exists($n->{"outs"})) {
166                 $out_arity = scalar(@{ $n->{"outs"} });
167         }
168         if($out_arity eq "variable") {
169                 $out_arity = $ARITY_VARIABLE;
170         } elsif($out_arity eq "dynamic") {
171                 $out_arity = $ARITY_DYNAMIC;
172         }
173         if ($out_arity != 0 && $out_arity != 1 && !defined($known_mode)) {
174                 $known_mode = "mode_T";
175         }
176
177         my $comment = $n->{"comment"};
178         if(!exists($n->{"comment"})) {
179                 $comment = "construct ${orig_op} node";
180         }
181         $comment =
182                 "/**\n".
183                 " * ${comment}\n".
184                 " */\n";
185
186         $obst_constructor .= $comment;
187
188         # create constructor head
189         my $complete_args = "";
190         $temp             = "";
191
192         $temp = "ir_node *new_bd_${arch}_${op}${suffix}(dbg_info *dbgi, ir_node *block";
193         if (!exists($n->{"args"})) { # default args
194                 if ($arity == $ARITY_VARIABLE) {
195                         $complete_args = ", int arity, ir_node *in[]";
196                 } elsif ($arity == $ARITY_DYNAMIC) {
197                         $complete_args = "";
198                 } else {
199                         for (my $i = 0; $i < $arity; $i++) {
200                                 my $opname = "op${i}";
201                                 if (exists($n->{"ins"})) {
202                                         my @ins = @{ $n->{"ins"} };
203                                         $opname = $ins[$i];
204                                 }
205
206                                 $complete_args .= ", ir_node *${opname}";
207                         }
208                 }
209                 if ($out_arity == $ARITY_VARIABLE) {
210                         $complete_args .= ", int n_res";
211                 }
212
213                 if (!defined($known_mode)) {
214                         $complete_args .= ", ir_mode *mode";
215                 }
216         } else { # user defined args
217                 for my $href (@{ $n->{"args"} }) {
218                         $href->{"type"} .= " " if ($href->{"type"} !~ / [*]?$/); # put a space between name and type if there is none at the end
219                         $complete_args  .= ", ".$href->{"type"}.$href->{"name"};
220                 }
221         }
222
223         # we have additional attribute arguements
224         if (exists($n->{"attr"})) {
225                 $complete_args .= ", ".$n->{"attr"};
226         }
227
228         $temp .= "$complete_args)";
229         $obst_constructor .= "${temp}\n{\n";
230
231         $obst_header .= $comment;
232         $obst_header .= "${temp};\n";
233
234         # emit constructor code
235         $temp = <<EOF;
236         ir_graph         *irg        = get_irn_irg(block);
237         ir_op            *op         = op_${arch}_${op};
238         arch_irn_flags_t  irn_flags_ = arch_irn_flags_none;
239         ir_node          *res;
240         backend_info_t   *info;
241 EOF
242
243         if($arity == $ARITY_DYNAMIC) {
244                 $temp .= <<EOF;
245         int             arity   = -1;
246         ir_node       **in      = NULL;
247 EOF
248         } elsif($arity == $ARITY_VARIABLE) {
249         } else {
250                 $temp .= <<EOF;
251         int             arity   = $arity;
252 EOF
253                 if($arity > 0) {
254                         $temp .= <<EOF;
255         ir_node        *in[$arity];
256 EOF
257                 } else {
258                         $temp .= <<EOF;
259         ir_node       **in      = NULL;
260 EOF
261                 }
262         }
263         if($out_arity == $ARITY_DYNAMIC) {
264                 $temp .= <<EOF;
265         int             n_res   = -1;
266 EOF
267         } elsif($out_arity == $ARITY_VARIABLE) {
268         } else {
269                 $temp .= <<EOF;
270         int             n_res   = ${out_arity};
271 EOF
272         }
273
274         if (defined($known_mode)) {
275                 $temp .= <<EOF;
276         ir_mode        *mode    = ${known_mode};
277 EOF
278         }
279
280         undef my $in_req_var;
281         undef my $out_req_var;
282
283         my $set_out_reqs = "";
284
285         # set up static variables for requirements and registers
286         if (exists($n->{"reg_req"})) {
287                 my %req = %{ $n->{"reg_req"} };
288                 my $idx;
289
290                 undef my @in;
291                 @in = @{ $req{"in"} } if (exists($req{"in"}));
292                 undef my @out;
293                 @out = @{ $req{"out"} } if exists(($req{"out"}));
294
295                 for(my $idx = 0; $idx < $#in; $idx++) {
296                         my $req = $in[$idx];
297                         generate_requirements($req, $n, "${arch}_${op}", $idx, 1);
298                 }
299                 for(my $idx = 0; $idx < $#out; $idx++) {
300                         my $req = $out[$idx];
301                         generate_requirements($req, $n, "${arch}_${op}", $idx, 0);
302                 }
303
304                 if (@in) {
305                         if($arity >= 0 && scalar(@in) != $arity) {
306                                 die "Fatal error: Arity and number of in requirements don't match for ${op}\n";
307                         }
308
309                         $temp .= "\tstatic const arch_register_req_t *in_reqs[] =\n";
310                         $temp .= "\t{\n";
311                         for ($idx = 0; $idx <= $#in; $idx++) {
312                                 my $req = $in[$idx];
313                                 my $reqstruct = generate_requirements($req, $n, "${arch}_${op}", $idx, 1);
314                                 $temp .= "\t\t& ${reqstruct},\n";
315                         }
316                         $temp .= "\t};\n";
317                 } else {
318                         if($arity > 0) {
319                                 die "Fatal error: need in requirements for ${op}\n";
320                         }
321                         $temp .= "\tstatic const arch_register_req_t **in_reqs = NULL;\n";
322                 }
323
324                 if (@out) {
325                         if($out_arity >= 0 && scalar(@out) != $out_arity) {
326                                 die "Fatal error: Out-Arity and number of out requirements don't match for ${op}\n";
327                         }
328
329                         for ($idx = 0; $idx <= $#out; $idx++) {
330                                 my $req = $out[$idx];
331                                 my $reqstruct = generate_requirements($req, $n, "${arch}_${op}", $idx, 0);
332                                 $set_out_reqs .= <<EOF;
333         info->out_infos[${idx}].req = &${reqstruct};
334 EOF
335                         }
336                 } else {
337                         if($out_arity > 0) {
338                                 die "Fatal error: need out requirements for ${op}\n";
339                         }
340                 }
341         } else {
342                 $temp .= "\tstatic const arch_register_req_t **in_reqs = NULL;\n";
343         }
344         my $attr_type = $on->{attr_type};
345         if(exists($n->{"init_attr"})) {
346                 $temp .= "\t${attr_type} *attr;\n";
347         }
348
349         $temp .= "\n";
350
351         if($arity > 0) {
352                 $temp .= "\t/* construct in array */\n";
353                 for (my $i = 0; $i < $arity; $i++) {
354                         my $opname = "op${i}";
355                         if (exists($n->{"ins"})) {
356                                 my @ins = @{ $n->{"ins"} };
357                                 $opname = $ins[$i];
358                         }
359
360                         $temp .= "\tin[${i}] = ${opname};\n";
361                 }
362                 $temp .= "\n";
363         }
364
365         # set flags
366         if (exists($n->{"irn_flags"})) {
367                 $temp .= "\t/* flags */\n";
368                 my %known_irn_flags = (
369                         "none"             => "arch_irn_flags_none",
370                         "dont_spill"       => "arch_irn_flags_dont_spill",
371                         "rematerializable" => "arch_irn_flags_rematerializable",
372                         "modify_flags"     => "arch_irn_flags_modify_flags",
373                         "simple_jump"      => "arch_irn_flags_simple_jump",
374                         "not_scheduled"    => "arch_irn_flags_not_scheduled",
375                 );
376                 if (%custom_irn_flags) {
377                         %known_irn_flags = (%known_irn_flags, %custom_irn_flags);
378                 }
379                 foreach my $flag (@{$n->{"irn_flags"}}) {
380                         if (not defined($known_irn_flags{$flag})) {
381                                 print STDERR "WARNING: irn_flag '$flag' in opcode $op is unknown\n";
382                         } else {
383                                 $temp .= "\tirn_flags_ |= " . $known_irn_flags{$flag} . ";\n";
384                         }
385                 }
386                 $temp .= "\n";
387         }
388
389         # lookup init function
390         my $attr_init_code = "(void)in;(void)irn_flags_;(void)in_reqs;(void)n_res;";
391         if ($attr_type ne "") {
392                 $attr_init_code = $init_attr{$attr_type};
393                 if(!defined($attr_init_code)) {
394                         die "Fatal error: Couldn't find attribute initialisation code for type '${attr_type}'";
395                 }
396         }
397         my $custominit = "";
398         if(defined($custom_init_attr_func)) {
399                 $custominit .= &$custom_init_attr_func($n, $on, "${arch}_${op}");
400         }
401         if(defined($n->{custominit})) {
402                 $custominit .= $n->{custominit};
403         }
404
405         $temp .= <<EOF;
406         /* create node */
407         assert(op != NULL);
408         res = new_ir_node(dbgi, irg, block, op, mode, arity, in);
409
410         /* init node attributes */
411         ${attr_init_code}
412         ${custominit}
413         info = be_get_info(res);
414         (void) info; /* avoid potential warning */
415 ${set_out_reqs}
416
417 EOF
418
419         if (exists($n->{"init_attr"})) {
420                 $temp .= "\tattr = (${attr_type}*)get_irn_generic_attr(res);\n";
421                 $temp .= "\t(void) attr; /* avoid potential warning */\n";
422                 $temp .= "\t".$n->{"init_attr"}."\n";
423         }
424
425         $temp .= <<EOF;
426         /* optimize node */
427         res = optimize_node(res);
428         irn_verify_irg(res, irg);
429
430         return res;
431 EOF
432
433         $obst_constructor .= $temp;
434
435         # close constructor function
436         $obst_constructor .= "}\n\n";
437 }
438
439 $obst_enum_op .= "typedef enum ${arch}_opcodes {\n";
440 foreach my $op (keys(%nodes)) {
441         my %n        = %{ $nodes{"$op"} };
442         my $known_mode;
443         my $num_outs = 0;
444         my $out_arity;
445         my @out_flags;
446
447         # determine arity
448         $arity = 0;
449         if(exists($n{"arity"})) {
450                 $arity = $n{"arity"};
451         } elsif (exists($n{"reg_req"}) && exists($n{"reg_req"}{"in"})) {
452                 $arity = scalar(@{ $n{"reg_req"}{"in"} });
453         } elsif (exists($n{"ins"})) {
454                 $arity = scalar(@{ $n{"ins"} });
455         }
456         if($arity eq "variable") {
457                 $arity = $ARITY_VARIABLE;
458         } elsif($arity eq "dynamic") {
459                 $arity = $ARITY_DYNAMIC;
460         }
461
462         # determine out arity
463         $out_arity = 0;
464         if(exists($n{"out_arity"})) {
465                 $out_arity = $n{"out_arity"};
466         } elsif (exists($n{"reg_req"}) && exists($n{"reg_req"}{"out"})) {
467                 $out_arity = scalar(@{ $n{"reg_req"}{"out"} });
468         } elsif (exists($n{"outs"})) {
469                 $out_arity = scalar(@{ $n{"outs"} });
470         }
471         if($out_arity eq "variable") {
472                 $out_arity = $ARITY_VARIABLE;
473         } elsif($out_arity eq "dynamic") {
474                 $out_arity = $ARITY_DYNAMIC;
475         }
476
477         $orig_op = $op;
478         $op      = $arch."_".$op;
479         $temp    = "";
480
481         # define proj numbers and in numbers
482         if (exists($n{"outs"})) {
483                 undef my @outs;
484
485                 @outs = @{ $n{"outs"} };
486                 if($out_arity >= 0 && scalar(@outs) != $out_arity) {
487                         die "Fatal error: Op ${op} has different number of outs and out_arity\n";
488                 }
489
490                 $num_outs = $#outs + 1;
491
492                 if ($num_outs > 0) {
493                         $obst_proj .= "\nenum pn_${op} {\n";
494
495                         for (my $idx = 0; $idx <= $#outs; $idx++) {
496                                 # check, if we have additional flags annotated to out
497                                 if ($outs[$idx] =~ /:((S|I)(\|(S|I))*)/) {
498                                         push(@out_flags, $1);
499                                         $outs[$idx] =~ s/:((S|I)(\|(S|I))*)//;
500                                 }
501                                 $obst_proj .= "\tpn_${op}_".$outs[$idx]." = ${idx},\n";
502                         }
503
504                         $obst_proj .= "};\n";
505                 }
506                 # outs have names, it must be a mode_T node
507                 if (!defined($n{mode})) {
508                         $n{mode} = "mode_T";
509                 }
510         }
511         if (exists($n{"ins"})) {
512                 undef my @ins;
513
514                 @ins = @{ $n{"ins"} };
515                 if($arity >= 0 && scalar(@ins) != $arity) {
516                         die "Fatal error: Op ${op} has different number of ins and arity\n";
517                 }
518
519                 if ($#ins >= 0) {
520                         $obst_proj .= "\nenum n_$op {\n";
521                         for (my $idx = 0; $idx <= $#ins; $idx++) {
522                                 $obst_proj .= "\tn_${op}_".$ins[$idx]." = ${idx},\n";
523                         }
524                         $obst_proj .= "};\n";
525                 }
526         }
527
528         # Create opcode
529         $obst_opvar     .= "ir_op *op_$op = NULL;\n";
530         $obst_get_opvar .= "ir_op *get_op_$op(void)         { return op_$op; }\n";
531         $obst_get_opvar .= "int    is_$op(const ir_node *n) { return get_$arch\_irn_opcode(n) == iro_$op; }\n\n";
532
533         $obst_header .= <<EOF;
534 extern ir_op *op_${op};
535 ir_op *get_op_${op}(void);
536 int is_${op}(const ir_node *n);
537 EOF
538
539         my $attr_type= $n{attr_type};
540         if(!defined($attr_type)) {
541                 $attr_type = $default_attr_type;
542                 $n{attr_type} = $attr_type;
543         }
544
545         # determine hash function
546         my $hash_func;
547         if (exists($n{"hash_func"})) {
548                 $hash_func = $n{"hash_func"};
549         }
550
551         # determine compare function
552         my $cmp_attr_func;
553         if (exists($n{"cmp_attr"})) {
554                 my $cmpcode = $n{"cmp_attr"};
555
556                 $obst_cmp_attr .= "static int cmp_attr_$op(const ir_node *a, const ir_node *b) {\n";
557                 if($cmpcode =~ m/attr_a/) {
558                         $obst_cmp_attr .= "\tconst ${attr_type} *attr_a = get_irn_generic_attr_const(a);\n";
559                 } else {
560                         $obst_cmp_attr .= "\t(void) a;\n";
561                 }
562                 if($cmpcode =~ m/attr_b/) {
563                         $obst_cmp_attr .= "\tconst ${attr_type} *attr_b = get_irn_generic_attr_const(b);\n";
564                 } else {
565                         $obst_cmp_attr .= "\t(void) b;\n";
566                 }
567                 $obst_cmp_attr .= "\t${cmpcode}\n";
568                 $obst_cmp_attr .= "}\n\n";
569
570                 $cmp_attr_func = "cmp_attr_${op}";
571         } elsif ($attr_type eq "") {
572                 $cmp_attr_func = "NULL";
573         } else {
574                 if(defined($compare_attr{${attr_type}})) {
575                         $cmp_attr_func = $compare_attr{${attr_type}};
576                 } else {
577                         die "Fatal error: No compare function defined for ${attr_type} attributes.";
578                 }
579         }
580
581         my %constructors;
582         if (exists($n{constructors})) {
583                 %constructors = %{ $n{constructors} };
584         } else {
585                 # Create 1 default constructor
586                 my %constructor = ();
587                 foreach my $a ("comment", "ins", "outs", "args", "attr",
588                                 "reg_req", "init_attr", "irn_flags", "mode", "arity",
589                                 "out_arity", "custominit") {
590                         if (defined($n{$a})) {
591                                 $constructor{$a} = $n{$a};
592                         }
593                 }
594                 %constructors = ( "" => \%constructor );
595         }
596
597         foreach my $constr (keys(%constructors)) {
598                 my %cstr = %{ $constructors{$constr} };
599                 # Copy some values from outer node if they don't exists in the constr
600                 foreach my $a ("ins", "outs", "irn_flags", "mode", "args", "attr",
601                                "custominit") {
602                         if (!defined($cstr{$a}) && defined($n{$a})) {
603                                 $cstr{$a} = $n{$a};
604                         }
605                 }
606                 create_constructor($orig_op, $constr, \%cstr, \%n);
607         }
608
609         # set default values for state and flags if not given
610         $n{"state"}     = "floats" if (! exists($n{"state"}));
611         $n{"op_flags"}  = ["none"] if (! exists($n{"op_flags"}));
612         $n{"dump_func"} = "${arch}_dump_node" if (!exists($n{"dump_func"}));
613         my $dump_func = $n{"dump_func"};
614
615         my %known_flags = map { $_ => 1 } (
616                 "none", "commutative", "cfopcode", "unknown_jump", "fragile",
617                 "forking", "highlevel", "constlike", "keep", "start_block",
618                 "uses_memory", "dump_noblock", "cse_neutral"
619         );
620         my $is_fragile = 0;
621         foreach my $flag (@{$n{"op_flags"}}) {
622                 if (not defined($known_flags{$flag})) {
623                         print STDERR "WARNING: Flag '$flag' in opcode $op is unknown\n";
624                 }
625                 if ($flag eq "fragile") {
626                         $is_fragile = 1;
627                 }
628         }
629         my @mapped = map { "irop_flag_$_" } @{$n{"op_flags"}};
630         my $op_flags = join('|', @mapped);
631
632         my $attr_size = "0";
633         if ($attr_type ne "") {
634                 $attr_size = "sizeof(${attr_type})"
635         }
636
637         $n_opcodes++;
638         $temp  = "\top = new_ir_op(cur_opcode + iro_$op, \"$op\", op_pin_state_".$n{"state"}.", $op_flags";
639         $temp .= ", ".translate_arity($arity).", 0, ${attr_size});\n";
640         $obst_new_irop .= $temp;
641         $obst_new_irop .= "\top->ops.be_ops        = be_ops;\n";
642         $obst_new_irop .= "\top->ops.dump_node     = ${dump_func};\n";
643         if (defined($cmp_attr_func)) {
644                 $obst_new_irop .= "\top->ops.node_cmp_attr = ${cmp_attr_func};\n";
645         }
646         my $copy_attr_func = $copy_attr{$attr_type};
647         if (!defined($copy_attr_func)) {
648                 # don't set a copy_attr function if the node has no additional attributes.
649                 if ($attr_type ne "") {
650                         $copy_attr_func = $default_copy_attr;
651                 }
652         }
653         if (defined($copy_attr_func)) {
654                 $obst_new_irop .= "\top->ops.copy_attr     = ${copy_attr_func};\n";
655         }
656         if (defined($hash_func)) {
657                 $obst_new_irop .= "\top->ops.hash          = ${hash_func};\n";
658         }
659
660         if ($is_fragile) {
661                 $obst_new_irop .= "\tir_op_set_memory_index(op, n_${op}_mem);\n";
662                 $obst_new_irop .= "\tir_op_set_fragile_indices(op, pn_${op}_X_regular, pn_${op}_X_except);\n";
663         }
664         $obst_new_irop .= "\tset_op_tag(op, $arch\_op_tag);\n";
665         if(defined($n{op_attr_init})) {
666                 $obst_new_irop .= "\t".$n{op_attr_init}."\n";
667         }
668         $obst_new_irop .= "\top_${op} = op;\n";
669
670         $obst_free_irop .= "\tfree_ir_op(op_$op); op_$op = NULL;\n";
671
672         $obst_enum_op .= "\tiro_$op,\n";
673
674         $obst_header .= "\n";
675 }
676 $obst_enum_op .= "\tiro_$arch\_last\n";
677 $obst_enum_op .= "} $arch\_opcodes;\n\n";
678
679 # emit the code
680
681 open(OUT, ">$target_c") || die("Fatal error: Could not open $target_c, reason: $!\n");
682
683 print OUT<<EOF;
684 #include "gen_$arch\_regalloc_if.h"
685 #include "irverify_t.h"
686 #include "fourcc.h"
687
688 $obst_cmp_attr
689 $obst_opvar
690 $obst_get_opvar
691
692 static int $arch\_opcode_start = -1;
693 static int $arch\_opcode_end   = -1;
694
695 EOF
696
697 # build the FOURCC arguments from $arch
698
699 my ($a, $b, $c, $d) = ('\0', '\0', '\0', '\0');
700
701 if (length($arch) >= 1) {
702         $a = uc(substr($arch, 0, 1));
703 }
704
705 if (length($arch) >= 2) {
706         $b = uc(substr($arch, 1, 1));
707 }
708
709 if (length($arch) >= 3) {
710         $c = uc(substr($arch, 2, 1));
711 }
712
713 if (length($arch) >= 4) {
714         $d = uc(substr($arch, 3, 1));
715 }
716
717 print OUT <<END;
718
719 /** A tag for the $arch opcodes. Note that the address is used as a tag value, NOT the FOURCC code. */
720 #define $arch\_op_tag FOURCC('$a', '$b', '$c', '$d')
721
722 /** Return the opcode number of the first $arch opcode. */
723 int get_$arch\_opcode_first(void) {
724         return $arch\_opcode_start;
725 }
726
727 /** Return the opcode number of the last $arch opcode + 1. */
728 int get_$arch\_opcode_last(void) {
729         return $arch\_opcode_end;
730 }
731
732 /** Return 1 if the given opcode is a $arch machine op, 0 otherwise */
733 int is_$arch\_op(const ir_op *op) {
734         return get_op_tag(op) == $arch\_op_tag;
735 }
736
737 /** Return 1 if the given node is a $arch machine node, 0 otherwise */
738 int is_$arch\_irn(const ir_node *node) {
739         return is_$arch\_op(get_irn_op(node));
740 }
741
742 int get_$arch\_irn_opcode(const ir_node *node) {
743         if (is_$arch\_irn(node))
744                 return get_irn_opcode(node) - $arch\_opcode_start;
745         return -1;
746 }
747
748 #ifdef BIT
749 #undef BIT
750 #endif
751 #define BIT(x)  (1 << (x))
752
753 $obst_limit_func
754 $obst_reg_reqs
755 $obst_constructor
756
757 /**
758  * Creates the $arch specific Firm machine operations
759  * needed for the assembler irgs.
760  */
761 void $arch\_create_opcodes(const arch_irn_ops_t *be_ops)
762 {
763         ir_op *op;
764         int    cur_opcode = get_next_ir_opcodes(iro_$arch\_last);
765
766         $arch\_opcode_start = cur_opcode;
767 $obst_new_irop
768         $arch\_opcode_end = cur_opcode + iro_$arch\_last;
769 }
770
771 void $arch\_free_opcodes(void)
772 {
773 $obst_free_irop
774 }
775 END
776
777 close(OUT);
778
779 open(OUT, ">$target_h") || die("Fatal error: Could not open $target_h, reason: $!\n");
780
781 my $creation_time = localtime(time());
782 my $tmp = uc($arch);
783
784 print OUT<<EOF;
785 /**
786  * \@file
787  * \@brief Function prototypes for the new opcode functions.
788  * \@note  DO NOT EDIT THIS FILE, your changes will be lost.
789  *        Edit $specfile instead.
790  *        created by: $0 $specfile $target_dir
791  * \@date  $creation_time
792  */
793 #ifndef FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
794 #define FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
795
796 $obst_enum_op
797 int is_${arch}_irn(const ir_node *node);
798 int is_${arch}_op(const ir_op *op);
799
800 int get_${arch}_opcode_first(void);
801 int get_${arch}_opcode_last(void);
802 int get_${arch}_irn_opcode(const ir_node *node);
803 ${obst_header}
804 ${obst_proj}
805
806 #endif
807 EOF
808
809 close(OUT);
810
811 ###
812 # Translates numeric arity into string constant.
813 ###
814 sub translate_arity {
815         my $arity = shift;
816
817         if ($arity =~ /^\d+$/) {
818                 if    ($arity == 0) {
819                         return "oparity_zero";
820                 }
821                 elsif ($arity == 1) {
822                         return "oparity_unary";
823                 }
824                 elsif ($arity == 2) {
825                         return "oparity_binary";
826                 }
827                 elsif ($arity == 3) {
828                         return "oparity_trinary";
829                 }
830                 else {
831                         return "oparity_any";
832                 }
833         } elsif ($arity == $ARITY_VARIABLE) {
834                 return "oparity_variable";
835         } elsif ($arity == $ARITY_DYNAMIC) {
836                 return "oparity_dynamic";
837         } else {
838                 die "Fatal error: Unknown arity $arity";
839         }
840 }
841
842 sub mangle_requirements {
843         my $reqs  = shift;
844         my $class = shift;
845         my $flags = shift;
846
847         my @alternatives = split(/ /, $reqs);
848         for(my $idx = 0; $idx < scalar(@alternatives); $idx++) {
849                 $alternatives[$idx] =~ s/!/not_/g;
850         }
851
852         @alternatives = sort @alternatives;
853
854         my $name = $class."_".join('_', @alternatives);
855         if (defined($flags)) {
856                 $flags =~ s/\|/_/g;
857                 $name .= "_$flags";
858         }
859
860         return $name;
861 }
862
863 ###
864 # Determines whether $name is a specified register class or not.
865 # @return 1 if name is register class, 0 otherwise
866 ###
867 sub is_reg_class {
868     my $name = shift;
869     return 1 if exists($reg_classes{"$name"});
870     return 0;
871 }
872
873 ###
874 # Returns the register class for a given register.
875 # @return class or undef
876 ###
877 sub get_reg_class {
878     my $reg = shift;
879     $reg = substr($reg, 1) if ($reg =~ /!.*/);
880     return $reg2class{"$reg"}{"class"} if (exists($reg2class{"$reg"}));
881     return undef;
882 }
883
884 ###
885 # Returns the index of a given register within its register class.
886 # @return index or undef
887 ###
888 sub get_reg_index {
889     my $reg = shift;
890     return $reg2class{"$reg"}{"index"} if (exists($reg2class{"$reg"}));
891     return undef;
892 }
893
894 ###
895 # Remember the register class for each index in the given requirements.
896 # We need this information for requirements like "in_sX" or "out_dX"
897 # @return array of classes corresponding to the requirement for each index
898 ###
899 sub build_inout_idx_class {
900         my $n     = shift;
901         my $op    = shift;
902         my $is_in = shift;
903         my @idx_class;
904
905         my $inout = ($is_in ? "in" : "out");
906
907         if (exists($n->{"reg_req"}{"$inout"})) {
908                 my @reqs = @{ $n->{"reg_req"}{"$inout"} };
909
910                 for (my $idx = 0; $idx <= $#reqs; $idx++) {
911                         my $class = undef;
912                         my ($req,) = split(/:/, $reqs[$idx]);
913
914                         if ($req eq "none") {
915                                 $class = "none";
916                         } elsif (is_reg_class($req)) {
917                                 $class = $req;
918                         } else {
919                                 my @regs = split(/ /, $req);
920 GET_CLASS:              foreach my $reg (@regs) {
921                                         if ($reg =~ /!?(in|out)\_r\d+/ || $reg =~ /!in/) {
922                                                 $class = "UNKNOWN_CLASS";
923                                         } else {
924                                                 $class = get_reg_class($reg);
925                                                 if (!defined $class) {
926                                                         die("Fatal error: Could not get ".uc($inout)." register class for '$op' pos $idx (reg $reg) ... exiting.\n");
927                                                 } else {
928                                                         last GET_CLASS;
929                                                 } # !defined class
930                                         } # if (reg =~ ...
931                                 } # foreach
932                         } # if
933
934                         push(@idx_class, $class);
935                 } # for
936         } # if
937
938         return @idx_class;
939 }
940
941 ###
942 # Generates the function for a given $op and a given IN-index
943 # which returns a subset of possible register from a register class
944 # @return classname from which the subset is derived or undef and
945 #         pos which corresponds to in/out reference position or undef
946 ###
947 sub build_subset_class_func {
948         my $neg           = undef;
949         my $class         = undef;
950         my $has_limit     = 0;
951         my $limit_name;
952         my $same_pos      = 0;
953         my $different_pos = 0;
954         my $temp;
955         my @obst_init;
956         my @obst_limits;
957         my @obst_ignore;
958         my @limit_array;
959         my $limit_reqs;   #used for name mangling
960
961         # build function header
962         my $node  = shift;
963         my $op    = shift;
964         my $idx   = shift;
965         my $is_in = shift;
966         my @regs  = split(/ /, shift);
967         my $flags = shift;
968
969         my @idx_class = build_inout_idx_class($node, $op, !$is_in);
970
971         # set/unset registers
972 CHECK_REQS: foreach (@regs) {
973                 if (!$is_in && /(!)?in_r(\d+)/) {
974                         my $bit_pos = 1 << ($2 - 1);
975                         if ($different_pos & $bit_pos) {
976                                 if ($1) {
977                                         print STDERR "duplicate !in constraint\n";
978                                 } else {
979                                         print STDERR "conflicting !in and in constraints\n";
980                                 }
981                                 return (undef, undef, undef, undef);
982                         }
983
984                         if ($same_pos & $bit_pos) {
985                                 if ($1) {
986                                         print STDERR "conflicting !in and in constraints\n";
987                                 } else {
988                                         print STDERR "duplicate in constraint\n";
989                                 }
990                                 return (undef, undef, undef, undef);
991                         }
992
993                         if ($1) {
994                                 $different_pos |= $bit_pos;
995                         } else {
996                                 $same_pos      |= $bit_pos;
997                         }
998
999                         $class = $idx_class[$2 - 1];
1000                         next CHECK_REQS;
1001                 }
1002
1003                 # check for negate
1004                 if (substr($_, 0, 1) eq "!") {
1005                         if (defined($neg) && $neg == 0) {
1006                                 # we have seen a positiv constraint as first one but this one is negative
1007                                 # this doesn't make sense
1008                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1009                                 return (undef, undef, undef, undef);
1010                         }
1011
1012                         if (!defined($neg)) {
1013                                 $has_limit = 1;
1014                         }
1015
1016                         $_   = substr($_, 1); # skip '!'
1017                         $neg = 1;
1018                 } else {
1019                         if (defined($neg) && $neg == 1) {
1020                                 # we have seen a negative constraint as first one but this one is positive
1021                                 # this doesn't make sense
1022                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1023                                 return (undef, undef, undef, undef);
1024                         }
1025
1026                         $has_limit = 1;
1027                         $neg = 0;
1028                 }
1029
1030                 # check if register belongs to one of the given classes
1031                 $temp = get_reg_class($_);
1032                 if (!defined($temp)) {
1033                         print STDERR "Unknown register '$_'!\n";
1034                         return (undef, undef, undef, undef);
1035                 }
1036
1037                 # set class
1038                 if (!defined($class)) {
1039                         $class = $temp;
1040                 } elsif ($class ne $temp) {
1041                         # all registers must belong to the same class
1042                         print STDERR "Registerclass mismatch. '$_' is not member of class '$class'.\n";
1043                         return (undef, undef, undef, undef);
1044                 }
1045
1046                 # calculate position inside the initializer bitfield (only 32 bits per
1047                 # element)
1048                 my $regidx = get_reg_index($_);
1049                 my $arrayp = $regidx / 32;
1050                 push(@{$limit_array[$arrayp]}, $_);
1051                 $limit_reqs .= "$_ ";
1052         }
1053
1054         # don't allow ignore regs in negative constraints
1055         if($neg) {
1056                 my @cur_class = @{ $reg_classes{"$class"} };
1057                 for (my $idx = 0; $idx <= $#cur_class; $idx++) {
1058                         if (defined($cur_class[$idx]{"type"}) && ($cur_class[$idx]{"type"} & 4)) {
1059                                 my $reg    = $cur_class[$idx]{"name"};
1060                                 my $regix  = get_reg_index($reg);
1061                                 my $arrayp = $regix / 32;
1062                                 push(@{$limit_array[$arrayp]}, $reg);
1063                                 $limit_reqs .= "$reg ";
1064                         }
1065                 }
1066         }
1067
1068         if ($has_limit == 1) {
1069                 $limit_name = "${arch}_limit_".mangle_requirements($limit_reqs, $class);
1070
1071                 if(defined($limit_bitsets{$limit_name})) {
1072                         $limit_name = $limit_bitsets{$limit_name};
1073                         return ($class, $limit_name, $same_pos, $different_pos);
1074                 }
1075
1076                 $limit_bitsets{$limit_name} = $limit_name;
1077
1078                 $obst_limit_func .= "static const unsigned $limit_name\[] = { ";
1079                 my $first = 1;
1080                 my $limitbitsetlen = $regclass2len{$class};
1081                 my $limitarraylen = ($limitbitsetlen+31) / 32;
1082                 for(my $i = 0; $i < $limitarraylen; $i++) {
1083
1084                         my $limitarraypart = $limit_array[$i];
1085                         if($first) {
1086                                 $first = 0;
1087                         } else {
1088                                 $obst_limit_func .= ", ";
1089                         }
1090                         my $temp;
1091                         if($neg) {
1092                                 $temp = "0xFFFFFFFF";
1093                         }
1094                         foreach my $reg (@{$limitarraypart}) {
1095                                 if($neg) {
1096                                         $temp .= " & ~";
1097                                 } elsif(defined($temp)) {
1098                                         $temp .= " | ";
1099                                 }
1100                                 my $firstreg = uc($reg_classes{$class}[0]->{"name"});
1101                                 my $classuc = uc($class);
1102                                 my $reguc = uc($reg);
1103                                 $temp .= "BIT(REG_${classuc}_${reguc})";
1104                         }
1105                         $obst_limit_func .= $temp || "0";
1106                 }
1107                 $obst_limit_func .= " };\n";
1108         }
1109
1110         return ($class, $limit_name, $same_pos, $different_pos);
1111 }
1112
1113 ###
1114 # Generate register requirements structure
1115 ###
1116 sub generate_requirements {
1117         my ($reqs, $flags) = split(/:/, shift);
1118         my $node  = shift;
1119         my $op    = shift;
1120         my $idx   = shift;
1121         my $is_in = shift;
1122         my $class = "";
1123         my $width = 1;
1124         my $result;
1125
1126         my @req_type_mask;
1127         if (defined($flags)) {
1128                 foreach my $f (split(/|/, $flags)) {
1129                         if ($f eq "I") {
1130                                 push(@req_type_mask, "arch_register_req_type_ignore");
1131                         } elsif ($f eq "S") {
1132                                 push(@req_type_mask, "arch_register_req_type_produces_sp");
1133                         } elsif ($f eq "a") {
1134                                 push(@req_type_mask, "arch_register_req_type_aligned");
1135                         } elsif ($f eq "2" or $f eq "4" or $f eq "8") {
1136                                 $width = int($f);
1137                         }
1138                 }
1139         }
1140
1141         if ($reqs eq "none") {
1142
1143                 $result = <<EOF;
1144 {
1145         arch_register_req_type_none,
1146         NULL,                         /* regclass */
1147         NULL,                         /* limit bitset */
1148         0,                            /* same pos */
1149         0,                            /* different pos */
1150         0                             /* width */
1151 };
1152
1153 EOF
1154         } elsif (is_reg_class($reqs)) {
1155                 push(@req_type_mask, "arch_register_req_type_normal");
1156                 my $reqtype = join(" | ", @req_type_mask);
1157                 $class  = $reqs;
1158                 $result = <<EOF;
1159 {
1160         ${reqtype},
1161         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1162         NULL,        /* limit bitset */
1163         0,           /* same pos */
1164         0,           /* different pos */
1165         $width            /* width */
1166 };
1167
1168 EOF
1169
1170         } else {
1171                 my ($regclass, $limit_bitset, $same_pos, $different_pos)
1172                         = build_subset_class_func($node, $op, $idx, $is_in, $reqs, $flags);
1173
1174                 if (!defined($regclass)) {
1175                         die("Fatal error: Could not build subset for requirements '$reqs' of '$op' pos $idx ... exiting.\n");
1176                 }
1177
1178                 if (defined($limit_bitset) && $limit_bitset ne "NULL") {
1179                         push(@req_type_mask, "arch_register_req_type_limited");
1180                 }
1181                 if ($same_pos != 0) {
1182                         push(@req_type_mask, "arch_register_req_type_should_be_same");
1183                 }
1184                 if ($different_pos != 0) {
1185                         push(@req_type_mask, "arch_register_req_type_must_be_different");
1186                 }
1187                 my $reqtype = join(" | ", @req_type_mask);
1188
1189                 if(!defined($limit_bitset)) {
1190                         $limit_bitset = "NULL";
1191                 }
1192
1193                 $class  = $regclass;
1194                 $result = <<EOF;
1195 {
1196         ${reqtype},
1197         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1198         ${limit_bitset},
1199         ${same_pos},        /* same pos */
1200         ${different_pos},       /* different pos */
1201         $width             /* width */
1202 };
1203
1204 EOF
1205         }
1206
1207         my $name = "${arch}_requirements_".mangle_requirements($reqs, $class, $flags);
1208         if(defined($requirements{$name})) {
1209                 return $name;
1210         }
1211         $requirements{$name} = $name;
1212         $obst_reg_reqs .= "static const arch_register_req_t ${name} = ${result}\n";
1213
1214         return $name;
1215 }