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