change backend node specification to use whole words instead of cryptical 1-char...
[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                 my %known_irn_flags = map { $_ => 1 } (
411                         "none", "dont_spill", "rematerializable",
412                         "modify_flags", "simple_jump"
413                 );
414                 foreach my $flag (@{$n->{"irn_flags"}}) {
415                         if (not defined($known_irn_flags{$flag})) {
416                                 print STDERR "WARNING: irn_flag '$flag' in opcode $op is unknown\n";
417                         }
418                         $temp .= "\tflags |= arch_irn_flags_$flag;\n";
419                 }
420                 $temp .= "\n";
421         }
422
423         # lookup init function
424         my $attr_init_code = $init_attr{$attr_type};
425         if(!defined($attr_init_code)) {
426                 die "Fatal error: Couldn't find attribute initialisation code for type '${attr_type}'";
427         }
428         my $custominit = "";
429         if(defined($custom_init_attr_func)) {
430                 $custominit .= &$custom_init_attr_func($n, $on, "${arch}_${op}");
431         }
432         if(defined($n->{custominit})) {
433                 $custominit .= $n->{custominit};
434         }
435
436         $temp .= <<EOF;
437         /* create node */
438         assert(op != NULL);
439         res = new_ir_node(dbgi, current_ir_graph, block, op, mode, arity, in);
440
441         /* init node attributes */
442         ${attr_init_code}
443         ${custominit}
444         info = be_get_info(res);
445         (void) info; /* avoid potential warning */
446         ${set_out_reqs}
447
448 EOF
449
450         if (exists($n->{"init_attr"})) {
451                 $temp .= "\tattr = get_irn_generic_attr(res);\n";
452                 $temp .= "\t".$n->{"init_attr"}."\n";
453         }
454
455         $temp .= <<EOF;
456         /* optimize node */
457         res = optimize_node(res);
458         irn_vrfy_irg(res, current_ir_graph);
459
460         return res;
461 EOF
462
463         $obst_constructor .= $temp;
464
465         # close constructor function
466         $obst_constructor .= "}\n\n";
467 }
468
469 push(@obst_enum_op, "typedef enum _${arch}_opcodes {\n");
470 foreach my $op (keys(%nodes)) {
471         my %n        = %{ $nodes{"$op"} };
472         my $known_mode;
473         my $num_outs = 0;
474         my $out_arity;
475         my @out_flags;
476
477         # determine arity
478         $arity = 0;
479         if(exists($n{"arity"})) {
480                 $arity = $n{"arity"};
481         } elsif (exists($n{"reg_req"}) && exists($n{"reg_req"}{"in"})) {
482                 $arity = scalar(@{ $n{"reg_req"}{"in"} });
483         } elsif (exists($n{"ins"})) {
484                 $arity = scalar(@{ $n{"ins"} });
485         }
486         if($arity eq "variable") {
487                 $arity = $ARITY_VARIABLE;
488         } elsif($arity eq "dynamic") {
489                 $arity = $ARITY_DYNAMIC;
490         }
491
492         # determine out arity
493         $out_arity = 0;
494         if(exists($n{"out_arity"})) {
495                 $out_arity = $n{"out_arity"};
496         } elsif (exists($n{"reg_req"}) && exists($n{"reg_req"}{"out"})) {
497                 $out_arity = scalar(@{ $n{"reg_req"}{"out"} });
498         } elsif (exists($n{"outs"})) {
499                 $out_arity = scalar(@{ $n{"outs"} });
500         }
501         if($out_arity eq "variable") {
502                 $out_arity = $ARITY_VARIABLE;
503         } elsif($out_arity eq "dynamic") {
504                 $out_arity = $ARITY_DYNAMIC;
505         }
506
507         $orig_op = $op;
508         $op      = $arch."_".$op;
509         $temp    = "";
510
511         # define proj numbers and in numbers
512         if (exists($n{"outs"})) {
513                 undef my @outs;
514
515                 @outs = @{ $n{"outs"} };
516                 if($out_arity >= 0 && scalar(@outs) != $out_arity) {
517                         die "Fatal error: Op ${op} has different number of outs and out_arity\n";
518                 }
519
520                 $num_outs = $#outs + 1;
521
522                 $obst_proj .= "\nenum pn_${op} {\n";
523
524                 for (my $idx = 0; $idx <= $#outs; $idx++) {
525                         # check, if we have additional flags annotated to out
526                         if ($outs[$idx] =~ /:((S|I)(\|(S|I))*)/) {
527                                 push(@out_flags, $1);
528                                 $outs[$idx] =~ s/:((S|I)(\|(S|I))*)//;
529                         }
530                         $obst_proj .= "\tpn_${op}_".$outs[$idx]." = ${idx},\n";
531                 }
532
533                 $obst_proj .= "};\n";
534                 # outs have names, it must be a mode_T node
535                 if (!defined($n{mode})) {
536                         $n{mode} = "mode_T";
537                 }
538         }
539         if (exists($n{"ins"})) {
540                 undef my @ins;
541
542                 @ins = @{ $n{"ins"} };
543                 if($arity >= 0 && scalar(@ins) != $arity) {
544                         die "Fatal error: Op ${op} has different number of ins and arity\n";
545                 }
546
547                 $obst_proj .= "\nenum n_$op {\n";
548                 for (my $idx = 0; $idx <= $#ins; $idx++) {
549                         $obst_proj .= "\tn_${op}_".$ins[$idx]." = ${idx},\n";
550                 }
551                 $obst_proj .= "};\n";
552         }
553
554         # Create opcode
555         push(@obst_opvar, "ir_op *op_$op = NULL;\n");
556         push(@obst_get_opvar, "ir_op *get_op_$op(void)         { return op_$op; }\n");
557         push(@obst_get_opvar, "int    is_$op(const ir_node *n) { return get_$arch\_irn_opcode(n) == iro_$op; }\n\n");
558
559         push(@obst_is_archirn, "is_$op(node)");
560
561         $obst_header .= <<EOF;
562 extern ir_op *op_${op};
563 ir_op *get_op_${op}(void);
564 int is_${op}(const ir_node *n);
565 EOF
566
567         my $attr_type= $n{attr_type};
568         if(!defined($attr_type)) {
569                 $attr_type = $default_attr_type;
570                 $n{attr_type} = $attr_type;
571         }
572
573         # determine hash function
574         my $hash_func;
575         if (exists($n{"hash_func"})) {
576                 $hash_func = $n{"hash_func"};
577         }
578
579         # determine compare function
580         my $cmp_attr_func;
581         if (exists($n{"cmp_attr"})) {
582                 my $cmpcode = $n{"cmp_attr"};
583
584                 push(@obst_cmp_attr, "static int cmp_attr_$op(ir_node *a, ir_node *b) {\n");
585                 if($cmpcode =~ m/attr_a/) {
586                         push(@obst_cmp_attr, "\t${attr_type} *attr_a = get_irn_generic_attr(a);\n");
587                 } else {
588                         push(@obst_cmp_attr, "\t(void) a;\n");
589                 }
590                 if($cmpcode =~ m/attr_b/) {
591                         push(@obst_cmp_attr, "\t${attr_type} *attr_b = get_irn_generic_attr(b);\n");
592                 } else {
593                         push(@obst_cmp_attr, "\t(void) b;\n");
594                 }
595                 push(@obst_cmp_attr, "\t${cmpcode}\n");
596                 push(@obst_cmp_attr, "}\n\n");
597
598                 $cmp_attr_func = "cmp_attr_${op}";
599         } else {
600                 if(defined($compare_attr{${attr_type}})) {
601                         $cmp_attr_func = $compare_attr{${attr_type}};
602                 } else {
603                         die "Fatal error: No compare function defined for ${attr_type} attributes.";
604                 }
605         }
606
607         my %constructors;
608         if (exists($n{constructors})) {
609                 %constructors = %{ $n{constructors} };
610         } else {
611                 # Create 1 default constructor
612                 my %constructor = ();
613                 foreach my $a ("comment", "ins", "outs", "args", "attr", "units",
614                                 "reg_req", "init_attr", "irn_flags", "mode", "arity",
615                                 "out_arity", "custominit") {
616                         if (defined($n{$a})) {
617                                 $constructor{$a} = $n{$a};
618                         }
619                 }
620                 %constructors = ( "" => \%constructor );
621         }
622
623         foreach my $constr (keys(%constructors)) {
624                 my %cstr = %{ $constructors{$constr} };
625                 # Copy some values from outer node if they don't exists in the constr
626                 foreach my $a ("ins", "outs", "irn_flags", "mode", "args", "attr",
627                                "custominit") {
628                         if (!defined($cstr{$a}) && defined($n{$a})) {
629                                 $cstr{$a} = $n{$a};
630                         }
631                 }
632                 create_constructor($orig_op, $constr, \%cstr, \%n);
633         }
634
635         # set default values for state and flags if not given
636         $n{"state"}    = "floats" if (! exists($n{"state"}));
637         $n{"op_flags"} = ["none"] if (! exists($n{"op_flags"}));
638
639         push(@obst_new_irop, "\n\tmemset(&ops, 0, sizeof(ops));\n");
640         push(@obst_new_irop, "\tops.be_ops        = be_ops;\n");
641         push(@obst_new_irop, "\tops.dump_node     = $arch\_dump_node;\n");
642
643         if (defined($cmp_attr_func)) {
644                 push(@obst_new_irop, "\tops.node_cmp_attr = ${cmp_attr_func};\n");
645         }
646         my $copy_attr_func = $copy_attr{$attr_type};
647         if (!defined($copy_attr_func)) {
648                 $copy_attr_func = $default_copy_attr;
649         }
650         if (defined($copy_attr_func)) {
651                 push(@obst_new_irop, "\tops.copy_attr = ${copy_attr_func};\n");
652         }
653         if (defined($hash_func)) {
654                 push(@obst_new_irop, "\tops.hash = ${hash_func};\n");
655         }
656
657         my %known_flags = map { $_ => 1 } (
658                 "none", "labeled", "commutative", "cfopcode", "op_cfopcode",
659                 "fragile", "forking", "highlevel", "constlike", "always_opt",
660                 "keep", "start_block", "uses_memory", "dump_noblock",
661                 "dump_noinput", "machine", "machine_op", "cse_neutral"
662         );
663         foreach my $flag (@{$n{"op_flags"}}) {
664                 if (not defined($known_flags{$flag})) {
665                         print STDERR "WARNING: Flag '$flag' in opcode $op is unknown\n";
666                 }
667         }
668         my @mapped = map { "irop_flag_$_" } @{$n{"op_flags"}};
669         my $op_flags = join('|', @mapped);
670
671         $n_opcodes++;
672         $temp  = "\top_$op = new_ir_op(cur_opcode + iro_$op, \"$op\", op_pin_state_".$n{"state"}.", $op_flags";
673         $temp .= "|irop_flag_machine, ".translate_arity($arity).", 0, sizeof(${attr_type}), &ops);\n";
674         push(@obst_new_irop, $temp);
675         push(@obst_new_irop, "\tset_op_tag(op_$op, $arch\_op_tag);\n");
676         if(defined($default_op_attr_type)) {
677                 push(@obst_new_irop, "\tattr = &attrs[iro_$op];\n");
678                 if(defined($n{op_attr_init})) {
679                         push(@obst_new_irop, "\t".$n{op_attr_init}."\n");
680                 }
681                 push(@obst_new_irop, "\tset_op_attr(op_$op, attr);\n");
682         }
683
684         push(@obst_enum_op, "\tiro_$op,\n");
685
686         $obst_header .= "\n";
687 }
688 push(@obst_enum_op, "\tiro_$arch\_last_generated,\n");
689 push(@obst_enum_op, "\tiro_$arch\_last = iro_$arch\_last_generated");
690 push(@obst_enum_op, " + $additional_opcodes") if (defined($additional_opcodes));
691 push(@obst_enum_op, "\n} $arch\_opcodes;\n\n");
692
693 # emit the code
694
695 open(OUT, ">$target_c") || die("Fatal error: Could not open $target_c, reason: $!\n");
696
697 print OUT "#include \"gen_$arch\_regalloc_if.h\"\n\n";
698 print OUT @obst_cmp_attr;
699 print OUT "\n";
700 print OUT @obst_opvar;
701 print OUT "\n";
702 print OUT @obst_get_opvar;
703 print OUT "\n";
704
705 print OUT<<EOF;
706
707 static int $arch\_opcode_start = -1;
708 static int $arch\_opcode_end   = -1;
709
710 EOF
711
712 # build the FOURCC arguments from $arch
713
714 my ($a, $b, $c, $d) = ('\0', '\0', '\0', '\0');
715
716 if (length($arch) >= 1) {
717         $a = uc(substr($arch, 0, 1));
718 }
719
720 if (length($arch) >= 2) {
721         $b = uc(substr($arch, 1, 1));
722 }
723
724 if (length($arch) >= 3) {
725         $c = uc(substr($arch, 2, 1));
726 }
727
728 if (length($arch) >= 4) {
729         $d = uc(substr($arch, 3, 1));
730 }
731
732 print OUT<<ENDOFISIRN;
733
734 /** A tag for the $arch opcodes. Note that the address is used as a tag value, NOT the FOURCC code. */
735 #define $arch\_op_tag FOURCC('$a', '$b', '$c', '$d')
736
737 /** Return the opcode number of the first $arch opcode. */
738 int get_$arch\_opcode_first(void) {
739         return $arch\_opcode_start;
740 }
741
742 /** Return the opcode number of the last $arch opcode + 1. */
743 int get_$arch\_opcode_last(void) {
744         return $arch\_opcode_end;
745 }
746
747 /** Return 1 if the given opcode is a $arch machine op, 0 otherwise */
748 int is_$arch\_op(const ir_op *op) {
749         return get_op_tag(op) == $arch\_op_tag;
750 }
751
752 /** Return 1 if the given node is a $arch machine node, 0 otherwise */
753 int is_$arch\_irn(const ir_node *node) {
754         return is_$arch\_op(get_irn_op(node));
755 }
756
757 int get_$arch\_irn_opcode(const ir_node *node) {
758         if (is_$arch\_irn(node))
759                 return get_irn_opcode(node) - $arch\_opcode_start;
760         return -1;
761 }
762
763 ENDOFISIRN
764
765 print OUT <<END;
766 #ifdef BIT
767 #undef BIT
768 #endif
769 #define BIT(x)  (1 << (x % 32))
770
771 END
772
773 print OUT @obst_limit_func;
774 print OUT "\n";
775
776 print OUT @obst_reg_reqs;
777 print OUT "\n";
778
779 print OUT<<ENDOFMAIN;
780 $obst_constructor
781
782 /**
783  * Creates the $arch specific Firm machine operations
784  * needed for the assembler irgs.
785  */
786 void $arch\_create_opcodes(const arch_irn_ops_t *be_ops) {
787 #define N   irop_flag_none
788 #define L   irop_flag_labeled
789 #define C   irop_flag_commutative
790 #define X   irop_flag_cfopcode
791 #define I   irop_flag_ip_cfopcode
792 #define F   irop_flag_fragile
793 #define Y   irop_flag_forking
794 #define H   irop_flag_highlevel
795 #define c   irop_flag_constlike
796 #define K   irop_flag_keep
797 #define M   irop_flag_machine
798 #define O   irop_flag_machine_op
799 #define NB  irop_flag_dump_noblock
800 #define NI  irop_flag_dump_noinput
801 #define n   irop_flag_cse_neutral
802 #define R   (irop_flag_user << 0)
803
804         ir_op_ops  ops;
805         int        cur_opcode;
806         static int run_once = 0;
807 ENDOFMAIN
808
809         if (defined($default_op_attr_type)) {
810                 print OUT "\t$default_op_attr_type *attr, *attrs;\n";
811         }
812
813 print OUT<<ENDOFMAIN;
814
815         if (run_once)
816                 return;
817         run_once = 1;
818
819         cur_opcode = get_next_ir_opcodes(iro_$arch\_last);
820
821         $arch\_opcode_start = cur_opcode;
822 ENDOFMAIN
823
824         if (defined($default_op_attr_type)) {
825                 print OUT "\tattrs = xmalloc(sizeof(attr[0]) * iro_$arch\_last);\n";
826                 print OUT "\tmemset(attrs, 0, sizeof(attr[0]) * iro_$arch\_last);\n";
827         }
828
829 print OUT @obst_new_irop;
830 print OUT "\n";
831 print OUT "\t$arch\_register_additional_opcodes(cur_opcode);\n" if (defined($additional_opcodes));
832 print OUT "\t$arch\_opcode_end = cur_opcode + iro_$arch\_last";
833 print OUT " + $additional_opcodes" if (defined($additional_opcodes));
834 print OUT ";\n";
835 print OUT "}\n";
836
837 close(OUT);
838
839 open(OUT, ">$target_h") || die("Fatal error: Could not open $target_h, reason: $!\n");
840
841 my $creation_time = localtime(time());
842 my $tmp = uc($arch);
843
844 print OUT<<EOF;
845 /**
846  * \@file
847  * \@brief Function prototypes for the new opcode functions.
848  * \@note  DO NOT EDIT THIS FILE, your changes will be lost.
849  *        Edit $specfile instead.
850  *        created by: $0 $specfile $target_dir
851  * \@date  $creation_time
852  */
853 #ifndef FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
854 #define FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
855
856 EOF
857
858 print OUT @obst_enum_op;
859 print OUT <<EOF;
860 int is_${arch}_irn(const ir_node *node);
861 int is_${arch}_op(const ir_op *op);
862
863 int get_${arch}_opcode_first(void);
864 int get_${arch}_opcode_last(void);
865 int get_${arch}_irn_opcode(const ir_node *node);
866 ${obst_header}
867 ${obst_proj}
868
869 #endif
870 EOF
871
872 close(OUT);
873
874 ###
875 # Translates numeric arity into string constant.
876 ###
877 sub translate_arity {
878         my $arity = shift;
879
880         if ($arity =~ /^\d+$/) {
881                 if    ($arity == 0) {
882                         return "oparity_zero";
883                 }
884                 elsif ($arity == 1) {
885                         return "oparity_unary";
886                 }
887                 elsif ($arity == 2) {
888                         return "oparity_binary";
889                 }
890                 elsif ($arity == 3) {
891                         return "oparity_trinary";
892                 }
893                 else {
894                         return "oparity_any";
895                 }
896         } elsif ($arity == $ARITY_VARIABLE) {
897                 return "oparity_variable";
898         } elsif ($arity == $ARITY_DYNAMIC) {
899                 return "oparity_dynamic";
900         } else {
901                 die "Fatal error: Unknown arity $arity";
902         }
903 }
904
905 ###
906 # Return the list of pointers for the given execution units.
907 ###
908 sub gen_execunit_list_initializer {
909         my $units   = shift;
910         my $uc_arch = uc($arch);
911         my $ret     = "";
912         my $ret2    = "";
913         my %init;
914
915         foreach my $unit (@{ $units }) {
916                 if ($unit eq "DUMMY") {
917                         push(@{ $init{"DUMMY"} }, "\t\t&be_machine_execution_units_DUMMY[0]");
918                 }
919                 elsif (exists($cpu{"$unit"})) {
920                         # operation can be executed on all units of this type
921                         # -> add them all
922                         my $tp_name = "$arch\_execution_units_$unit";
923                         my $idx     = 0;
924                         foreach (@{ $cpu{"$unit"} }) {
925                                 next if ($idx++ == 0);  # skip first element (it's not a unit)
926                                 my $unit_name = "$uc_arch\_EXECUNIT_TP_$unit\_$_";
927                                 push(@{ $init{"$unit"} }, "\t\t&".$tp_name."[".$unit_name."]");
928                         }
929                 }
930                 else {
931                         # operation can be executed only a certain unit
932                         # -> find corresponding unit type
933                         my $found = 0;
934 TP_SEARCH:      foreach my $cur_type (keys(%cpu)) {
935                                 foreach my $cur_unit (@{ $cpu{"$cur_type"} }) {
936                                         if ($unit eq $cur_unit) {
937                                                 my $tp_name   = "$arch\_execution_units_$cur_type";
938                                                 my $unit_name = "$uc_arch\_EXECUNIT_TP_$cur_type\_$unit";
939                                                 push(@{ $init{"$unit"} }, "\t\t&".$tp_name."[".$unit_name."]");
940                                                 $found = 1;
941                                                 last TP_SEARCH;
942                                         }
943                                 }
944                         }
945
946                         if (! $found) {
947                                 print STDERR "Invalid execution unit $unit specified!\n";
948                         }
949                 }
950         }
951
952         # prepare the 2-dim array init
953         foreach my $key (keys(%init)) {
954                 $ret .= "\tstatic const be_execution_unit_t *allowed_units_".$key."[] =\n";
955                 $ret .= "\t{\n";
956                 foreach (@{ $init{"$key"} }) {
957                         $ret .= "$_,\n";
958                 }
959                 $ret .= "\t\tNULL\n";
960                 $ret .= "\t};\n";
961                 $ret2 .= "\t\tallowed_units_$key,\n";
962         }
963         $ret2 .= "\t\tNULL\n";
964
965         $ret .= "\tstatic const be_execution_unit_t **exec_units[] =\n";
966         $ret .= "\t{\n";
967         $ret .= $ret2;
968         $ret .= "\t};\n";
969
970         return $ret;
971 }
972
973 sub mangle_requirements {
974         my $reqs  = shift;
975         my $class = shift;
976         my $flags = shift;
977
978         my @alternatives = split(/ /, $reqs);
979         for(my $idx = 0; $idx < scalar(@alternatives); $idx++) {
980                 $alternatives[$idx] =~ s/!/not_/g;
981         }
982
983         @alternatives = sort @alternatives;
984
985         my $name = $class."_".join('_', @alternatives);
986         if (defined($flags)) {
987                 $flags =~ s/\|/_/g;
988                 $name .= "_$flags";
989         }
990
991         return $name;
992 }
993
994 ###
995 # Determines whether $name is a specified register class or not.
996 # @return 1 if name is register class, 0 otherwise
997 ###
998 sub is_reg_class {
999     my $name = shift;
1000     return 1 if exists($reg_classes{"$name"});
1001     return 0;
1002 }
1003
1004 ###
1005 # Returns the register class for a given register.
1006 # @return class or undef
1007 ###
1008 sub get_reg_class {
1009     my $reg = shift;
1010     $reg = substr($reg, 1) if ($reg =~ /!.*/);
1011     return $reg2class{"$reg"}{"class"} if (exists($reg2class{"$reg"}));
1012     return undef;
1013 }
1014
1015 ###
1016 # Returns the index of a given register within it's register class.
1017 # @return index or undef
1018 ###
1019 sub get_reg_index {
1020     my $reg = shift;
1021     return $reg2class{"$reg"}{"index"} if (exists($reg2class{"$reg"}));
1022     return undef;
1023 }
1024
1025 ###
1026 # Remember the register class for each index in the given requirements.
1027 # We need this information for requirements like "in_sX" or "out_dX"
1028 # @return array of classes corresponding to the requirement for each index
1029 ###
1030 sub build_inout_idx_class {
1031         my $n     = shift;
1032         my $op    = shift;
1033         my $is_in = shift;
1034         my @idx_class;
1035
1036         my $inout = ($is_in ? "in" : "out");
1037
1038         if (exists($n->{"reg_req"}{"$inout"})) {
1039                 my @reqs = @{ $n->{"reg_req"}{"$inout"} };
1040
1041                 for (my $idx = 0; $idx <= $#reqs; $idx++) {
1042                         my $class = undef;
1043                         my ($req,) = split(/:/, $reqs[$idx]);
1044
1045                         if ($req eq "none") {
1046                                 $class = "none";
1047                         } elsif (is_reg_class($req)) {
1048                                 $class = $req;
1049                         } else {
1050                                 my @regs = split(/ /, $req);
1051 GET_CLASS:              foreach my $reg (@regs) {
1052                                         if ($reg =~ /!?(in|out)\_r\d+/ || $reg =~ /!in/) {
1053                                                 $class = "UNKNOWN_CLASS";
1054                                         } else {
1055                                                 $class = get_reg_class($reg);
1056                                                 if (!defined $class) {
1057                                                         die("Fatal error: Could not get ".uc($inout)." register class for '$op' pos $idx (reg $reg) ... exiting.\n");
1058                                                 } else {
1059                                                         last GET_CLASS;
1060                                                 } # !defined class
1061                                         } # if (reg =~ ...
1062                                 } # foreach
1063                         } # if
1064
1065                         push(@idx_class, $class);
1066                 } # for
1067         } # if
1068
1069         return @idx_class;
1070 }
1071
1072 ###
1073 # Generates the function for a given $op and a given IN-index
1074 # which returns a subset of possible register from a register class
1075 # @return classname from which the subset is derived or undef and
1076 #         pos which corresponds to in/out reference position or undef
1077 ###
1078 sub build_subset_class_func {
1079         my $neg           = undef;
1080         my $class         = undef;
1081         my $has_limit     = 0;
1082         my $limit_name;
1083         my $same_pos      = 0;
1084         my $different_pos = 0;
1085         my $temp;
1086         my @obst_init;
1087         my @obst_limits;
1088         my @obst_ignore;
1089         my @limit_array;
1090         my $limit_reqs;   #used for name mangling
1091
1092         # build function header
1093         my $node  = shift;
1094         my $op    = shift;
1095         my $idx   = shift;
1096         my $is_in = shift;
1097         my @regs  = split(/ /, shift);
1098         my $flags = shift;
1099
1100         my @idx_class = build_inout_idx_class($node, $op, !$is_in);
1101
1102         # set/unset registers
1103 CHECK_REQS: foreach (@regs) {
1104                 if (!$is_in && /(!)?in_r(\d+)/) {
1105                         my $bit_pos = 1 << ($2 - 1);
1106                         if ($different_pos & $bit_pos) {
1107                                 if ($1) {
1108                                         print STDERR "duplicate !in constraint\n";
1109                                 } else {
1110                                         print STDERR "conflicting !in and in constraints\n";
1111                                 }
1112                                 return (undef, undef, undef, undef);
1113                         }
1114
1115                         if ($same_pos & $bit_pos) {
1116                                 if ($1) {
1117                                         print STDERR "conflicting !in and in constraints\n";
1118                                 } else {
1119                                         print STDERR "duplicate in constraint\n";
1120                                 }
1121                                 return (undef, undef, undef, undef);
1122                         }
1123
1124                         if ($1) {
1125                                 $different_pos |= $bit_pos;
1126                         } else {
1127                                 $same_pos      |= $bit_pos;
1128                         }
1129
1130                         $class = $idx_class[$2 - 1];
1131                         next CHECK_REQS;
1132                 }
1133
1134                 # check for negate
1135                 if (substr($_, 0, 1) eq "!") {
1136                         if (defined($neg) && $neg == 0) {
1137                                 # we have seen a positiv constraint as first one but this one is negative
1138                                 # this doesn't make sense
1139                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1140                                 return (undef, undef, undef, undef);
1141                         }
1142
1143                         if (!defined($neg)) {
1144                                 $has_limit = 1;
1145                         }
1146
1147                         $_   = substr($_, 1); # skip '!'
1148                         $neg = 1;
1149                 } else {
1150                         if (defined($neg) && $neg == 1) {
1151                                 # we have seen a negative constraint as first one but this one is positive
1152                                 # this doesn't make sense
1153                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1154                                 return (undef, undef, undef, undef);
1155                         }
1156
1157                         $has_limit = 1;
1158                         $neg = 0;
1159                 }
1160
1161                 # check if register belongs to one of the given classes
1162                 $temp = get_reg_class($_);
1163                 if (!defined($temp)) {
1164                         print STDERR "Unknown register '$_'!\n";
1165                         return (undef, undef, undef, undef);
1166                 }
1167
1168                 # set class
1169                 if (!defined($class)) {
1170                         $class = $temp;
1171                 } elsif ($class ne $temp) {
1172                         # all registers must belong to the same class
1173                         print STDERR "Registerclass mismatch. '$_' is not member of class '$class'.\n";
1174                         return (undef, undef, undef, undef);
1175                 }
1176
1177                 # calculate position inside the initializer bitfield (only 32 bits per
1178                 # element)
1179                 my $regidx = get_reg_index($_);
1180                 my $arrayp = $regidx / 32;
1181                 push(@{$limit_array[$arrayp]}, $_);
1182                 $limit_reqs .= "$_ ";
1183         }
1184
1185         # don't allow ignore regs in negative constraints
1186         if($neg) {
1187                 my @cur_class = @{ $reg_classes{"$class"} };
1188                 for (my $idx = 0; $idx <= $#cur_class; $idx++) {
1189                         if (defined($cur_class[$idx]{"type"}) && ($cur_class[$idx]{"type"} & 4)) {
1190                                 my $reg    = $cur_class[$idx]{"name"};
1191                                 my $regix  = get_reg_index($reg);
1192                                 my $arrayp = $regix / 32;
1193                                 push(@{$limit_array[$arrayp]}, $reg);
1194                                 $limit_reqs .= "$reg ";
1195                         }
1196                 }
1197         }
1198
1199         if ($has_limit == 1) {
1200                 $limit_name = "${arch}_limit_".mangle_requirements($limit_reqs, $class);
1201
1202                 if(defined($limit_bitsets{$limit_name})) {
1203                         $limit_name = $limit_bitsets{$limit_name};
1204                         return ($class, $limit_name, $same_pos, $different_pos);
1205                 }
1206
1207                 $limit_bitsets{$limit_name} = $limit_name;
1208
1209                 push(@obst_limit_func, "static const unsigned " . $limit_name . "[] = { ");
1210                 my $first = 1;
1211                 my $limitbitsetlen = $regclass2len{$class};
1212                 my $limitarraylen = ($limitbitsetlen+31) / 32;
1213                 for(my $i = 0; $i < $limitarraylen; $i++) {
1214
1215                         my $limitarraypart = $limit_array[$i];
1216                         if($first) {
1217                                 $first = 0;
1218                         } else {
1219                                 push(@obst_limit_func, ", ");
1220                         }
1221                         my $temp;
1222                         if($neg) {
1223                                 $temp = "0xFFFFFFFF";
1224                         }
1225                         foreach my $reg (@{$limitarraypart}) {
1226                                 if($neg) {
1227                                         $temp .= " & ~";
1228                                 } elsif(defined($temp)) {
1229                                         $temp .= " | ";
1230                                 }
1231                                 $temp .= "BIT(REG_".uc(${reg}).")";
1232                         }
1233                         if(defined($temp)) {
1234                                 push(@obst_limit_func, "${temp}");
1235                         } else {
1236                                 push(@obst_limit_func, "0");
1237                         }
1238                 }
1239                 push(@obst_limit_func, " };\n");
1240         }
1241
1242         return ($class, $limit_name, $same_pos, $different_pos);
1243 }
1244
1245 ###
1246 # Generate register requirements structure
1247 ###
1248 sub generate_requirements {
1249         my ($reqs, $flags) = split(/:/, shift);
1250         my $node  = shift;
1251         my $op    = shift;
1252         my $idx   = shift;
1253         my $is_in = shift;
1254         my $class = "";
1255         my $result;
1256
1257         my @req_type_mask;
1258         if (defined($flags)) {
1259                 foreach my $f (split(/|/, $flags)) {
1260                         if ($f eq "I") {
1261                                 push(@req_type_mask, "arch_register_req_type_ignore");
1262                         } elsif ($f eq "S") {
1263                                 push(@req_type_mask, "arch_register_req_type_produces_sp");
1264                         }
1265                 }
1266         }
1267
1268         if ($reqs eq "none") {
1269
1270                 $result = <<EOF;
1271 {
1272         arch_register_req_type_none,
1273         NULL,                         /* regclass */
1274         NULL,                         /* limit bitset */
1275         0,                            /* same pos */
1276         0                             /* different pos */
1277 };
1278
1279 EOF
1280         } elsif (is_reg_class($reqs)) {
1281                 push(@req_type_mask, "arch_register_req_type_normal");
1282                 my $reqtype = join(" | ", @req_type_mask);
1283                 $class  = $reqs;
1284                 $result = <<EOF;
1285 {
1286         ${reqtype},
1287         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1288         NULL,        /* limit bitset */
1289         0,           /* same pos */
1290         0            /* different pos */
1291 };
1292
1293 EOF
1294
1295         } else {
1296                 my ($regclass, $limit_bitset, $same_pos, $different_pos)
1297                         = build_subset_class_func($node, $op, $idx, $is_in, $reqs, $flags);
1298
1299                 if (!defined($regclass)) {
1300                         die("Fatal error: Could not build subset for requirements '$reqs' of '$op' pos $idx ... exiting.\n");
1301                 }
1302
1303                 if (defined($limit_bitset) && $limit_bitset ne "NULL") {
1304                         push(@req_type_mask, "arch_register_req_type_limited");
1305                 }
1306                 if ($same_pos != 0) {
1307                         push(@req_type_mask, "arch_register_req_type_should_be_same");
1308                 }
1309                 if ($different_pos != 0) {
1310                         push(@req_type_mask, "arch_register_req_type_must_be_different");
1311                 }
1312                 my $reqtype = join(" | ", @req_type_mask);
1313
1314                 if(!defined($limit_bitset)) {
1315                         $limit_bitset = "NULL";
1316                 }
1317
1318                 $class  = $regclass;
1319                 $result = <<EOF;
1320 {
1321         ${reqtype},
1322         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1323         ${limit_bitset},
1324         ${same_pos},        /* same pos */
1325         ${different_pos}        /* different pos */
1326 };
1327
1328 EOF
1329         }
1330
1331         my $name = "${arch}_requirements_".mangle_requirements($reqs, $class, $flags);
1332         if(defined($requirements{$name})) {
1333                 return $name;
1334         }
1335         $requirements{$name} = $name;
1336         push(@obst_reg_reqs, <<EOF);
1337 static const arch_register_req_t ${name} = ${result}
1338 EOF
1339
1340         return $name;
1341 }