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