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