This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix ill-named Test::Harness test and bump version.
[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 #
9 # from information stored in regen/opcodes, plus the
10 # values hardcoded into this script in @raw_alias.
11 #
12 # Accepts the standard regen_lib -q and -v args.
13 #
14 # This script is normally invoked from regen.pl.
15
16 use strict;
17
18 BEGIN {
19     # Get function prototypes
20     require 'regen/regen_lib.pl';
21 }
22
23 my $oc = open_new('opcode.h', '>',
24                   {by => 'regen/opcode.pl', from => 'its data',
25                    file => 'opcode.h', style => '*',
26                    copyright => [1993 .. 2007]});
27
28 my $on = open_new('opnames.h', '>',
29                   { by => 'regen/opcode.pl', from => 'its data', style => '*',
30                     file => 'opnames.h', copyright => [1999 .. 2008] });
31
32 # Read data.
33
34 my %seen;
35 my (@ops, %desc, %check, %ckname, %flags, %args, %opnum);
36
37 open OPS, 'regen/opcodes' or die $!;
38
39 while (<OPS>) {
40     chop;
41     next unless $_;
42     next if /^#/;
43     my ($key, $desc, $check, $flags, $args) = split(/\t+/, $_, 5);
44     $args = '' unless defined $args;
45
46     warn qq[Description "$desc" duplicates $seen{$desc}\n]
47      if $seen{$desc} and $key ne "transr";
48     die qq[Opcode "$key" duplicates $seen{$key}\n] if $seen{$key};
49     die qq[Opcode "freed" is reserved for the slab allocator\n]
50         if $key eq 'freed';
51     $seen{$desc} = qq[description of opcode "$key"];
52     $seen{$key} = qq[opcode "$key"];
53
54     push(@ops, $key);
55     $opnum{$key} = $#ops;
56     $desc{$key} = $desc;
57     $check{$key} = $check;
58     $ckname{$check}++;
59     $flags{$key} = $flags;
60     $args{$key} = $args;
61 }
62
63 # Set up aliases
64
65 my %alias;
66
67 # Format is "this function" => "does these op names"
68 my @raw_alias = (
69                  Perl_do_kv => [qw( keys values )],
70                  Perl_unimplemented_op => [qw(padany mapstart custom)],
71                  # All the ops with a body of { return NORMAL; }
72                  Perl_pp_null => [qw(scalar regcmaybe lineseq scope)],
73
74                  Perl_pp_goto => ['dump'],
75                  Perl_pp_require => ['dofile'],
76                  Perl_pp_untie => ['dbmclose'],
77                  Perl_pp_sysread => {read => '', recv => '#ifdef HAS_SOCKET'},
78                  Perl_pp_sysseek => ['seek'],
79                  Perl_pp_ioctl => ['fcntl'],
80                  Perl_pp_ssockopt => {gsockopt => '#ifdef HAS_SOCKET'},
81                  Perl_pp_getpeername => {getsockname => '#ifdef HAS_SOCKET'},
82                  Perl_pp_stat => ['lstat'],
83                  Perl_pp_ftrowned => [qw(fteowned ftzero ftsock ftchr ftblk
84                                          ftfile ftdir ftpipe ftsuid ftsgid
85                                          ftsvtx)],
86                  Perl_pp_fttext => ['ftbinary'],
87                  Perl_pp_gmtime => ['localtime'],
88                  Perl_pp_semget => [qw(shmget msgget)],
89                  Perl_pp_semctl => [qw(shmctl msgctl)],
90                  Perl_pp_ghostent => [qw(ghbyname ghbyaddr)],
91                  Perl_pp_gnetent => [qw(gnbyname gnbyaddr)],
92                  Perl_pp_gprotoent => [qw(gpbyname gpbynumber)],
93                  Perl_pp_gservent => [qw(gsbyname gsbyport)],
94                  Perl_pp_gpwent => [qw(gpwnam gpwuid)],
95                  Perl_pp_ggrent => [qw(ggrnam ggrgid)],
96                  Perl_pp_ftis => [qw(ftsize ftmtime ftatime ftctime)],
97                  Perl_pp_chown => [qw(unlink chmod utime kill)],
98                  Perl_pp_link => ['symlink'],
99                  Perl_pp_ftrread => [qw(ftrwrite ftrexec fteread ftewrite
100                                         fteexec)],
101                  Perl_pp_shmwrite => [qw(shmread msgsnd msgrcv semop)],
102                  Perl_pp_syswrite => {send => '#ifdef HAS_SOCKET'},
103                  Perl_pp_defined => [qw(dor dorassign)],
104                  Perl_pp_and => ['andassign'],
105                  Perl_pp_or => ['orassign'],
106                  Perl_pp_ucfirst => ['lcfirst'],
107                  Perl_pp_sle => [qw(slt sgt sge)],
108                  Perl_pp_print => ['say'],
109                  Perl_pp_index => ['rindex'],
110                  Perl_pp_oct => ['hex'],
111                  Perl_pp_shift => ['pop'],
112                  Perl_pp_sin => [qw(cos exp log sqrt)],
113                  Perl_pp_bit_or => ['bit_xor'],
114                  Perl_pp_rv2av => ['rv2hv'],
115                  Perl_pp_akeys => ['avalues'],
116                  Perl_pp_rkeys => [qw(rvalues reach)],
117                  Perl_pp_trans => [qw(trans transr)],
118                  Perl_pp_chop => [qw(chop chomp)],
119                  Perl_pp_schop => [qw(schop schomp)],
120                  Perl_pp_bind => {connect => '#ifdef HAS_SOCKET'},
121                  Perl_pp_preinc => ['i_preinc', 'predec', 'i_predec'],
122                  Perl_pp_postinc => ['i_postinc', 'postdec', 'i_postdec'],
123                  Perl_pp_ehostent => [qw(enetent eprotoent eservent
124                                          spwent epwent sgrent egrent)],
125                  Perl_pp_shostent => [qw(snetent sprotoent sservent)],
126                  Perl_pp_aelemfast => ['aelemfast_lex'],
127                 );
128
129 while (my ($func, $names) = splice @raw_alias, 0, 2) {
130     if (ref $names eq 'ARRAY') {
131         foreach (@$names) {
132             $alias{$_} = [$func, ''];
133         }
134     } else {
135         while (my ($opname, $cond) = each %$names) {
136             $alias{$opname} = [$func, $cond];
137         }
138     }
139 }
140
141 foreach my $sock_func (qw(socket bind listen accept shutdown
142                           ssockopt getpeername)) {
143     $alias{$sock_func} = ["Perl_pp_$sock_func", '#ifdef HAS_SOCKET'],
144 }
145
146 # Emit defines.
147
148 print $oc    "#ifndef PERL_GLOBAL_STRUCT_INIT\n\n";
149
150 {
151     my $last_cond = '';
152     my @unimplemented;
153
154     sub unimplemented {
155         if (@unimplemented) {
156             print $oc "#else\n";
157             foreach (@unimplemented) {
158                 print $oc "#define $_ Perl_unimplemented_op\n";
159             }
160             print $oc "#endif\n";
161             @unimplemented = ();
162         }
163
164     }
165
166     for (@ops) {
167         my ($impl, $cond) = @{$alias{$_} || ["Perl_pp_$_", '']};
168         my $op_func = "Perl_pp_$_";
169
170         if ($cond ne $last_cond) {
171             # A change in condition. (including to or from no condition)
172             unimplemented();
173             $last_cond = $cond;
174             if ($last_cond) {
175                 print $oc "$last_cond\n";
176             }
177         }
178         push @unimplemented, $op_func if $last_cond;
179         print $oc "#define $op_func $impl\n" if $impl ne $op_func;
180     }
181     # If the last op was conditional, we need to close it out:
182     unimplemented();
183 }
184
185 print $on "typedef enum opcode {\n";
186
187 my $i = 0;
188 for (@ops) {
189       print $on "\t", tab(3,"OP_\U$_"), " = ", $i++, ",\n";
190 }
191 print $on "\t", tab(3,"OP_max"), "\n";
192 print $on "} opcode;\n";
193 print $on "\n#define MAXO ", scalar @ops, "\n";
194 print $on "#define OP_FREED MAXO\n";
195
196 # Emit op names and descriptions.
197
198 print $oc <<'END';
199 START_EXTERN_C
200
201 #ifndef DOINIT
202 EXTCONST char* const PL_op_name[];
203 #else
204 EXTCONST char* const PL_op_name[] = {
205 END
206
207 for (@ops) {
208     print $oc qq(\t"$_",\n);
209 }
210
211 print $oc <<'END';
212 };
213 #endif
214
215 #ifndef DOINIT
216 EXTCONST char* const PL_op_desc[];
217 #else
218 EXTCONST char* const PL_op_desc[] = {
219 END
220
221 for (@ops) {
222     my($safe_desc) = $desc{$_};
223
224     # Have to escape double quotes and escape characters.
225     $safe_desc =~ s/([\\"])/\\$1/g;
226
227     print $oc qq(\t"$safe_desc",\n);
228 }
229
230 print $oc <<'END';
231 };
232 #endif
233
234 END_EXTERN_C
235
236 #endif /* !PERL_GLOBAL_STRUCT_INIT */
237 END
238
239 # Emit ppcode switch array.
240
241 print $oc <<'END';
242
243 START_EXTERN_C
244
245 #ifdef PERL_GLOBAL_STRUCT_INIT
246 #  define PERL_PPADDR_INITED
247 static const Perl_ppaddr_t Gppaddr[]
248 #else
249 #  ifndef PERL_GLOBAL_STRUCT
250 #    define PERL_PPADDR_INITED
251 EXT Perl_ppaddr_t PL_ppaddr[] /* or perlvars.h */
252 #  endif
253 #endif /* PERL_GLOBAL_STRUCT */
254 #if (defined(DOINIT) && !defined(PERL_GLOBAL_STRUCT)) || defined(PERL_GLOBAL_STRUCT_INIT)
255 #  define PERL_PPADDR_INITED
256 = {
257 END
258
259 for (@ops) {
260     my $op_func = "Perl_pp_$_";
261     my $name = $alias{$_};
262     if ($name && $name->[0] ne $op_func) {
263         print $oc "\t$op_func,\t/* implemented by $name->[0] */\n";
264     }
265     else {
266         print $oc "\t$op_func,\n";
267     }
268 }
269
270 print $oc <<'END';
271 }
272 #endif
273 #ifdef PERL_PPADDR_INITED
274 ;
275 #endif
276
277 #ifdef PERL_GLOBAL_STRUCT_INIT
278 #  define PERL_CHECK_INITED
279 static const Perl_check_t Gcheck[]
280 #else
281 #  ifndef PERL_GLOBAL_STRUCT
282 #    define PERL_CHECK_INITED
283 EXT Perl_check_t PL_check[] /* or perlvars.h */
284 #  endif
285 #endif
286 #if (defined(DOINIT) && !defined(PERL_GLOBAL_STRUCT)) || defined(PERL_GLOBAL_STRUCT_INIT)
287 #  define PERL_CHECK_INITED
288 = {
289 END
290
291 for (@ops) {
292     print $oc "\t", tab(3, "Perl_$check{$_},"), "\t/* $_ */\n";
293 }
294
295 print $oc <<'END';
296 }
297 #endif
298 #ifdef PERL_CHECK_INITED
299 ;
300 #endif /* #ifdef PERL_CHECK_INITED */
301
302 #ifndef PERL_GLOBAL_STRUCT_INIT
303
304 #ifndef DOINIT
305 EXTCONST U32 PL_opargs[];
306 #else
307 EXTCONST U32 PL_opargs[] = {
308 END
309
310 # Emit allowed argument types.
311
312 my $ARGBITS = 32;
313
314 my %argnum = (
315     'S',  1,            # scalar
316     'L',  2,            # list
317     'A',  3,            # array value
318     'H',  4,            # hash value
319     'C',  5,            # code value
320     'F',  6,            # file value
321     'R',  7,            # scalar reference
322 );
323
324 my %opclass = (
325     '0',  0,            # baseop
326     '1',  1,            # unop
327     '2',  2,            # binop
328     '|',  3,            # logop
329     '@',  4,            # listop
330     '/',  5,            # pmop
331     '$',  6,            # svop_or_padop
332     '#',  7,            # padop
333     '"',  8,            # pvop_or_svop
334     '{',  9,            # loop
335     ';',  10,           # cop
336     '%',  11,           # baseop_or_unop
337     '-',  12,           # filestatop
338     '}',  13,           # loopexop
339 );
340
341 my %opflags = (
342     'm' =>   1,         # needs stack mark
343     'f' =>   2,         # fold constants
344     's' =>   4,         # always produces scalar
345     't' =>   8,         # needs target scalar
346     'T' =>   8 | 16,    # ... which may be lexical
347     'i' =>   0,         # always produces integer (unused since e7311069)
348     'I' =>  32,         # has corresponding int op
349     'd' =>  64,         # danger, unknown side effects
350     'u' => 128,         # defaults to $_
351 );
352
353 my %OP_IS_SOCKET;       # /Fs/
354 my %OP_IS_FILETEST;     # /F-/
355 my %OP_IS_FT_ACCESS;    # /F-+/
356 my %OP_IS_NUMCOMPARE;   # /S</
357 my %OP_IS_DIRHOP;       # /Fd/
358
359 my $OCSHIFT = 8;
360 my $OASHIFT = 12;
361
362 for my $op (@ops) {
363     my $argsum = 0;
364     my $flags = $flags{$op};
365     for my $flag (keys %opflags) {
366         if ($flags =~ s/$flag//) {
367             die "Flag collision for '$op' ($flags{$op}, $flag)\n"
368                 if $argsum & $opflags{$flag};
369             $argsum |= $opflags{$flag};
370         }
371     }
372     die qq[Opcode '$op' has no class indicator ($flags{$op} => $flags)\n]
373         unless exists $opclass{$flags};
374     $argsum |= $opclass{$flags} << $OCSHIFT;
375     my $argshift = $OASHIFT;
376     for my $arg (split(' ',$args{$op})) {
377         if ($arg =~ s/^D//) {
378             # handle 1st, just to put D 1st.
379             $OP_IS_DIRHOP{$op}   = $opnum{$op};
380         }
381         if ($arg =~ /^F/) {
382             # record opnums of these opnames
383             $OP_IS_SOCKET{$op}   = $opnum{$op} if $arg =~ s/s//;
384             $OP_IS_FILETEST{$op} = $opnum{$op} if $arg =~ s/-//;
385             $OP_IS_FT_ACCESS{$op} = $opnum{$op} if $arg =~ s/\+//;
386         }
387         elsif ($arg =~ /^S</) {
388             $OP_IS_NUMCOMPARE{$op} = $opnum{$op} if $arg =~ s/<//;
389         }
390         my $argnum = ($arg =~ s/\?//) ? 8 : 0;
391         die "op = $op, arg = $arg\n"
392             unless exists $argnum{$arg};
393         $argnum += $argnum{$arg};
394         die "Argument overflow for '$op'\n"
395             if $argshift >= $ARGBITS ||
396                $argnum > ((1 << ($ARGBITS - $argshift)) - 1);
397         $argsum += $argnum << $argshift;
398         $argshift += 4;
399     }
400     $argsum = sprintf("0x%08x", $argsum);
401     print $oc "\t", tab(3, "$argsum,"), "/* $op */\n";
402 }
403
404 print $oc <<'END';
405 };
406 #endif
407
408 #endif /* !PERL_GLOBAL_STRUCT_INIT */
409
410 END_EXTERN_C
411 END
412
413 # Emit OP_IS_* macros
414
415 print $on <<'EO_OP_IS_COMMENT';
416
417 /* the OP_IS_* macros are optimized to a simple range check because
418     all the member OPs are contiguous in regen/opcodes table.
419     opcode.pl verifies the range contiguity, or generates an OR-equals
420     expression */
421 EO_OP_IS_COMMENT
422
423 gen_op_is_macro( \%OP_IS_SOCKET, 'OP_IS_SOCKET');
424 gen_op_is_macro( \%OP_IS_FILETEST, 'OP_IS_FILETEST');
425 gen_op_is_macro( \%OP_IS_FT_ACCESS, 'OP_IS_FILETEST_ACCESS');
426 gen_op_is_macro( \%OP_IS_NUMCOMPARE, 'OP_IS_NUMCOMPARE');
427 gen_op_is_macro( \%OP_IS_DIRHOP, 'OP_IS_DIRHOP');
428
429 sub gen_op_is_macro {
430     my ($op_is, $macname) = @_;
431     if (keys %$op_is) {
432         
433         # get opnames whose numbers are lowest and highest
434         my ($first, @rest) = sort {
435             $op_is->{$a} <=> $op_is->{$b}
436         } keys %$op_is;
437         
438         my $last = pop @rest;   # @rest slurped, get its last
439         die "Invalid range of ops: $first .. $last\n" unless $last;
440
441         print $on "\n#define $macname(op)       \\\n\t(";
442
443         # verify that op-ct matches 1st..last range (and fencepost)
444         # (we know there are no dups)
445         if ( $op_is->{$last} - $op_is->{$first} == scalar @rest + 1) {
446             
447             # contiguous ops -> optimized version
448             print $on "(op) >= OP_" . uc($first)
449                 . " && (op) <= OP_" . uc($last);
450         }
451         else {
452             print $on join(" || \\\n\t ",
453                            map { "(op) == OP_" . uc() } sort keys %$op_is);
454         }
455         print $on ")\n";
456     }
457 }
458
459 my $pp = open_new('pp_proto.h', '>',
460                   { by => 'opcode.pl', from => 'its data' });
461
462 {
463     my %funcs;
464     for (@ops) {
465         my $name = $alias{$_} ? $alias{$_}[0] : "Perl_pp_$_";
466         ++$funcs{$name};
467     }
468     print $pp "PERL_CALLCONV OP *$_(pTHX);\n" foreach sort keys %funcs;
469 }
470 foreach ($oc, $on, $pp) {
471     read_only_bottom_close_and_rename($_);
472 }
473
474 # Some comments about 'T' opcode classifier:
475
476 # Safe to set if the ppcode uses:
477 #       tryAMAGICbin, tryAMAGICun, SETn, SETi, SETu, PUSHn, PUSHTARG, SETTARG,
478 #       SETs(TARG), XPUSHn, XPUSHu,
479
480 # Unsafe to set if the ppcode uses dTARG or [X]RETPUSH[YES|NO|UNDEF]
481
482 # lt and friends do SETs (including ncmp, but not scmp)
483
484 # Additional mode of failure: the opcode can modify TARG before it "used"
485 # all the arguments (or may call an external function which does the same).
486 # If the target coincides with one of the arguments ==> kaboom.
487
488 # pp.c  pos substr each not OK (RETPUSHUNDEF)
489 #       substr vec also not OK due to LV to target (are they???)
490 #       ref not OK (RETPUSHNO)
491 #       trans not OK (dTARG; TARG = sv_newmortal();)
492 #       ucfirst etc not OK: TMP arg processed inplace
493 #       quotemeta not OK (unsafe when TARG == arg)
494 #       each repeat not OK too due to list context
495 #       pack split - unknown whether they are safe
496 #       sprintf: is calling do_sprintf(TARG,...) which can act on TARG
497 #         before other args are processed.
498
499 #       Suspicious wrt "additional mode of failure" (and only it):
500 #       schop, chop, postinc/dec, bit_and etc, negate, complement.
501
502 #       Also suspicious: 4-arg substr, sprintf, uc/lc (POK_only), reverse, pack.
503
504 #       substr/vec: doing TAINT_off()???
505
506 # pp_hot.c
507 #       readline - unknown whether it is safe
508 #       match subst not OK (dTARG)
509 #       grepwhile not OK (not always setting)
510 #       join not OK (unsafe when TARG == arg)
511
512 #       Suspicious wrt "additional mode of failure": concat (dealt with
513 #       in ck_sassign()), join (same).
514
515 # pp_ctl.c
516 #       mapwhile flip caller not OK (not always setting)
517
518 # pp_sys.c
519 #       backtick glob warn die not OK (not always setting)
520 #       warn not OK (RETPUSHYES)
521 #       open fileno getc sysread syswrite ioctl accept shutdown
522 #        ftsize(etc) readlink telldir fork alarm getlogin not OK (RETPUSHUNDEF)
523 #       umask select not OK (XPUSHs(&PL_sv_undef);)
524 #       fileno getc sysread syswrite tell not OK (meth("FILENO" "GETC"))
525 #       sselect shm* sem* msg* syscall - unknown whether they are safe
526 #       gmtime not OK (list context)
527
528 #       Suspicious wrt "additional mode of failure": warn, die, select.