3 # Copyright (c) 1996, 1997, 1998 Malcolm Beattie
5 # You may distribute under the terms of either the GNU General Public
6 # License or the Artistic License, as specified in the README file.
12 @B::ISA = qw(Exporter);
14 # walkoptree_slow comes from B.pm (you are there),
15 # walkoptree comes from B.xs
20 @B::EXPORT_OK = qw(minus_c ppname save_BEGINs
21 class peekop cast_I32 cstring cchar hash threadsv_names
22 main_root main_start main_cv svref_2object opnumber
23 sub_generation amagic_generation perlstring
24 walkoptree_slow walkoptree walkoptree_exec walksymtable
25 parents comppadlist sv_undef compile_stats timing_info
26 begin_av init_av check_av end_av regex_padav dowarn
27 defstash curstash warnhook diehook inc_gv @optype
30 push @B::EXPORT_OK, qw(unitcheck_av) if $] > 5.009;
32 # All the above in this BEGIN, because our BOOT code needs $VERSION set,
33 # and will append to @EXPORT_OK. And we need to run the BOOT code before
34 # we see OPf_KIDS below.
39 @B::SV::ISA = 'B::OBJECT';
40 @B::NULL::ISA = 'B::SV';
41 @B::PV::ISA = 'B::SV';
42 @B::IV::ISA = 'B::SV';
43 @B::NV::ISA = 'B::SV';
44 # RV is eliminated with 5.11.0, but effectively is a specialisation of IV now.
45 @B::RV::ISA = $] >= 5.011 ? 'B::IV' : 'B::SV';
46 @B::PVIV::ISA = qw(B::PV B::IV);
47 @B::PVNV::ISA = qw(B::PVIV B::NV);
48 @B::PVMG::ISA = 'B::PVNV';
49 @B::REGEXP::ISA = 'B::PVMG' if $] >= 5.011;
50 # Change in the inheritance hierarchy post 5.9.0
51 @B::PVLV::ISA = $] > 5.009 ? 'B::GV' : 'B::PVMG';
52 # BM is eliminated post 5.9.5, but effectively is a specialisation of GV now.
53 @B::BM::ISA = $] > 5.009005 ? 'B::GV' : 'B::PVMG';
54 @B::AV::ISA = 'B::PVMG';
55 @B::GV::ISA = 'B::PVMG';
56 @B::HV::ISA = 'B::PVMG';
57 @B::CV::ISA = 'B::PVMG';
58 @B::IO::ISA = 'B::PVMG';
59 @B::FM::ISA = 'B::CV';
61 @B::OP::ISA = 'B::OBJECT';
62 @B::UNOP::ISA = 'B::OP';
63 @B::BINOP::ISA = 'B::UNOP';
64 @B::LOGOP::ISA = 'B::UNOP';
65 @B::LISTOP::ISA = 'B::BINOP';
66 @B::SVOP::ISA = 'B::OP';
67 @B::PADOP::ISA = 'B::OP';
68 @B::PVOP::ISA = 'B::OP';
69 @B::LOOP::ISA = 'B::LISTOP';
70 @B::PMOP::ISA = 'B::LISTOP';
71 @B::COP::ISA = 'B::OP';
73 @B::SPECIAL::ISA = 'B::OBJECT';
75 @B::optype = qw(OP UNOP BINOP LOGOP LISTOP PMOP SVOP PADOP PVOP LOOP COP);
76 # bytecode.pl contained the following comment:
77 # Nullsv *must* come first in the following so that the condition
78 # ($$sv == 0) can continue to be used to test (sv == Nullsv).
79 @B::specialsv_name = qw(Nullsv &PL_sv_undef &PL_sv_yes &PL_sv_no
80 (SV*)pWARN_ALL (SV*)pWARN_NONE (SV*)pWARN_STD);
83 # Stop "-w" from complaining about the lack of a real B::OBJECT class
88 my $name = (shift())->NAME;
90 # The regex below corresponds to the isCONTROLVAR macro
93 $name =~ s/^([\cA-\cZ\c\\c[\c]\c?\c_\c^])/"^".
94 chr( utf8::unicode_to_native( 64 ^ ord($1) ))/e;
96 # When we say unicode_to_native we really mean ascii_to_native,
97 # which matters iff this is a non-ASCII platform (EBCDIC).
102 sub B::IV::int_value {
104 return (($self->FLAGS() & SVf_IVisUV()) ? $self->UVX : $self->IV);
107 sub B::NULL::as_string() {""}
108 *B::IV::as_string = \*B::IV::int_value;
109 *B::PV::as_string = \*B::PV::PV;
111 # The input typemap checking makes no distinction between different SV types,
112 # so the XS body will generate the same C code, despite the different XS
113 # "types". So there is no change in behaviour from doing "newXS" like this,
114 # compared with the old approach of having a (near) duplicate XS body.
115 # We should fix the typemap checking.
116 *B::IV::RV = \*B::PV::RV if $] > 5.012;
123 my ($class, $value) = @_;
125 walkoptree_debug($value);
135 sub parents { \@parents }
140 return sprintf("%s (0x%x) %s", class($op), $$op, $op->name);
143 sub walkoptree_slow {
144 my($op, $method, $level) = @_;
145 $op_count++; # just for statistics
147 warn(sprintf("walkoptree: %d. %s\n", $level, peekop($op))) if $debug;
148 $op->$method($level) if $op->can($method);
149 if ($$op && ($op->flags & OPf_KIDS)) {
151 unshift(@parents, $op);
152 for ($kid = $op->first; $$kid; $kid = $kid->sibling) {
153 walkoptree_slow($kid, $method, $level + 1);
157 if (class($op) eq 'PMOP'
158 && ref($op->pmreplroot)
159 && ${$op->pmreplroot}
160 && $op->pmreplroot->isa( 'B::OP' ))
162 unshift(@parents, $op);
163 walkoptree_slow($op->pmreplroot, $method, $level + 1);
169 return "Total number of OPs processed: $op_count\n";
173 my ($sec, $min, $hr) = localtime;
174 my ($user, $sys) = times;
175 sprintf("%02d:%02d:%02d user=$user sys=$sys",
176 $hr, $min, $sec, $user, $sys);
186 my ($obj, $value) = @_;
187 # warn(sprintf("savesym: sym_%x => %s\n", $$obj, $value)); # debug
188 $symtable{sprintf("sym_%x", $$obj)} = $value;
193 return $symtable{sprintf("sym_%x", $$obj)};
196 sub walkoptree_exec {
197 my ($op, $method, $level) = @_;
200 my $prefix = " " x $level;
201 for (; $$op; $op = $op->next) {
204 print $prefix, "goto $sym\n";
207 savesym($op, sprintf("%s (0x%lx)", class($op), $$op));
208 $op->$method($level);
211 /^(d?or(assign)?|and(assign)?|mapwhile|grepwhile|entertry|range|cond_expr)$/)
213 print $prefix, uc($1), " => {\n";
214 walkoptree_exec($op->other, $method, $level + 1);
215 print $prefix, "}\n";
216 } elsif ($ppname eq "match" || $ppname eq "subst") {
217 my $pmreplstart = $op->pmreplstart;
219 print $prefix, "PMREPLSTART => {\n";
220 walkoptree_exec($pmreplstart, $method, $level + 1);
221 print $prefix, "}\n";
223 } elsif ($ppname eq "substcont") {
224 print $prefix, "SUBSTCONT => {\n";
225 walkoptree_exec($op->other->pmreplstart, $method, $level + 1);
226 print $prefix, "}\n";
228 } elsif ($ppname eq "enterloop") {
229 print $prefix, "REDO => {\n";
230 walkoptree_exec($op->redoop, $method, $level + 1);
231 print $prefix, "}\n", $prefix, "NEXT => {\n";
232 walkoptree_exec($op->nextop, $method, $level + 1);
233 print $prefix, "}\n", $prefix, "LAST => {\n";
234 walkoptree_exec($op->lastop, $method, $level + 1);
235 print $prefix, "}\n";
236 } elsif ($ppname eq "subst") {
237 my $replstart = $op->pmreplstart;
239 print $prefix, "SUBST => {\n";
240 walkoptree_exec($replstart, $method, $level + 1);
241 print $prefix, "}\n";
248 my ($symref, $method, $recurse, $prefix) = @_;
253 $prefix = '' unless defined $prefix;
254 while (($sym, $ref) = each %$symref) {
255 $fullname = "*main::".$prefix.$sym;
257 $sym = $prefix . $sym;
258 if (svref_2object(\*$sym)->NAME ne "main::" && $sym ne "<none>::" && &$recurse($sym)) {
259 walksymtable(\%$fullname, $method, $recurse, $sym);
262 svref_2object(\*$fullname)->$method();
273 my ($class, $section, $symtable, $default) = @_;
274 $output_fh ||= FileHandle->new_tmpfile;
275 my $obj = bless [-1, $section, $symtable, $default], $class;
276 $sections{$section} = $obj;
281 my ($class, $section) = @_;
282 return $sections{$section};
287 while (defined($_ = shift)) {
288 print $output_fh "$section->[1]\t$_\n";
295 return $section->[0];
300 return $section->[1];
305 return $section->[2];
310 return $section->[3];
314 my ($section, $fh, $format) = @_;
315 my $name = $section->name;
316 my $sym = $section->symtable || {};
317 my $default = $section->default;
319 seek($output_fh, 0, 0);
320 while (<$output_fh>) {
325 exists($sym->{$1}) ? $sym->{$1} : $default;
327 printf $fh $format, $_;
339 B - The Perl Compiler Backend
347 The C<B> module supplies classes which allow a Perl program to delve
348 into its own innards. It is the module used to implement the
349 "backends" of the Perl compiler. Usage of the compiler does not
350 require knowledge of this module: see the F<O> module for the
351 user-visible part. The C<B> module is of use to those who want to
352 write new compiler backends. This documentation assumes that the
353 reader knows a fair amount about perl's internals including such
354 things as SVs, OPs and the internal symbol table and syntax tree
359 The C<B> module contains a set of utility functions for querying the
360 current state of the Perl interpreter; typically these functions
361 return objects from the B::SV and B::OP classes, or their derived
362 classes. These classes in turn define methods for querying the
363 resulting objects about their own internal state.
365 =head1 Utility Functions
367 The C<B> module exports a variety of functions: some are simple
368 utility functions, others provide a Perl program with a way to
369 get an initial "handle" on an internal object.
371 =head2 Functions Returning C<B::SV>, C<B::AV>, C<B::HV>, and C<B::CV> objects
373 For descriptions of the class hierarchy of these objects and the
374 methods that can be called on them, see below, L<"OVERVIEW OF
375 CLASSES"> and L<"SV-RELATED CLASSES">.
381 Returns the SV object corresponding to the C variable C<sv_undef>.
385 Returns the SV object corresponding to the C variable C<sv_yes>.
389 Returns the SV object corresponding to the C variable C<sv_no>.
391 =item svref_2object(SVREF)
393 Takes a reference to any Perl value, and turns the referred-to value
394 into an object in the appropriate B::OP-derived or B::SV-derived
395 class. Apart from functions such as C<main_root>, this is the primary
396 way to get an initial "handle" on an internal perl data structure
397 which can then be followed with the other access methods.
399 The returned object will only be valid as long as the underlying OPs
400 and SVs continue to exist. Do not attempt to use the object after the
401 underlying structures are freed.
403 =item amagic_generation
405 Returns the SV object corresponding to the C variable C<amagic_generation>.
409 Returns the AV object (i.e. in class B::AV) representing INIT blocks.
413 Returns the AV object (i.e. in class B::AV) representing CHECK blocks.
417 Returns the AV object (i.e. in class B::AV) representing UNITCHECK blocks.
421 Returns the AV object (i.e. in class B::AV) representing BEGIN blocks.
425 Returns the AV object (i.e. in class B::AV) representing END blocks.
429 Returns the AV object (i.e. in class B::AV) of the global comppadlist.
433 Only when perl was compiled with ithreads.
437 Return the (faked) CV corresponding to the main part of the Perl
442 =head2 Functions for Examining the Symbol Table
446 =item walksymtable(SYMREF, METHOD, RECURSE, PREFIX)
448 Walk the symbol table starting at SYMREF and call METHOD on each
449 symbol (a B::GV object) visited. When the walk reaches package
450 symbols (such as "Foo::") it invokes RECURSE, passing in the symbol
451 name, and only recurses into the package if that sub returns true.
453 PREFIX is the name of the SYMREF you're walking.
457 # Walk CGI's symbol table calling print_subs on each symbol.
458 # Recurse only into CGI::Util::
459 walksymtable(\%CGI::, 'print_subs', sub { $_[0] eq 'CGI::Util::' },
462 print_subs() is a B::GV method you have declared. Also see L<"B::GV
467 =head2 Functions Returning C<B::OP> objects or for walking op trees
469 For descriptions of the class hierarchy of these objects and the
470 methods that can be called on them, see below, L<"OVERVIEW OF
471 CLASSES"> and L<"OP-RELATED CLASSES">.
477 Returns the root op (i.e. an object in the appropriate B::OP-derived
478 class) of the main part of the Perl program.
482 Returns the starting op of the main part of the Perl program.
484 =item walkoptree(OP, METHOD)
486 Does a tree-walk of the syntax tree based at OP and calls METHOD on
487 each op it visits. Each node is visited before its children. If
488 C<walkoptree_debug> (see below) has been called to turn debugging on then
489 the method C<walkoptree_debug> is called on each op before METHOD is
492 =item walkoptree_debug(DEBUG)
494 Returns the current debugging flag for C<walkoptree>. If the optional
495 DEBUG argument is non-zero, it sets the debugging flag to that. See
496 the description of C<walkoptree> above for what the debugging flag
501 =head2 Miscellaneous Utility Functions
507 Return the PP function name (e.g. "pp_add") of op number OPNUM.
511 Returns a string in the form "0x..." representing the value of the
512 internal hash function used by perl on string STR.
516 Casts I to the internal I32 type used by that perl.
520 Does the equivalent of the C<-c> command-line option. Obviously, this
521 is only useful in a BEGIN block or else the flag is set too late.
525 Returns a double-quote-surrounded escaped version of STR which can
526 be used as a string in C source code.
528 =item perlstring(STR)
530 Returns a double-quote-surrounded escaped version of STR which can
531 be used as a string in Perl source code.
535 Returns the class of an object without the part of the classname
536 preceding the first C<"::">. This is used to turn C<"B::UNOP"> into
537 C<"UNOP"> for example.
541 In a perl compiled for threads, this returns a list of the special
542 per-thread threadsv variables.
546 =head2 Exported utility variables
552 my $op_type = $optype[$op_type_num];
554 A simple mapping of the op type number to its type (like 'COP' or 'BINOP').
556 =item @specialsv_name
558 my $sv_name = $specialsv_name[$sv_index];
560 Certain SV types are considered 'special'. They're represented by
561 B::SPECIAL and are referred to by a number from the specialsv_list.
562 This array maps that number back to the name of the SV (like 'Nullsv'
568 =head1 OVERVIEW OF CLASSES
570 The C structures used by Perl's internals to hold SV and OP
571 information (PVIV, AV, HV, ..., OP, SVOP, UNOP, ...) are modelled on a
572 class hierarchy and the C<B> module gives access to them via a true
573 object hierarchy. Structure fields which point to other objects
574 (whether types of SV or types of OP) are represented by the C<B>
575 module as Perl objects of the appropriate class.
577 The bulk of the C<B> module is the methods for accessing fields of
580 Note that all access is read-only. You cannot modify the internals by
581 using this module. Also, note that the B::OP and B::SV objects created
582 by this module are only valid for as long as the underlying objects
583 exist; their creation doesn't increase the reference counts of the
584 underlying objects. Trying to access the fields of a freed object will
585 give incomprehensible results, or worse.
587 =head2 SV-RELATED CLASSES
589 B::IV, B::NV, B::RV, B::PV, B::PVIV, B::PVNV, B::PVMG, B::BM (5.9.5 and
590 earlier), B::PVLV, B::AV, B::HV, B::CV, B::GV, B::FM, B::IO. These classes
591 correspond in the obvious way to the underlying C structures of similar names.
592 The inheritance hierarchy mimics the underlying C "inheritance". For the
593 5.10.x branch, (I<ie> 5.10.0, 5.10.1 I<etc>) this is:
597 +------------+------------+------------+
599 B::PV B::IV B::NV B::RV
611 +-----+-----+-----+-----+
613 B::AV B::GV B::HV B::CV B::IO
618 For 5.9.0 and earlier, PVLV is a direct subclass of PVMG, and BM is still
619 present as a distinct type, so the base of this diagram is
626 +------+-----+-----+-----+-----+-----+
628 B::PVLV B::BM B::AV B::GV B::HV B::CV B::IO
633 For 5.11.0 and later, B::RV is abolished, and IVs can be used to store
634 references, and a new type B::REGEXP is introduced, giving this structure:
638 +------------+------------+
652 +-------+-------+---+---+-------+-------+
654 B::AV B::GV B::HV B::CV B::IO B::REGEXP
660 Access methods correspond to the underlying C macros for field access,
661 usually with the leading "class indication" prefix removed (Sv, Av,
662 Hv, ...). The leading prefix is only left in cases where its removal
663 would cause a clash in method name. For example, C<GvREFCNT> stays
664 as-is since its abbreviation would clash with the "superclass" method
665 C<REFCNT> (corresponding to the C function C<SvREFCNT>).
677 Returns a reference to the regular scalar corresponding to this
678 B::SV object. In other words, this method is the inverse operation
679 to the svref_2object() subroutine. This scalar and other data it points
680 at should be considered read-only: modifying them is neither safe nor
681 guaranteed to have a sensible effect.
691 Returns the value of the IV, I<interpreted as
692 a signed integer>. This will be misleading
693 if C<FLAGS & SVf_IVisUV>. Perhaps you want the
694 C<int_value> method instead?
702 This method returns the value of the IV as an integer.
703 It differs from C<IV> in that it returns the correct
704 value regardless of whether it's stored signed or
737 This method is the one you usually want. It constructs a
738 string using the length and offset information in the struct:
739 for ordinary scalars it will return the string that you'd see
740 from Perl, even if it contains null characters.
744 Same as B::RV::RV, except that it will die() if the PV isn't
749 This method is less often useful. It assumes that the string
750 stored in the struct is null-terminated, and disregards the
753 It is the appropriate method to use if you need to get the name
754 of a lexical variable from a padname array. Lexical variable names
755 are always stored with a null terminator, and the length field
756 (SvCUR) is overloaded for other purposes and can't be relied on here.
760 =head2 B::PVMG Methods
770 =head2 B::MAGIC Methods
778 Only valid on r-magic, returns the string that generated the regexp.
788 Will die() if called on r-magic.
794 Only valid on r-magic, returns the integer value of the REGEX stored
799 =head2 B::PVLV Methods
833 This method returns TRUE if the GP field of the GV is NULL.
839 This method returns the name of the glob, but if the first
840 character of the name is a control character, then it converts
841 it to ^X first, so that *^G would return "^G" rather than "\cG".
843 It's useful if you want to print out the name of a variable.
844 If you restrict yourself to globs which exist at compile-time
845 then the result ought to be unambiguous, because code like
846 C<${"^G"} = 1> is compiled as two ops - a constant string and
847 a dereference (rv2gv) - so that the glob is created at runtime.
849 If you're working with globs at runtime, and need to disambiguate
850 *^G from *{"^G"}, then you should use the raw NAME method.
914 Takes one arguments ( 'stdin' | 'stdout' | 'stderr' ) and returns true
915 if the IoIFP of the object is equal to the handle whose name was
916 passed as argument ( i.e. $io->IsSTD('stderr') is true if
917 IoIFP($io) == PerlIO_stdin() ).
933 Like C<ARRAY>, but takes an index as an argument to get only one element,
934 rather than a list of all of them.
938 This method is deprecated if running under Perl 5.8, and is no longer present
939 if running under Perl 5.9
943 This method returns the AV specific flags. In Perl 5.9 these are now stored
944 in with the main SV flags, so this method is no longer present.
974 For constant subroutines, returns the constant SV returned by the subroutine.
1000 This method is not present if running under Perl 5.9, as the PMROOT
1001 information is no longer stored directly in the hash.
1005 =head2 OP-RELATED CLASSES
1007 C<B::OP>, C<B::UNOP>, C<B::BINOP>, C<B::LOGOP>, C<B::LISTOP>, C<B::PMOP>,
1008 C<B::SVOP>, C<B::PADOP>, C<B::PVOP>, C<B::LOOP>, C<B::COP>.
1010 These classes correspond in the obvious way to the underlying C
1011 structures of similar names. The inheritance hierarchy mimics the
1012 underlying C "inheritance":
1016 +---------------+--------+--------+-------+
1018 B::UNOP B::SVOP B::PADOP B::COP B::PVOP
1029 Access methods correspond to the underlying C structre field names,
1030 with the leading "class indication" prefix (C<"op_">) removed.
1032 =head2 B::OP Methods
1034 These methods get the values of similarly named fields within the OP
1035 data structure. See top of C<op.h> for more info.
1045 This returns the op name as a string (e.g. "add", "rv2av").
1049 This returns the function name as a string (e.g. "PL_ppaddr[OP_ADD]",
1050 "PL_ppaddr[OP_RV2AV]").
1054 This returns the op description from the global C PL_op_desc array
1055 (e.g. "addition" "array deref").
1071 =head2 B::UNOP METHOD
1079 =head2 B::BINOP METHOD
1087 =head2 B::LOGOP METHOD
1095 =head2 B::LISTOP METHOD
1103 =head2 B::PMOP Methods
1113 Only up to Perl 5.9.4
1125 Only when perl was compiled with ithreads.
1129 =head2 B::SVOP METHOD
1139 =head2 B::PADOP METHOD
1147 =head2 B::PVOP METHOD
1155 =head2 B::LOOP Methods
1167 =head2 B::COP Methods
1198 Malcolm Beattie, C<mbeattie@sable.ox.ac.uk>