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