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