Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1749 lines
47 KiB

  1. # CC.pm
  2. #
  3. # Copyright (c) 1996, 1997, 1998 Malcolm Beattie
  4. #
  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.
  7. #
  8. package B::CC;
  9. use strict;
  10. use B qw(main_start main_root class comppadlist peekop svref_2object
  11. timing_info);
  12. use B::C qw(save_unused_subs objsym init_sections
  13. output_all output_boilerplate output_main);
  14. use B::Bblock qw(find_leaders);
  15. use B::Stackobj qw(:types :flags);
  16. # These should probably be elsewhere
  17. # Flags for $op->flags
  18. sub OPf_LIST () { 1 }
  19. sub OPf_KNOW () { 2 }
  20. sub OPf_MOD () { 32 }
  21. sub OPf_STACKED () { 64 }
  22. sub OPf_SPECIAL () { 128 }
  23. # op-specific flags for $op->private
  24. sub OPpASSIGN_BACKWARDS () { 64 }
  25. sub OPpLVAL_INTRO () { 128 }
  26. sub OPpDEREF_AV () { 32 }
  27. sub OPpDEREF_HV () { 64 }
  28. sub OPpDEREF () { OPpDEREF_AV|OPpDEREF_HV }
  29. sub OPpFLIP_LINENUM () { 64 }
  30. sub G_ARRAY () { 1 }
  31. # cop.h
  32. sub CXt_NULL () { 0 }
  33. sub CXt_SUB () { 1 }
  34. sub CXt_EVAL () { 2 }
  35. sub CXt_LOOP () { 3 }
  36. sub CXt_SUBST () { 4 }
  37. sub CXt_BLOCK () { 5 }
  38. my $module; # module name (when compiled with -m)
  39. my %done; # hash keyed by $$op of leaders of basic blocks
  40. # which have already been done.
  41. my $leaders; # ref to hash of basic block leaders. Keys are $$op
  42. # addresses, values are the $op objects themselves.
  43. my @bblock_todo; # list of leaders of basic blocks that need visiting
  44. # sometime.
  45. my @cc_todo; # list of tuples defining what PP code needs to be
  46. # saved (e.g. CV, main or PMOP repl code). Each tuple
  47. # is [$name, $root, $start, @padlist]. PMOP repl code
  48. # tuples inherit padlist.
  49. my @stack; # shadows perl's stack when contents are known.
  50. # Values are objects derived from class B::Stackobj
  51. my @pad; # Lexicals in current pad as Stackobj-derived objects
  52. my @padlist; # Copy of current padlist so PMOP repl code can find it
  53. my @cxstack; # Shadows the (compile-time) cxstack for next,last,redo
  54. my $jmpbuf_ix = 0; # Next free index for dynamically allocated jmpbufs
  55. my %constobj; # OP_CONST constants as Stackobj-derived objects
  56. # keyed by $$sv.
  57. my $need_freetmps = 0; # We may postpone FREETMPS to the end of each basic
  58. # block or even to the end of each loop of blocks,
  59. # depending on optimisation options.
  60. my $know_op = 0; # Set when C variable op already holds the right op
  61. # (from an immediately preceding DOOP(ppname)).
  62. my $errors = 0; # Number of errors encountered
  63. my %skip_stack; # Hash of PP names which don't need write_back_stack
  64. my %skip_lexicals; # Hash of PP names which don't need write_back_lexicals
  65. my %skip_invalidate; # Hash of PP names which don't need invalidate_lexicals
  66. my %ignore_op; # Hash of ops which do nothing except returning op_next
  67. BEGIN {
  68. foreach (qw(pp_scalar pp_regcmaybe pp_lineseq pp_scope pp_null)) {
  69. $ignore_op{$_} = 1;
  70. }
  71. }
  72. my @unused_sub_packages; # list of packages (given by -u options) to search
  73. # explicitly and save every sub we find there, even
  74. # if apparently unused (could be only referenced from
  75. # an eval "" or from a $SIG{FOO} = "bar").
  76. my ($module_name);
  77. my ($debug_op, $debug_stack, $debug_cxstack, $debug_pad, $debug_runtime,
  78. $debug_shadow, $debug_queue, $debug_lineno, $debug_timings);
  79. # Optimisation options. On the command line, use hyphens instead of
  80. # underscores for compatibility with gcc-style options. We use
  81. # underscores here because they are OK in (strict) barewords.
  82. my ($freetmps_each_bblock, $freetmps_each_loop, $omit_taint);
  83. my %optimise = (freetmps_each_bblock => \$freetmps_each_bblock,
  84. freetmps_each_loop => \$freetmps_each_loop,
  85. omit_taint => \$omit_taint);
  86. # perl patchlevel to generate code for (defaults to current patchlevel)
  87. my $patchlevel = int(0.5 + 1000 * ($] - 5));
  88. # Could rewrite push_runtime() and output_runtime() to use a
  89. # temporary file if memory is at a premium.
  90. my $ppname; # name of current fake PP function
  91. my $runtime_list_ref;
  92. my $declare_ref; # Hash ref keyed by C variable type of declarations.
  93. my @pp_list; # list of [$ppname, $runtime_list_ref, $declare_ref]
  94. # tuples to be written out.
  95. my ($init, $decl);
  96. sub init_hash { map { $_ => 1 } @_ }
  97. #
  98. # Initialise the hashes for the default PP functions where we can avoid
  99. # either write_back_stack, write_back_lexicals or invalidate_lexicals.
  100. #
  101. %skip_lexicals = init_hash qw(pp_enter pp_enterloop);
  102. %skip_invalidate = init_hash qw(pp_enter pp_enterloop);
  103. sub debug {
  104. if ($debug_runtime) {
  105. warn(@_);
  106. } else {
  107. runtime(map { chomp; "/* $_ */"} @_);
  108. }
  109. }
  110. sub declare {
  111. my ($type, $var) = @_;
  112. push(@{$declare_ref->{$type}}, $var);
  113. }
  114. sub push_runtime {
  115. push(@$runtime_list_ref, @_);
  116. warn join("\n", @_) . "\n" if $debug_runtime;
  117. }
  118. sub save_runtime {
  119. push(@pp_list, [$ppname, $runtime_list_ref, $declare_ref]);
  120. }
  121. sub output_runtime {
  122. my $ppdata;
  123. print qq(#include "cc_runtime.h"\n);
  124. foreach $ppdata (@pp_list) {
  125. my ($name, $runtime, $declare) = @$ppdata;
  126. print "\nstatic\nPP($name)\n{\n";
  127. my ($type, $varlist, $line);
  128. while (($type, $varlist) = each %$declare) {
  129. print "\t$type ", join(", ", @$varlist), ";\n";
  130. }
  131. foreach $line (@$runtime) {
  132. print $line, "\n";
  133. }
  134. print "}\n";
  135. }
  136. }
  137. sub runtime {
  138. my $line;
  139. foreach $line (@_) {
  140. push_runtime("\t$line");
  141. }
  142. }
  143. sub init_pp {
  144. $ppname = shift;
  145. $runtime_list_ref = [];
  146. $declare_ref = {};
  147. runtime("djSP;");
  148. declare("I32", "oldsave");
  149. declare("SV", "**svp");
  150. map { declare("SV", "*$_") } qw(sv src dst left right);
  151. declare("MAGIC", "*mg");
  152. $decl->add("static OP * $ppname _((ARGSproto));");
  153. debug "init_pp: $ppname\n" if $debug_queue;
  154. }
  155. # Initialise runtime_callback function for Stackobj class
  156. BEGIN { B::Stackobj::set_callback(\&runtime) }
  157. # Initialise saveoptree_callback for B::C class
  158. sub cc_queue {
  159. my ($name, $root, $start, @pl) = @_;
  160. debug "cc_queue: name $name, root $root, start $start, padlist (@pl)\n"
  161. if $debug_queue;
  162. if ($name eq "*ignore*") {
  163. $name = 0;
  164. } else {
  165. push(@cc_todo, [$name, $root, $start, (@pl ? @pl : @padlist)]);
  166. }
  167. my $fakeop = new B::FAKEOP ("next" => 0, sibling => 0, ppaddr => $name);
  168. $start = $fakeop->save;
  169. debug "cc_queue: name $name returns $start\n" if $debug_queue;
  170. return $start;
  171. }
  172. BEGIN { B::C::set_callback(\&cc_queue) }
  173. sub valid_int { $_[0]->{flags} & VALID_INT }
  174. sub valid_double { $_[0]->{flags} & VALID_DOUBLE }
  175. sub valid_numeric { $_[0]->{flags} & (VALID_INT | VALID_DOUBLE) }
  176. sub valid_sv { $_[0]->{flags} & VALID_SV }
  177. sub top_int { @stack ? $stack[-1]->as_int : "TOPi" }
  178. sub top_double { @stack ? $stack[-1]->as_double : "TOPn" }
  179. sub top_numeric { @stack ? $stack[-1]->as_numeric : "TOPn" }
  180. sub top_sv { @stack ? $stack[-1]->as_sv : "TOPs" }
  181. sub top_bool { @stack ? $stack[-1]->as_numeric : "SvTRUE(TOPs)" }
  182. sub pop_int { @stack ? (pop @stack)->as_int : "POPi" }
  183. sub pop_double { @stack ? (pop @stack)->as_double : "POPn" }
  184. sub pop_numeric { @stack ? (pop @stack)->as_numeric : "POPn" }
  185. sub pop_sv { @stack ? (pop @stack)->as_sv : "POPs" }
  186. sub pop_bool {
  187. if (@stack) {
  188. return ((pop @stack)->as_numeric);
  189. } else {
  190. # Careful: POPs has an auto-decrement and SvTRUE evaluates
  191. # its argument more than once.
  192. runtime("sv = POPs;");
  193. return "SvTRUE(sv)";
  194. }
  195. }
  196. sub write_back_lexicals {
  197. my $avoid = shift || 0;
  198. debug "write_back_lexicals($avoid) called from @{[(caller(1))[3]]}\n"
  199. if $debug_shadow;
  200. my $lex;
  201. foreach $lex (@pad) {
  202. next unless ref($lex);
  203. $lex->write_back unless $lex->{flags} & $avoid;
  204. }
  205. }
  206. sub write_back_stack {
  207. my $obj;
  208. return unless @stack;
  209. runtime(sprintf("EXTEND(sp, %d);", scalar(@stack)));
  210. foreach $obj (@stack) {
  211. runtime(sprintf("PUSHs((SV*)%s);", $obj->as_sv));
  212. }
  213. @stack = ();
  214. }
  215. sub invalidate_lexicals {
  216. my $avoid = shift || 0;
  217. debug "invalidate_lexicals($avoid) called from @{[(caller(1))[3]]}\n"
  218. if $debug_shadow;
  219. my $lex;
  220. foreach $lex (@pad) {
  221. next unless ref($lex);
  222. $lex->invalidate unless $lex->{flags} & $avoid;
  223. }
  224. }
  225. sub reload_lexicals {
  226. my $lex;
  227. foreach $lex (@pad) {
  228. next unless ref($lex);
  229. my $type = $lex->{type};
  230. if ($type == T_INT) {
  231. $lex->as_int;
  232. } elsif ($type == T_DOUBLE) {
  233. $lex->as_double;
  234. } else {
  235. $lex->as_sv;
  236. }
  237. }
  238. }
  239. {
  240. package B::Pseudoreg;
  241. #
  242. # This class allocates pseudo-registers (OK, so they're C variables).
  243. #
  244. my %alloc; # Keyed by variable name. A value of 1 means the
  245. # variable has been declared. A value of 2 means
  246. # it's in use.
  247. sub new_scope { %alloc = () }
  248. sub new ($$$) {
  249. my ($class, $type, $prefix) = @_;
  250. my ($ptr, $i, $varname, $status, $obj);
  251. $prefix =~ s/^(\**)//;
  252. $ptr = $1;
  253. $i = 0;
  254. do {
  255. $varname = "$prefix$i";
  256. $status = $alloc{$varname};
  257. } while $status == 2;
  258. if ($status != 1) {
  259. # Not declared yet
  260. B::CC::declare($type, "$ptr$varname");
  261. $alloc{$varname} = 2; # declared and in use
  262. }
  263. $obj = bless \$varname, $class;
  264. return $obj;
  265. }
  266. sub DESTROY {
  267. my $obj = shift;
  268. $alloc{$$obj} = 1; # no longer in use but still declared
  269. }
  270. }
  271. {
  272. package B::Shadow;
  273. #
  274. # This class gives a standard API for a perl object to shadow a
  275. # C variable and only generate reloads/write-backs when necessary.
  276. #
  277. # Use $obj->load($foo) instead of runtime("shadowed_c_var = foo").
  278. # Use $obj->write_back whenever shadowed_c_var needs to be up to date.
  279. # Use $obj->invalidate whenever an unknown function may have
  280. # set shadow itself.
  281. sub new {
  282. my ($class, $write_back) = @_;
  283. # Object fields are perl shadow variable, validity flag
  284. # (for *C* variable) and callback sub for write_back
  285. # (passed perl shadow variable as argument).
  286. bless [undef, 1, $write_back], $class;
  287. }
  288. sub load {
  289. my ($obj, $newval) = @_;
  290. $obj->[1] = 0; # C variable no longer valid
  291. $obj->[0] = $newval;
  292. }
  293. sub write_back {
  294. my $obj = shift;
  295. if (!($obj->[1])) {
  296. $obj->[1] = 1; # C variable will now be valid
  297. &{$obj->[2]}($obj->[0]);
  298. }
  299. }
  300. sub invalidate { $_[0]->[1] = 0 } # force C variable to be invalid
  301. }
  302. my $curcop = new B::Shadow (sub {
  303. my $opsym = shift->save;
  304. runtime("PL_curcop = (COP*)$opsym;");
  305. });
  306. #
  307. # Context stack shadowing. Mimics stuff in pp_ctl.c, cop.h and so on.
  308. #
  309. sub dopoptoloop {
  310. my $cxix = $#cxstack;
  311. while ($cxix >= 0 && $cxstack[$cxix]->{type} != CXt_LOOP) {
  312. $cxix--;
  313. }
  314. debug "dopoptoloop: returning $cxix" if $debug_cxstack;
  315. return $cxix;
  316. }
  317. sub dopoptolabel {
  318. my $label = shift;
  319. my $cxix = $#cxstack;
  320. while ($cxix >= 0 && $cxstack[$cxix]->{type} != CXt_LOOP
  321. && $cxstack[$cxix]->{label} ne $label) {
  322. $cxix--;
  323. }
  324. debug "dopoptolabel: returning $cxix" if $debug_cxstack;
  325. return $cxix;
  326. }
  327. sub error {
  328. my $format = shift;
  329. my $file = $curcop->[0]->filegv->SV->PV;
  330. my $line = $curcop->[0]->line;
  331. $errors++;
  332. if (@_) {
  333. warn sprintf("%s:%d: $format\n", $file, $line, @_);
  334. } else {
  335. warn sprintf("%s:%d: %s\n", $file, $line, $format);
  336. }
  337. }
  338. #
  339. # Load pad takes (the elements of) a PADLIST as arguments and loads
  340. # up @pad with Stackobj-derived objects which represent those lexicals.
  341. # If/when perl itself can generate type information (my int $foo) then
  342. # we'll take advantage of that here. Until then, we'll use various hacks
  343. # to tell the compiler when we want a lexical to be a particular type
  344. # or to be a register.
  345. #
  346. sub load_pad {
  347. my ($namelistav, $valuelistav) = @_;
  348. @padlist = @_;
  349. my @namelist = $namelistav->ARRAY;
  350. my @valuelist = $valuelistav->ARRAY;
  351. my $ix;
  352. @pad = ();
  353. debug "load_pad: $#namelist names, $#valuelist values\n" if $debug_pad;
  354. # Temporary lexicals don't get named so it's possible for @valuelist
  355. # to be strictly longer than @namelist. We count $ix up to the end of
  356. # @valuelist but index into @namelist for the name. Any temporaries which
  357. # run off the end of @namelist will make $namesv undefined and we treat
  358. # that the same as having an explicit SPECIAL sv_undef object in @namelist.
  359. # [XXX If/when @_ becomes a lexical, we must start at 0 here.]
  360. for ($ix = 1; $ix < @valuelist; $ix++) {
  361. my $namesv = $namelist[$ix];
  362. my $type = T_UNKNOWN;
  363. my $flags = 0;
  364. my $name = "tmp$ix";
  365. my $class = class($namesv);
  366. if (!defined($namesv) || $class eq "SPECIAL") {
  367. # temporaries have &PL_sv_undef instead of a PVNV for a name
  368. $flags = VALID_SV|TEMPORARY|REGISTER;
  369. } else {
  370. if ($namesv->PV =~ /^\$(.*)_([di])(r?)$/) {
  371. $name = $1;
  372. if ($2 eq "i") {
  373. $type = T_INT;
  374. $flags = VALID_SV|VALID_INT;
  375. } elsif ($2 eq "d") {
  376. $type = T_DOUBLE;
  377. $flags = VALID_SV|VALID_DOUBLE;
  378. }
  379. $flags |= REGISTER if $3;
  380. }
  381. }
  382. $pad[$ix] = new B::Stackobj::Padsv ($type, $flags, $ix,
  383. "i_$name", "d_$name");
  384. declare("IV", $type == T_INT ? "i_$name = 0" : "i_$name");
  385. declare("double", $type == T_DOUBLE ? "d_$name = 0" : "d_$name");
  386. debug sprintf("PL_curpad[$ix] = %s\n", $pad[$ix]->peek) if $debug_pad;
  387. }
  388. }
  389. #
  390. # Debugging stuff
  391. #
  392. sub peek_stack { sprintf "stack = %s\n", join(" ", map($_->minipeek, @stack)) }
  393. #
  394. # OP stuff
  395. #
  396. sub label {
  397. my $op = shift;
  398. # XXX Preserve original label name for "real" labels?
  399. return sprintf("lab_%x", $$op);
  400. }
  401. sub write_label {
  402. my $op = shift;
  403. push_runtime(sprintf(" %s:", label($op)));
  404. }
  405. sub loadop {
  406. my $op = shift;
  407. my $opsym = $op->save;
  408. runtime("PL_op = $opsym;") unless $know_op;
  409. return $opsym;
  410. }
  411. sub doop {
  412. my $op = shift;
  413. my $ppname = $op->ppaddr;
  414. my $sym = loadop($op);
  415. runtime("DOOP($ppname);");
  416. $know_op = 1;
  417. return $sym;
  418. }
  419. sub gimme {
  420. my $op = shift;
  421. my $flags = $op->flags;
  422. return (($flags & OPf_KNOW) ? ($flags & OPf_LIST) : "dowantarray()");
  423. }
  424. #
  425. # Code generation for PP code
  426. #
  427. sub pp_null {
  428. my $op = shift;
  429. return $op->next;
  430. }
  431. sub pp_stub {
  432. my $op = shift;
  433. my $gimme = gimme($op);
  434. if ($gimme != 1) {
  435. # XXX Change to push a constant sv_undef Stackobj onto @stack
  436. write_back_stack();
  437. runtime("if ($gimme != G_ARRAY) XPUSHs(&PL_sv_undef);");
  438. }
  439. return $op->next;
  440. }
  441. sub pp_unstack {
  442. my $op = shift;
  443. @stack = ();
  444. runtime("PP_UNSTACK;");
  445. return $op->next;
  446. }
  447. sub pp_and {
  448. my $op = shift;
  449. my $next = $op->next;
  450. reload_lexicals();
  451. unshift(@bblock_todo, $next);
  452. if (@stack >= 1) {
  453. my $bool = pop_bool();
  454. write_back_stack();
  455. runtime(sprintf("if (!$bool) goto %s;", label($next)));
  456. } else {
  457. runtime(sprintf("if (!%s) goto %s;", top_bool(), label($next)),
  458. "*sp--;");
  459. }
  460. return $op->other;
  461. }
  462. sub pp_or {
  463. my $op = shift;
  464. my $next = $op->next;
  465. reload_lexicals();
  466. unshift(@bblock_todo, $next);
  467. if (@stack >= 1) {
  468. my $obj = pop @stack;
  469. write_back_stack();
  470. runtime(sprintf("if (%s) { XPUSHs(%s); goto %s; }",
  471. $obj->as_numeric, $obj->as_sv, label($next)));
  472. } else {
  473. runtime(sprintf("if (%s) goto %s;", top_bool(), label($next)),
  474. "*sp--;");
  475. }
  476. return $op->other;
  477. }
  478. sub pp_cond_expr {
  479. my $op = shift;
  480. my $false = $op->false;
  481. unshift(@bblock_todo, $false);
  482. reload_lexicals();
  483. my $bool = pop_bool();
  484. write_back_stack();
  485. runtime(sprintf("if (!$bool) goto %s;", label($false)));
  486. return $op->true;
  487. }
  488. sub pp_padsv {
  489. my $op = shift;
  490. my $ix = $op->targ;
  491. push(@stack, $pad[$ix]);
  492. if ($op->flags & OPf_MOD) {
  493. my $private = $op->private;
  494. if ($private & OPpLVAL_INTRO) {
  495. runtime("SAVECLEARSV(PL_curpad[$ix]);");
  496. } elsif ($private & OPpDEREF) {
  497. runtime(sprintf("vivify_ref(PL_curpad[%d], %d);",
  498. $ix, $private & OPpDEREF));
  499. $pad[$ix]->invalidate;
  500. }
  501. }
  502. return $op->next;
  503. }
  504. sub pp_const {
  505. my $op = shift;
  506. my $sv = $op->sv;
  507. my $obj = $constobj{$$sv};
  508. if (!defined($obj)) {
  509. $obj = $constobj{$$sv} = new B::Stackobj::Const ($sv);
  510. }
  511. push(@stack, $obj);
  512. return $op->next;
  513. }
  514. sub pp_nextstate {
  515. my $op = shift;
  516. $curcop->load($op);
  517. @stack = ();
  518. debug(sprintf("%s:%d\n", $op->filegv->SV->PV, $op->line)) if $debug_lineno;
  519. runtime("TAINT_NOT;") unless $omit_taint;
  520. runtime("sp = PL_stack_base + cxstack[cxstack_ix].blk_oldsp;");
  521. if ($freetmps_each_bblock || $freetmps_each_loop) {
  522. $need_freetmps = 1;
  523. } else {
  524. runtime("FREETMPS;");
  525. }
  526. return $op->next;
  527. }
  528. sub pp_dbstate {
  529. my $op = shift;
  530. $curcop->invalidate; # XXX?
  531. return default_pp($op);
  532. }
  533. sub pp_rv2gv { $curcop->write_back; default_pp(@_) }
  534. sub pp_bless { $curcop->write_back; default_pp(@_) }
  535. sub pp_repeat { $curcop->write_back; default_pp(@_) }
  536. # The following subs need $curcop->write_back if we decide to support arybase:
  537. # pp_pos, pp_substr, pp_index, pp_rindex, pp_aslice, pp_lslice, pp_splice
  538. sub pp_sort { $curcop->write_back; default_pp(@_) }
  539. sub pp_caller { $curcop->write_back; default_pp(@_) }
  540. sub pp_reset { $curcop->write_back; default_pp(@_) }
  541. sub pp_gv {
  542. my $op = shift;
  543. my $gvsym = $op->gv->save;
  544. write_back_stack();
  545. runtime("XPUSHs((SV*)$gvsym);");
  546. return $op->next;
  547. }
  548. sub pp_gvsv {
  549. my $op = shift;
  550. my $gvsym = $op->gv->save;
  551. write_back_stack();
  552. if ($op->private & OPpLVAL_INTRO) {
  553. runtime("XPUSHs(save_scalar($gvsym));");
  554. } else {
  555. runtime("XPUSHs(GvSV($gvsym));");
  556. }
  557. return $op->next;
  558. }
  559. sub pp_aelemfast {
  560. my $op = shift;
  561. my $gvsym = $op->gv->save;
  562. my $ix = $op->private;
  563. my $flag = $op->flags & OPf_MOD;
  564. write_back_stack();
  565. runtime("svp = av_fetch(GvAV($gvsym), $ix, $flag);",
  566. "PUSHs(svp ? *svp : &PL_sv_undef);");
  567. return $op->next;
  568. }
  569. sub int_binop {
  570. my ($op, $operator) = @_;
  571. if ($op->flags & OPf_STACKED) {
  572. my $right = pop_int();
  573. if (@stack >= 1) {
  574. my $left = top_int();
  575. $stack[-1]->set_int(&$operator($left, $right));
  576. } else {
  577. runtime(sprintf("sv_setiv(TOPs, %s);",&$operator("TOPi", $right)));
  578. }
  579. } else {
  580. my $targ = $pad[$op->targ];
  581. my $right = new B::Pseudoreg ("IV", "riv");
  582. my $left = new B::Pseudoreg ("IV", "liv");
  583. runtime(sprintf("$$right = %s; $$left = %s;", pop_int(), pop_int));
  584. $targ->set_int(&$operator($$left, $$right));
  585. push(@stack, $targ);
  586. }
  587. return $op->next;
  588. }
  589. sub INTS_CLOSED () { 0x1 }
  590. sub INT_RESULT () { 0x2 }
  591. sub NUMERIC_RESULT () { 0x4 }
  592. sub numeric_binop {
  593. my ($op, $operator, $flags) = @_;
  594. my $force_int = 0;
  595. $force_int ||= ($flags & INT_RESULT);
  596. $force_int ||= ($flags & INTS_CLOSED && @stack >= 2
  597. && valid_int($stack[-2]) && valid_int($stack[-1]));
  598. if ($op->flags & OPf_STACKED) {
  599. my $right = pop_numeric();
  600. if (@stack >= 1) {
  601. my $left = top_numeric();
  602. if ($force_int) {
  603. $stack[-1]->set_int(&$operator($left, $right));
  604. } else {
  605. $stack[-1]->set_numeric(&$operator($left, $right));
  606. }
  607. } else {
  608. if ($force_int) {
  609. runtime(sprintf("sv_setiv(TOPs, %s);",
  610. &$operator("TOPi", $right)));
  611. } else {
  612. runtime(sprintf("sv_setnv(TOPs, %s);",
  613. &$operator("TOPn", $right)));
  614. }
  615. }
  616. } else {
  617. my $targ = $pad[$op->targ];
  618. $force_int ||= ($targ->{type} == T_INT);
  619. if ($force_int) {
  620. my $right = new B::Pseudoreg ("IV", "riv");
  621. my $left = new B::Pseudoreg ("IV", "liv");
  622. runtime(sprintf("$$right = %s; $$left = %s;",
  623. pop_numeric(), pop_numeric));
  624. $targ->set_int(&$operator($$left, $$right));
  625. } else {
  626. my $right = new B::Pseudoreg ("double", "rnv");
  627. my $left = new B::Pseudoreg ("double", "lnv");
  628. runtime(sprintf("$$right = %s; $$left = %s;",
  629. pop_numeric(), pop_numeric));
  630. $targ->set_numeric(&$operator($$left, $$right));
  631. }
  632. push(@stack, $targ);
  633. }
  634. return $op->next;
  635. }
  636. sub sv_binop {
  637. my ($op, $operator, $flags) = @_;
  638. if ($op->flags & OPf_STACKED) {
  639. my $right = pop_sv();
  640. if (@stack >= 1) {
  641. my $left = top_sv();
  642. if ($flags & INT_RESULT) {
  643. $stack[-1]->set_int(&$operator($left, $right));
  644. } elsif ($flags & NUMERIC_RESULT) {
  645. $stack[-1]->set_numeric(&$operator($left, $right));
  646. } else {
  647. # XXX Does this work?
  648. runtime(sprintf("sv_setsv($left, %s);",
  649. &$operator($left, $right)));
  650. $stack[-1]->invalidate;
  651. }
  652. } else {
  653. my $f;
  654. if ($flags & INT_RESULT) {
  655. $f = "sv_setiv";
  656. } elsif ($flags & NUMERIC_RESULT) {
  657. $f = "sv_setnv";
  658. } else {
  659. $f = "sv_setsv";
  660. }
  661. runtime(sprintf("%s(TOPs, %s);", $f, &$operator("TOPs", $right)));
  662. }
  663. } else {
  664. my $targ = $pad[$op->targ];
  665. runtime(sprintf("right = %s; left = %s;", pop_sv(), pop_sv));
  666. if ($flags & INT_RESULT) {
  667. $targ->set_int(&$operator("left", "right"));
  668. } elsif ($flags & NUMERIC_RESULT) {
  669. $targ->set_numeric(&$operator("left", "right"));
  670. } else {
  671. # XXX Does this work?
  672. runtime(sprintf("sv_setsv(%s, %s);",
  673. $targ->as_sv, &$operator("left", "right")));
  674. $targ->invalidate;
  675. }
  676. push(@stack, $targ);
  677. }
  678. return $op->next;
  679. }
  680. sub bool_int_binop {
  681. my ($op, $operator) = @_;
  682. my $right = new B::Pseudoreg ("IV", "riv");
  683. my $left = new B::Pseudoreg ("IV", "liv");
  684. runtime(sprintf("$$right = %s; $$left = %s;", pop_int(), pop_int()));
  685. my $bool = new B::Stackobj::Bool (new B::Pseudoreg ("int", "b"));
  686. $bool->set_int(&$operator($$left, $$right));
  687. push(@stack, $bool);
  688. return $op->next;
  689. }
  690. sub bool_numeric_binop {
  691. my ($op, $operator) = @_;
  692. my $right = new B::Pseudoreg ("double", "rnv");
  693. my $left = new B::Pseudoreg ("double", "lnv");
  694. runtime(sprintf("$$right = %s; $$left = %s;",
  695. pop_numeric(), pop_numeric()));
  696. my $bool = new B::Stackobj::Bool (new B::Pseudoreg ("int", "b"));
  697. $bool->set_numeric(&$operator($$left, $$right));
  698. push(@stack, $bool);
  699. return $op->next;
  700. }
  701. sub bool_sv_binop {
  702. my ($op, $operator) = @_;
  703. runtime(sprintf("right = %s; left = %s;", pop_sv(), pop_sv()));
  704. my $bool = new B::Stackobj::Bool (new B::Pseudoreg ("int", "b"));
  705. $bool->set_numeric(&$operator("left", "right"));
  706. push(@stack, $bool);
  707. return $op->next;
  708. }
  709. sub infix_op {
  710. my $opname = shift;
  711. return sub { "$_[0] $opname $_[1]" }
  712. }
  713. sub prefix_op {
  714. my $opname = shift;
  715. return sub { sprintf("%s(%s)", $opname, join(", ", @_)) }
  716. }
  717. BEGIN {
  718. my $plus_op = infix_op("+");
  719. my $minus_op = infix_op("-");
  720. my $multiply_op = infix_op("*");
  721. my $divide_op = infix_op("/");
  722. my $modulo_op = infix_op("%");
  723. my $lshift_op = infix_op("<<");
  724. my $rshift_op = infix_op(">>");
  725. my $ncmp_op = sub { "($_[0] > $_[1] ? 1 : ($_[0] < $_[1]) ? -1 : 0)" };
  726. my $scmp_op = prefix_op("sv_cmp");
  727. my $seq_op = prefix_op("sv_eq");
  728. my $sne_op = prefix_op("!sv_eq");
  729. my $slt_op = sub { "sv_cmp($_[0], $_[1]) < 0" };
  730. my $sgt_op = sub { "sv_cmp($_[0], $_[1]) > 0" };
  731. my $sle_op = sub { "sv_cmp($_[0], $_[1]) <= 0" };
  732. my $sge_op = sub { "sv_cmp($_[0], $_[1]) >= 0" };
  733. my $eq_op = infix_op("==");
  734. my $ne_op = infix_op("!=");
  735. my $lt_op = infix_op("<");
  736. my $gt_op = infix_op(">");
  737. my $le_op = infix_op("<=");
  738. my $ge_op = infix_op(">=");
  739. #
  740. # XXX The standard perl PP code has extra handling for
  741. # some special case arguments of these operators.
  742. #
  743. sub pp_add { numeric_binop($_[0], $plus_op, INTS_CLOSED) }
  744. sub pp_subtract { numeric_binop($_[0], $minus_op, INTS_CLOSED) }
  745. sub pp_multiply { numeric_binop($_[0], $multiply_op, INTS_CLOSED) }
  746. sub pp_divide { numeric_binop($_[0], $divide_op) }
  747. sub pp_modulo { int_binop($_[0], $modulo_op) } # differs from perl's
  748. sub pp_ncmp { numeric_binop($_[0], $ncmp_op, INT_RESULT) }
  749. sub pp_left_shift { int_binop($_[0], $lshift_op) }
  750. sub pp_right_shift { int_binop($_[0], $rshift_op) }
  751. sub pp_i_add { int_binop($_[0], $plus_op) }
  752. sub pp_i_subtract { int_binop($_[0], $minus_op) }
  753. sub pp_i_multiply { int_binop($_[0], $multiply_op) }
  754. sub pp_i_divide { int_binop($_[0], $divide_op) }
  755. sub pp_i_modulo { int_binop($_[0], $modulo_op) }
  756. sub pp_eq { bool_numeric_binop($_[0], $eq_op) }
  757. sub pp_ne { bool_numeric_binop($_[0], $ne_op) }
  758. sub pp_lt { bool_numeric_binop($_[0], $lt_op) }
  759. sub pp_gt { bool_numeric_binop($_[0], $gt_op) }
  760. sub pp_le { bool_numeric_binop($_[0], $le_op) }
  761. sub pp_ge { bool_numeric_binop($_[0], $ge_op) }
  762. sub pp_i_eq { bool_int_binop($_[0], $eq_op) }
  763. sub pp_i_ne { bool_int_binop($_[0], $ne_op) }
  764. sub pp_i_lt { bool_int_binop($_[0], $lt_op) }
  765. sub pp_i_gt { bool_int_binop($_[0], $gt_op) }
  766. sub pp_i_le { bool_int_binop($_[0], $le_op) }
  767. sub pp_i_ge { bool_int_binop($_[0], $ge_op) }
  768. sub pp_scmp { sv_binop($_[0], $scmp_op, INT_RESULT) }
  769. sub pp_slt { bool_sv_binop($_[0], $slt_op) }
  770. sub pp_sgt { bool_sv_binop($_[0], $sgt_op) }
  771. sub pp_sle { bool_sv_binop($_[0], $sle_op) }
  772. sub pp_sge { bool_sv_binop($_[0], $sge_op) }
  773. sub pp_seq { bool_sv_binop($_[0], $seq_op) }
  774. sub pp_sne { bool_sv_binop($_[0], $sne_op) }
  775. }
  776. sub pp_sassign {
  777. my $op = shift;
  778. my $backwards = $op->private & OPpASSIGN_BACKWARDS;
  779. my ($dst, $src);
  780. if (@stack >= 2) {
  781. $dst = pop @stack;
  782. $src = pop @stack;
  783. ($src, $dst) = ($dst, $src) if $backwards;
  784. my $type = $src->{type};
  785. if ($type == T_INT) {
  786. $dst->set_int($src->as_int);
  787. } elsif ($type == T_DOUBLE) {
  788. $dst->set_numeric($src->as_numeric);
  789. } else {
  790. $dst->set_sv($src->as_sv);
  791. }
  792. push(@stack, $dst);
  793. } elsif (@stack == 1) {
  794. if ($backwards) {
  795. my $src = pop @stack;
  796. my $type = $src->{type};
  797. runtime("if (PL_tainting && PL_tainted) TAINT_NOT;");
  798. if ($type == T_INT) {
  799. runtime sprintf("sv_setiv(TOPs, %s);", $src->as_int);
  800. } elsif ($type == T_DOUBLE) {
  801. runtime sprintf("sv_setnv(TOPs, %s);", $src->as_double);
  802. } else {
  803. runtime sprintf("sv_setsv(TOPs, %s);", $src->as_sv);
  804. }
  805. runtime("SvSETMAGIC(TOPs);");
  806. } else {
  807. my $dst = $stack[-1];
  808. my $type = $dst->{type};
  809. runtime("sv = POPs;");
  810. runtime("MAYBE_TAINT_SASSIGN_SRC(sv);");
  811. if ($type == T_INT) {
  812. $dst->set_int("SvIV(sv)");
  813. } elsif ($type == T_DOUBLE) {
  814. $dst->set_double("SvNV(sv)");
  815. } else {
  816. runtime("SvSetSV($dst->{sv}, sv);");
  817. $dst->invalidate;
  818. }
  819. }
  820. } else {
  821. if ($backwards) {
  822. runtime("src = POPs; dst = TOPs;");
  823. } else {
  824. runtime("dst = POPs; src = TOPs;");
  825. }
  826. runtime("MAYBE_TAINT_SASSIGN_SRC(src);",
  827. "SvSetSV(dst, src);",
  828. "SvSETMAGIC(dst);",
  829. "SETs(dst);");
  830. }
  831. return $op->next;
  832. }
  833. sub pp_preinc {
  834. my $op = shift;
  835. if (@stack >= 1) {
  836. my $obj = $stack[-1];
  837. my $type = $obj->{type};
  838. if ($type == T_INT || $type == T_DOUBLE) {
  839. $obj->set_int($obj->as_int . " + 1");
  840. } else {
  841. runtime sprintf("PP_PREINC(%s);", $obj->as_sv);
  842. $obj->invalidate();
  843. }
  844. } else {
  845. runtime sprintf("PP_PREINC(TOPs);");
  846. }
  847. return $op->next;
  848. }
  849. sub pp_pushmark {
  850. my $op = shift;
  851. write_back_stack();
  852. runtime("PUSHMARK(sp);");
  853. return $op->next;
  854. }
  855. sub pp_list {
  856. my $op = shift;
  857. write_back_stack();
  858. my $gimme = gimme($op);
  859. if ($gimme == 1) { # sic
  860. runtime("POPMARK;"); # need this even though not a "full" pp_list
  861. } else {
  862. runtime("PP_LIST($gimme);");
  863. }
  864. return $op->next;
  865. }
  866. sub pp_entersub {
  867. my $op = shift;
  868. write_back_lexicals(REGISTER|TEMPORARY);
  869. write_back_stack();
  870. my $sym = doop($op);
  871. runtime("while (PL_op != ($sym)->op_next && PL_op != (OP*)0 ){");
  872. runtime("PL_op = (*PL_op->op_ppaddr)(ARGS);");
  873. runtime("SPAGAIN;}");
  874. $know_op = 0;
  875. invalidate_lexicals(REGISTER|TEMPORARY);
  876. return $op->next;
  877. }
  878. sub pp_goto{
  879. my $op = shift;
  880. my $ppname = $op->ppaddr;
  881. write_back_lexicals() unless $skip_lexicals{$ppname};
  882. write_back_stack() unless $skip_stack{$ppname};
  883. my $sym=doop($op);
  884. runtime("if (PL_op != ($sym)->op_next && PL_op != (OP*)0){return PL_op;}");
  885. invalidate_lexicals() unless $skip_invalidate{$ppname};
  886. return $op->next;
  887. }
  888. sub pp_enterwrite {
  889. my $op = shift;
  890. pp_entersub($op);
  891. }
  892. sub pp_leavewrite {
  893. my $op = shift;
  894. write_back_lexicals(REGISTER|TEMPORARY);
  895. write_back_stack();
  896. my $sym = doop($op);
  897. # XXX Is this the right way to distinguish between it returning
  898. # CvSTART(cv) (via doform) and pop_return()?
  899. runtime("if (PL_op) PL_op = (*PL_op->op_ppaddr)(ARGS);");
  900. runtime("SPAGAIN;");
  901. $know_op = 0;
  902. invalidate_lexicals(REGISTER|TEMPORARY);
  903. return $op->next;
  904. }
  905. sub doeval {
  906. my $op = shift;
  907. $curcop->write_back;
  908. write_back_lexicals(REGISTER|TEMPORARY);
  909. write_back_stack();
  910. my $sym = loadop($op);
  911. my $ppaddr = $op->ppaddr;
  912. runtime("PP_EVAL($ppaddr, ($sym)->op_next);");
  913. $know_op = 1;
  914. invalidate_lexicals(REGISTER|TEMPORARY);
  915. return $op->next;
  916. }
  917. sub pp_entereval { doeval(@_) }
  918. sub pp_require { doeval(@_) }
  919. sub pp_dofile { doeval(@_) }
  920. sub pp_entertry {
  921. my $op = shift;
  922. $curcop->write_back;
  923. write_back_lexicals(REGISTER|TEMPORARY);
  924. write_back_stack();
  925. my $sym = doop($op);
  926. my $jmpbuf = sprintf("jmpbuf%d", $jmpbuf_ix++);
  927. declare("Sigjmp_buf", $jmpbuf);
  928. runtime(sprintf("PP_ENTERTRY(%s,%s);", $jmpbuf, label($op->other->next)));
  929. invalidate_lexicals(REGISTER|TEMPORARY);
  930. return $op->next;
  931. }
  932. sub pp_grepstart {
  933. my $op = shift;
  934. if ($need_freetmps && $freetmps_each_loop) {
  935. runtime("FREETMPS;"); # otherwise the grepwhile loop messes things up
  936. $need_freetmps = 0;
  937. }
  938. write_back_stack();
  939. doop($op);
  940. return $op->next->other;
  941. }
  942. sub pp_mapstart {
  943. my $op = shift;
  944. if ($need_freetmps && $freetmps_each_loop) {
  945. runtime("FREETMPS;"); # otherwise the mapwhile loop messes things up
  946. $need_freetmps = 0;
  947. }
  948. write_back_stack();
  949. doop($op);
  950. return $op->next->other;
  951. }
  952. sub pp_grepwhile {
  953. my $op = shift;
  954. my $next = $op->next;
  955. unshift(@bblock_todo, $next);
  956. write_back_lexicals();
  957. write_back_stack();
  958. my $sym = doop($op);
  959. # pp_grepwhile can return either op_next or op_other and we need to
  960. # be able to distinguish the two at runtime. Since it's possible for
  961. # both ops to be "inlined", the fields could both be zero. To get
  962. # around that, we hack op_next to be our own op (purely because we
  963. # know it's a non-NULL pointer and can't be the same as op_other).
  964. $init->add("((LOGOP*)$sym)->op_next = $sym;");
  965. runtime(sprintf("if (PL_op == ($sym)->op_next) goto %s;", label($next)));
  966. $know_op = 0;
  967. return $op->other;
  968. }
  969. sub pp_mapwhile {
  970. pp_grepwhile(@_);
  971. }
  972. sub pp_return {
  973. my $op = shift;
  974. write_back_lexicals(REGISTER|TEMPORARY);
  975. write_back_stack();
  976. doop($op);
  977. runtime("PUTBACK;", "return (PL_op)?PL_op->op_next:0;");
  978. $know_op = 0;
  979. return $op->next;
  980. }
  981. sub nyi {
  982. my $op = shift;
  983. warn sprintf("%s not yet implemented properly\n", $op->ppaddr);
  984. return default_pp($op);
  985. }
  986. sub pp_range {
  987. my $op = shift;
  988. my $flags = $op->flags;
  989. if (!($flags & OPf_KNOW)) {
  990. error("context of range unknown at compile-time");
  991. }
  992. write_back_lexicals();
  993. write_back_stack();
  994. if (!($flags & OPf_LIST)) {
  995. # We need to save our UNOP structure since pp_flop uses
  996. # it to find and adjust out targ. We don't need it ourselves.
  997. $op->save;
  998. runtime sprintf("if (SvTRUE(PL_curpad[%d])) goto %s;",
  999. $op->targ, label($op->false));
  1000. unshift(@bblock_todo, $op->false);
  1001. }
  1002. return $op->true;
  1003. }
  1004. sub pp_flip {
  1005. my $op = shift;
  1006. my $flags = $op->flags;
  1007. if (!($flags & OPf_KNOW)) {
  1008. error("context of flip unknown at compile-time");
  1009. }
  1010. if ($flags & OPf_LIST) {
  1011. return $op->first->false;
  1012. }
  1013. write_back_lexicals();
  1014. write_back_stack();
  1015. # We need to save our UNOP structure since pp_flop uses
  1016. # it to find and adjust out targ. We don't need it ourselves.
  1017. $op->save;
  1018. my $ix = $op->targ;
  1019. my $rangeix = $op->first->targ;
  1020. runtime(($op->private & OPpFLIP_LINENUM) ?
  1021. "if (PL_last_in_gv && SvIV(TOPs) == IoLINES(GvIOp(PL_last_in_gv))) {"
  1022. : "if (SvTRUE(TOPs)) {");
  1023. runtime("\tsv_setiv(PL_curpad[$rangeix], 1);");
  1024. if ($op->flags & OPf_SPECIAL) {
  1025. runtime("sv_setiv(PL_curpad[$ix], 1);");
  1026. } else {
  1027. runtime("\tsv_setiv(PL_curpad[$ix], 0);",
  1028. "\tsp--;",
  1029. sprintf("\tgoto %s;", label($op->first->false)));
  1030. }
  1031. runtime("}",
  1032. qq{sv_setpv(PL_curpad[$ix], "");},
  1033. "SETs(PL_curpad[$ix]);");
  1034. $know_op = 0;
  1035. return $op->next;
  1036. }
  1037. sub pp_flop {
  1038. my $op = shift;
  1039. default_pp($op);
  1040. $know_op = 0;
  1041. return $op->next;
  1042. }
  1043. sub enterloop {
  1044. my $op = shift;
  1045. my $nextop = $op->nextop;
  1046. my $lastop = $op->lastop;
  1047. my $redoop = $op->redoop;
  1048. $curcop->write_back;
  1049. debug "enterloop: pushing on cxstack" if $debug_cxstack;
  1050. push(@cxstack, {
  1051. type => CXt_LOOP,
  1052. op => $op,
  1053. "label" => $curcop->[0]->label,
  1054. nextop => $nextop,
  1055. lastop => $lastop,
  1056. redoop => $redoop
  1057. });
  1058. $nextop->save;
  1059. $lastop->save;
  1060. $redoop->save;
  1061. return default_pp($op);
  1062. }
  1063. sub pp_enterloop { enterloop(@_) }
  1064. sub pp_enteriter { enterloop(@_) }
  1065. sub pp_leaveloop {
  1066. my $op = shift;
  1067. if (!@cxstack) {
  1068. die "panic: leaveloop";
  1069. }
  1070. debug "leaveloop: popping from cxstack" if $debug_cxstack;
  1071. pop(@cxstack);
  1072. return default_pp($op);
  1073. }
  1074. sub pp_next {
  1075. my $op = shift;
  1076. my $cxix;
  1077. if ($op->flags & OPf_SPECIAL) {
  1078. $cxix = dopoptoloop();
  1079. if ($cxix < 0) {
  1080. error('"next" used outside loop');
  1081. return $op->next; # ignore the op
  1082. }
  1083. } else {
  1084. $cxix = dopoptolabel($op->pv);
  1085. if ($cxix < 0) {
  1086. error('Label not found at compile time for "next %s"', $op->pv);
  1087. return $op->next; # ignore the op
  1088. }
  1089. }
  1090. default_pp($op);
  1091. my $nextop = $cxstack[$cxix]->{nextop};
  1092. push(@bblock_todo, $nextop);
  1093. runtime(sprintf("goto %s;", label($nextop)));
  1094. return $op->next;
  1095. }
  1096. sub pp_redo {
  1097. my $op = shift;
  1098. my $cxix;
  1099. if ($op->flags & OPf_SPECIAL) {
  1100. $cxix = dopoptoloop();
  1101. if ($cxix < 0) {
  1102. error('"redo" used outside loop');
  1103. return $op->next; # ignore the op
  1104. }
  1105. } else {
  1106. $cxix = dopoptolabel($op->pv);
  1107. if ($cxix < 0) {
  1108. error('Label not found at compile time for "redo %s"', $op->pv);
  1109. return $op->next; # ignore the op
  1110. }
  1111. }
  1112. default_pp($op);
  1113. my $redoop = $cxstack[$cxix]->{redoop};
  1114. push(@bblock_todo, $redoop);
  1115. runtime(sprintf("goto %s;", label($redoop)));
  1116. return $op->next;
  1117. }
  1118. sub pp_last {
  1119. my $op = shift;
  1120. my $cxix;
  1121. if ($op->flags & OPf_SPECIAL) {
  1122. $cxix = dopoptoloop();
  1123. if ($cxix < 0) {
  1124. error('"last" used outside loop');
  1125. return $op->next; # ignore the op
  1126. }
  1127. } else {
  1128. $cxix = dopoptolabel($op->pv);
  1129. if ($cxix < 0) {
  1130. error('Label not found at compile time for "last %s"', $op->pv);
  1131. return $op->next; # ignore the op
  1132. }
  1133. # XXX Add support for "last" to leave non-loop blocks
  1134. if ($cxstack[$cxix]->{type} != CXt_LOOP) {
  1135. error('Use of "last" for non-loop blocks is not yet implemented');
  1136. return $op->next; # ignore the op
  1137. }
  1138. }
  1139. default_pp($op);
  1140. my $lastop = $cxstack[$cxix]->{lastop}->next;
  1141. push(@bblock_todo, $lastop);
  1142. runtime(sprintf("goto %s;", label($lastop)));
  1143. return $op->next;
  1144. }
  1145. sub pp_subst {
  1146. my $op = shift;
  1147. write_back_lexicals();
  1148. write_back_stack();
  1149. my $sym = doop($op);
  1150. my $replroot = $op->pmreplroot;
  1151. if ($$replroot) {
  1152. runtime sprintf("if (PL_op == ((PMOP*)(%s))->op_pmreplroot) goto %s;",
  1153. $sym, label($replroot));
  1154. $op->pmreplstart->save;
  1155. push(@bblock_todo, $replroot);
  1156. }
  1157. invalidate_lexicals();
  1158. return $op->next;
  1159. }
  1160. sub pp_substcont {
  1161. my $op = shift;
  1162. write_back_lexicals();
  1163. write_back_stack();
  1164. doop($op);
  1165. my $pmop = $op->other;
  1166. warn sprintf("substcont: op = %s, pmop = %s\n",
  1167. peekop($op), peekop($pmop));#debug
  1168. # my $pmopsym = objsym($pmop);
  1169. my $pmopsym = $pmop->save; # XXX can this recurse?
  1170. warn "pmopsym = $pmopsym\n";#debug
  1171. runtime sprintf("if (PL_op == ((PMOP*)(%s))->op_pmreplstart) goto %s;",
  1172. $pmopsym, label($pmop->pmreplstart));
  1173. invalidate_lexicals();
  1174. return $pmop->next;
  1175. }
  1176. sub default_pp {
  1177. my $op = shift;
  1178. my $ppname = $op->ppaddr;
  1179. write_back_lexicals() unless $skip_lexicals{$ppname};
  1180. write_back_stack() unless $skip_stack{$ppname};
  1181. doop($op);
  1182. # XXX If the only way that ops can write to a TEMPORARY lexical is
  1183. # when it's named in $op->targ then we could call
  1184. # invalidate_lexicals(TEMPORARY) and avoid having to write back all
  1185. # the temporaries. For now, we'll play it safe and write back the lot.
  1186. invalidate_lexicals() unless $skip_invalidate{$ppname};
  1187. return $op->next;
  1188. }
  1189. sub compile_op {
  1190. my $op = shift;
  1191. my $ppname = $op->ppaddr;
  1192. if (exists $ignore_op{$ppname}) {
  1193. return $op->next;
  1194. }
  1195. debug peek_stack() if $debug_stack;
  1196. if ($debug_op) {
  1197. debug sprintf("%s [%s]\n",
  1198. peekop($op),
  1199. $op->flags & OPf_STACKED ? "OPf_STACKED" : $op->targ);
  1200. }
  1201. no strict 'refs';
  1202. if (defined(&$ppname)) {
  1203. $know_op = 0;
  1204. return &$ppname($op);
  1205. } else {
  1206. return default_pp($op);
  1207. }
  1208. }
  1209. sub compile_bblock {
  1210. my $op = shift;
  1211. #warn "compile_bblock: ", peekop($op), "\n"; # debug
  1212. write_label($op);
  1213. $know_op = 0;
  1214. do {
  1215. $op = compile_op($op);
  1216. } while (defined($op) && $$op && !exists($leaders->{$$op}));
  1217. write_back_stack(); # boo hoo: big loss
  1218. reload_lexicals();
  1219. return $op;
  1220. }
  1221. sub cc {
  1222. my ($name, $root, $start, @padlist) = @_;
  1223. my $op;
  1224. init_pp($name);
  1225. load_pad(@padlist);
  1226. B::Pseudoreg->new_scope;
  1227. @cxstack = ();
  1228. if ($debug_timings) {
  1229. warn sprintf("Basic block analysis at %s\n", timing_info);
  1230. }
  1231. $leaders = find_leaders($root, $start);
  1232. @bblock_todo = ($start, values %$leaders);
  1233. if ($debug_timings) {
  1234. warn sprintf("Compilation at %s\n", timing_info);
  1235. }
  1236. while (@bblock_todo) {
  1237. $op = shift @bblock_todo;
  1238. #warn sprintf("Considering basic block %s\n", peekop($op)); # debug
  1239. next if !defined($op) || !$$op || $done{$$op};
  1240. #warn "...compiling it\n"; # debug
  1241. do {
  1242. $done{$$op} = 1;
  1243. $op = compile_bblock($op);
  1244. if ($need_freetmps && $freetmps_each_bblock) {
  1245. runtime("FREETMPS;");
  1246. $need_freetmps = 0;
  1247. }
  1248. } while defined($op) && $$op && !$done{$$op};
  1249. if ($need_freetmps && $freetmps_each_loop) {
  1250. runtime("FREETMPS;");
  1251. $need_freetmps = 0;
  1252. }
  1253. if (!$$op) {
  1254. runtime("PUTBACK;","return (PL_op)?PL_op->op_next:0;");
  1255. } elsif ($done{$$op}) {
  1256. runtime(sprintf("goto %s;", label($op)));
  1257. }
  1258. }
  1259. if ($debug_timings) {
  1260. warn sprintf("Saving runtime at %s\n", timing_info);
  1261. }
  1262. save_runtime();
  1263. }
  1264. sub cc_recurse {
  1265. my $ccinfo;
  1266. my $start;
  1267. $start = cc_queue(@_) if @_;
  1268. while ($ccinfo = shift @cc_todo) {
  1269. cc(@$ccinfo);
  1270. }
  1271. return $start;
  1272. }
  1273. sub cc_obj {
  1274. my ($name, $cvref) = @_;
  1275. my $cv = svref_2object($cvref);
  1276. my @padlist = $cv->PADLIST->ARRAY;
  1277. my $curpad_sym = $padlist[1]->save;
  1278. cc_recurse($name, $cv->ROOT, $cv->START, @padlist);
  1279. }
  1280. sub cc_main {
  1281. my @comppadlist = comppadlist->ARRAY;
  1282. my $curpad_nam = $comppadlist[0]->save;
  1283. my $curpad_sym = $comppadlist[1]->save;
  1284. my $start = cc_recurse("pp_main", main_root, main_start, @comppadlist);
  1285. save_unused_subs(@unused_sub_packages);
  1286. cc_recurse();
  1287. return if $errors;
  1288. if (!defined($module)) {
  1289. $init->add(sprintf("PL_main_root = s\\_%x;", ${main_root()}),
  1290. "PL_main_start = $start;",
  1291. "PL_curpad = AvARRAY($curpad_sym);",
  1292. "av_store(CvPADLIST(PL_main_cv),0,SvREFCNT_inc($curpad_nam));",
  1293. "av_store(CvPADLIST(PL_main_cv),1,SvREFCNT_inc($curpad_sym));");
  1294. }
  1295. output_boilerplate();
  1296. print "\n";
  1297. output_all("perl_init");
  1298. output_runtime();
  1299. print "\n";
  1300. output_main();
  1301. if (defined($module)) {
  1302. my $cmodule = $module;
  1303. $cmodule =~ s/::/__/g;
  1304. print <<"EOT";
  1305. #include "XSUB.h"
  1306. XS(boot_$cmodule)
  1307. {
  1308. dXSARGS;
  1309. perl_init();
  1310. ENTER;
  1311. SAVETMPS;
  1312. SAVESPTR(PL_curpad);
  1313. SAVESPTR(PL_op);
  1314. PL_curpad = AvARRAY($curpad_sym);
  1315. PL_op = $start;
  1316. pp_main(ARGS);
  1317. FREETMPS;
  1318. LEAVE;
  1319. ST(0) = &PL_sv_yes;
  1320. XSRETURN(1);
  1321. }
  1322. EOT
  1323. }
  1324. if ($debug_timings) {
  1325. warn sprintf("Done at %s\n", timing_info);
  1326. }
  1327. }
  1328. sub compile {
  1329. my @options = @_;
  1330. my ($option, $opt, $arg);
  1331. OPTION:
  1332. while ($option = shift @options) {
  1333. if ($option =~ /^-(.)(.*)/) {
  1334. $opt = $1;
  1335. $arg = $2;
  1336. } else {
  1337. unshift @options, $option;
  1338. last OPTION;
  1339. }
  1340. if ($opt eq "-" && $arg eq "-") {
  1341. shift @options;
  1342. last OPTION;
  1343. } elsif ($opt eq "o") {
  1344. $arg ||= shift @options;
  1345. open(STDOUT, ">$arg") or return "open '>$arg': $!\n";
  1346. } elsif ($opt eq "n") {
  1347. $arg ||= shift @options;
  1348. $module_name = $arg;
  1349. } elsif ($opt eq "u") {
  1350. $arg ||= shift @options;
  1351. push(@unused_sub_packages, $arg);
  1352. } elsif ($opt eq "f") {
  1353. $arg ||= shift @options;
  1354. my $value = $arg !~ s/^no-//;
  1355. $arg =~ s/-/_/g;
  1356. my $ref = $optimise{$arg};
  1357. if (defined($ref)) {
  1358. $$ref = $value;
  1359. } else {
  1360. warn qq(ignoring unknown optimisation option "$arg"\n);
  1361. }
  1362. } elsif ($opt eq "O") {
  1363. $arg = 1 if $arg eq "";
  1364. my $ref;
  1365. foreach $ref (values %optimise) {
  1366. $$ref = 0;
  1367. }
  1368. if ($arg >= 2) {
  1369. $freetmps_each_loop = 1;
  1370. }
  1371. if ($arg >= 1) {
  1372. $freetmps_each_bblock = 1 unless $freetmps_each_loop;
  1373. }
  1374. } elsif ($opt eq "m") {
  1375. $arg ||= shift @options;
  1376. $module = $arg;
  1377. push(@unused_sub_packages, $arg);
  1378. } elsif ($opt eq "p") {
  1379. $arg ||= shift @options;
  1380. $patchlevel = $arg;
  1381. } elsif ($opt eq "D") {
  1382. $arg ||= shift @options;
  1383. foreach $arg (split(//, $arg)) {
  1384. if ($arg eq "o") {
  1385. B->debug(1);
  1386. } elsif ($arg eq "O") {
  1387. $debug_op = 1;
  1388. } elsif ($arg eq "s") {
  1389. $debug_stack = 1;
  1390. } elsif ($arg eq "c") {
  1391. $debug_cxstack = 1;
  1392. } elsif ($arg eq "p") {
  1393. $debug_pad = 1;
  1394. } elsif ($arg eq "r") {
  1395. $debug_runtime = 1;
  1396. } elsif ($arg eq "S") {
  1397. $debug_shadow = 1;
  1398. } elsif ($arg eq "q") {
  1399. $debug_queue = 1;
  1400. } elsif ($arg eq "l") {
  1401. $debug_lineno = 1;
  1402. } elsif ($arg eq "t") {
  1403. $debug_timings = 1;
  1404. }
  1405. }
  1406. }
  1407. }
  1408. init_sections();
  1409. $init = B::Section->get("init");
  1410. $decl = B::Section->get("decl");
  1411. if (@options) {
  1412. return sub {
  1413. my ($objname, $ppname);
  1414. foreach $objname (@options) {
  1415. $objname = "main::$objname" unless $objname =~ /::/;
  1416. ($ppname = $objname) =~ s/^.*?:://;
  1417. eval "cc_obj(qq(pp_sub_$ppname), \\&$objname)";
  1418. die "cc_obj(qq(pp_sub_$ppname, \\&$objname) failed: $@" if $@;
  1419. return if $errors;
  1420. }
  1421. output_boilerplate();
  1422. print "\n";
  1423. output_all($module_name || "init_module");
  1424. output_runtime();
  1425. }
  1426. } else {
  1427. return sub { cc_main() };
  1428. }
  1429. }
  1430. 1;
  1431. __END__
  1432. =head1 NAME
  1433. B::CC - Perl compiler's optimized C translation backend
  1434. =head1 SYNOPSIS
  1435. perl -MO=CC[,OPTIONS] foo.pl
  1436. =head1 DESCRIPTION
  1437. This compiler backend takes Perl source and generates C source code
  1438. corresponding to the flow of your program. In other words, this
  1439. backend is somewhat a "real" compiler in the sense that many people
  1440. think about compilers. Note however that, currently, it is a very
  1441. poor compiler in that although it generates (mostly, or at least
  1442. sometimes) correct code, it performs relatively few optimisations.
  1443. This will change as the compiler develops. The result is that
  1444. running an executable compiled with this backend may start up more
  1445. quickly than running the original Perl program (a feature shared
  1446. by the B<C> compiler backend--see F<B::C>) and may also execute
  1447. slightly faster. This is by no means a good optimising compiler--yet.
  1448. =head1 OPTIONS
  1449. If there are any non-option arguments, they are taken to be
  1450. names of objects to be saved (probably doesn't work properly yet).
  1451. Without extra arguments, it saves the main program.
  1452. =over 4
  1453. =item B<-ofilename>
  1454. Output to filename instead of STDOUT
  1455. =item B<-v>
  1456. Verbose compilation (currently gives a few compilation statistics).
  1457. =item B<-->
  1458. Force end of options
  1459. =item B<-uPackname>
  1460. Force apparently unused subs from package Packname to be compiled.
  1461. This allows programs to use eval "foo()" even when sub foo is never
  1462. seen to be used at compile time. The down side is that any subs which
  1463. really are never used also have code generated. This option is
  1464. necessary, for example, if you have a signal handler foo which you
  1465. initialise with C<$SIG{BAR} = "foo">. A better fix, though, is just
  1466. to change it to C<$SIG{BAR} = \&foo>. You can have multiple B<-u>
  1467. options. The compiler tries to figure out which packages may possibly
  1468. have subs in which need compiling but the current version doesn't do
  1469. it very well. In particular, it is confused by nested packages (i.e.
  1470. of the form C<A::B>) where package C<A> does not contain any subs.
  1471. =item B<-mModulename>
  1472. Instead of generating source for a runnable executable, generate
  1473. source for an XSUB module. The boot_Modulename function (which
  1474. DynaLoader can look for) does the appropriate initialisation and runs
  1475. the main part of the Perl source that is being compiled.
  1476. =item B<-D>
  1477. Debug options (concatenated or separate flags like C<perl -D>).
  1478. =item B<-Dr>
  1479. Writes debugging output to STDERR just as it's about to write to the
  1480. program's runtime (otherwise writes debugging info as comments in
  1481. its C output).
  1482. =item B<-DO>
  1483. Outputs each OP as it's compiled
  1484. =item B<-Ds>
  1485. Outputs the contents of the shadow stack at each OP
  1486. =item B<-Dp>
  1487. Outputs the contents of the shadow pad of lexicals as it's loaded for
  1488. each sub or the main program.
  1489. =item B<-Dq>
  1490. Outputs the name of each fake PP function in the queue as it's about
  1491. to process it.
  1492. =item B<-Dl>
  1493. Output the filename and line number of each original line of Perl
  1494. code as it's processed (C<pp_nextstate>).
  1495. =item B<-Dt>
  1496. Outputs timing information of compilation stages.
  1497. =item B<-f>
  1498. Force optimisations on or off one at a time.
  1499. =item B<-ffreetmps-each-bblock>
  1500. Delays FREETMPS from the end of each statement to the end of the each
  1501. basic block.
  1502. =item B<-ffreetmps-each-loop>
  1503. Delays FREETMPS from the end of each statement to the end of the group
  1504. of basic blocks forming a loop. At most one of the freetmps-each-*
  1505. options can be used.
  1506. =item B<-fomit-taint>
  1507. Omits generating code for handling perl's tainting mechanism.
  1508. =item B<-On>
  1509. Optimisation level (n = 0, 1, 2, ...). B<-O> means B<-O1>.
  1510. Currently, B<-O1> sets B<-ffreetmps-each-bblock> and B<-O2>
  1511. sets B<-ffreetmps-each-loop>.
  1512. =back
  1513. =head1 EXAMPLES
  1514. perl -MO=CC,-O2,-ofoo.c foo.pl
  1515. perl cc_harness -o foo foo.c
  1516. Note that C<cc_harness> lives in the C<B> subdirectory of your perl
  1517. library directory. The utility called C<perlcc> may also be used to
  1518. help make use of this compiler.
  1519. perl -MO=CC,-mFoo,-oFoo.c Foo.pm
  1520. perl cc_harness -shared -c -o Foo.so Foo.c
  1521. =head1 BUGS
  1522. Plenty. Current status: experimental.
  1523. =head1 DIFFERENCES
  1524. These aren't really bugs but they are constructs which are heavily
  1525. tied to perl's compile-and-go implementation and with which this
  1526. compiler backend cannot cope.
  1527. =head2 Loops
  1528. Standard perl calculates the target of "next", "last", and "redo"
  1529. at run-time. The compiler calculates the targets at compile-time.
  1530. For example, the program
  1531. sub skip_on_odd { next NUMBER if $_[0] % 2 }
  1532. NUMBER: for ($i = 0; $i < 5; $i++) {
  1533. skip_on_odd($i);
  1534. print $i;
  1535. }
  1536. produces the output
  1537. 024
  1538. with standard perl but gives a compile-time error with the compiler.
  1539. =head2 Context of ".."
  1540. The context (scalar or array) of the ".." operator determines whether
  1541. it behaves as a range or a flip/flop. Standard perl delays until
  1542. runtime the decision of which context it is in but the compiler needs
  1543. to know the context at compile-time. For example,
  1544. @a = (4,6,1,0,0,1);
  1545. sub range { (shift @a)..(shift @a) }
  1546. print range();
  1547. while (@a) { print scalar(range()) }
  1548. generates the output
  1549. 456123E0
  1550. with standard Perl but gives a compile-time error with compiled Perl.
  1551. =head2 Arithmetic
  1552. Compiled Perl programs use native C arithemtic much more frequently
  1553. than standard perl. Operations on large numbers or on boundary
  1554. cases may produce different behaviour.
  1555. =head2 Deprecated features
  1556. Features of standard perl such as C<$[> which have been deprecated
  1557. in standard perl since Perl5 was released have not been implemented
  1558. in the compiler.
  1559. =head1 AUTHOR
  1560. Malcolm Beattie, C<[email protected]>
  1561. =cut