This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
op_private: Update note about targlex and trans
[perl5.git] / regen / opcode.pl
1 #!/usr/bin/perl -w
2
3 # Regenerate (overwriting only if changed):
4 #
5 #    opcode.h
6 #    opnames.h
7 #    pp_proto.h
8 #    lib/B/Op_private.pm
9 #
10 # from:
11 #  * information stored in regen/opcodes;
12 #  * information stored in regen/op_private (which is actually perl code);
13 #  * the values hardcoded into this script in @raw_alias.
14 #
15 # Accepts the standard regen_lib -q and -v args.
16 #
17 # This script is normally invoked from regen.pl.
18
19 use strict;
20
21 BEGIN {
22     # Get function prototypes
23     require 'regen/regen_lib.pl';
24 }
25
26 my $oc = open_new('opcode.h', '>',
27                   {by => 'regen/opcode.pl', from => 'its data',
28                    file => 'opcode.h', style => '*',
29                    copyright => [1993 .. 2007]});
30
31 my $on = open_new('opnames.h', '>',
32                   { by => 'regen/opcode.pl', from => 'its data', style => '*',
33                     file => 'opnames.h', copyright => [1999 .. 2008] });
34
35 my $oprivpm = open_new('lib/B/Op_private.pm', '>',
36                   { by => 'regen/opcode.pl',
37                     from => "data in\nregen/op_private "
38                            ."and pod embedded in regen/opcode.pl",
39                     style => '#',
40                     file => 'lib/B/Op_private.pm',
41                     copyright => [2014 .. 2014] });
42
43 # Read 'opcodes' data.
44
45 my %seen;
46 my (@ops, %desc, %check, %ckname, %flags, %args, %opnum);
47
48 open OPS, 'regen/opcodes' or die $!;
49
50 while (<OPS>) {
51     chop;
52     next unless $_;
53     next if /^#/;
54     my ($key, $desc, $check, $flags, $args) = split(/\t+/, $_, 5);
55     $args = '' unless defined $args;
56
57     warn qq[Description "$desc" duplicates $seen{$desc}\n]
58      if $seen{$desc} and $key !~ "transr|(?:intro|clone)cv|lvref";
59     die qq[Opcode "$key" duplicates $seen{$key}\n] if $seen{$key};
60     die qq[Opcode "freed" is reserved for the slab allocator\n]
61         if $key eq 'freed';
62     $seen{$desc} = qq[description of opcode "$key"];
63     $seen{$key} = qq[opcode "$key"];
64
65     push(@ops, $key);
66     $opnum{$key} = $#ops;
67     $desc{$key} = $desc;
68     $check{$key} = $check;
69     $ckname{$check}++;
70     $flags{$key} = $flags;
71     $args{$key} = $args;
72 }
73
74 # Set up aliases
75
76 my %alias;
77
78 # Format is "this function" => "does these op names"
79 my @raw_alias = (
80                  Perl_do_kv => [qw( keys values )],
81                  Perl_unimplemented_op => [qw(padany custom)],
82                  # All the ops with a body of { return NORMAL; }
83                  Perl_pp_null => [qw(scalar regcmaybe lineseq scope)],
84
85                  Perl_pp_goto => ['dump'],
86                  Perl_pp_require => ['dofile'],
87                  Perl_pp_untie => ['dbmclose'],
88                  Perl_pp_sysread => {read => '', recv => '#ifdef HAS_SOCKET'},
89                  Perl_pp_sysseek => ['seek'],
90                  Perl_pp_ioctl => ['fcntl'],
91                  Perl_pp_ssockopt => {gsockopt => '#ifdef HAS_SOCKET'},
92                  Perl_pp_getpeername => {getsockname => '#ifdef HAS_SOCKET'},
93                  Perl_pp_stat => ['lstat'],
94                  Perl_pp_ftrowned => [qw(fteowned ftzero ftsock ftchr ftblk
95                                          ftfile ftdir ftpipe ftsuid ftsgid
96                                          ftsvtx)],
97                  Perl_pp_fttext => ['ftbinary'],
98                  Perl_pp_gmtime => ['localtime'],
99                  Perl_pp_semget => [qw(shmget msgget)],
100                  Perl_pp_semctl => [qw(shmctl msgctl)],
101                  Perl_pp_ghostent => [qw(ghbyname ghbyaddr)],
102                  Perl_pp_gnetent => [qw(gnbyname gnbyaddr)],
103                  Perl_pp_gprotoent => [qw(gpbyname gpbynumber)],
104                  Perl_pp_gservent => [qw(gsbyname gsbyport)],
105                  Perl_pp_gpwent => [qw(gpwnam gpwuid)],
106                  Perl_pp_ggrent => [qw(ggrnam ggrgid)],
107                  Perl_pp_ftis => [qw(ftsize ftmtime ftatime ftctime)],
108                  Perl_pp_chown => [qw(unlink chmod utime kill)],
109                  Perl_pp_link => ['symlink'],
110                  Perl_pp_ftrread => [qw(ftrwrite ftrexec fteread ftewrite
111                                         fteexec)],
112                  Perl_pp_shmwrite => [qw(shmread msgsnd msgrcv semop)],
113                  Perl_pp_syswrite => {send => '#ifdef HAS_SOCKET'},
114                  Perl_pp_defined => [qw(dor dorassign)],
115                  Perl_pp_and => ['andassign'],
116                  Perl_pp_or => ['orassign'],
117                  Perl_pp_ucfirst => ['lcfirst'],
118                  Perl_pp_sle => [qw(slt sgt sge)],
119                  Perl_pp_print => ['say'],
120                  Perl_pp_index => ['rindex'],
121                  Perl_pp_oct => ['hex'],
122                  Perl_pp_shift => ['pop'],
123                  Perl_pp_sin => [qw(cos exp log sqrt)],
124                  Perl_pp_bit_or => ['bit_xor'],
125                  Perl_pp_rv2av => ['rv2hv'],
126                  Perl_pp_akeys => ['avalues'],
127                  Perl_pp_rkeys => [qw(rvalues reach)],
128                  Perl_pp_trans => [qw(trans transr)],
129                  Perl_pp_chop => [qw(chop chomp)],
130                  Perl_pp_schop => [qw(schop schomp)],
131                  Perl_pp_bind => {connect => '#ifdef HAS_SOCKET'},
132                  Perl_pp_preinc => ['i_preinc', 'predec', 'i_predec'],
133                  Perl_pp_postinc => ['i_postinc', 'postdec', 'i_postdec'],
134                  Perl_pp_ehostent => [qw(enetent eprotoent eservent
135                                          spwent epwent sgrent egrent)],
136                  Perl_pp_shostent => [qw(snetent sprotoent sservent)],
137                  Perl_pp_aelemfast => ['aelemfast_lex'],
138                  Perl_pp_grepstart => ['mapstart'],
139                 );
140
141 while (my ($func, $names) = splice @raw_alias, 0, 2) {
142     if (ref $names eq 'ARRAY') {
143         foreach (@$names) {
144             $alias{$_} = [$func, ''];
145         }
146     } else {
147         while (my ($opname, $cond) = each %$names) {
148             $alias{$opname} = [$func, $cond];
149         }
150     }
151 }
152
153 foreach my $sock_func (qw(socket bind listen accept shutdown
154                           ssockopt getpeername)) {
155     $alias{$sock_func} = ["Perl_pp_$sock_func", '#ifdef HAS_SOCKET'],
156 }
157
158
159
160 # =================================================================
161 #
162 # Functions for processing regen/op_private data.
163 #
164 # Put them in a separate package so that croak() does the right thing
165
166 package OP_PRIVATE;
167
168 use Carp;
169
170
171 # the vars holding the global state built up by all the calls to addbits()
172
173
174 # map OPpLVAL_INTRO => LVINTRO
175 my %LABELS;
176
177
178 # the numeric values of flags - what will get output as a #define
179 my %DEFINES;
180
181 # %BITFIELDS: the various bit field types. The key is the concatenation of
182 # all the field values that make up a bit field hash; the values are bit
183 # field hash refs.  This allows us to de-dup identical bit field defs
184 # across different ops, and thus make the output tables more compact (esp
185 # important for the C version)
186 my %BITFIELDS;
187
188 # %FLAGS: the main data structure. Indexed by op name, then bit index:
189 # single bit flag:
190 #   $FLAGS{rv2av}{2} = 'OPpSLICEWARNING';
191 # bit field (bits 5 and 6):
192 #   $FLAGS{rv2av}{5} = $FLAGS{rv2av}{6} = { .... };
193 my %FLAGS;
194
195
196 # do, with checking, $LABELS{$name} = $label
197
198 sub add_label {
199     my ($name, $label) = @_;
200     if (exists $LABELS{$name} and $LABELS{$name} ne $label) {
201         croak "addbits(): label for flag '$name' redefined:\n"
202         .  "  was '$LABELS{$name}', now '$label'";
203     }
204     $LABELS{$name} = $label;
205 }
206
207 #
208 # do, with checking, $DEFINES{$name} = $val
209
210 sub add_define {
211     my ($name, $val) = @_;
212     if (exists $DEFINES{$name} && $DEFINES{$name} != $val) {
213         croak "addbits(): value for flag '$name' redefined:\n"
214         .  "  was $DEFINES{$name}, now $val";
215     }
216     $DEFINES{$name} = $val;
217 }
218
219
220 # intended to be called from regen/op_private; see that file for details
221
222 sub ::addbits {
223     my @args = @_;
224
225     croak "too few arguments for addbits()" unless @args >= 3;
226     my $op = shift @args;
227     croak "invalid op name: '$op'" unless exists $opnum{$op};
228
229     while (@args) {
230         my $bits = shift @args;
231         if ($bits =~ /^[0-7]$/) {
232             # single bit
233             croak "addbits(): too few arguments for single bit flag"
234                 unless @args >= 2;
235             my $flag_name   = shift @args;
236             my $flag_label  = shift @args;
237             add_label($flag_name, $flag_label);
238             croak "addbits(): bit $bits of $op already specified"
239                 if defined $FLAGS{$op}{$bits};
240             $FLAGS{$op}{$bits} = $flag_name;
241             add_define($flag_name, (1 << $bits));
242         }
243         elsif ($bits =~ /^([0-7])\.\.([0-7])$/) {
244             # bit range
245             my ($bitmin, $bitmax) = ($1,$2);
246
247             croak "addbits(): min bit > max bit in bit range '$bits'"
248                 unless $bitmin <= $bitmax;
249             croak "addbits(): bit field argument missing"
250                 unless @args >= 1;
251
252             my $arg_hash = shift @args;
253             croak "addbits(): arg to $bits must be a hash ref"
254                 unless defined $arg_hash and ref($arg_hash) =~ /HASH/;
255
256             my %valid_keys;
257             @valid_keys{qw(baseshift_def bitcount_def mask_def label enum)} = ();
258             for (keys %$arg_hash) {
259                 croak "addbits(): unrecognised bifield key: '$_'"
260                     unless exists $valid_keys{$_};
261             }
262
263             my $bitmask = 0;
264             $bitmask += (1 << $_) for $bitmin..$bitmax;
265
266             my $enum_id ='';
267
268             if (defined $arg_hash->{enum}) {
269                 my $enum = $arg_hash->{enum};
270                 croak "addbits(): arg to enum must be an array ref"
271                     unless defined $enum and ref($enum) =~ /ARRAY/;
272                 croak "addbits(): enum list must be in triplets"
273                     unless @$enum % 3 == 0;
274
275                 my $max_id = (1 << ($bitmax - $bitmin + 1)) - 1;
276
277                 my @e = @$enum;
278                 while (@e) {
279                     my $enum_ix     = shift @e;
280                     my $enum_name   = shift @e;
281                     my $enum_label  = shift @e;
282                     croak "addbits(): enum index must be a number: '$enum_ix'"
283                         unless $enum_ix =~ /^\d+$/;
284                     croak "addbits(): enum index too big: '$enum_ix'"
285                         unless $enum_ix  <= $max_id;
286                     add_label($enum_name, $enum_label);
287                     add_define($enum_name, $enum_ix << $bitmin);
288                     $enum_id .= "($enum_ix:$enum_name:$enum_label)";
289                 }
290             }
291
292             # id is a fingerprint of all the content of the bit field hash
293             my $id = join ':', map defined() ? $_ : "-undef-",
294                 $bitmin, $bitmax,
295                 $arg_hash->{label},
296                 $arg_hash->{mask_def},
297                 $arg_hash->{baseshift_def},
298                 $arg_hash->{bitcount_def},
299                 $enum_id;
300
301             unless (defined $BITFIELDS{$id}) {
302
303                 if (defined $arg_hash->{mask_def}) {
304                     add_define($arg_hash->{mask_def}, $bitmask);
305                 }
306
307                 if (defined $arg_hash->{baseshift_def}) {
308                     add_define($arg_hash->{baseshift_def}, $bitmin);
309                 }
310
311                 if (defined $arg_hash->{bitcount_def}) {
312                     add_define($arg_hash->{bitcount_def}, $bitmax-$bitmin+1);
313                 }
314
315                 # create deep copy
316
317                 my $copy = {};
318                 for (qw(baseshift_def  bitcount_def mask_def label)) {
319                     $copy->{$_} = $arg_hash->{$_} if defined $arg_hash->{$_};
320                 }
321                 if (defined $arg_hash->{enum}) {
322                     $copy->{enum} = [ @{$arg_hash->{enum}} ];
323                 }
324
325                 # and add some extra fields
326
327                 $copy->{bitmask} = $bitmask;
328                 $copy->{bitmin} = $bitmin;
329                 $copy->{bitmax} = $bitmax;
330
331                 $BITFIELDS{$id} = $copy;
332             }
333
334             for my $bit ($bitmin..$bitmax) {
335                 croak "addbits(): bit $bit of $op already specified"
336                     if defined $FLAGS{$op}{$bit};
337                 $FLAGS{$op}{$bit} = $BITFIELDS{$id};
338             }
339         }
340         else {
341             croak "addbits(): invalid bit specifier '$bits'";
342         }
343     }
344 }
345
346
347 # intended to be called from regen/op_private; see that file for details
348
349 sub ::ops_with_flag {
350     my $flag = shift;
351     return grep $flags{$_} =~ /\Q$flag/, sort keys %flags;
352 }
353
354
355 # intended to be called from regen/op_private; see that file for details
356
357 sub ::ops_with_check {
358     my $c = shift;
359     return grep $check{$_} eq $c, sort keys %check;
360 }
361
362
363 # intended to be called from regen/op_private; see that file for details
364
365 sub ::ops_with_arg {
366     my ($i, $arg_type) = @_;
367     my @ops;
368     for my $op (sort keys %args) {
369         my @args = split(' ',$args{$op});
370         push @ops, $op if defined $args[$i] and $args[$i] eq $arg_type;
371     }
372     @ops;
373 }
374
375
376 # output '#define OPpLVAL_INTRO 0x80' etc
377
378 sub print_defines {
379     my $fh = shift;
380
381     for (sort { $DEFINES{$a} <=> $DEFINES{$b} || $a cmp $b } keys %DEFINES) {
382         printf $fh "#define %-23s 0x%02x\n", $_, $DEFINES{$_};
383     }
384 }
385
386
387 # Generate the content of B::Op_private
388
389 sub print_B_Op_private {
390     my $fh = shift;
391
392     my $header = <<'EOF';
393 @=head1 NAME
394 @
395 @B::Op_private -  OP op_private flag definitions
396 @
397 @=head1 SYNOPSIS
398 @
399 @    use B::Op_private;
400 @
401 @    # flag details for bit 7 of OP_AELEM's op_private:
402 @    my $name  = $B::Op_private::bits{aelem}{7}; # OPpLVAL_INTRO
403 @    my $value = $B::Op_private::defines{$name}; # 128
404 @    my $label = $B::Op_private::labels{$name};  # LVINTRO
405 @
406 @    # the bit field at bits 5..6 of OP_AELEM's op_private:
407 @    my $bf  = $B::Op_private::bits{aelem}{6};
408 @    my $mask = $bf->{bitmask}; # etc
409 @
410 @=head1 DESCRIPTION
411 @
412 @This module provides four global hashes:
413 @
414 @    %B::Op_private::bits
415 @    %B::Op_private::defines
416 @    %B::Op_private::labels
417 @    %B::Op_private::ops_using
418 @
419 @which contain information about the per-op meanings of the bits in the
420 @op_private field.
421 @
422 @=head2 C<%bits>
423 @
424 @This is indexed by op name and then bit number (0..7). For single bit flags,
425 @it returns the name of the define (if any) for that bit:
426 @
427 @   $B::Op_private::bits{aelem}{7} eq 'OPpLVAL_INTRO';
428 @
429 @For bit fields, it returns a hash ref containing details about the field.
430 @The same reference will be returned for all bit positions that make
431 @up the bit field; so for example these both return the same hash ref:
432 @
433 @    $bitfield = $B::Op_private::bits{aelem}{5};
434 @    $bitfield = $B::Op_private::bits{aelem}{6};
435 @
436 @The general format of this hash ref is
437 @
438 @    {
439 @        # The bit range and mask; these are always present.
440 @        bitmin        => 5,
441 @        bitmax        => 6,
442 @        bitmask       => 0x60,
443 @
444 @        # (The remaining keys are optional)
445 @
446 @        # The names of any defines that were requested:
447 @        mask_def      => 'OPpFOO_MASK',
448 @        baseshift_def => 'OPpFOO_SHIFT',
449 @        bitcount_def  => 'OPpFOO_BITS',
450 @
451 @        # If present, Concise etc will display the value with a 'FOO='
452 @        # prefix. If it equals '-', then Concise will treat the bit
453 @        # field as raw bits and not try to interpret it.
454 @        label         => 'FOO',
455 @
456 @        # If present, specifies the names of some defines and the
457 @        # display labels that are used to assign meaning to particu-
458 @        # lar integer values within the bit field; e.g. 3 is dis-
459 @        # played as 'C'.
460 @        enum          => [ qw(
461 @                             1   OPpFOO_A  A
462 @                             2   OPpFOO_B  B
463 @                             3   OPpFOO_C  C
464 @                         )],
465 @
466 @    };
467 @
468 @
469 @=head2 C<%defines>
470 @
471 @This gives the value of every C<OPp> define, e.g.
472 @
473 @    $B::Op_private::defines{OPpLVAL_INTRO} == 128;
474 @
475 @=head2 C<%labels>
476 @
477 @This gives the short display label for each define, as used by C<B::Concise>
478 @and C<perl -Dx>, e.g.
479 @
480 @    $B::Op_private::labels{OPpLVAL_INTRO} eq 'LVINTRO';
481 @
482 @If the label equals '-', then Concise will treat the bit as a raw bit and
483 @not try to display it symbolically.
484 @
485 @=head2 C<%ops_using>
486 @
487 @For each define, this gives a reference to an array of op names that use
488 @the flag.
489 @
490 @    @ops_using_lvintro = @{ $B::Op_private::ops_using{OPp_LVAL_INTRO} };
491 @
492 @=cut
493
494 package B::Op_private;
495
496 our %bits;
497
498 EOF
499     # remove podcheck.t-defeating leading char
500     $header =~ s/^\@//gm;
501     print $fh $header;
502     my $v = (::perl_version())[3];
503     print $fh qq{\nour \$VERSION = "$v";\n\n};
504
505     my %ops_using;
506
507     # for each flag/bit combination, find the ops which use it
508     my %combos;
509     for my $op (sort keys %FLAGS) {
510         my $entry = $FLAGS{$op};
511         for my $bit (0..7) {
512             my $e = $entry->{$bit};
513             next unless defined $e;
514             next if ref $e; # bit field, not flag
515             push @{$combos{$e}{$bit}}, $op;
516             push @{$ops_using{$e}}, $op;
517         }
518     }
519
520     # dump flags used by multiple ops
521     for my $flag (sort keys %combos) {
522         for my $bit (sort keys %{$combos{$flag}}) {
523             my $ops = $combos{$flag}{$bit};
524             next unless @$ops > 1;
525             my @o = sort @$ops;
526             print $fh "\$bits{\$_}{$bit} = '$flag' for qw(@o);\n";
527         }
528     }
529
530     # dump bit field definitions
531
532     my %bitfield_ix;
533     {
534         my %bitfields;
535         # stringified-ref to ref mapping
536         $bitfields{$_} = $_ for values %BITFIELDS;
537         my $ix = -1;
538         my $s = "\nmy \@bf = (\n";
539         for my $bitfield_key (sort keys %BITFIELDS) {
540             my $bitfield = $BITFIELDS{$bitfield_key};
541             $ix++;
542             $bitfield_ix{$bitfield} = $ix;
543
544             $s .= "    {\n";
545             for (qw(label mask_def baseshift_def bitcount_def)) {
546                 next unless defined $bitfield->{$_};
547                 $s .= sprintf "        %-9s => '%s',\n",
548                             $_,  $bitfield->{$_};
549             }
550             for (qw(bitmin bitmax bitmask)) {
551                 croak "panic" unless defined $bitfield->{$_};
552                 $s .= sprintf "        %-9s => %d,\n",
553                             $_,  $bitfield->{$_};
554             }
555             if (defined $bitfield->{enum}) {
556                 $s .= "        enum      => [\n";
557                 my @enum = @{$bitfield->{enum}};
558                 while (@enum) {
559                     my $i     = shift @enum;
560                     my $name  = shift @enum;
561                     my $label = shift @enum;
562                     $s .= sprintf "            %d, %-10s, %s,\n",
563                             $i, "'$name'", "'$label'";
564                 }
565                 $s .= "        ],\n";
566             }
567             $s .= "    },\n";
568
569         }
570         $s .= ");\n";
571         print $fh "$s\n";
572     }
573
574     # dump bitfields and remaining labels
575
576     for my $op (sort keys %FLAGS) {
577         my @indices;
578         my @vals;
579         my $entry = $FLAGS{$op};
580         my $bit;
581
582         for ($bit = 7; $bit >= 0; $bit--) {
583             next unless defined $entry->{$bit};
584             my $e = $entry->{$bit};
585             if (ref $e) {
586                 my $ix = $bitfield_ix{$e};
587                 for (reverse $e->{bitmin}..$e->{bitmax}) {
588                     push @indices,  $_;
589                     push @vals, "\$bf[$ix]";
590                 }
591                 $bit = $e->{bitmin};
592             }
593             else {
594                 next if @{$combos{$e}{$bit}} > 1;  # already output
595                 push @indices, $bit;
596                 push @vals, "'$e'";
597             }
598         }
599         if (@indices) {
600             my $s = '';
601             $s = '@{' if @indices > 1;
602             $s .= "\$bits{$op}";
603             $s .= '}' if @indices > 1;
604             $s .= '{' . join(',', @indices) . '} = ';
605             $s .= '(' if @indices > 1;
606             $s .= join ', ', @vals;
607             $s .= ')' if @indices > 1;
608             print $fh "$s;\n";
609         }
610     }
611
612     # populate %defines and %labels
613
614     print  $fh "\n\nour %defines = (\n";
615     printf $fh "    %-23s  => %3d,\n", $_ , $DEFINES{$_} for sort keys %DEFINES;
616     print  $fh ");\n\nour %labels = (\n";
617     printf $fh "    %-23s  => '%s',\n", $_ , $LABELS{$_}  for sort keys %LABELS;
618     print  $fh ");\n";
619
620     # %ops_using
621     print  $fh "\n\nour %ops_using = (\n";
622     # Save memory by using the same array wherever possible.
623     my %flag_by_op_list;
624     my $pending = '';
625     for my $flag (sort keys %ops_using) {
626         my $op_list = $ops_using{$flag} = "@{$ops_using{$flag}}";
627         if (!exists $flag_by_op_list{$op_list}) {
628             $flag_by_op_list{$op_list} = $flag;
629             printf $fh "    %-23s  => %s,\n", $flag , "[qw($op_list)]"
630         }
631         else {
632             $pending .= "\$ops_using{$flag} = "
633                       . "\$ops_using{$flag_by_op_list{$op_list}};\n";
634         }
635     }
636     print  $fh ");\n\n$pending";
637
638 }
639
640
641
642 # output the contents of the assorted PL_op_private_*[] tables
643
644 sub print_PL_op_private_tables {
645     my $fh = shift;
646
647     my $PL_op_private_labels     = '';
648     my $PL_op_private_valid      = '';
649     my $PL_op_private_bitdef_ix  = '';
650     my $PL_op_private_bitdefs    = '';
651     my $PL_op_private_bitfields  = '';
652
653     my %label_ix;
654     my %bitfield_ix;
655
656     # generate $PL_op_private_labels
657
658     {
659         my %labs;
660         $labs{$_} = 1 for values %LABELS; # de-duplicate labels
661         # add in bit field labels
662         for (values %BITFIELDS) {
663             next unless defined $_->{label};
664             $labs{$_->{label}} = 1;
665         }
666
667         my $labels = '';
668         for my $lab (sort keys %labs) {
669             $label_ix{$lab} = length $labels;
670             $labels .= "$lab\0";
671             $PL_op_private_labels .=
672                   "    "
673                 . join(',', map("'$_'", split //, $lab))
674                 . ",'\\0',\n";
675         }
676     }
677
678
679     # generate PL_op_private_bitfields
680
681     {
682         my %bitfields;
683         # stringified-ref to ref mapping
684         $bitfields{$_} = $_ for values %BITFIELDS;
685
686         my $ix = 0;
687         for my $bitfield_key (sort keys %BITFIELDS) {
688             my $bf = $BITFIELDS{$bitfield_key};
689             $bitfield_ix{$bf} = $ix;
690
691             my @b;
692             push @b, $bf->{bitmin},
693                 defined $bf->{label} ? $label_ix{$bf->{label}} : -1;
694             my $enum = $bf->{enum};
695             if (defined $enum) {
696                 my @enum = @$enum;
697                 while (@enum) {
698                     my $i     = shift @enum;
699                     my $name  = shift @enum;
700                     my $label = shift @enum;
701                     push @b, $i, $label_ix{$label};
702                 }
703             }
704             push @b, -1; # terminate enum list
705
706             $PL_op_private_bitfields .= "    " .  join(', ', @b) .",\n";
707             $ix += @b;
708         }
709     }
710
711
712     # generate PL_op_private_bitdefs, PL_op_private_bitdef_ix
713
714     {
715         my $bitdef_count = 0;
716
717         my %not_seen = %FLAGS;
718         my @seen_bitdefs;
719         my %seen_bitdefs;
720
721         my $opnum = -1;
722         for my $op (sort { $opnum{$a} <=> $opnum{$b} } keys %opnum) {
723             $opnum++;
724             die "panic: opnum misorder: opnum=$opnum opnum{op}=$opnum{$op}"
725                 unless $opnum == $opnum{$op};
726             delete $not_seen{$op};
727
728             my @bitdefs;
729             my $entry = $FLAGS{$op};
730             my $bit;
731             my $index;
732
733             for ($bit = 7; $bit >= 0; $bit--) {
734                 my $e = $entry->{$bit};
735                 next unless defined $e;
736
737                 my $ix;
738                 if (ref $e) {
739                     $ix = $bitfield_ix{$e};
740                     die "panic: \$bit =\= $e->{bitmax}"
741                         unless $bit == $e->{bitmax};
742
743                     push @bitdefs, ( ($ix << 5) | ($bit << 2) | 2 );
744                     $bit = $e->{bitmin};
745                 }
746                 else {
747                     $ix = $label_ix{$LABELS{$e}};
748                     die "panic: no label ix for '$e'" unless defined $ix;
749                     push @bitdefs, ( ($ix << 5) | ($bit << 2));
750                 }
751                 if ($ix > 2047) {
752                     die "Too many labels or bitfields (ix=$ix): "
753                     . "maybe the type of PL_op_private_bitdefs needs "
754                     . "expanding from U16 to U32???";
755                 }
756             }
757             if (@bitdefs) {
758                 $bitdefs[-1] |= 1; # stop bit
759                 my $key = join(', ', map(sprintf("0x%04x", $_), @bitdefs));
760                 if (!$seen_bitdefs{$key}) {
761                     $index = $bitdef_count;
762                     $bitdef_count += @bitdefs;
763                     push @seen_bitdefs,
764                          $seen_bitdefs{$key} = [$index, $key];
765                 }
766                 else {
767                     $index = $seen_bitdefs{$key}[0];
768                 }
769                 push @{$seen_bitdefs{$key}}, $op;
770             }
771             else {
772                 $index = -1;
773             }
774             $PL_op_private_bitdef_ix .= sprintf "    %4d, /* %s */\n", $index, $op;
775         }
776         if (%not_seen) {
777             die "panic: unprocessed ops: ". join(',', keys %not_seen);
778         }
779         for (@seen_bitdefs) {
780             local $" = ", ";
781             $PL_op_private_bitdefs .= "    $$_[1], /* @$_[2..$#$_] */\n";
782         }
783     }
784
785
786     # generate PL_op_private_valid
787
788     for my $op (@ops) {
789         my $last;
790         my @flags;
791         for my $bit (0..7) {
792             next unless exists $FLAGS{$op};
793             my $entry = $FLAGS{$op}{$bit};
794             next unless defined $entry;
795             if (ref $entry) {
796                 # skip later entries for the same bit field
797                 next if defined $last and $last == $entry;
798                 $last = $entry;
799                 push @flags,
800                     defined $entry->{mask_def}
801                         ? $entry->{mask_def}
802                         : $entry->{bitmask};
803             }
804             else {
805                 push @flags, $entry;
806             }
807         }
808
809         # all bets are off
810         @flags = '0xff' if $op eq 'null' or $op eq 'custom';
811
812         $PL_op_private_valid .= sprintf "    /* %-10s */ (%s),\n", uc($op),
813                                     @flags ? join('|', @flags): '0';
814     }
815
816     print $fh <<EOF;
817 START_EXTERN_C
818
819 #ifndef PERL_GLOBAL_STRUCT_INIT
820
821 #  ifndef DOINIT
822
823 /* data about the flags in op_private */
824
825 EXTCONST I16  PL_op_private_bitdef_ix[];
826 EXTCONST U16  PL_op_private_bitdefs[];
827 EXTCONST char PL_op_private_labels[];
828 EXTCONST I16  PL_op_private_bitfields[];
829 EXTCONST U8   PL_op_private_valid[];
830
831 #  else
832
833
834 /* PL_op_private_labels[]: the short descriptions of private flags.
835  * All labels are concatenated into a single char array
836  * (separated by \\0's) for compactness.
837  */
838
839 EXTCONST char PL_op_private_labels[] = {
840 $PL_op_private_labels
841 };
842
843
844
845 /* PL_op_private_bitfields[]: details about each bit field type.
846  * Each definition consists of the following list of words:
847  *    bitmin
848  *    label (index into PL_op_private_labels[]; -1 if no label)
849  *    repeat for each enum entry (if any):
850  *       enum value
851  *       enum label (index into PL_op_private_labels[])
852  *    -1
853  */
854
855 EXTCONST I16 PL_op_private_bitfields[] = {
856 $PL_op_private_bitfields
857 };
858
859
860 /* PL_op_private_bitdef_ix[]: map an op number to a starting position
861  * in PL_op_private_bitdefs.  If -1, the op has no bits defined */
862
863 EXTCONST I16  PL_op_private_bitdef_ix[] = {
864 $PL_op_private_bitdef_ix
865 };
866
867
868
869 /* PL_op_private_bitdefs[]: given a starting position in this array (as
870  * supplied by PL_op_private_bitdef_ix[]), each word (until a stop bit is
871  * seen) defines the meaning of a particular op_private bit for a
872  * particular op. Each word consists of:
873  *  bit  0:     stop bit: this is the last bit def for the current op
874  *  bit  1:     bitfield: if set, this defines a bit field rather than a flag
875  *  bits 2..4:  unsigned number in the range 0..7 which is the bit number
876  *  bits 5..15: unsigned number in the range 0..2047 which is an index
877  *              into PL_op_private_labels[]    (for a flag), or
878  *              into PL_op_private_bitfields[] (for a bit field)
879  */
880
881 EXTCONST U16  PL_op_private_bitdefs[] = {
882 $PL_op_private_bitdefs
883 };
884
885
886 /* PL_op_private_valid: for each op, indexed by op_type, indicate which
887  * flags bits in op_private are legal */
888
889 EXTCONST U8 PL_op_private_valid[] = {
890 $PL_op_private_valid
891 };
892
893 #  endif /* !DOINIT */
894 #endif /* !PERL_GLOBAL_STRUCT_INIT */
895
896 END_EXTERN_C
897
898
899 EOF
900
901 }
902
903
904 # =================================================================
905
906
907 package main;
908
909 # read regen/op_private data
910 #
911 # This file contains Perl code that builds up some data structures
912 # which define what bits in op_private have what meanings for each op.
913 # It populates %LABELS, %DEFINES, %FLAGS, %BITFIELDS.
914
915 require 'regen/op_private';
916
917 #use Data::Dumper;
918 #print Dumper \%LABELS, \%DEFINES, \%FLAGS, \%BITFIELDS;
919
920
921 # Emit defines.
922
923 print $oc    "#ifndef PERL_GLOBAL_STRUCT_INIT\n\n";
924
925 {
926     my $last_cond = '';
927     my @unimplemented;
928
929     sub unimplemented {
930         if (@unimplemented) {
931             print $oc "#else\n";
932             foreach (@unimplemented) {
933                 print $oc "#define $_ Perl_unimplemented_op\n";
934             }
935             print $oc "#endif\n";
936             @unimplemented = ();
937         }
938
939     }
940
941     for (@ops) {
942         my ($impl, $cond) = @{$alias{$_} || ["Perl_pp_$_", '']};
943         my $op_func = "Perl_pp_$_";
944
945         if ($cond ne $last_cond) {
946             # A change in condition. (including to or from no condition)
947             unimplemented();
948             $last_cond = $cond;
949             if ($last_cond) {
950                 print $oc "$last_cond\n";
951             }
952         }
953         push @unimplemented, $op_func if $last_cond;
954         print $oc "#define $op_func $impl\n" if $impl ne $op_func;
955     }
956     # If the last op was conditional, we need to close it out:
957     unimplemented();
958 }
959
960 print $on "typedef enum opcode {\n";
961
962 my $i = 0;
963 for (@ops) {
964       print $on "\t", tab(3,"OP_\U$_"), " = ", $i++, ",\n";
965 }
966 print $on "\t", tab(3,"OP_max"), "\n";
967 print $on "} opcode;\n";
968 print $on "\n#define MAXO ", scalar @ops, "\n";
969 print $on "#define OP_FREED MAXO\n";
970
971 # Emit op names and descriptions.
972
973 print $oc <<'END';
974 START_EXTERN_C
975
976 #ifndef DOINIT
977 EXTCONST char* const PL_op_name[];
978 #else
979 EXTCONST char* const PL_op_name[] = {
980 END
981
982 for (@ops) {
983     print $oc qq(\t"$_",\n);
984 }
985
986 print $oc <<'END';
987         "freed",
988 };
989 #endif
990
991 #ifndef DOINIT
992 EXTCONST char* const PL_op_desc[];
993 #else
994 EXTCONST char* const PL_op_desc[] = {
995 END
996
997 for (@ops) {
998     my($safe_desc) = $desc{$_};
999
1000     # Have to escape double quotes and escape characters.
1001     $safe_desc =~ s/([\\"])/\\$1/g;
1002
1003     print $oc qq(\t"$safe_desc",\n);
1004 }
1005
1006 print $oc <<'END';
1007         "freed op",
1008 };
1009 #endif
1010
1011 END_EXTERN_C
1012
1013 #endif /* !PERL_GLOBAL_STRUCT_INIT */
1014 END
1015
1016 # Emit ppcode switch array.
1017
1018 print $oc <<'END';
1019
1020 START_EXTERN_C
1021
1022 #ifdef PERL_GLOBAL_STRUCT_INIT
1023 #  define PERL_PPADDR_INITED
1024 static const Perl_ppaddr_t Gppaddr[]
1025 #else
1026 #  ifndef PERL_GLOBAL_STRUCT
1027 #    define PERL_PPADDR_INITED
1028 EXT Perl_ppaddr_t PL_ppaddr[] /* or perlvars.h */
1029 #  endif
1030 #endif /* PERL_GLOBAL_STRUCT */
1031 #if (defined(DOINIT) && !defined(PERL_GLOBAL_STRUCT)) || defined(PERL_GLOBAL_STRUCT_INIT)
1032 #  define PERL_PPADDR_INITED
1033 = {
1034 END
1035
1036 for (@ops) {
1037     my $op_func = "Perl_pp_$_";
1038     my $name = $alias{$_};
1039     if ($name && $name->[0] ne $op_func) {
1040         print $oc "\t$op_func,\t/* implemented by $name->[0] */\n";
1041     }
1042     else {
1043         print $oc "\t$op_func,\n";
1044     }
1045 }
1046
1047 print $oc <<'END';
1048 }
1049 #endif
1050 #ifdef PERL_PPADDR_INITED
1051 ;
1052 #endif
1053
1054 #ifdef PERL_GLOBAL_STRUCT_INIT
1055 #  define PERL_CHECK_INITED
1056 static const Perl_check_t Gcheck[]
1057 #else
1058 #  ifndef PERL_GLOBAL_STRUCT
1059 #    define PERL_CHECK_INITED
1060 EXT Perl_check_t PL_check[] /* or perlvars.h */
1061 #  endif
1062 #endif
1063 #if (defined(DOINIT) && !defined(PERL_GLOBAL_STRUCT)) || defined(PERL_GLOBAL_STRUCT_INIT)
1064 #  define PERL_CHECK_INITED
1065 = {
1066 END
1067
1068 for (@ops) {
1069     print $oc "\t", tab(3, "Perl_$check{$_},"), "\t/* $_ */\n";
1070 }
1071
1072 print $oc <<'END';
1073 }
1074 #endif
1075 #ifdef PERL_CHECK_INITED
1076 ;
1077 #endif /* #ifdef PERL_CHECK_INITED */
1078
1079 #ifndef PERL_GLOBAL_STRUCT_INIT
1080
1081 #ifndef DOINIT
1082 EXTCONST U32 PL_opargs[];
1083 #else
1084 EXTCONST U32 PL_opargs[] = {
1085 END
1086
1087 # Emit allowed argument types.
1088
1089 my $ARGBITS = 32;
1090
1091 my %argnum = (
1092     'S',  1,            # scalar
1093     'L',  2,            # list
1094     'A',  3,            # array value
1095     'H',  4,            # hash value
1096     'C',  5,            # code value
1097     'F',  6,            # file value
1098     'R',  7,            # scalar reference
1099 );
1100
1101 my %opclass = (
1102     '0',  0,            # baseop
1103     '1',  1,            # unop
1104     '2',  2,            # binop
1105     '|',  3,            # logop
1106     '@',  4,            # listop
1107     '/',  5,            # pmop
1108     '$',  6,            # svop_or_padop
1109     '#',  7,            # padop
1110     '"',  8,            # pvop_or_svop
1111     '{',  9,            # loop
1112     ';',  10,           # cop
1113     '%',  11,           # baseop_or_unop
1114     '-',  12,           # filestatop
1115     '}',  13,           # loopexop
1116     '.',  14,           # methop
1117     '+',  15,           # unop_aux
1118 );
1119
1120 my %opflags = (
1121     'm' =>   1,         # needs stack mark
1122     'f' =>   2,         # fold constants
1123     's' =>   4,         # always produces scalar
1124     't' =>   8,         # needs target scalar
1125     'T' =>   8 | 16,    # ... which may be lexical
1126     'i' =>   0,         # always produces integer (unused since e7311069)
1127     'I' =>  32,         # has corresponding int op
1128     'd' =>  64,         # danger, make temp copy in list assignment
1129     'u' => 128,         # defaults to $_
1130 );
1131
1132 my %OP_IS_SOCKET;       # /Fs/
1133 my %OP_IS_FILETEST;     # /F-/
1134 my %OP_IS_FT_ACCESS;    # /F-+/
1135 my %OP_IS_NUMCOMPARE;   # /S</
1136 my %OP_IS_DIRHOP;       # /Fd/
1137
1138 my $OCSHIFT = 8;
1139 my $OASHIFT = 12;
1140
1141 for my $op (@ops) {
1142     my $argsum = 0;
1143     my $flags = $flags{$op};
1144     for my $flag (keys %opflags) {
1145         if ($flags =~ s/$flag//) {
1146             die "Flag collision for '$op' ($flags{$op}, $flag)\n"
1147                 if $argsum & $opflags{$flag};
1148             $argsum |= $opflags{$flag};
1149         }
1150     }
1151     die qq[Opcode '$op' has no class indicator ($flags{$op} => $flags)\n]
1152         unless exists $opclass{$flags};
1153     $argsum |= $opclass{$flags} << $OCSHIFT;
1154     my $argshift = $OASHIFT;
1155     for my $arg (split(' ',$args{$op})) {
1156         if ($arg =~ s/^D//) {
1157             # handle 1st, just to put D 1st.
1158             $OP_IS_DIRHOP{$op}   = $opnum{$op};
1159         }
1160         if ($arg =~ /^F/) {
1161             # record opnums of these opnames
1162             $OP_IS_SOCKET{$op}   = $opnum{$op} if $arg =~ s/s//;
1163             $OP_IS_FILETEST{$op} = $opnum{$op} if $arg =~ s/-//;
1164             $OP_IS_FT_ACCESS{$op} = $opnum{$op} if $arg =~ s/\+//;
1165         }
1166         elsif ($arg =~ /^S</) {
1167             $OP_IS_NUMCOMPARE{$op} = $opnum{$op} if $arg =~ s/<//;
1168         }
1169         my $argnum = ($arg =~ s/\?//) ? 8 : 0;
1170         die "op = $op, arg = $arg\n"
1171             unless exists $argnum{$arg};
1172         $argnum += $argnum{$arg};
1173         die "Argument overflow for '$op'\n"
1174             if $argshift >= $ARGBITS ||
1175                $argnum > ((1 << ($ARGBITS - $argshift)) - 1);
1176         $argsum += $argnum << $argshift;
1177         $argshift += 4;
1178     }
1179     $argsum = sprintf("0x%08x", $argsum);
1180     print $oc "\t", tab(3, "$argsum,"), "/* $op */\n";
1181 }
1182
1183 print $oc <<'END';
1184 };
1185 #endif
1186
1187 #endif /* !PERL_GLOBAL_STRUCT_INIT */
1188
1189 END_EXTERN_C
1190 END
1191
1192 # Emit OP_IS_* macros
1193
1194 print $on <<'EO_OP_IS_COMMENT';
1195
1196 /* the OP_IS_* macros are optimized to a simple range check because
1197     all the member OPs are contiguous in regen/opcodes table.
1198     opcode.pl verifies the range contiguity, or generates an OR-equals
1199     expression */
1200 EO_OP_IS_COMMENT
1201
1202 gen_op_is_macro( \%OP_IS_SOCKET, 'OP_IS_SOCKET');
1203 gen_op_is_macro( \%OP_IS_FILETEST, 'OP_IS_FILETEST');
1204 gen_op_is_macro( \%OP_IS_FT_ACCESS, 'OP_IS_FILETEST_ACCESS');
1205 gen_op_is_macro( \%OP_IS_NUMCOMPARE, 'OP_IS_NUMCOMPARE');
1206 gen_op_is_macro( \%OP_IS_DIRHOP, 'OP_IS_DIRHOP');
1207
1208 sub gen_op_is_macro {
1209     my ($op_is, $macname) = @_;
1210     if (keys %$op_is) {
1211         
1212         # get opnames whose numbers are lowest and highest
1213         my ($first, @rest) = sort {
1214             $op_is->{$a} <=> $op_is->{$b}
1215         } keys %$op_is;
1216         
1217         my $last = pop @rest;   # @rest slurped, get its last
1218         die "Invalid range of ops: $first .. $last\n" unless $last;
1219
1220         print $on "\n#define $macname(op)       \\\n\t(";
1221
1222         # verify that op-ct matches 1st..last range (and fencepost)
1223         # (we know there are no dups)
1224         if ( $op_is->{$last} - $op_is->{$first} == scalar @rest + 1) {
1225             
1226             # contiguous ops -> optimized version
1227             print $on "(op) >= OP_" . uc($first)
1228                 . " && (op) <= OP_" . uc($last);
1229         }
1230         else {
1231             print $on join(" || \\\n\t ",
1232                            map { "(op) == OP_" . uc() } sort keys %$op_is);
1233         }
1234         print $on ")\n";
1235     }
1236 }
1237
1238 my $pp = open_new('pp_proto.h', '>',
1239                   { by => 'opcode.pl', from => 'its data' });
1240
1241 {
1242     my %funcs;
1243     for (@ops) {
1244         my $name = $alias{$_} ? $alias{$_}[0] : "Perl_pp_$_";
1245         ++$funcs{$name};
1246     }
1247     print $pp "PERL_CALLCONV OP *$_(pTHX);\n" foreach sort keys %funcs;
1248 }
1249
1250 print $oc "\n\n";
1251 OP_PRIVATE::print_defines($oc);
1252 OP_PRIVATE::print_PL_op_private_tables($oc);
1253
1254 OP_PRIVATE::print_B_Op_private($oprivpm);
1255
1256 foreach ($oc, $on, $pp, $oprivpm) {
1257     read_only_bottom_close_and_rename($_);
1258 }
1259