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