This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #113470] Constant folding for pack
[perl5.git] / op.c
1 #line 2 "op.c"
2 /*    op.c
3  *
4  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
5  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'You see: Mr. Drogo, he married poor Miss Primula Brandybuck.  She was
14  *  our Mr. Bilbo's first cousin on the mother's side (her mother being the
15  *  youngest of the Old Took's daughters); and Mr. Drogo was his second
16  *  cousin.  So Mr. Frodo is his first *and* second cousin, once removed
17  *  either way, as the saying is, if you follow me.'       --the Gaffer
18  *
19  *     [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
20  */
21
22 /* This file contains the functions that create, manipulate and optimize
23  * the OP structures that hold a compiled perl program.
24  *
25  * A Perl program is compiled into a tree of OPs. Each op contains
26  * structural pointers (eg to its siblings and the next op in the
27  * execution sequence), a pointer to the function that would execute the
28  * op, plus any data specific to that op. For example, an OP_CONST op
29  * points to the pp_const() function and to an SV containing the constant
30  * value. When pp_const() is executed, its job is to push that SV onto the
31  * stack.
32  *
33  * OPs are mainly created by the newFOO() functions, which are mainly
34  * called from the parser (in perly.y) as the code is parsed. For example
35  * the Perl code $a + $b * $c would cause the equivalent of the following
36  * to be called (oversimplifying a bit):
37  *
38  *  newBINOP(OP_ADD, flags,
39  *      newSVREF($a),
40  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
41  *  )
42  *
43  * Note that during the build of miniperl, a temporary copy of this file
44  * is made, called opmini.c.
45  */
46
47 /*
48 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
49
50     A bottom-up pass
51     A top-down pass
52     An execution-order pass
53
54 The bottom-up pass is represented by all the "newOP" routines and
55 the ck_ routines.  The bottom-upness is actually driven by yacc.
56 So at the point that a ck_ routine fires, we have no idea what the
57 context is, either upward in the syntax tree, or either forward or
58 backward in the execution order.  (The bottom-up parser builds that
59 part of the execution order it knows about, but if you follow the "next"
60 links around, you'll find it's actually a closed loop through the
61 top level node.)
62
63 Whenever the bottom-up parser gets to a node that supplies context to
64 its components, it invokes that portion of the top-down pass that applies
65 to that part of the subtree (and marks the top node as processed, so
66 if a node further up supplies context, it doesn't have to take the
67 plunge again).  As a particular subcase of this, as the new node is
68 built, it takes all the closed execution loops of its subcomponents
69 and links them into a new closed loop for the higher level node.  But
70 it's still not the real execution order.
71
72 The actual execution order is not known till we get a grammar reduction
73 to a top-level unit like a subroutine or file that will be called by
74 "name" rather than via a "next" pointer.  At that point, we can call
75 into peep() to do that code's portion of the 3rd pass.  It has to be
76 recursive, but it's recursive on basic blocks, not on tree nodes.
77 */
78
79 /* To implement user lexical pragmas, there needs to be a way at run time to
80    get the compile time state of %^H for that block.  Storing %^H in every
81    block (or even COP) would be very expensive, so a different approach is
82    taken.  The (running) state of %^H is serialised into a tree of HE-like
83    structs.  Stores into %^H are chained onto the current leaf as a struct
84    refcounted_he * with the key and the value.  Deletes from %^H are saved
85    with a value of PL_sv_placeholder.  The state of %^H at any point can be
86    turned back into a regular HV by walking back up the tree from that point's
87    leaf, ignoring any key you've already seen (placeholder or not), storing
88    the rest into the HV structure, then removing the placeholders. Hence
89    memory is only used to store the %^H deltas from the enclosing COP, rather
90    than the entire %^H on each COP.
91
92    To cause actions on %^H to write out the serialisation records, it has
93    magic type 'H'. This magic (itself) does nothing, but its presence causes
94    the values to gain magic type 'h', which has entries for set and clear.
95    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
96    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
97    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
98    it will be correctly restored when any inner compiling scope is exited.
99 */
100
101 #include "EXTERN.h"
102 #define PERL_IN_OP_C
103 #include "perl.h"
104 #include "keywords.h"
105 #include "feature.h"
106 #include "regcomp.h"
107
108 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
109 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
110 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
111
112 /* See the explanatory comments above struct opslab in op.h. */
113
114 #ifdef PERL_DEBUG_READONLY_OPS
115 #  define PERL_SLAB_SIZE 128
116 #  define PERL_MAX_SLAB_SIZE 4096
117 #  include <sys/mman.h>
118 #endif
119
120 #ifndef PERL_SLAB_SIZE
121 #  define PERL_SLAB_SIZE 64
122 #endif
123 #ifndef PERL_MAX_SLAB_SIZE
124 #  define PERL_MAX_SLAB_SIZE 2048
125 #endif
126
127 /* rounds up to nearest pointer */
128 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
129 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
130
131 static OPSLAB *
132 S_new_slab(pTHX_ size_t sz)
133 {
134 #ifdef PERL_DEBUG_READONLY_OPS
135     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
136                                    PROT_READ|PROT_WRITE,
137                                    MAP_ANON|MAP_PRIVATE, -1, 0);
138     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
139                           (unsigned long) sz, slab));
140     if (slab == MAP_FAILED) {
141         perror("mmap failed");
142         abort();
143     }
144     slab->opslab_size = (U16)sz;
145 #else
146     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
147 #endif
148     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
149     return slab;
150 }
151
152 /* requires double parens and aTHX_ */
153 #define DEBUG_S_warn(args)                                             \
154     DEBUG_S(                                                            \
155         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
156     )
157
158 void *
159 Perl_Slab_Alloc(pTHX_ size_t sz)
160 {
161     dVAR;
162     OPSLAB *slab;
163     OPSLAB *slab2;
164     OPSLOT *slot;
165     OP *o;
166     size_t opsz, space;
167
168     if (!PL_compcv || CvROOT(PL_compcv)
169      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
170         return PerlMemShared_calloc(1, sz);
171
172     if (!CvSTART(PL_compcv)) { /* sneak it in here */
173         CvSTART(PL_compcv) =
174             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
175         CvSLABBED_on(PL_compcv);
176         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
177     }
178     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
179
180     opsz = SIZE_TO_PSIZE(sz);
181     sz = opsz + OPSLOT_HEADER_P;
182
183     if (slab->opslab_freed) {
184         OP **too = &slab->opslab_freed;
185         o = *too;
186         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", o, slab));
187         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
188             DEBUG_S_warn((aTHX_ "Alas! too small"));
189             o = *(too = &o->op_next);
190             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", o)); }
191         }
192         if (o) {
193             *too = o->op_next;
194             Zero(o, opsz, I32 *);
195             o->op_slabbed = 1;
196             return (void *)o;
197         }
198     }
199
200 #define INIT_OPSLOT \
201             slot->opslot_slab = slab;                   \
202             slot->opslot_next = slab2->opslab_first;    \
203             slab2->opslab_first = slot;                 \
204             o = &slot->opslot_op;                       \
205             o->op_slabbed = 1
206
207     /* The partially-filled slab is next in the chain. */
208     slab2 = slab->opslab_next ? slab->opslab_next : slab;
209     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
210         /* Remaining space is too small. */
211
212         /* If we can fit a BASEOP, add it to the free chain, so as not
213            to waste it. */
214         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
215             slot = &slab2->opslab_slots;
216             INIT_OPSLOT;
217             o->op_type = OP_FREED;
218             o->op_next = slab->opslab_freed;
219             slab->opslab_freed = o;
220         }
221
222         /* Create a new slab.  Make this one twice as big. */
223         slot = slab2->opslab_first;
224         while (slot->opslot_next) slot = slot->opslot_next;
225         slab2 = S_new_slab(aTHX_
226                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
227                                         ? PERL_MAX_SLAB_SIZE
228                                         : (DIFF(slab2, slot)+1)*2);
229         slab2->opslab_next = slab->opslab_next;
230         slab->opslab_next = slab2;
231     }
232     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
233
234     /* Create a new op slot */
235     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
236     assert(slot >= &slab2->opslab_slots);
237     if (DIFF(&slab2->opslab_slots, slot)
238          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
239         slot = &slab2->opslab_slots;
240     INIT_OPSLOT;
241     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", o, slab));
242     return (void *)o;
243 }
244
245 #undef INIT_OPSLOT
246
247 #ifdef PERL_DEBUG_READONLY_OPS
248 void
249 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
250 {
251     PERL_ARGS_ASSERT_SLAB_TO_RO;
252
253     if (slab->opslab_readonly) return;
254     slab->opslab_readonly = 1;
255     for (; slab; slab = slab->opslab_next) {
256         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
257                               (unsigned long) slab->opslab_size, slab));*/
258         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
259             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
260                              (unsigned long)slab->opslab_size, errno);
261     }
262 }
263
264 STATIC void
265 S_Slab_to_rw(pTHX_ void *op)
266 {
267     OP * const o = (OP *)op;
268     OPSLAB *slab;
269     OPSLAB *slab2;
270
271     PERL_ARGS_ASSERT_SLAB_TO_RW;
272
273     if (!o->op_slabbed) return;
274
275     slab = OpSLAB(o);
276     if (!slab->opslab_readonly) return;
277     slab2 = slab;
278     for (; slab2; slab2 = slab2->opslab_next) {
279         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
280                               (unsigned long) size, slab2));*/
281         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
282                      PROT_READ|PROT_WRITE)) {
283             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
284                              (unsigned long)slab2->opslab_size, errno);
285         }
286     }
287     slab->opslab_readonly = 0;
288 }
289
290 #else
291 #  define Slab_to_rw(op)
292 #endif
293
294 /* This cannot possibly be right, but it was copied from the old slab
295    allocator, to which it was originally added, without explanation, in
296    commit 083fcd5. */
297 #ifdef NETWARE
298 #    define PerlMemShared PerlMem
299 #endif
300
301 void
302 Perl_Slab_Free(pTHX_ void *op)
303 {
304     dVAR;
305     OP * const o = (OP *)op;
306     OPSLAB *slab;
307
308     PERL_ARGS_ASSERT_SLAB_FREE;
309
310     if (!o->op_slabbed) {
311         PerlMemShared_free(op);
312         return;
313     }
314
315     slab = OpSLAB(o);
316     /* If this op is already freed, our refcount will get screwy. */
317     assert(o->op_type != OP_FREED);
318     o->op_type = OP_FREED;
319     o->op_next = slab->opslab_freed;
320     slab->opslab_freed = o;
321     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", o, slab));
322     OpslabREFCNT_dec_padok(slab);
323 }
324
325 void
326 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
327 {
328     dVAR;
329     const bool havepad = !!PL_comppad;
330     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
331     if (havepad) {
332         ENTER;
333         PAD_SAVE_SETNULLPAD();
334     }
335     opslab_free(slab);
336     if (havepad) LEAVE;
337 }
338
339 void
340 Perl_opslab_free(pTHX_ OPSLAB *slab)
341 {
342     dVAR;
343     OPSLAB *slab2;
344     PERL_ARGS_ASSERT_OPSLAB_FREE;
345     DEBUG_S_warn((aTHX_ "freeing slab %p", slab));
346     assert(slab->opslab_refcnt == 1);
347     for (; slab; slab = slab2) {
348         slab2 = slab->opslab_next;
349 #ifdef DEBUGGING
350         slab->opslab_refcnt = ~(size_t)0;
351 #endif
352 #ifdef PERL_DEBUG_READONLY_OPS
353         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
354                                                slab));
355         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
356             perror("munmap failed");
357             abort();
358         }
359 #else
360         PerlMemShared_free(slab);
361 #endif
362     }
363 }
364
365 void
366 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
367 {
368     OPSLAB *slab2;
369     OPSLOT *slot;
370 #ifdef DEBUGGING
371     size_t savestack_count = 0;
372 #endif
373     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
374     slab2 = slab;
375     do {
376         for (slot = slab2->opslab_first;
377              slot->opslot_next;
378              slot = slot->opslot_next) {
379             if (slot->opslot_op.op_type != OP_FREED
380              && !(slot->opslot_op.op_savefree
381 #ifdef DEBUGGING
382                   && ++savestack_count
383 #endif
384                  )
385             ) {
386                 assert(slot->opslot_op.op_slabbed);
387                 slab->opslab_refcnt++; /* op_free may free slab */
388                 op_free(&slot->opslot_op);
389                 if (!--slab->opslab_refcnt) goto free;
390             }
391         }
392     } while ((slab2 = slab2->opslab_next));
393     /* > 1 because the CV still holds a reference count. */
394     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
395 #ifdef DEBUGGING
396         assert(savestack_count == slab->opslab_refcnt-1);
397 #endif
398         return;
399     }
400    free:
401     opslab_free(slab);
402 }
403
404 #ifdef PERL_DEBUG_READONLY_OPS
405 OP *
406 Perl_op_refcnt_inc(pTHX_ OP *o)
407 {
408     if(o) {
409         Slab_to_rw(o);
410         ++o->op_targ;
411     }
412     return o;
413
414 }
415
416 PADOFFSET
417 Perl_op_refcnt_dec(pTHX_ OP *o)
418 {
419     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
420     Slab_to_rw(o);
421     return --o->op_targ;
422 }
423 #endif
424 /*
425  * In the following definition, the ", (OP*)0" is just to make the compiler
426  * think the expression is of the right type: croak actually does a Siglongjmp.
427  */
428 #define CHECKOP(type,o) \
429     ((PL_op_mask && PL_op_mask[type])                           \
430      ? ( op_free((OP*)o),                                       \
431          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
432          (OP*)0 )                                               \
433      : PL_check[type](aTHX_ (OP*)o))
434
435 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
436
437 #define CHANGE_TYPE(o,type) \
438     STMT_START {                                \
439         o->op_type = (OPCODE)type;              \
440         o->op_ppaddr = PL_ppaddr[type];         \
441     } STMT_END
442
443 STATIC SV*
444 S_gv_ename(pTHX_ GV *gv)
445 {
446     SV* const tmpsv = sv_newmortal();
447
448     PERL_ARGS_ASSERT_GV_ENAME;
449
450     gv_efullname3(tmpsv, gv, NULL);
451     return tmpsv;
452 }
453
454 STATIC OP *
455 S_no_fh_allowed(pTHX_ OP *o)
456 {
457     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
458
459     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
460                  OP_DESC(o)));
461     return o;
462 }
463
464 STATIC OP *
465 S_too_few_arguments_sv(pTHX_ OP *o, SV *namesv, U32 flags)
466 {
467     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_SV;
468     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf, namesv),
469                                     SvUTF8(namesv) | flags);
470     return o;
471 }
472
473 STATIC OP *
474 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
475 {
476     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
477     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
478     return o;
479 }
480  
481 STATIC OP *
482 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
483 {
484     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
485
486     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
487     return o;
488 }
489
490 STATIC OP *
491 S_too_many_arguments_sv(pTHX_ OP *o, SV *namesv, U32 flags)
492 {
493     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_SV;
494
495     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf, SVfARG(namesv)),
496                 SvUTF8(namesv) | flags);
497     return o;
498 }
499
500 STATIC void
501 S_bad_type_pv(pTHX_ I32 n, const char *t, const char *name, U32 flags, const OP *kid)
502 {
503     PERL_ARGS_ASSERT_BAD_TYPE_PV;
504
505     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
506                  (int)n, name, t, OP_DESC(kid)), flags);
507 }
508
509 STATIC void
510 S_bad_type_sv(pTHX_ I32 n, const char *t, SV *namesv, U32 flags, const OP *kid)
511 {
512     PERL_ARGS_ASSERT_BAD_TYPE_SV;
513  
514     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
515                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv) | flags);
516 }
517
518 STATIC void
519 S_no_bareword_allowed(pTHX_ OP *o)
520 {
521     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
522
523     if (PL_madskills)
524         return;         /* various ok barewords are hidden in extra OP_NULL */
525     qerror(Perl_mess(aTHX_
526                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
527                      SVfARG(cSVOPo_sv)));
528     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
529 }
530
531 /* "register" allocation */
532
533 PADOFFSET
534 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
535 {
536     dVAR;
537     PADOFFSET off;
538     const bool is_our = (PL_parser->in_my == KEY_our);
539
540     PERL_ARGS_ASSERT_ALLOCMY;
541
542     if (flags & ~SVf_UTF8)
543         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
544                    (UV)flags);
545
546     /* Until we're using the length for real, cross check that we're being
547        told the truth.  */
548     assert(strlen(name) == len);
549
550     /* complain about "my $<special_var>" etc etc */
551     if (len &&
552         !(is_our ||
553           isALPHA(name[1]) ||
554           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
555           (name[1] == '_' && (*name == '$' || len > 2))))
556     {
557         /* name[2] is true if strlen(name) > 2  */
558         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
559          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
560             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
561                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
562                               PL_parser->in_my == KEY_state ? "state" : "my"));
563         } else {
564             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
565                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
566         }
567     }
568
569     /* allocate a spare slot and store the name in that slot */
570
571     off = pad_add_name_pvn(name, len,
572                        (is_our ? padadd_OUR :
573                         PL_parser->in_my == KEY_state ? padadd_STATE : 0)
574                             | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ),
575                     PL_parser->in_my_stash,
576                     (is_our
577                         /* $_ is always in main::, even with our */
578                         ? (PL_curstash && !strEQ(name,"$_") ? PL_curstash : PL_defstash)
579                         : NULL
580                     )
581     );
582     /* anon sub prototypes contains state vars should always be cloned,
583      * otherwise the state var would be shared between anon subs */
584
585     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
586         CvCLONE_on(PL_compcv);
587
588     return off;
589 }
590
591 /*
592 =for apidoc alloccopstash
593
594 Available only under threaded builds, this function allocates an entry in
595 C<PL_stashpad> for the stash passed to it.
596
597 =cut
598 */
599
600 #ifdef USE_ITHREADS
601 PADOFFSET
602 Perl_alloccopstash(pTHX_ HV *hv)
603 {
604     PADOFFSET off = 0, o = 1;
605     bool found_slot = FALSE;
606
607     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
608
609     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
610
611     for (; o < PL_stashpadmax; ++o) {
612         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
613         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
614             found_slot = TRUE, off = o;
615     }
616     if (!found_slot) {
617         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
618         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
619         off = PL_stashpadmax;
620         PL_stashpadmax += 10;
621     }
622
623     PL_stashpad[PL_stashpadix = off] = hv;
624     return off;
625 }
626 #endif
627
628 /* free the body of an op without examining its contents.
629  * Always use this rather than FreeOp directly */
630
631 static void
632 S_op_destroy(pTHX_ OP *o)
633 {
634     if (o->op_latefree) {
635         o->op_latefreed = 1;
636         return;
637     }
638     FreeOp(o);
639 }
640
641 #ifdef USE_ITHREADS
642 #  define forget_pmop(a,b)      S_forget_pmop(aTHX_ a,b)
643 #else
644 #  define forget_pmop(a,b)      S_forget_pmop(aTHX_ a)
645 #endif
646
647 /* Destructor */
648
649 void
650 Perl_op_free(pTHX_ OP *o)
651 {
652     dVAR;
653     OPCODE type;
654
655     /* Though ops may be freed twice, freeing the op after its slab is a
656        big no-no. */
657     assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0); 
658     /* During the forced freeing of ops after compilation failure, kidops
659        may be freed before their parents. */
660     if (!o || o->op_type == OP_FREED)
661         return;
662     if (o->op_latefreed) {
663         if (o->op_latefree)
664             return;
665         goto do_free;
666     }
667
668     type = o->op_type;
669     if (o->op_private & OPpREFCOUNTED) {
670         switch (type) {
671         case OP_LEAVESUB:
672         case OP_LEAVESUBLV:
673         case OP_LEAVEEVAL:
674         case OP_LEAVE:
675         case OP_SCOPE:
676         case OP_LEAVEWRITE:
677             {
678             PADOFFSET refcnt;
679             OP_REFCNT_LOCK;
680             refcnt = OpREFCNT_dec(o);
681             OP_REFCNT_UNLOCK;
682             if (refcnt) {
683                 /* Need to find and remove any pattern match ops from the list
684                    we maintain for reset().  */
685                 find_and_forget_pmops(o);
686                 return;
687             }
688             }
689             break;
690         default:
691             break;
692         }
693     }
694
695     /* Call the op_free hook if it has been set. Do it now so that it's called
696      * at the right time for refcounted ops, but still before all of the kids
697      * are freed. */
698     CALL_OPFREEHOOK(o);
699
700     if (o->op_flags & OPf_KIDS) {
701         register OP *kid, *nextkid;
702         for (kid = cUNOPo->op_first; kid; kid = nextkid) {
703             nextkid = kid->op_sibling; /* Get before next freeing kid */
704             op_free(kid);
705         }
706     }
707
708     Slab_to_rw(o);
709
710     /* COP* is not cleared by op_clear() so that we may track line
711      * numbers etc even after null() */
712     if (type == OP_NEXTSTATE || type == OP_DBSTATE
713             || (type == OP_NULL /* the COP might have been null'ed */
714                 && ((OPCODE)o->op_targ == OP_NEXTSTATE
715                     || (OPCODE)o->op_targ == OP_DBSTATE))) {
716         cop_free((COP*)o);
717     }
718
719     if (type == OP_NULL)
720         type = (OPCODE)o->op_targ;
721
722     op_clear(o);
723     if (o->op_latefree) {
724         o->op_latefreed = 1;
725         return;
726     }
727   do_free:
728     FreeOp(o);
729 #ifdef DEBUG_LEAKING_SCALARS
730     if (PL_op == o)
731         PL_op = NULL;
732 #endif
733 }
734
735 void
736 Perl_op_clear(pTHX_ OP *o)
737 {
738
739     dVAR;
740
741     PERL_ARGS_ASSERT_OP_CLEAR;
742
743 #ifdef PERL_MAD
744     mad_free(o->op_madprop);
745     o->op_madprop = 0;
746 #endif    
747
748  retry:
749     switch (o->op_type) {
750     case OP_NULL:       /* Was holding old type, if any. */
751         if (PL_madskills && o->op_targ != OP_NULL) {
752             o->op_type = (Optype)o->op_targ;
753             o->op_targ = 0;
754             goto retry;
755         }
756     case OP_ENTERTRY:
757     case OP_ENTEREVAL:  /* Was holding hints. */
758         o->op_targ = 0;
759         break;
760     default:
761         if (!(o->op_flags & OPf_REF)
762             || (PL_check[o->op_type] != Perl_ck_ftst))
763             break;
764         /* FALL THROUGH */
765     case OP_GVSV:
766     case OP_GV:
767     case OP_AELEMFAST:
768         {
769             GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV)
770 #ifdef USE_ITHREADS
771                         && PL_curpad
772 #endif
773                         ? cGVOPo_gv : NULL;
774             /* It's possible during global destruction that the GV is freed
775                before the optree. Whilst the SvREFCNT_inc is happy to bump from
776                0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
777                will trigger an assertion failure, because the entry to sv_clear
778                checks that the scalar is not already freed.  A check of for
779                !SvIS_FREED(gv) turns out to be invalid, because during global
780                destruction the reference count can be forced down to zero
781                (with SVf_BREAK set).  In which case raising to 1 and then
782                dropping to 0 triggers cleanup before it should happen.  I
783                *think* that this might actually be a general, systematic,
784                weakness of the whole idea of SVf_BREAK, in that code *is*
785                allowed to raise and lower references during global destruction,
786                so any *valid* code that happens to do this during global
787                destruction might well trigger premature cleanup.  */
788             bool still_valid = gv && SvREFCNT(gv);
789
790             if (still_valid)
791                 SvREFCNT_inc_simple_void(gv);
792 #ifdef USE_ITHREADS
793             if (cPADOPo->op_padix > 0) {
794                 /* No GvIN_PAD_off(cGVOPo_gv) here, because other references
795                  * may still exist on the pad */
796                 pad_swipe(cPADOPo->op_padix, TRUE);
797                 cPADOPo->op_padix = 0;
798             }
799 #else
800             SvREFCNT_dec(cSVOPo->op_sv);
801             cSVOPo->op_sv = NULL;
802 #endif
803             if (still_valid) {
804                 int try_downgrade = SvREFCNT(gv) == 2;
805                 SvREFCNT_dec(gv);
806                 if (try_downgrade)
807                     gv_try_downgrade(gv);
808             }
809         }
810         break;
811     case OP_METHOD_NAMED:
812     case OP_CONST:
813     case OP_HINTSEVAL:
814         SvREFCNT_dec(cSVOPo->op_sv);
815         cSVOPo->op_sv = NULL;
816 #ifdef USE_ITHREADS
817         /** Bug #15654
818           Even if op_clear does a pad_free for the target of the op,
819           pad_free doesn't actually remove the sv that exists in the pad;
820           instead it lives on. This results in that it could be reused as 
821           a target later on when the pad was reallocated.
822         **/
823         if(o->op_targ) {
824           pad_swipe(o->op_targ,1);
825           o->op_targ = 0;
826         }
827 #endif
828         break;
829     case OP_GOTO:
830     case OP_NEXT:
831     case OP_LAST:
832     case OP_REDO:
833         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
834             break;
835         /* FALL THROUGH */
836     case OP_TRANS:
837     case OP_TRANSR:
838         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
839 #ifdef USE_ITHREADS
840             if (cPADOPo->op_padix > 0) {
841                 pad_swipe(cPADOPo->op_padix, TRUE);
842                 cPADOPo->op_padix = 0;
843             }
844 #else
845             SvREFCNT_dec(cSVOPo->op_sv);
846             cSVOPo->op_sv = NULL;
847 #endif
848         }
849         else {
850             PerlMemShared_free(cPVOPo->op_pv);
851             cPVOPo->op_pv = NULL;
852         }
853         break;
854     case OP_SUBST:
855         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
856         goto clear_pmop;
857     case OP_PUSHRE:
858 #ifdef USE_ITHREADS
859         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
860             /* No GvIN_PAD_off here, because other references may still
861              * exist on the pad */
862             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
863         }
864 #else
865         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
866 #endif
867         /* FALL THROUGH */
868     case OP_MATCH:
869     case OP_QR:
870 clear_pmop:
871         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
872             op_free(cPMOPo->op_code_list);
873         cPMOPo->op_code_list = NULL;
874         forget_pmop(cPMOPo, 1);
875         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
876         /* we use the same protection as the "SAFE" version of the PM_ macros
877          * here since sv_clean_all might release some PMOPs
878          * after PL_regex_padav has been cleared
879          * and the clearing of PL_regex_padav needs to
880          * happen before sv_clean_all
881          */
882 #ifdef USE_ITHREADS
883         if(PL_regex_pad) {        /* We could be in destruction */
884             const IV offset = (cPMOPo)->op_pmoffset;
885             ReREFCNT_dec(PM_GETRE(cPMOPo));
886             PL_regex_pad[offset] = &PL_sv_undef;
887             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
888                            sizeof(offset));
889         }
890 #else
891         ReREFCNT_dec(PM_GETRE(cPMOPo));
892         PM_SETRE(cPMOPo, NULL);
893 #endif
894
895         break;
896     }
897
898     if (o->op_targ > 0) {
899         pad_free(o->op_targ);
900         o->op_targ = 0;
901     }
902 }
903
904 STATIC void
905 S_cop_free(pTHX_ COP* cop)
906 {
907     PERL_ARGS_ASSERT_COP_FREE;
908
909     CopFILE_free(cop);
910     if (! specialWARN(cop->cop_warnings))
911         PerlMemShared_free(cop->cop_warnings);
912     cophh_free(CopHINTHASH_get(cop));
913 }
914
915 STATIC void
916 S_forget_pmop(pTHX_ PMOP *const o
917 #ifdef USE_ITHREADS
918               , U32 flags
919 #endif
920               )
921 {
922     HV * const pmstash = PmopSTASH(o);
923
924     PERL_ARGS_ASSERT_FORGET_PMOP;
925
926     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
927         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
928         if (mg) {
929             PMOP **const array = (PMOP**) mg->mg_ptr;
930             U32 count = mg->mg_len / sizeof(PMOP**);
931             U32 i = count;
932
933             while (i--) {
934                 if (array[i] == o) {
935                     /* Found it. Move the entry at the end to overwrite it.  */
936                     array[i] = array[--count];
937                     mg->mg_len = count * sizeof(PMOP**);
938                     /* Could realloc smaller at this point always, but probably
939                        not worth it. Probably worth free()ing if we're the
940                        last.  */
941                     if(!count) {
942                         Safefree(mg->mg_ptr);
943                         mg->mg_ptr = NULL;
944                     }
945                     break;
946                 }
947             }
948         }
949     }
950     if (PL_curpm == o) 
951         PL_curpm = NULL;
952 #ifdef USE_ITHREADS
953     if (flags)
954         PmopSTASH_free(o);
955 #endif
956 }
957
958 STATIC void
959 S_find_and_forget_pmops(pTHX_ OP *o)
960 {
961     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
962
963     if (o->op_flags & OPf_KIDS) {
964         OP *kid = cUNOPo->op_first;
965         while (kid) {
966             switch (kid->op_type) {
967             case OP_SUBST:
968             case OP_PUSHRE:
969             case OP_MATCH:
970             case OP_QR:
971                 forget_pmop((PMOP*)kid, 0);
972             }
973             find_and_forget_pmops(kid);
974             kid = kid->op_sibling;
975         }
976     }
977 }
978
979 void
980 Perl_op_null(pTHX_ OP *o)
981 {
982     dVAR;
983
984     PERL_ARGS_ASSERT_OP_NULL;
985
986     if (o->op_type == OP_NULL)
987         return;
988     if (!PL_madskills)
989         op_clear(o);
990     o->op_targ = o->op_type;
991     o->op_type = OP_NULL;
992     o->op_ppaddr = PL_ppaddr[OP_NULL];
993 }
994
995 void
996 Perl_op_refcnt_lock(pTHX)
997 {
998     dVAR;
999     PERL_UNUSED_CONTEXT;
1000     OP_REFCNT_LOCK;
1001 }
1002
1003 void
1004 Perl_op_refcnt_unlock(pTHX)
1005 {
1006     dVAR;
1007     PERL_UNUSED_CONTEXT;
1008     OP_REFCNT_UNLOCK;
1009 }
1010
1011 /* Contextualizers */
1012
1013 /*
1014 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1015
1016 Applies a syntactic context to an op tree representing an expression.
1017 I<o> is the op tree, and I<context> must be C<G_SCALAR>, C<G_ARRAY>,
1018 or C<G_VOID> to specify the context to apply.  The modified op tree
1019 is returned.
1020
1021 =cut
1022 */
1023
1024 OP *
1025 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1026 {
1027     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1028     switch (context) {
1029         case G_SCALAR: return scalar(o);
1030         case G_ARRAY:  return list(o);
1031         case G_VOID:   return scalarvoid(o);
1032         default:
1033             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1034                        (long) context);
1035             return o;
1036     }
1037 }
1038
1039 /*
1040 =head1 Optree Manipulation Functions
1041
1042 =for apidoc Am|OP*|op_linklist|OP *o
1043 This function is the implementation of the L</LINKLIST> macro. It should
1044 not be called directly.
1045
1046 =cut
1047 */
1048
1049 OP *
1050 Perl_op_linklist(pTHX_ OP *o)
1051 {
1052     OP *first;
1053
1054     PERL_ARGS_ASSERT_OP_LINKLIST;
1055
1056     if (o->op_next)
1057         return o->op_next;
1058
1059     /* establish postfix order */
1060     first = cUNOPo->op_first;
1061     if (first) {
1062         register OP *kid;
1063         o->op_next = LINKLIST(first);
1064         kid = first;
1065         for (;;) {
1066             if (kid->op_sibling) {
1067                 kid->op_next = LINKLIST(kid->op_sibling);
1068                 kid = kid->op_sibling;
1069             } else {
1070                 kid->op_next = o;
1071                 break;
1072             }
1073         }
1074     }
1075     else
1076         o->op_next = o;
1077
1078     return o->op_next;
1079 }
1080
1081 static OP *
1082 S_scalarkids(pTHX_ OP *o)
1083 {
1084     if (o && o->op_flags & OPf_KIDS) {
1085         OP *kid;
1086         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1087             scalar(kid);
1088     }
1089     return o;
1090 }
1091
1092 STATIC OP *
1093 S_scalarboolean(pTHX_ OP *o)
1094 {
1095     dVAR;
1096
1097     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1098
1099     if (o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST
1100      && !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) {
1101         if (ckWARN(WARN_SYNTAX)) {
1102             const line_t oldline = CopLINE(PL_curcop);
1103
1104             if (PL_parser && PL_parser->copline != NOLINE)
1105                 CopLINE_set(PL_curcop, PL_parser->copline);
1106             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1107             CopLINE_set(PL_curcop, oldline);
1108         }
1109     }
1110     return scalar(o);
1111 }
1112
1113 OP *
1114 Perl_scalar(pTHX_ OP *o)
1115 {
1116     dVAR;
1117     OP *kid;
1118
1119     /* assumes no premature commitment */
1120     if (!o || (PL_parser && PL_parser->error_count)
1121          || (o->op_flags & OPf_WANT)
1122          || o->op_type == OP_RETURN)
1123     {
1124         return o;
1125     }
1126
1127     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1128
1129     switch (o->op_type) {
1130     case OP_REPEAT:
1131         scalar(cBINOPo->op_first);
1132         break;
1133     case OP_OR:
1134     case OP_AND:
1135     case OP_COND_EXPR:
1136         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
1137             scalar(kid);
1138         break;
1139         /* FALL THROUGH */
1140     case OP_SPLIT:
1141     case OP_MATCH:
1142     case OP_QR:
1143     case OP_SUBST:
1144     case OP_NULL:
1145     default:
1146         if (o->op_flags & OPf_KIDS) {
1147             for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1148                 scalar(kid);
1149         }
1150         break;
1151     case OP_LEAVE:
1152     case OP_LEAVETRY:
1153         kid = cLISTOPo->op_first;
1154         scalar(kid);
1155         kid = kid->op_sibling;
1156     do_kids:
1157         while (kid) {
1158             OP *sib = kid->op_sibling;
1159             if (sib && kid->op_type != OP_LEAVEWHEN)
1160                 scalarvoid(kid);
1161             else
1162                 scalar(kid);
1163             kid = sib;
1164         }
1165         PL_curcop = &PL_compiling;
1166         break;
1167     case OP_SCOPE:
1168     case OP_LINESEQ:
1169     case OP_LIST:
1170         kid = cLISTOPo->op_first;
1171         goto do_kids;
1172     case OP_SORT:
1173         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1174         break;
1175     }
1176     return o;
1177 }
1178
1179 OP *
1180 Perl_scalarvoid(pTHX_ OP *o)
1181 {
1182     dVAR;
1183     OP *kid;
1184     const char* useless = NULL;
1185     U32 useless_is_utf8 = 0;
1186     SV* sv;
1187     U8 want;
1188
1189     PERL_ARGS_ASSERT_SCALARVOID;
1190
1191     /* trailing mad null ops don't count as "there" for void processing */
1192     if (PL_madskills &&
1193         o->op_type != OP_NULL &&
1194         o->op_sibling &&
1195         o->op_sibling->op_type == OP_NULL)
1196     {
1197         OP *sib;
1198         for (sib = o->op_sibling;
1199                 sib && sib->op_type == OP_NULL;
1200                 sib = sib->op_sibling) ;
1201         
1202         if (!sib)
1203             return o;
1204     }
1205
1206     if (o->op_type == OP_NEXTSTATE
1207         || o->op_type == OP_DBSTATE
1208         || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1209                                       || o->op_targ == OP_DBSTATE)))
1210         PL_curcop = (COP*)o;            /* for warning below */
1211
1212     /* assumes no premature commitment */
1213     want = o->op_flags & OPf_WANT;
1214     if ((want && want != OPf_WANT_SCALAR)
1215          || (PL_parser && PL_parser->error_count)
1216          || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1217     {
1218         return o;
1219     }
1220
1221     if ((o->op_private & OPpTARGET_MY)
1222         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1223     {
1224         return scalar(o);                       /* As if inside SASSIGN */
1225     }
1226
1227     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1228
1229     switch (o->op_type) {
1230     default:
1231         if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1232             break;
1233         /* FALL THROUGH */
1234     case OP_REPEAT:
1235         if (o->op_flags & OPf_STACKED)
1236             break;
1237         goto func_ops;
1238     case OP_SUBSTR:
1239         if (o->op_private == 4)
1240             break;
1241         /* FALL THROUGH */
1242     case OP_GVSV:
1243     case OP_WANTARRAY:
1244     case OP_GV:
1245     case OP_SMARTMATCH:
1246     case OP_PADSV:
1247     case OP_PADAV:
1248     case OP_PADHV:
1249     case OP_PADANY:
1250     case OP_AV2ARYLEN:
1251     case OP_REF:
1252     case OP_REFGEN:
1253     case OP_SREFGEN:
1254     case OP_DEFINED:
1255     case OP_HEX:
1256     case OP_OCT:
1257     case OP_LENGTH:
1258     case OP_VEC:
1259     case OP_INDEX:
1260     case OP_RINDEX:
1261     case OP_SPRINTF:
1262     case OP_AELEM:
1263     case OP_AELEMFAST:
1264     case OP_AELEMFAST_LEX:
1265     case OP_ASLICE:
1266     case OP_HELEM:
1267     case OP_HSLICE:
1268     case OP_UNPACK:
1269     case OP_PACK:
1270     case OP_JOIN:
1271     case OP_LSLICE:
1272     case OP_ANONLIST:
1273     case OP_ANONHASH:
1274     case OP_SORT:
1275     case OP_REVERSE:
1276     case OP_RANGE:
1277     case OP_FLIP:
1278     case OP_FLOP:
1279     case OP_CALLER:
1280     case OP_FILENO:
1281     case OP_EOF:
1282     case OP_TELL:
1283     case OP_GETSOCKNAME:
1284     case OP_GETPEERNAME:
1285     case OP_READLINK:
1286     case OP_TELLDIR:
1287     case OP_GETPPID:
1288     case OP_GETPGRP:
1289     case OP_GETPRIORITY:
1290     case OP_TIME:
1291     case OP_TMS:
1292     case OP_LOCALTIME:
1293     case OP_GMTIME:
1294     case OP_GHBYNAME:
1295     case OP_GHBYADDR:
1296     case OP_GHOSTENT:
1297     case OP_GNBYNAME:
1298     case OP_GNBYADDR:
1299     case OP_GNETENT:
1300     case OP_GPBYNAME:
1301     case OP_GPBYNUMBER:
1302     case OP_GPROTOENT:
1303     case OP_GSBYNAME:
1304     case OP_GSBYPORT:
1305     case OP_GSERVENT:
1306     case OP_GPWNAM:
1307     case OP_GPWUID:
1308     case OP_GGRNAM:
1309     case OP_GGRGID:
1310     case OP_GETLOGIN:
1311     case OP_PROTOTYPE:
1312     case OP_RUNCV:
1313       func_ops:
1314         if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1315             /* Otherwise it's "Useless use of grep iterator" */
1316             useless = OP_DESC(o);
1317         break;
1318
1319     case OP_SPLIT:
1320         kid = cLISTOPo->op_first;
1321         if (kid && kid->op_type == OP_PUSHRE
1322 #ifdef USE_ITHREADS
1323                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff)
1324 #else
1325                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv)
1326 #endif
1327             useless = OP_DESC(o);
1328         break;
1329
1330     case OP_NOT:
1331        kid = cUNOPo->op_first;
1332        if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1333            kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1334                 goto func_ops;
1335        }
1336        useless = "negative pattern binding (!~)";
1337        break;
1338
1339     case OP_SUBST:
1340         if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1341             useless = "non-destructive substitution (s///r)";
1342         break;
1343
1344     case OP_TRANSR:
1345         useless = "non-destructive transliteration (tr///r)";
1346         break;
1347
1348     case OP_RV2GV:
1349     case OP_RV2SV:
1350     case OP_RV2AV:
1351     case OP_RV2HV:
1352         if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1353                 (!o->op_sibling || o->op_sibling->op_type != OP_READLINE))
1354             useless = "a variable";
1355         break;
1356
1357     case OP_CONST:
1358         sv = cSVOPo_sv;
1359         if (cSVOPo->op_private & OPpCONST_STRICT)
1360             no_bareword_allowed(o);
1361         else {
1362             if (ckWARN(WARN_VOID)) {
1363                 /* don't warn on optimised away booleans, eg 
1364                  * use constant Foo, 5; Foo || print; */
1365                 if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1366                     useless = NULL;
1367                 /* the constants 0 and 1 are permitted as they are
1368                    conventionally used as dummies in constructs like
1369                         1 while some_condition_with_side_effects;  */
1370                 else if (SvNIOK(sv) && (SvNV(sv) == 0.0 || SvNV(sv) == 1.0))
1371                     useless = NULL;
1372                 else if (SvPOK(sv)) {
1373                   /* perl4's way of mixing documentation and code
1374                      (before the invention of POD) was based on a
1375                      trick to mix nroff and perl code. The trick was
1376                      built upon these three nroff macros being used in
1377                      void context. The pink camel has the details in
1378                      the script wrapman near page 319. */
1379                     const char * const maybe_macro = SvPVX_const(sv);
1380                     if (strnEQ(maybe_macro, "di", 2) ||
1381                         strnEQ(maybe_macro, "ds", 2) ||
1382                         strnEQ(maybe_macro, "ig", 2))
1383                             useless = NULL;
1384                     else {
1385                         SV * const dsv = newSVpvs("");
1386                         SV* msv = sv_2mortal(Perl_newSVpvf(aTHX_
1387                                     "a constant (%s)",
1388                                     pv_pretty(dsv, maybe_macro, SvCUR(sv), 32, NULL, NULL,
1389                                             PERL_PV_PRETTY_DUMP | PERL_PV_ESCAPE_NOCLEAR | PERL_PV_ESCAPE_UNI_DETECT )));
1390                         SvREFCNT_dec(dsv);
1391                         useless = SvPV_nolen(msv);
1392                         useless_is_utf8 = SvUTF8(msv);
1393                     }
1394                 }
1395                 else if (SvOK(sv)) {
1396                     SV* msv = sv_2mortal(Perl_newSVpvf(aTHX_
1397                                 "a constant (%"SVf")", sv));
1398                     useless = SvPV_nolen(msv);
1399                 }
1400                 else
1401                     useless = "a constant (undef)";
1402             }
1403         }
1404         op_null(o);             /* don't execute or even remember it */
1405         break;
1406
1407     case OP_POSTINC:
1408         o->op_type = OP_PREINC;         /* pre-increment is faster */
1409         o->op_ppaddr = PL_ppaddr[OP_PREINC];
1410         break;
1411
1412     case OP_POSTDEC:
1413         o->op_type = OP_PREDEC;         /* pre-decrement is faster */
1414         o->op_ppaddr = PL_ppaddr[OP_PREDEC];
1415         break;
1416
1417     case OP_I_POSTINC:
1418         o->op_type = OP_I_PREINC;       /* pre-increment is faster */
1419         o->op_ppaddr = PL_ppaddr[OP_I_PREINC];
1420         break;
1421
1422     case OP_I_POSTDEC:
1423         o->op_type = OP_I_PREDEC;       /* pre-decrement is faster */
1424         o->op_ppaddr = PL_ppaddr[OP_I_PREDEC];
1425         break;
1426
1427     case OP_SASSIGN: {
1428         OP *rv2gv;
1429         UNOP *refgen, *rv2cv;
1430         LISTOP *exlist;
1431
1432         if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
1433             break;
1434
1435         rv2gv = ((BINOP *)o)->op_last;
1436         if (!rv2gv || rv2gv->op_type != OP_RV2GV)
1437             break;
1438
1439         refgen = (UNOP *)((BINOP *)o)->op_first;
1440
1441         if (!refgen || refgen->op_type != OP_REFGEN)
1442             break;
1443
1444         exlist = (LISTOP *)refgen->op_first;
1445         if (!exlist || exlist->op_type != OP_NULL
1446             || exlist->op_targ != OP_LIST)
1447             break;
1448
1449         if (exlist->op_first->op_type != OP_PUSHMARK)
1450             break;
1451
1452         rv2cv = (UNOP*)exlist->op_last;
1453
1454         if (rv2cv->op_type != OP_RV2CV)
1455             break;
1456
1457         assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
1458         assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
1459         assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
1460
1461         o->op_private |= OPpASSIGN_CV_TO_GV;
1462         rv2gv->op_private |= OPpDONT_INIT_GV;
1463         rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
1464
1465         break;
1466     }
1467
1468     case OP_AASSIGN: {
1469         inplace_aassign(o);
1470         break;
1471     }
1472
1473     case OP_OR:
1474     case OP_AND:
1475         kid = cLOGOPo->op_first;
1476         if (kid->op_type == OP_NOT
1477             && (kid->op_flags & OPf_KIDS)
1478             && !PL_madskills) {
1479             if (o->op_type == OP_AND) {
1480                 o->op_type = OP_OR;
1481                 o->op_ppaddr = PL_ppaddr[OP_OR];
1482             } else {
1483                 o->op_type = OP_AND;
1484                 o->op_ppaddr = PL_ppaddr[OP_AND];
1485             }
1486             op_null(kid);
1487         }
1488
1489     case OP_DOR:
1490     case OP_COND_EXPR:
1491     case OP_ENTERGIVEN:
1492     case OP_ENTERWHEN:
1493         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
1494             scalarvoid(kid);
1495         break;
1496
1497     case OP_NULL:
1498         if (o->op_flags & OPf_STACKED)
1499             break;
1500         /* FALL THROUGH */
1501     case OP_NEXTSTATE:
1502     case OP_DBSTATE:
1503     case OP_ENTERTRY:
1504     case OP_ENTER:
1505         if (!(o->op_flags & OPf_KIDS))
1506             break;
1507         /* FALL THROUGH */
1508     case OP_SCOPE:
1509     case OP_LEAVE:
1510     case OP_LEAVETRY:
1511     case OP_LEAVELOOP:
1512     case OP_LINESEQ:
1513     case OP_LIST:
1514     case OP_LEAVEGIVEN:
1515     case OP_LEAVEWHEN:
1516         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1517             scalarvoid(kid);
1518         break;
1519     case OP_ENTEREVAL:
1520         scalarkids(o);
1521         break;
1522     case OP_SCALAR:
1523         return scalar(o);
1524     }
1525     if (useless)
1526        Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of %"SVf" in void context",
1527                        newSVpvn_flags(useless, strlen(useless),
1528                             SVs_TEMP | ( useless_is_utf8 ? SVf_UTF8 : 0 )));
1529     return o;
1530 }
1531
1532 static OP *
1533 S_listkids(pTHX_ OP *o)
1534 {
1535     if (o && o->op_flags & OPf_KIDS) {
1536         OP *kid;
1537         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1538             list(kid);
1539     }
1540     return o;
1541 }
1542
1543 OP *
1544 Perl_list(pTHX_ OP *o)
1545 {
1546     dVAR;
1547     OP *kid;
1548
1549     /* assumes no premature commitment */
1550     if (!o || (o->op_flags & OPf_WANT)
1551          || (PL_parser && PL_parser->error_count)
1552          || o->op_type == OP_RETURN)
1553     {
1554         return o;
1555     }
1556
1557     if ((o->op_private & OPpTARGET_MY)
1558         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1559     {
1560         return o;                               /* As if inside SASSIGN */
1561     }
1562
1563     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
1564
1565     switch (o->op_type) {
1566     case OP_FLOP:
1567     case OP_REPEAT:
1568         list(cBINOPo->op_first);
1569         break;
1570     case OP_OR:
1571     case OP_AND:
1572     case OP_COND_EXPR:
1573         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
1574             list(kid);
1575         break;
1576     default:
1577     case OP_MATCH:
1578     case OP_QR:
1579     case OP_SUBST:
1580     case OP_NULL:
1581         if (!(o->op_flags & OPf_KIDS))
1582             break;
1583         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
1584             list(cBINOPo->op_first);
1585             return gen_constant_list(o);
1586         }
1587     case OP_LIST:
1588         listkids(o);
1589         break;
1590     case OP_LEAVE:
1591     case OP_LEAVETRY:
1592         kid = cLISTOPo->op_first;
1593         list(kid);
1594         kid = kid->op_sibling;
1595     do_kids:
1596         while (kid) {
1597             OP *sib = kid->op_sibling;
1598             if (sib && kid->op_type != OP_LEAVEWHEN)
1599                 scalarvoid(kid);
1600             else
1601                 list(kid);
1602             kid = sib;
1603         }
1604         PL_curcop = &PL_compiling;
1605         break;
1606     case OP_SCOPE:
1607     case OP_LINESEQ:
1608         kid = cLISTOPo->op_first;
1609         goto do_kids;
1610     }
1611     return o;
1612 }
1613
1614 static OP *
1615 S_scalarseq(pTHX_ OP *o)
1616 {
1617     dVAR;
1618     if (o) {
1619         const OPCODE type = o->op_type;
1620
1621         if (type == OP_LINESEQ || type == OP_SCOPE ||
1622             type == OP_LEAVE || type == OP_LEAVETRY)
1623         {
1624             OP *kid;
1625             for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling) {
1626                 if (kid->op_sibling) {
1627                     scalarvoid(kid);
1628                 }
1629             }
1630             PL_curcop = &PL_compiling;
1631         }
1632         o->op_flags &= ~OPf_PARENS;
1633         if (PL_hints & HINT_BLOCK_SCOPE)
1634             o->op_flags |= OPf_PARENS;
1635     }
1636     else
1637         o = newOP(OP_STUB, 0);
1638     return o;
1639 }
1640
1641 STATIC OP *
1642 S_modkids(pTHX_ OP *o, I32 type)
1643 {
1644     if (o && o->op_flags & OPf_KIDS) {
1645         OP *kid;
1646         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1647             op_lvalue(kid, type);
1648     }
1649     return o;
1650 }
1651
1652 /*
1653 =for apidoc finalize_optree
1654
1655 This function finalizes the optree. Should be called directly after
1656 the complete optree is built. It does some additional
1657 checking which can't be done in the normal ck_xxx functions and makes
1658 the tree thread-safe.
1659
1660 =cut
1661 */
1662 void
1663 Perl_finalize_optree(pTHX_ OP* o)
1664 {
1665     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
1666
1667     ENTER;
1668     SAVEVPTR(PL_curcop);
1669
1670     finalize_op(o);
1671
1672     LEAVE;
1673 }
1674
1675 STATIC void
1676 S_finalize_op(pTHX_ OP* o)
1677 {
1678     PERL_ARGS_ASSERT_FINALIZE_OP;
1679
1680 #if defined(PERL_MAD) && defined(USE_ITHREADS)
1681     {
1682         /* Make sure mad ops are also thread-safe */
1683         MADPROP *mp = o->op_madprop;
1684         while (mp) {
1685             if (mp->mad_type == MAD_OP && mp->mad_vlen) {
1686                 OP *prop_op = (OP *) mp->mad_val;
1687                 /* We only need "Relocate sv to the pad for thread safety.", but this
1688                    easiest way to make sure it traverses everything */
1689                 if (prop_op->op_type == OP_CONST)
1690                     cSVOPx(prop_op)->op_private &= ~OPpCONST_STRICT;
1691                 finalize_op(prop_op);
1692             }
1693             mp = mp->mad_next;
1694         }
1695     }
1696 #endif
1697
1698     switch (o->op_type) {
1699     case OP_NEXTSTATE:
1700     case OP_DBSTATE:
1701         PL_curcop = ((COP*)o);          /* for warnings */
1702         break;
1703     case OP_EXEC:
1704         if ( o->op_sibling
1705             && (o->op_sibling->op_type == OP_NEXTSTATE || o->op_sibling->op_type == OP_DBSTATE)
1706             && ckWARN(WARN_SYNTAX))
1707             {
1708                 if (o->op_sibling->op_sibling) {
1709                     const OPCODE type = o->op_sibling->op_sibling->op_type;
1710                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
1711                         const line_t oldline = CopLINE(PL_curcop);
1712                         CopLINE_set(PL_curcop, CopLINE((COP*)o->op_sibling));
1713                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
1714                             "Statement unlikely to be reached");
1715                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
1716                             "\t(Maybe you meant system() when you said exec()?)\n");
1717                         CopLINE_set(PL_curcop, oldline);
1718                     }
1719                 }
1720             }
1721         break;
1722
1723     case OP_GV:
1724         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
1725             GV * const gv = cGVOPo_gv;
1726             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
1727                 /* XXX could check prototype here instead of just carping */
1728                 SV * const sv = sv_newmortal();
1729                 gv_efullname3(sv, gv, NULL);
1730                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
1731                     "%"SVf"() called too early to check prototype",
1732                     SVfARG(sv));
1733             }
1734         }
1735         break;
1736
1737     case OP_CONST:
1738         if (cSVOPo->op_private & OPpCONST_STRICT)
1739             no_bareword_allowed(o);
1740         /* FALLTHROUGH */
1741 #ifdef USE_ITHREADS
1742     case OP_HINTSEVAL:
1743     case OP_METHOD_NAMED:
1744         /* Relocate sv to the pad for thread safety.
1745          * Despite being a "constant", the SV is written to,
1746          * for reference counts, sv_upgrade() etc. */
1747         if (cSVOPo->op_sv) {
1748             const PADOFFSET ix = pad_alloc(OP_CONST, SVs_PADTMP);
1749             if (o->op_type != OP_METHOD_NAMED &&
1750                 (SvPADTMP(cSVOPo->op_sv) || SvPADMY(cSVOPo->op_sv)))
1751             {
1752                 /* If op_sv is already a PADTMP/MY then it is being used by
1753                  * some pad, so make a copy. */
1754                 sv_setsv(PAD_SVl(ix),cSVOPo->op_sv);
1755                 SvREADONLY_on(PAD_SVl(ix));
1756                 SvREFCNT_dec(cSVOPo->op_sv);
1757             }
1758             else if (o->op_type != OP_METHOD_NAMED
1759                 && cSVOPo->op_sv == &PL_sv_undef) {
1760                 /* PL_sv_undef is hack - it's unsafe to store it in the
1761                    AV that is the pad, because av_fetch treats values of
1762                    PL_sv_undef as a "free" AV entry and will merrily
1763                    replace them with a new SV, causing pad_alloc to think
1764                    that this pad slot is free. (When, clearly, it is not)
1765                 */
1766                 SvOK_off(PAD_SVl(ix));
1767                 SvPADTMP_on(PAD_SVl(ix));
1768                 SvREADONLY_on(PAD_SVl(ix));
1769             }
1770             else {
1771                 SvREFCNT_dec(PAD_SVl(ix));
1772                 SvPADTMP_on(cSVOPo->op_sv);
1773                 PAD_SETSV(ix, cSVOPo->op_sv);
1774                 /* XXX I don't know how this isn't readonly already. */
1775                 SvREADONLY_on(PAD_SVl(ix));
1776             }
1777             cSVOPo->op_sv = NULL;
1778             o->op_targ = ix;
1779         }
1780 #endif
1781         break;
1782
1783     case OP_HELEM: {
1784         UNOP *rop;
1785         SV *lexname;
1786         GV **fields;
1787         SV **svp, *sv;
1788         const char *key = NULL;
1789         STRLEN keylen;
1790
1791         if (((BINOP*)o)->op_last->op_type != OP_CONST)
1792             break;
1793
1794         /* Make the CONST have a shared SV */
1795         svp = cSVOPx_svp(((BINOP*)o)->op_last);
1796         if ((!SvFAKE(sv = *svp) || !SvREADONLY(sv))
1797             && SvTYPE(sv) < SVt_PVMG && !SvROK(sv)) {
1798             key = SvPV_const(sv, keylen);
1799             lexname = newSVpvn_share(key,
1800                 SvUTF8(sv) ? -(I32)keylen : (I32)keylen,
1801                 0);
1802             SvREFCNT_dec(sv);
1803             *svp = lexname;
1804         }
1805
1806         if ((o->op_private & (OPpLVAL_INTRO)))
1807             break;
1808
1809         rop = (UNOP*)((BINOP*)o)->op_first;
1810         if (rop->op_type != OP_RV2HV || rop->op_first->op_type != OP_PADSV)
1811             break;
1812         lexname = *av_fetch(PL_comppad_name, rop->op_first->op_targ, TRUE);
1813         if (!SvPAD_TYPED(lexname))
1814             break;
1815         fields = (GV**)hv_fetchs(SvSTASH(lexname), "FIELDS", FALSE);
1816         if (!fields || !GvHV(*fields))
1817             break;
1818         key = SvPV_const(*svp, keylen);
1819         if (!hv_fetch(GvHV(*fields), key,
1820                 SvUTF8(*svp) ? -(I32)keylen : (I32)keylen, FALSE)) {
1821             Perl_croak(aTHX_ "No such class field \"%"SVf"\" " 
1822                            "in variable %"SVf" of type %"HEKf, 
1823                       SVfARG(*svp), SVfARG(lexname),
1824                       HEKfARG(HvNAME_HEK(SvSTASH(lexname))));
1825         }
1826         break;
1827     }
1828
1829     case OP_HSLICE: {
1830         UNOP *rop;
1831         SV *lexname;
1832         GV **fields;
1833         SV **svp;
1834         const char *key;
1835         STRLEN keylen;
1836         SVOP *first_key_op, *key_op;
1837
1838         if ((o->op_private & (OPpLVAL_INTRO))
1839             /* I bet there's always a pushmark... */
1840             || ((LISTOP*)o)->op_first->op_sibling->op_type != OP_LIST)
1841             /* hmmm, no optimization if list contains only one key. */
1842             break;
1843         rop = (UNOP*)((LISTOP*)o)->op_last;
1844         if (rop->op_type != OP_RV2HV)
1845             break;
1846         if (rop->op_first->op_type == OP_PADSV)
1847             /* @$hash{qw(keys here)} */
1848             rop = (UNOP*)rop->op_first;
1849         else {
1850             /* @{$hash}{qw(keys here)} */
1851             if (rop->op_first->op_type == OP_SCOPE
1852                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
1853                 {
1854                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
1855                 }
1856             else
1857                 break;
1858         }
1859
1860         lexname = *av_fetch(PL_comppad_name, rop->op_targ, TRUE);
1861         if (!SvPAD_TYPED(lexname))
1862             break;
1863         fields = (GV**)hv_fetchs(SvSTASH(lexname), "FIELDS", FALSE);
1864         if (!fields || !GvHV(*fields))
1865             break;
1866         /* Again guessing that the pushmark can be jumped over.... */
1867         first_key_op = (SVOP*)((LISTOP*)((LISTOP*)o)->op_first->op_sibling)
1868             ->op_first->op_sibling;
1869         for (key_op = first_key_op; key_op;
1870              key_op = (SVOP*)key_op->op_sibling) {
1871             if (key_op->op_type != OP_CONST)
1872                 continue;
1873             svp = cSVOPx_svp(key_op);
1874             key = SvPV_const(*svp, keylen);
1875             if (!hv_fetch(GvHV(*fields), key,
1876                     SvUTF8(*svp) ? -(I32)keylen : (I32)keylen, FALSE)) {
1877                 Perl_croak(aTHX_ "No such class field \"%"SVf"\" " 
1878                            "in variable %"SVf" of type %"HEKf, 
1879                       SVfARG(*svp), SVfARG(lexname),
1880                       HEKfARG(HvNAME_HEK(SvSTASH(lexname))));
1881             }
1882         }
1883         break;
1884     }
1885     case OP_SUBST: {
1886         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
1887             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
1888         break;
1889     }
1890     default:
1891         break;
1892     }
1893
1894     if (o->op_flags & OPf_KIDS) {
1895         OP *kid;
1896         for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1897             finalize_op(kid);
1898     }
1899 }
1900
1901 /*
1902 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
1903
1904 Propagate lvalue ("modifiable") context to an op and its children.
1905 I<type> represents the context type, roughly based on the type of op that
1906 would do the modifying, although C<local()> is represented by OP_NULL,
1907 because it has no op type of its own (it is signalled by a flag on
1908 the lvalue op).
1909
1910 This function detects things that can't be modified, such as C<$x+1>, and
1911 generates errors for them. For example, C<$x+1 = 2> would cause it to be
1912 called with an op of type OP_ADD and a C<type> argument of OP_SASSIGN.
1913
1914 It also flags things that need to behave specially in an lvalue context,
1915 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
1916
1917 =cut
1918 */
1919
1920 OP *
1921 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
1922 {
1923     dVAR;
1924     OP *kid;
1925     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
1926     int localize = -1;
1927
1928     if (!o || (PL_parser && PL_parser->error_count))
1929         return o;
1930
1931     if ((o->op_private & OPpTARGET_MY)
1932         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1933     {
1934         return o;
1935     }
1936
1937     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
1938
1939     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
1940
1941     switch (o->op_type) {
1942     case OP_UNDEF:
1943         PL_modcount++;
1944         return o;
1945     case OP_STUB:
1946         if ((o->op_flags & OPf_PARENS) || PL_madskills)
1947             break;
1948         goto nomod;
1949     case OP_ENTERSUB:
1950         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
1951             !(o->op_flags & OPf_STACKED)) {
1952             o->op_type = OP_RV2CV;              /* entersub => rv2cv */
1953             /* Both ENTERSUB and RV2CV use this bit, but for different pur-
1954                poses, so we need it clear.  */
1955             o->op_private &= ~1;
1956             o->op_ppaddr = PL_ppaddr[OP_RV2CV];
1957             assert(cUNOPo->op_first->op_type == OP_NULL);
1958             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
1959             break;
1960         }
1961         else {                          /* lvalue subroutine call */
1962             o->op_private |= OPpLVAL_INTRO
1963                            |(OPpENTERSUB_INARGS * (type == OP_LEAVESUBLV));
1964             PL_modcount = RETURN_UNLIMITED_NUMBER;
1965             if (type == OP_GREPSTART || type == OP_ENTERSUB || type == OP_REFGEN) {
1966                 /* Potential lvalue context: */
1967                 o->op_private |= OPpENTERSUB_INARGS;
1968                 break;
1969             }
1970             else {                      /* Compile-time error message: */
1971                 OP *kid = cUNOPo->op_first;
1972                 CV *cv;
1973
1974                 if (kid->op_type != OP_PUSHMARK) {
1975                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
1976                         Perl_croak(aTHX_
1977                                 "panic: unexpected lvalue entersub "
1978                                 "args: type/targ %ld:%"UVuf,
1979                                 (long)kid->op_type, (UV)kid->op_targ);
1980                     kid = kLISTOP->op_first;
1981                 }
1982                 while (kid->op_sibling)
1983                     kid = kid->op_sibling;
1984                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
1985                     break;      /* Postpone until runtime */
1986                 }
1987
1988                 kid = kUNOP->op_first;
1989                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
1990                     kid = kUNOP->op_first;
1991                 if (kid->op_type == OP_NULL)
1992                     Perl_croak(aTHX_
1993                                "Unexpected constant lvalue entersub "
1994                                "entry via type/targ %ld:%"UVuf,
1995                                (long)kid->op_type, (UV)kid->op_targ);
1996                 if (kid->op_type != OP_GV) {
1997                     break;
1998                 }
1999
2000                 cv = GvCV(kGVOP_gv);
2001                 if (!cv)
2002                     break;
2003                 if (CvLVALUE(cv))
2004                     break;
2005             }
2006         }
2007         /* FALL THROUGH */
2008     default:
2009       nomod:
2010         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2011         /* grep, foreach, subcalls, refgen */
2012         if (type == OP_GREPSTART || type == OP_ENTERSUB
2013          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2014             break;
2015         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2016                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2017                       ? "do block"
2018                       : (o->op_type == OP_ENTERSUB
2019                         ? "non-lvalue subroutine call"
2020                         : OP_DESC(o))),
2021                      type ? PL_op_desc[type] : "local"));
2022         return o;
2023
2024     case OP_PREINC:
2025     case OP_PREDEC:
2026     case OP_POW:
2027     case OP_MULTIPLY:
2028     case OP_DIVIDE:
2029     case OP_MODULO:
2030     case OP_REPEAT:
2031     case OP_ADD:
2032     case OP_SUBTRACT:
2033     case OP_CONCAT:
2034     case OP_LEFT_SHIFT:
2035     case OP_RIGHT_SHIFT:
2036     case OP_BIT_AND:
2037     case OP_BIT_XOR:
2038     case OP_BIT_OR:
2039     case OP_I_MULTIPLY:
2040     case OP_I_DIVIDE:
2041     case OP_I_MODULO:
2042     case OP_I_ADD:
2043     case OP_I_SUBTRACT:
2044         if (!(o->op_flags & OPf_STACKED))
2045             goto nomod;
2046         PL_modcount++;
2047         break;
2048
2049     case OP_COND_EXPR:
2050         localize = 1;
2051         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
2052             op_lvalue(kid, type);
2053         break;
2054
2055     case OP_RV2AV:
2056     case OP_RV2HV:
2057         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2058            PL_modcount = RETURN_UNLIMITED_NUMBER;
2059             return o;           /* Treat \(@foo) like ordinary list. */
2060         }
2061         /* FALL THROUGH */
2062     case OP_RV2GV:
2063         if (scalar_mod_type(o, type))
2064             goto nomod;
2065         ref(cUNOPo->op_first, o->op_type);
2066         /* FALL THROUGH */
2067     case OP_ASLICE:
2068     case OP_HSLICE:
2069         if (type == OP_LEAVESUBLV)
2070             o->op_private |= OPpMAYBE_LVSUB;
2071         localize = 1;
2072         /* FALL THROUGH */
2073     case OP_AASSIGN:
2074     case OP_NEXTSTATE:
2075     case OP_DBSTATE:
2076        PL_modcount = RETURN_UNLIMITED_NUMBER;
2077         break;
2078     case OP_AV2ARYLEN:
2079         PL_hints |= HINT_BLOCK_SCOPE;
2080         if (type == OP_LEAVESUBLV)
2081             o->op_private |= OPpMAYBE_LVSUB;
2082         PL_modcount++;
2083         break;
2084     case OP_RV2SV:
2085         ref(cUNOPo->op_first, o->op_type);
2086         localize = 1;
2087         /* FALL THROUGH */
2088     case OP_GV:
2089         PL_hints |= HINT_BLOCK_SCOPE;
2090     case OP_SASSIGN:
2091     case OP_ANDASSIGN:
2092     case OP_ORASSIGN:
2093     case OP_DORASSIGN:
2094         PL_modcount++;
2095         break;
2096
2097     case OP_AELEMFAST:
2098     case OP_AELEMFAST_LEX:
2099         localize = -1;
2100         PL_modcount++;
2101         break;
2102
2103     case OP_PADAV:
2104     case OP_PADHV:
2105        PL_modcount = RETURN_UNLIMITED_NUMBER;
2106         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2107             return o;           /* Treat \(@foo) like ordinary list. */
2108         if (scalar_mod_type(o, type))
2109             goto nomod;
2110         if (type == OP_LEAVESUBLV)
2111             o->op_private |= OPpMAYBE_LVSUB;
2112         /* FALL THROUGH */
2113     case OP_PADSV:
2114         PL_modcount++;
2115         if (!type) /* local() */
2116             Perl_croak(aTHX_ "Can't localize lexical variable %"SVf,
2117                  PAD_COMPNAME_SV(o->op_targ));
2118         break;
2119
2120     case OP_PUSHMARK:
2121         localize = 0;
2122         break;
2123
2124     case OP_KEYS:
2125     case OP_RKEYS:
2126         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
2127             goto nomod;
2128         goto lvalue_func;
2129     case OP_SUBSTR:
2130         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
2131             goto nomod;
2132         /* FALL THROUGH */
2133     case OP_POS:
2134     case OP_VEC:
2135       lvalue_func:
2136         if (type == OP_LEAVESUBLV)
2137             o->op_private |= OPpMAYBE_LVSUB;
2138         pad_free(o->op_targ);
2139         o->op_targ = pad_alloc(o->op_type, SVs_PADMY);
2140         assert(SvTYPE(PAD_SV(o->op_targ)) == SVt_NULL);
2141         if (o->op_flags & OPf_KIDS)
2142             op_lvalue(cBINOPo->op_first->op_sibling, type);
2143         break;
2144
2145     case OP_AELEM:
2146     case OP_HELEM:
2147         ref(cBINOPo->op_first, o->op_type);
2148         if (type == OP_ENTERSUB &&
2149              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
2150             o->op_private |= OPpLVAL_DEFER;
2151         if (type == OP_LEAVESUBLV)
2152             o->op_private |= OPpMAYBE_LVSUB;
2153         localize = 1;
2154         PL_modcount++;
2155         break;
2156
2157     case OP_SCOPE:
2158     case OP_LEAVE:
2159     case OP_ENTER:
2160     case OP_LINESEQ:
2161         localize = 0;
2162         if (o->op_flags & OPf_KIDS)
2163             op_lvalue(cLISTOPo->op_last, type);
2164         break;
2165
2166     case OP_NULL:
2167         localize = 0;
2168         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2169             goto nomod;
2170         else if (!(o->op_flags & OPf_KIDS))
2171             break;
2172         if (o->op_targ != OP_LIST) {
2173             op_lvalue(cBINOPo->op_first, type);
2174             break;
2175         }
2176         /* FALL THROUGH */
2177     case OP_LIST:
2178         localize = 0;
2179         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
2180             /* elements might be in void context because the list is
2181                in scalar context or because they are attribute sub calls */
2182             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
2183                 op_lvalue(kid, type);
2184         break;
2185
2186     case OP_RETURN:
2187         if (type != OP_LEAVESUBLV)
2188             goto nomod;
2189         break; /* op_lvalue()ing was handled by ck_return() */
2190
2191     case OP_COREARGS:
2192         return o;
2193     }
2194
2195     /* [20011101.069] File test operators interpret OPf_REF to mean that
2196        their argument is a filehandle; thus \stat(".") should not set
2197        it. AMS 20011102 */
2198     if (type == OP_REFGEN &&
2199         PL_check[o->op_type] == Perl_ck_ftst)
2200         return o;
2201
2202     if (type != OP_LEAVESUBLV)
2203         o->op_flags |= OPf_MOD;
2204
2205     if (type == OP_AASSIGN || type == OP_SASSIGN)
2206         o->op_flags |= OPf_SPECIAL|OPf_REF;
2207     else if (!type) { /* local() */
2208         switch (localize) {
2209         case 1:
2210             o->op_private |= OPpLVAL_INTRO;
2211             o->op_flags &= ~OPf_SPECIAL;
2212             PL_hints |= HINT_BLOCK_SCOPE;
2213             break;
2214         case 0:
2215             break;
2216         case -1:
2217             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
2218                            "Useless localization of %s", OP_DESC(o));
2219         }
2220     }
2221     else if (type != OP_GREPSTART && type != OP_ENTERSUB
2222              && type != OP_LEAVESUBLV)
2223         o->op_flags |= OPf_REF;
2224     return o;
2225 }
2226
2227 STATIC bool
2228 S_scalar_mod_type(const OP *o, I32 type)
2229 {
2230     switch (type) {
2231     case OP_POS:
2232     case OP_SASSIGN:
2233         if (o && o->op_type == OP_RV2GV)
2234             return FALSE;
2235         /* FALL THROUGH */
2236     case OP_PREINC:
2237     case OP_PREDEC:
2238     case OP_POSTINC:
2239     case OP_POSTDEC:
2240     case OP_I_PREINC:
2241     case OP_I_PREDEC:
2242     case OP_I_POSTINC:
2243     case OP_I_POSTDEC:
2244     case OP_POW:
2245     case OP_MULTIPLY:
2246     case OP_DIVIDE:
2247     case OP_MODULO:
2248     case OP_REPEAT:
2249     case OP_ADD:
2250     case OP_SUBTRACT:
2251     case OP_I_MULTIPLY:
2252     case OP_I_DIVIDE:
2253     case OP_I_MODULO:
2254     case OP_I_ADD:
2255     case OP_I_SUBTRACT:
2256     case OP_LEFT_SHIFT:
2257     case OP_RIGHT_SHIFT:
2258     case OP_BIT_AND:
2259     case OP_BIT_XOR:
2260     case OP_BIT_OR:
2261     case OP_CONCAT:
2262     case OP_SUBST:
2263     case OP_TRANS:
2264     case OP_TRANSR:
2265     case OP_READ:
2266     case OP_SYSREAD:
2267     case OP_RECV:
2268     case OP_ANDASSIGN:
2269     case OP_ORASSIGN:
2270     case OP_DORASSIGN:
2271         return TRUE;
2272     default:
2273         return FALSE;
2274     }
2275 }
2276
2277 STATIC bool
2278 S_is_handle_constructor(const OP *o, I32 numargs)
2279 {
2280     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
2281
2282     switch (o->op_type) {
2283     case OP_PIPE_OP:
2284     case OP_SOCKPAIR:
2285         if (numargs == 2)
2286             return TRUE;
2287         /* FALL THROUGH */
2288     case OP_SYSOPEN:
2289     case OP_OPEN:
2290     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
2291     case OP_SOCKET:
2292     case OP_OPEN_DIR:
2293     case OP_ACCEPT:
2294         if (numargs == 1)
2295             return TRUE;
2296         /* FALLTHROUGH */
2297     default:
2298         return FALSE;
2299     }
2300 }
2301
2302 static OP *
2303 S_refkids(pTHX_ OP *o, I32 type)
2304 {
2305     if (o && o->op_flags & OPf_KIDS) {
2306         OP *kid;
2307         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
2308             ref(kid, type);
2309     }
2310     return o;
2311 }
2312
2313 OP *
2314 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
2315 {
2316     dVAR;
2317     OP *kid;
2318
2319     PERL_ARGS_ASSERT_DOREF;
2320
2321     if (!o || (PL_parser && PL_parser->error_count))
2322         return o;
2323
2324     switch (o->op_type) {
2325     case OP_ENTERSUB:
2326         if ((type == OP_EXISTS || type == OP_DEFINED) &&
2327             !(o->op_flags & OPf_STACKED)) {
2328             o->op_type = OP_RV2CV;             /* entersub => rv2cv */
2329             o->op_ppaddr = PL_ppaddr[OP_RV2CV];
2330             assert(cUNOPo->op_first->op_type == OP_NULL);
2331             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
2332             o->op_flags |= OPf_SPECIAL;
2333             o->op_private &= ~1;
2334         }
2335         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
2336             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2337                               : type == OP_RV2HV ? OPpDEREF_HV
2338                               : OPpDEREF_SV);
2339             o->op_flags |= OPf_MOD;
2340         }
2341
2342         break;
2343
2344     case OP_COND_EXPR:
2345         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
2346             doref(kid, type, set_op_ref);
2347         break;
2348     case OP_RV2SV:
2349         if (type == OP_DEFINED)
2350             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
2351         doref(cUNOPo->op_first, o->op_type, set_op_ref);
2352         /* FALL THROUGH */
2353     case OP_PADSV:
2354         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
2355             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2356                               : type == OP_RV2HV ? OPpDEREF_HV
2357                               : OPpDEREF_SV);
2358             o->op_flags |= OPf_MOD;
2359         }
2360         break;
2361
2362     case OP_RV2AV:
2363     case OP_RV2HV:
2364         if (set_op_ref)
2365             o->op_flags |= OPf_REF;
2366         /* FALL THROUGH */
2367     case OP_RV2GV:
2368         if (type == OP_DEFINED)
2369             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
2370         doref(cUNOPo->op_first, o->op_type, set_op_ref);
2371         break;
2372
2373     case OP_PADAV:
2374     case OP_PADHV:
2375         if (set_op_ref)
2376             o->op_flags |= OPf_REF;
2377         break;
2378
2379     case OP_SCALAR:
2380     case OP_NULL:
2381         if (!(o->op_flags & OPf_KIDS))
2382             break;
2383         doref(cBINOPo->op_first, type, set_op_ref);
2384         break;
2385     case OP_AELEM:
2386     case OP_HELEM:
2387         doref(cBINOPo->op_first, o->op_type, set_op_ref);
2388         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
2389             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2390                               : type == OP_RV2HV ? OPpDEREF_HV
2391                               : OPpDEREF_SV);
2392             o->op_flags |= OPf_MOD;
2393         }
2394         break;
2395
2396     case OP_SCOPE:
2397     case OP_LEAVE:
2398         set_op_ref = FALSE;
2399         /* FALL THROUGH */
2400     case OP_ENTER:
2401     case OP_LIST:
2402         if (!(o->op_flags & OPf_KIDS))
2403             break;
2404         doref(cLISTOPo->op_last, type, set_op_ref);
2405         break;
2406     default:
2407         break;
2408     }
2409     return scalar(o);
2410
2411 }
2412
2413 STATIC OP *
2414 S_dup_attrlist(pTHX_ OP *o)
2415 {
2416     dVAR;
2417     OP *rop;
2418
2419     PERL_ARGS_ASSERT_DUP_ATTRLIST;
2420
2421     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
2422      * where the first kid is OP_PUSHMARK and the remaining ones
2423      * are OP_CONST.  We need to push the OP_CONST values.
2424      */
2425     if (o->op_type == OP_CONST)
2426         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
2427 #ifdef PERL_MAD
2428     else if (o->op_type == OP_NULL)
2429         rop = NULL;
2430 #endif
2431     else {
2432         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
2433         rop = NULL;
2434         for (o = cLISTOPo->op_first; o; o=o->op_sibling) {
2435             if (o->op_type == OP_CONST)
2436                 rop = op_append_elem(OP_LIST, rop,
2437                                   newSVOP(OP_CONST, o->op_flags,
2438                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
2439         }
2440     }
2441     return rop;
2442 }
2443
2444 STATIC void
2445 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs, bool for_my)
2446 {
2447     dVAR;
2448     SV *stashsv;
2449
2450     PERL_ARGS_ASSERT_APPLY_ATTRS;
2451
2452     /* fake up C<use attributes $pkg,$rv,@attrs> */
2453     ENTER;              /* need to protect against side-effects of 'use' */
2454     stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
2455
2456 #define ATTRSMODULE "attributes"
2457 #define ATTRSMODULE_PM "attributes.pm"
2458
2459     if (for_my) {
2460         /* Don't force the C<use> if we don't need it. */
2461         SV * const * const svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
2462         if (svp && *svp != &PL_sv_undef)
2463             NOOP;       /* already in %INC */
2464         else
2465             Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
2466                              newSVpvs(ATTRSMODULE), NULL);
2467     }
2468     else {
2469         Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
2470                          newSVpvs(ATTRSMODULE),
2471                          NULL,
2472                          op_prepend_elem(OP_LIST,
2473                                       newSVOP(OP_CONST, 0, stashsv),
2474                                       op_prepend_elem(OP_LIST,
2475                                                    newSVOP(OP_CONST, 0,
2476                                                            newRV(target)),
2477                                                    dup_attrlist(attrs))));
2478     }
2479     LEAVE;
2480 }
2481
2482 STATIC void
2483 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
2484 {
2485     dVAR;
2486     OP *pack, *imop, *arg;
2487     SV *meth, *stashsv;
2488
2489     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
2490
2491     if (!attrs)
2492         return;
2493
2494     assert(target->op_type == OP_PADSV ||
2495            target->op_type == OP_PADHV ||
2496            target->op_type == OP_PADAV);
2497
2498     /* Ensure that attributes.pm is loaded. */
2499     apply_attrs(stash, PAD_SV(target->op_targ), attrs, TRUE);
2500
2501     /* Need package name for method call. */
2502     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
2503
2504     /* Build up the real arg-list. */
2505     stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
2506
2507     arg = newOP(OP_PADSV, 0);
2508     arg->op_targ = target->op_targ;
2509     arg = op_prepend_elem(OP_LIST,
2510                        newSVOP(OP_CONST, 0, stashsv),
2511                        op_prepend_elem(OP_LIST,
2512                                     newUNOP(OP_REFGEN, 0,
2513                                             op_lvalue(arg, OP_REFGEN)),
2514                                     dup_attrlist(attrs)));
2515
2516     /* Fake up a method call to import */
2517     meth = newSVpvs_share("import");
2518     imop = convert(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
2519                    op_append_elem(OP_LIST,
2520                                op_prepend_elem(OP_LIST, pack, list(arg)),
2521                                newSVOP(OP_METHOD_NAMED, 0, meth)));
2522
2523     /* Combine the ops. */
2524     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
2525 }
2526
2527 /*
2528 =notfor apidoc apply_attrs_string
2529
2530 Attempts to apply a list of attributes specified by the C<attrstr> and
2531 C<len> arguments to the subroutine identified by the C<cv> argument which
2532 is expected to be associated with the package identified by the C<stashpv>
2533 argument (see L<attributes>).  It gets this wrong, though, in that it
2534 does not correctly identify the boundaries of the individual attribute
2535 specifications within C<attrstr>.  This is not really intended for the
2536 public API, but has to be listed here for systems such as AIX which
2537 need an explicit export list for symbols.  (It's called from XS code
2538 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
2539 to respect attribute syntax properly would be welcome.
2540
2541 =cut
2542 */
2543
2544 void
2545 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
2546                         const char *attrstr, STRLEN len)
2547 {
2548     OP *attrs = NULL;
2549
2550     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
2551
2552     if (!len) {
2553         len = strlen(attrstr);
2554     }
2555
2556     while (len) {
2557         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
2558         if (len) {
2559             const char * const sstr = attrstr;
2560             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
2561             attrs = op_append_elem(OP_LIST, attrs,
2562                                 newSVOP(OP_CONST, 0,
2563                                         newSVpvn(sstr, attrstr-sstr)));
2564         }
2565     }
2566
2567     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
2568                      newSVpvs(ATTRSMODULE),
2569                      NULL, op_prepend_elem(OP_LIST,
2570                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
2571                                   op_prepend_elem(OP_LIST,
2572                                                newSVOP(OP_CONST, 0,
2573                                                        newRV(MUTABLE_SV(cv))),
2574                                                attrs)));
2575 }
2576
2577 STATIC OP *
2578 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
2579 {
2580     dVAR;
2581     I32 type;
2582     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
2583
2584     PERL_ARGS_ASSERT_MY_KID;
2585
2586     if (!o || (PL_parser && PL_parser->error_count))
2587         return o;
2588
2589     type = o->op_type;
2590     if (PL_madskills && type == OP_NULL && o->op_flags & OPf_KIDS) {
2591         (void)my_kid(cUNOPo->op_first, attrs, imopsp);
2592         return o;
2593     }
2594
2595     if (type == OP_LIST) {
2596         OP *kid;
2597         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
2598             my_kid(kid, attrs, imopsp);
2599         return o;
2600     } else if (type == OP_UNDEF || type == OP_STUB) {
2601         return o;
2602     } else if (type == OP_RV2SV ||      /* "our" declaration */
2603                type == OP_RV2AV ||
2604                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
2605         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
2606             yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
2607                         OP_DESC(o),
2608                         PL_parser->in_my == KEY_our
2609                             ? "our"
2610                             : PL_parser->in_my == KEY_state ? "state" : "my"));
2611         } else if (attrs) {
2612             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
2613             PL_parser->in_my = FALSE;
2614             PL_parser->in_my_stash = NULL;
2615             apply_attrs(GvSTASH(gv),
2616                         (type == OP_RV2SV ? GvSV(gv) :
2617                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
2618                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
2619                         attrs, FALSE);
2620         }
2621         o->op_private |= OPpOUR_INTRO;
2622         return o;
2623     }
2624     else if (type != OP_PADSV &&
2625              type != OP_PADAV &&
2626              type != OP_PADHV &&
2627              type != OP_PUSHMARK)
2628     {
2629         yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
2630                           OP_DESC(o),
2631                           PL_parser->in_my == KEY_our
2632                             ? "our"
2633                             : PL_parser->in_my == KEY_state ? "state" : "my"));
2634         return o;
2635     }
2636     else if (attrs && type != OP_PUSHMARK) {
2637         HV *stash;
2638
2639         PL_parser->in_my = FALSE;
2640         PL_parser->in_my_stash = NULL;
2641
2642         /* check for C<my Dog $spot> when deciding package */
2643         stash = PAD_COMPNAME_TYPE(o->op_targ);
2644         if (!stash)
2645             stash = PL_curstash;
2646         apply_attrs_my(stash, o, attrs, imopsp);
2647     }
2648     o->op_flags |= OPf_MOD;
2649     o->op_private |= OPpLVAL_INTRO;
2650     if (stately)
2651         o->op_private |= OPpPAD_STATE;
2652     return o;
2653 }
2654
2655 OP *
2656 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
2657 {
2658     dVAR;
2659     OP *rops;
2660     int maybe_scalar = 0;
2661
2662     PERL_ARGS_ASSERT_MY_ATTRS;
2663
2664 /* [perl #17376]: this appears to be premature, and results in code such as
2665    C< our(%x); > executing in list mode rather than void mode */
2666 #if 0
2667     if (o->op_flags & OPf_PARENS)
2668         list(o);
2669     else
2670         maybe_scalar = 1;
2671 #else
2672     maybe_scalar = 1;
2673 #endif
2674     if (attrs)
2675         SAVEFREEOP(attrs);
2676     rops = NULL;
2677     o = my_kid(o, attrs, &rops);
2678     if (rops) {
2679         if (maybe_scalar && o->op_type == OP_PADSV) {
2680             o = scalar(op_append_list(OP_LIST, rops, o));
2681             o->op_private |= OPpLVAL_INTRO;
2682         }
2683         else {
2684             /* The listop in rops might have a pushmark at the beginning,
2685                which will mess up list assignment. */
2686             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
2687             if (rops->op_type == OP_LIST && 
2688                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
2689             {
2690                 OP * const pushmark = lrops->op_first;
2691                 lrops->op_first = pushmark->op_sibling;
2692                 op_free(pushmark);
2693             }
2694             o = op_append_list(OP_LIST, o, rops);
2695         }
2696     }
2697     PL_parser->in_my = FALSE;
2698     PL_parser->in_my_stash = NULL;
2699     return o;
2700 }
2701
2702 OP *
2703 Perl_sawparens(pTHX_ OP *o)
2704 {
2705     PERL_UNUSED_CONTEXT;
2706     if (o)
2707         o->op_flags |= OPf_PARENS;
2708     return o;
2709 }
2710
2711 OP *
2712 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
2713 {
2714     OP *o;
2715     bool ismatchop = 0;
2716     const OPCODE ltype = left->op_type;
2717     const OPCODE rtype = right->op_type;
2718
2719     PERL_ARGS_ASSERT_BIND_MATCH;
2720
2721     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
2722           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
2723     {
2724       const char * const desc
2725           = PL_op_desc[(
2726                           rtype == OP_SUBST || rtype == OP_TRANS
2727                        || rtype == OP_TRANSR
2728                        )
2729                        ? (int)rtype : OP_MATCH];
2730       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
2731       GV *gv;
2732       SV * const name =
2733        (ltype == OP_RV2AV || ltype == OP_RV2HV)
2734         ?    cUNOPx(left)->op_first->op_type == OP_GV
2735           && (gv = cGVOPx_gv(cUNOPx(left)->op_first))
2736               ? varname(gv, isary ? '@' : '%', 0, NULL, 0, 1)
2737               : NULL
2738         : varname(
2739            (GV *)PL_compcv, isary ? '@' : '%', left->op_targ, NULL, 0, 1
2740           );
2741       if (name)
2742         Perl_warner(aTHX_ packWARN(WARN_MISC),
2743              "Applying %s to %"SVf" will act on scalar(%"SVf")",
2744              desc, name, name);
2745       else {
2746         const char * const sample = (isary
2747              ? "@array" : "%hash");
2748         Perl_warner(aTHX_ packWARN(WARN_MISC),
2749              "Applying %s to %s will act on scalar(%s)",
2750              desc, sample, sample);
2751       }
2752     }
2753
2754     if (rtype == OP_CONST &&
2755         cSVOPx(right)->op_private & OPpCONST_BARE &&
2756         cSVOPx(right)->op_private & OPpCONST_STRICT)
2757     {
2758         no_bareword_allowed(right);
2759     }
2760
2761     /* !~ doesn't make sense with /r, so error on it for now */
2762     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
2763         type == OP_NOT)
2764         yyerror("Using !~ with s///r doesn't make sense");
2765     if (rtype == OP_TRANSR && type == OP_NOT)
2766         yyerror("Using !~ with tr///r doesn't make sense");
2767
2768     ismatchop = (rtype == OP_MATCH ||
2769                  rtype == OP_SUBST ||
2770                  rtype == OP_TRANS || rtype == OP_TRANSR)
2771              && !(right->op_flags & OPf_SPECIAL);
2772     if (ismatchop && right->op_private & OPpTARGET_MY) {
2773         right->op_targ = 0;
2774         right->op_private &= ~OPpTARGET_MY;
2775     }
2776     if (!(right->op_flags & OPf_STACKED) && ismatchop) {
2777         OP *newleft;
2778
2779         right->op_flags |= OPf_STACKED;
2780         if (rtype != OP_MATCH && rtype != OP_TRANSR &&
2781             ! (rtype == OP_TRANS &&
2782                right->op_private & OPpTRANS_IDENTICAL) &&
2783             ! (rtype == OP_SUBST &&
2784                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
2785             newleft = op_lvalue(left, rtype);
2786         else
2787             newleft = left;
2788         if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
2789             o = newBINOP(OP_NULL, OPf_STACKED, scalar(newleft), right);
2790         else
2791             o = op_prepend_elem(rtype, scalar(newleft), right);
2792         if (type == OP_NOT)
2793             return newUNOP(OP_NOT, 0, scalar(o));
2794         return o;
2795     }
2796     else
2797         return bind_match(type, left,
2798                 pmruntime(newPMOP(OP_MATCH, 0), right, 0, 0));
2799 }
2800
2801 OP *
2802 Perl_invert(pTHX_ OP *o)
2803 {
2804     if (!o)
2805         return NULL;
2806     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
2807 }
2808
2809 /*
2810 =for apidoc Amx|OP *|op_scope|OP *o
2811
2812 Wraps up an op tree with some additional ops so that at runtime a dynamic
2813 scope will be created.  The original ops run in the new dynamic scope,
2814 and then, provided that they exit normally, the scope will be unwound.
2815 The additional ops used to create and unwind the dynamic scope will
2816 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
2817 instead if the ops are simple enough to not need the full dynamic scope
2818 structure.
2819
2820 =cut
2821 */
2822
2823 OP *
2824 Perl_op_scope(pTHX_ OP *o)
2825 {
2826     dVAR;
2827     if (o) {
2828         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || PL_tainting) {
2829             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
2830             o->op_type = OP_LEAVE;
2831             o->op_ppaddr = PL_ppaddr[OP_LEAVE];
2832         }
2833         else if (o->op_type == OP_LINESEQ) {
2834             OP *kid;
2835             o->op_type = OP_SCOPE;
2836             o->op_ppaddr = PL_ppaddr[OP_SCOPE];
2837             kid = ((LISTOP*)o)->op_first;
2838             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2839                 op_null(kid);
2840
2841                 /* The following deals with things like 'do {1 for 1}' */
2842                 kid = kid->op_sibling;
2843                 if (kid &&
2844                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
2845                     op_null(kid);
2846             }
2847         }
2848         else
2849             o = newLISTOP(OP_SCOPE, 0, o, NULL);
2850     }
2851     return o;
2852 }
2853
2854 int
2855 Perl_block_start(pTHX_ int full)
2856 {
2857     dVAR;
2858     const int retval = PL_savestack_ix;
2859
2860     pad_block_start(full);
2861     SAVEHINTS();
2862     PL_hints &= ~HINT_BLOCK_SCOPE;
2863     SAVECOMPILEWARNINGS();
2864     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
2865
2866     CALL_BLOCK_HOOKS(bhk_start, full);
2867
2868     return retval;
2869 }
2870
2871 OP*
2872 Perl_block_end(pTHX_ I32 floor, OP *seq)
2873 {
2874     dVAR;
2875     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
2876     OP* retval = scalarseq(seq);
2877
2878     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
2879
2880     LEAVE_SCOPE(floor);
2881     CopHINTS_set(&PL_compiling, PL_hints);
2882     if (needblockscope)
2883         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
2884     pad_leavemy();
2885
2886     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
2887
2888     return retval;
2889 }
2890
2891 /*
2892 =head1 Compile-time scope hooks
2893
2894 =for apidoc Aox||blockhook_register
2895
2896 Register a set of hooks to be called when the Perl lexical scope changes
2897 at compile time. See L<perlguts/"Compile-time scope hooks">.
2898
2899 =cut
2900 */
2901
2902 void
2903 Perl_blockhook_register(pTHX_ BHK *hk)
2904 {
2905     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
2906
2907     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
2908 }
2909
2910 STATIC OP *
2911 S_newDEFSVOP(pTHX)
2912 {
2913     dVAR;
2914     const PADOFFSET offset = pad_findmy_pvs("$_", 0);
2915     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
2916         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
2917     }
2918     else {
2919         OP * const o = newOP(OP_PADSV, 0);
2920         o->op_targ = offset;
2921         return o;
2922     }
2923 }
2924
2925 void
2926 Perl_newPROG(pTHX_ OP *o)
2927 {
2928     dVAR;
2929
2930     PERL_ARGS_ASSERT_NEWPROG;
2931
2932     if (PL_in_eval) {
2933         PERL_CONTEXT *cx;
2934         I32 i;
2935         if (PL_eval_root)
2936                 return;
2937         PL_eval_root = newUNOP(OP_LEAVEEVAL,
2938                                ((PL_in_eval & EVAL_KEEPERR)
2939                                 ? OPf_SPECIAL : 0), o);
2940
2941         cx = &cxstack[cxstack_ix];
2942         assert(CxTYPE(cx) == CXt_EVAL);
2943
2944         if ((cx->blk_gimme & G_WANT) == G_VOID)
2945             scalarvoid(PL_eval_root);
2946         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
2947             list(PL_eval_root);
2948         else
2949             scalar(PL_eval_root);
2950
2951         PL_eval_start = op_linklist(PL_eval_root);
2952         PL_eval_root->op_private |= OPpREFCOUNTED;
2953         OpREFCNT_set(PL_eval_root, 1);
2954         PL_eval_root->op_next = 0;
2955         i = PL_savestack_ix;
2956         SAVEFREEOP(o);
2957         ENTER;
2958         CALL_PEEP(PL_eval_start);
2959         finalize_optree(PL_eval_root);
2960         LEAVE;
2961         PL_savestack_ix = i;
2962     }
2963     else {
2964         if (o->op_type == OP_STUB) {
2965             PL_comppad_name = 0;
2966             PL_compcv = 0;
2967             S_op_destroy(aTHX_ o);
2968             return;
2969         }
2970         PL_main_root = op_scope(sawparens(scalarvoid(o)));
2971         PL_curcop = &PL_compiling;
2972         PL_main_start = LINKLIST(PL_main_root);
2973         PL_main_root->op_private |= OPpREFCOUNTED;
2974         OpREFCNT_set(PL_main_root, 1);
2975         PL_main_root->op_next = 0;
2976         CALL_PEEP(PL_main_start);
2977         finalize_optree(PL_main_root);
2978         cv_forget_slab(PL_compcv);
2979         PL_compcv = 0;
2980
2981         /* Register with debugger */
2982         if (PERLDB_INTER) {
2983             CV * const cv = get_cvs("DB::postponed", 0);
2984             if (cv) {
2985                 dSP;
2986                 PUSHMARK(SP);
2987                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
2988                 PUTBACK;
2989                 call_sv(MUTABLE_SV(cv), G_DISCARD);
2990             }
2991         }
2992     }
2993 }
2994
2995 OP *
2996 Perl_localize(pTHX_ OP *o, I32 lex)
2997 {
2998     dVAR;
2999
3000     PERL_ARGS_ASSERT_LOCALIZE;
3001
3002     if (o->op_flags & OPf_PARENS)
3003 /* [perl #17376]: this appears to be premature, and results in code such as
3004    C< our(%x); > executing in list mode rather than void mode */
3005 #if 0
3006         list(o);
3007 #else
3008         NOOP;
3009 #endif
3010     else {
3011         if ( PL_parser->bufptr > PL_parser->oldbufptr
3012             && PL_parser->bufptr[-1] == ','
3013             && ckWARN(WARN_PARENTHESIS))
3014         {
3015             char *s = PL_parser->bufptr;
3016             bool sigil = FALSE;
3017
3018             /* some heuristics to detect a potential error */
3019             while (*s && (strchr(", \t\n", *s)))
3020                 s++;
3021
3022             while (1) {
3023                 if (*s && strchr("@$%*", *s) && *++s
3024                        && (isALNUM(*s) || UTF8_IS_CONTINUED(*s))) {
3025                     s++;
3026                     sigil = TRUE;
3027                     while (*s && (isALNUM(*s) || UTF8_IS_CONTINUED(*s)))
3028                         s++;
3029                     while (*s && (strchr(", \t\n", *s)))
3030                         s++;
3031                 }
3032                 else
3033                     break;
3034             }
3035             if (sigil && (*s == ';' || *s == '=')) {
3036                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
3037                                 "Parentheses missing around \"%s\" list",
3038                                 lex
3039                                     ? (PL_parser->in_my == KEY_our
3040                                         ? "our"
3041                                         : PL_parser->in_my == KEY_state
3042                                             ? "state"
3043                                             : "my")
3044                                     : "local");
3045             }
3046         }
3047     }
3048     if (lex)
3049         o = my(o);
3050     else
3051         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
3052     PL_parser->in_my = FALSE;
3053     PL_parser->in_my_stash = NULL;
3054     return o;
3055 }
3056
3057 OP *
3058 Perl_jmaybe(pTHX_ OP *o)
3059 {
3060     PERL_ARGS_ASSERT_JMAYBE;
3061
3062     if (o->op_type == OP_LIST) {
3063         OP * const o2
3064             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
3065         o = convert(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
3066     }
3067     return o;
3068 }
3069
3070 PERL_STATIC_INLINE OP *
3071 S_op_std_init(pTHX_ OP *o)
3072 {
3073     I32 type = o->op_type;
3074
3075     PERL_ARGS_ASSERT_OP_STD_INIT;
3076
3077     if (PL_opargs[type] & OA_RETSCALAR)
3078         scalar(o);
3079     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
3080         o->op_targ = pad_alloc(type, SVs_PADTMP);
3081
3082     return o;
3083 }
3084
3085 PERL_STATIC_INLINE OP *
3086 S_op_integerize(pTHX_ OP *o)
3087 {
3088     I32 type = o->op_type;
3089
3090     PERL_ARGS_ASSERT_OP_INTEGERIZE;
3091
3092     /* integerize op. */
3093     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
3094     {
3095         dVAR;
3096         o->op_ppaddr = PL_ppaddr[type = ++(o->op_type)];
3097     }
3098
3099     if (type == OP_NEGATE)
3100         /* XXX might want a ck_negate() for this */
3101         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
3102
3103     return o;
3104 }
3105
3106 static OP *
3107 S_fold_constants(pTHX_ register OP *o)
3108 {
3109     dVAR;
3110     register OP * VOL curop;
3111     OP *newop;
3112     VOL I32 type = o->op_type;
3113     SV * VOL sv = NULL;
3114     int ret = 0;
3115     I32 oldscope;
3116     OP *old_next;
3117     SV * const oldwarnhook = PL_warnhook;
3118     SV * const olddiehook  = PL_diehook;
3119     COP not_compiling;
3120     dJMPENV;
3121
3122     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
3123
3124     if (!(PL_opargs[type] & OA_FOLDCONST))
3125         goto nope;
3126
3127     switch (type) {
3128     case OP_UCFIRST:
3129     case OP_LCFIRST:
3130     case OP_UC:
3131     case OP_LC:
3132     case OP_SLT:
3133     case OP_SGT:
3134     case OP_SLE:
3135     case OP_SGE:
3136     case OP_SCMP:
3137     case OP_SPRINTF:
3138         /* XXX what about the numeric ops? */
3139         if (IN_LOCALE_COMPILETIME)
3140             goto nope;
3141         break;
3142     case OP_PACK:
3143         if (!cLISTOPo->op_first->op_sibling
3144           || cLISTOPo->op_first->op_sibling->op_type != OP_CONST)
3145             goto nope;
3146         {
3147             SV * const sv = cSVOPx_sv(cLISTOPo->op_first->op_sibling);
3148             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
3149             {
3150                 const char *s = SvPVX_const(sv);
3151                 while (s < SvEND(sv)) {
3152                     if (*s == 'p' || *s == 'P') goto nope;
3153                     s++;
3154                 }
3155             }
3156         }
3157         break;
3158     case OP_REPEAT:
3159         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
3160     }
3161
3162     if (PL_parser && PL_parser->error_count)
3163         goto nope;              /* Don't try to run w/ errors */
3164
3165     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
3166         const OPCODE type = curop->op_type;
3167         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
3168             type != OP_LIST &&
3169             type != OP_SCALAR &&
3170             type != OP_NULL &&
3171             type != OP_PUSHMARK)
3172         {
3173             goto nope;
3174         }
3175     }
3176
3177     curop = LINKLIST(o);
3178     old_next = o->op_next;
3179     o->op_next = 0;
3180     PL_op = curop;
3181
3182     oldscope = PL_scopestack_ix;
3183     create_eval_scope(G_FAKINGEVAL);
3184
3185     /* Verify that we don't need to save it:  */
3186     assert(PL_curcop == &PL_compiling);
3187     StructCopy(&PL_compiling, &not_compiling, COP);
3188     PL_curcop = &not_compiling;
3189     /* The above ensures that we run with all the correct hints of the
3190        currently compiling COP, but that IN_PERL_RUNTIME is not true. */
3191     assert(IN_PERL_RUNTIME);
3192     PL_warnhook = PERL_WARNHOOK_FATAL;
3193     PL_diehook  = NULL;
3194     JMPENV_PUSH(ret);
3195
3196     switch (ret) {
3197     case 0:
3198         CALLRUNOPS(aTHX);
3199         sv = *(PL_stack_sp--);
3200         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
3201 #ifdef PERL_MAD
3202             /* Can't simply swipe the SV from the pad, because that relies on
3203                the op being freed "real soon now". Under MAD, this doesn't
3204                happen (see the #ifdef below).  */
3205             sv = newSVsv(sv);
3206 #else
3207             pad_swipe(o->op_targ,  FALSE);
3208 #endif
3209         }
3210         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
3211             SvREFCNT_inc_simple_void(sv);
3212             SvTEMP_off(sv);
3213         }
3214         break;
3215     case 3:
3216         /* Something tried to die.  Abandon constant folding.  */
3217         /* Pretend the error never happened.  */
3218         CLEAR_ERRSV();
3219         o->op_next = old_next;
3220         break;
3221     default:
3222         JMPENV_POP;
3223         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
3224         PL_warnhook = oldwarnhook;
3225         PL_diehook  = olddiehook;
3226         /* XXX note that this croak may fail as we've already blown away
3227          * the stack - eg any nested evals */
3228         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
3229     }
3230     JMPENV_POP;
3231     PL_warnhook = oldwarnhook;
3232     PL_diehook  = olddiehook;
3233     PL_curcop = &PL_compiling;
3234
3235     if (PL_scopestack_ix > oldscope)
3236         delete_eval_scope();
3237
3238     if (ret)
3239         goto nope;
3240
3241 #ifndef PERL_MAD
3242     op_free(o);
3243 #endif
3244     assert(sv);
3245     if (type == OP_RV2GV)
3246         newop = newGVOP(OP_GV, 0, MUTABLE_GV(sv));
3247     else
3248         newop = newSVOP(OP_CONST, OPpCONST_FOLDED<<8, MUTABLE_SV(sv));
3249     op_getmad(o,newop,'f');
3250     return newop;
3251
3252  nope:
3253     return o;
3254 }
3255
3256 static OP *
3257 S_gen_constant_list(pTHX_ register OP *o)
3258 {
3259     dVAR;
3260     register OP *curop;
3261     const I32 oldtmps_floor = PL_tmps_floor;
3262
3263     list(o);
3264     if (PL_parser && PL_parser->error_count)
3265         return o;               /* Don't attempt to run with errors */
3266
3267     PL_op = curop = LINKLIST(o);
3268     o->op_next = 0;
3269     CALL_PEEP(curop);
3270     Perl_pp_pushmark(aTHX);
3271     CALLRUNOPS(aTHX);
3272     PL_op = curop;
3273     assert (!(curop->op_flags & OPf_SPECIAL));
3274     assert(curop->op_type == OP_RANGE);
3275     Perl_pp_anonlist(aTHX);
3276     PL_tmps_floor = oldtmps_floor;
3277
3278     o->op_type = OP_RV2AV;
3279     o->op_ppaddr = PL_ppaddr[OP_RV2AV];
3280     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
3281     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
3282     o->op_opt = 0;              /* needs to be revisited in rpeep() */
3283     curop = ((UNOP*)o)->op_first;
3284     ((UNOP*)o)->op_first = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(*PL_stack_sp--));
3285 #ifdef PERL_MAD
3286     op_getmad(curop,o,'O');
3287 #else
3288     op_free(curop);
3289 #endif
3290     LINKLIST(o);
3291     return list(o);
3292 }
3293
3294 OP *
3295 Perl_convert(pTHX_ I32 type, I32 flags, OP *o)
3296 {
3297     dVAR;
3298     if (type < 0) type = -type, flags |= OPf_SPECIAL;
3299     if (!o || o->op_type != OP_LIST)
3300         o = newLISTOP(OP_LIST, 0, o, NULL);
3301     else
3302         o->op_flags &= ~OPf_WANT;
3303
3304     if (!(PL_opargs[type] & OA_MARK))
3305         op_null(cLISTOPo->op_first);
3306     else {
3307         OP * const kid2 = cLISTOPo->op_first->op_sibling;
3308         if (kid2 && kid2->op_type == OP_COREARGS) {
3309             op_null(cLISTOPo->op_first);
3310             kid2->op_private |= OPpCOREARGS_PUSHMARK;
3311         }
3312     }   
3313
3314     o->op_type = (OPCODE)type;
3315     o->op_ppaddr = PL_ppaddr[type];
3316     o->op_flags |= flags;
3317
3318     o = CHECKOP(type, o);
3319     if (o->op_type != (unsigned)type)
3320         return o;
3321
3322     return fold_constants(op_integerize(op_std_init(o)));
3323 }
3324
3325 /*
3326 =head1 Optree Manipulation Functions
3327 */
3328
3329 /* List constructors */
3330
3331 /*
3332 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
3333
3334 Append an item to the list of ops contained directly within a list-type
3335 op, returning the lengthened list.  I<first> is the list-type op,
3336 and I<last> is the op to append to the list.  I<optype> specifies the
3337 intended opcode for the list.  If I<first> is not already a list of the
3338 right type, it will be upgraded into one.  If either I<first> or I<last>
3339 is null, the other is returned unchanged.
3340
3341 =cut
3342 */
3343
3344 OP *
3345 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
3346 {
3347     if (!first)
3348         return last;
3349
3350     if (!last)
3351         return first;
3352
3353     if (first->op_type != (unsigned)type
3354         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
3355     {
3356         return newLISTOP(type, 0, first, last);
3357     }
3358
3359     if (first->op_flags & OPf_KIDS)
3360         ((LISTOP*)first)->op_last->op_sibling = last;
3361     else {
3362         first->op_flags |= OPf_KIDS;
3363         ((LISTOP*)first)->op_first = last;
3364     }
3365     ((LISTOP*)first)->op_last = last;
3366     return first;
3367 }
3368
3369 /*
3370 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
3371
3372 Concatenate the lists of ops contained directly within two list-type ops,
3373 returning the combined list.  I<first> and I<last> are the list-type ops
3374 to concatenate.  I<optype> specifies the intended opcode for the list.
3375 If either I<first> or I<last> is not already a list of the right type,
3376 it will be upgraded into one.  If either I<first> or I<last> is null,
3377 the other is returned unchanged.
3378
3379 =cut
3380 */
3381
3382 OP *
3383 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
3384 {
3385     if (!first)
3386         return last;
3387
3388     if (!last)
3389         return first;
3390
3391     if (first->op_type != (unsigned)type)
3392         return op_prepend_elem(type, first, last);
3393
3394     if (last->op_type != (unsigned)type)
3395         return op_append_elem(type, first, last);
3396
3397     ((LISTOP*)first)->op_last->op_sibling = ((LISTOP*)last)->op_first;
3398     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
3399     first->op_flags |= (last->op_flags & OPf_KIDS);
3400
3401 #ifdef PERL_MAD
3402     if (((LISTOP*)last)->op_first && first->op_madprop) {
3403         MADPROP *mp = ((LISTOP*)last)->op_first->op_madprop;
3404         if (mp) {
3405             while (mp->mad_next)
3406                 mp = mp->mad_next;
3407             mp->mad_next = first->op_madprop;
3408         }
3409         else {
3410             ((LISTOP*)last)->op_first->op_madprop = first->op_madprop;
3411         }
3412     }
3413     first->op_madprop = last->op_madprop;
3414     last->op_madprop = 0;
3415 #endif
3416
3417     S_op_destroy(aTHX_ last);
3418
3419     return first;
3420 }
3421
3422 /*
3423 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
3424
3425 Prepend an item to the list of ops contained directly within a list-type
3426 op, returning the lengthened list.  I<first> is the op to prepend to the
3427 list, and I<last> is the list-type op.  I<optype> specifies the intended
3428 opcode for the list.  If I<last> is not already a list of the right type,
3429 it will be upgraded into one.  If either I<first> or I<last> is null,
3430 the other is returned unchanged.
3431
3432 =cut
3433 */
3434
3435 OP *
3436 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
3437 {
3438     if (!first)
3439         return last;
3440
3441     if (!last)
3442         return first;
3443
3444     if (last->op_type == (unsigned)type) {
3445         if (type == OP_LIST) {  /* already a PUSHMARK there */
3446             first->op_sibling = ((LISTOP*)last)->op_first->op_sibling;
3447             ((LISTOP*)last)->op_first->op_sibling = first;
3448             if (!(first->op_flags & OPf_PARENS))
3449                 last->op_flags &= ~OPf_PARENS;
3450         }
3451         else {
3452             if (!(last->op_flags & OPf_KIDS)) {
3453                 ((LISTOP*)last)->op_last = first;
3454                 last->op_flags |= OPf_KIDS;
3455             }
3456             first->op_sibling = ((LISTOP*)last)->op_first;
3457             ((LISTOP*)last)->op_first = first;
3458         }
3459         last->op_flags |= OPf_KIDS;
3460         return last;
3461     }
3462
3463     return newLISTOP(type, 0, first, last);
3464 }
3465
3466 /* Constructors */
3467
3468 #ifdef PERL_MAD
3469  
3470 TOKEN *
3471 Perl_newTOKEN(pTHX_ I32 optype, YYSTYPE lval, MADPROP* madprop)
3472 {
3473     TOKEN *tk;
3474     Newxz(tk, 1, TOKEN);
3475     tk->tk_type = (OPCODE)optype;
3476     tk->tk_type = 12345;
3477     tk->tk_lval = lval;
3478     tk->tk_mad = madprop;
3479     return tk;
3480 }
3481
3482 void
3483 Perl_token_free(pTHX_ TOKEN* tk)
3484 {
3485     PERL_ARGS_ASSERT_TOKEN_FREE;
3486
3487     if (tk->tk_type != 12345)
3488         return;
3489     mad_free(tk->tk_mad);
3490     Safefree(tk);
3491 }
3492
3493 void
3494 Perl_token_getmad(pTHX_ TOKEN* tk, OP* o, char slot)
3495 {
3496     MADPROP* mp;
3497     MADPROP* tm;
3498
3499     PERL_ARGS_ASSERT_TOKEN_GETMAD;
3500
3501     if (tk->tk_type != 12345) {
3502         Perl_warner(aTHX_ packWARN(WARN_MISC),
3503              "Invalid TOKEN object ignored");
3504         return;
3505     }
3506     tm = tk->tk_mad;
3507     if (!tm)
3508         return;
3509
3510     /* faked up qw list? */
3511     if (slot == '(' &&
3512         tm->mad_type == MAD_SV &&
3513         SvPVX((SV *)tm->mad_val)[0] == 'q')
3514             slot = 'x';
3515
3516     if (o) {
3517         mp = o->op_madprop;
3518         if (mp) {
3519             for (;;) {
3520                 /* pretend constant fold didn't happen? */
3521                 if (mp->mad_key == 'f' &&
3522                     (o->op_type == OP_CONST ||
3523                      o->op_type == OP_GV) )
3524                 {
3525                     token_getmad(tk,(OP*)mp->mad_val,slot);
3526                     return;
3527                 }
3528                 if (!mp->mad_next)
3529                     break;
3530                 mp = mp->mad_next;
3531             }
3532             mp->mad_next = tm;
3533             mp = mp->mad_next;
3534         }
3535         else {
3536             o->op_madprop = tm;
3537             mp = o->op_madprop;
3538         }
3539         if (mp->mad_key == 'X')
3540             mp->mad_key = slot; /* just change the first one */
3541
3542         tk->tk_mad = 0;
3543     }
3544     else
3545         mad_free(tm);
3546     Safefree(tk);
3547 }
3548
3549 void
3550 Perl_op_getmad_weak(pTHX_ OP* from, OP* o, char slot)
3551 {
3552     MADPROP* mp;
3553     if (!from)
3554         return;
3555     if (o) {
3556         mp = o->op_madprop;
3557         if (mp) {
3558             for (;;) {
3559                 /* pretend constant fold didn't happen? */
3560                 if (mp->mad_key == 'f' &&
3561                     (o->op_type == OP_CONST ||
3562                      o->op_type == OP_GV) )
3563                 {
3564                     op_getmad(from,(OP*)mp->mad_val,slot);
3565                     return;
3566                 }
3567                 if (!mp->mad_next)
3568                     break;
3569                 mp = mp->mad_next;
3570             }
3571             mp->mad_next = newMADPROP(slot,MAD_OP,from,0);
3572         }
3573         else {
3574             o->op_madprop = newMADPROP(slot,MAD_OP,from,0);
3575         }
3576     }
3577 }
3578
3579 void
3580 Perl_op_getmad(pTHX_ OP* from, OP* o, char slot)
3581 {
3582     MADPROP* mp;
3583     if (!from)
3584         return;
3585     if (o) {
3586         mp = o->op_madprop;
3587         if (mp) {
3588             for (;;) {
3589                 /* pretend constant fold didn't happen? */
3590                 if (mp->mad_key == 'f' &&
3591                     (o->op_type == OP_CONST ||
3592                      o->op_type == OP_GV) )
3593                 {
3594                     op_getmad(from,(OP*)mp->mad_val,slot);
3595                     return;
3596                 }
3597                 if (!mp->mad_next)
3598                     break;
3599                 mp = mp->mad_next;
3600             }
3601             mp->mad_next = newMADPROP(slot,MAD_OP,from,1);
3602         }
3603         else {
3604             o->op_madprop = newMADPROP(slot,MAD_OP,from,1);
3605         }
3606     }
3607     else {
3608         PerlIO_printf(PerlIO_stderr(),
3609                       "DESTROYING op = %0"UVxf"\n", PTR2UV(from));
3610         op_free(from);
3611     }
3612 }
3613
3614 void
3615 Perl_prepend_madprops(pTHX_ MADPROP* mp, OP* o, char slot)
3616 {
3617     MADPROP* tm;
3618     if (!mp || !o)
3619         return;
3620     if (slot)
3621         mp->mad_key = slot;
3622     tm = o->op_madprop;
3623     o->op_madprop = mp;
3624     for (;;) {
3625         if (!mp->mad_next)
3626             break;
3627         mp = mp->mad_next;
3628     }
3629     mp->mad_next = tm;
3630 }
3631
3632 void
3633 Perl_append_madprops(pTHX_ MADPROP* tm, OP* o, char slot)
3634 {
3635     if (!o)
3636         return;
3637     addmad(tm, &(o->op_madprop), slot);
3638 }
3639
3640 void
3641 Perl_addmad(pTHX_ MADPROP* tm, MADPROP** root, char slot)
3642 {
3643     MADPROP* mp;
3644     if (!tm || !root)
3645         return;
3646     if (slot)
3647         tm->mad_key = slot;
3648     mp = *root;
3649     if (!mp) {
3650         *root = tm;
3651         return;
3652     }
3653     for (;;) {
3654         if (!mp->mad_next)
3655             break;
3656         mp = mp->mad_next;
3657     }
3658     mp->mad_next = tm;
3659 }
3660
3661 MADPROP *
3662 Perl_newMADsv(pTHX_ char key, SV* sv)
3663 {
3664     PERL_ARGS_ASSERT_NEWMADSV;
3665
3666     return newMADPROP(key, MAD_SV, sv, 0);
3667 }
3668
3669 MADPROP *
3670 Perl_newMADPROP(pTHX_ char key, char type, void* val, I32 vlen)
3671 {
3672     MADPROP *const mp = (MADPROP *) PerlMemShared_malloc(sizeof(MADPROP));
3673     mp->mad_next = 0;
3674     mp->mad_key = key;
3675     mp->mad_vlen = vlen;
3676     mp->mad_type = type;
3677     mp->mad_val = val;
3678 /*    PerlIO_printf(PerlIO_stderr(), "NEW  mp = %0x\n", mp);  */
3679     return mp;
3680 }
3681
3682 void
3683 Perl_mad_free(pTHX_ MADPROP* mp)
3684 {
3685 /*    PerlIO_printf(PerlIO_stderr(), "FREE mp = %0x\n", mp); */
3686     if (!mp)
3687         return;
3688     if (mp->mad_next)
3689         mad_free(mp->mad_next);
3690 /*    if (PL_parser && PL_parser->lex_state != LEX_NOTPARSING && mp->mad_vlen)
3691         PerlIO_printf(PerlIO_stderr(), "DESTROYING '%c'=<%s>\n", mp->mad_key & 255, mp->mad_val); */
3692     switch (mp->mad_type) {
3693     case MAD_NULL:
3694         break;
3695     case MAD_PV:
3696         Safefree((char*)mp->mad_val);
3697         break;
3698     case MAD_OP:
3699         if (mp->mad_vlen)       /* vlen holds "strong/weak" boolean */
3700             op_free((OP*)mp->mad_val);
3701         break;
3702     case MAD_SV:
3703         sv_free(MUTABLE_SV(mp->mad_val));
3704         break;
3705     default:
3706         PerlIO_printf(PerlIO_stderr(), "Unrecognized mad\n");
3707         break;
3708     }
3709     PerlMemShared_free(mp);
3710 }
3711
3712 #endif
3713
3714 /*
3715 =head1 Optree construction
3716
3717 =for apidoc Am|OP *|newNULLLIST
3718
3719 Constructs, checks, and returns a new C<stub> op, which represents an
3720 empty list expression.
3721
3722 =cut
3723 */
3724
3725 OP *
3726 Perl_newNULLLIST(pTHX)
3727 {
3728     return newOP(OP_STUB, 0);
3729 }
3730
3731 static OP *
3732 S_force_list(pTHX_ OP *o)
3733 {
3734     if (!o || o->op_type != OP_LIST)
3735         o = newLISTOP(OP_LIST, 0, o, NULL);
3736     op_null(o);
3737     return o;
3738 }
3739
3740 /*
3741 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
3742
3743 Constructs, checks, and returns an op of any list type.  I<type> is
3744 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
3745 C<OPf_KIDS> will be set automatically if required.  I<first> and I<last>
3746 supply up to two ops to be direct children of the list op; they are
3747 consumed by this function and become part of the constructed op tree.
3748
3749 =cut
3750 */
3751
3752 OP *
3753 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
3754 {
3755     dVAR;
3756     LISTOP *listop;
3757
3758     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP);
3759
3760     NewOp(1101, listop, 1, LISTOP);
3761
3762     listop->op_type = (OPCODE)type;
3763     listop->op_ppaddr = PL_ppaddr[type];
3764     if (first || last)
3765         flags |= OPf_KIDS;
3766     listop->op_flags = (U8)flags;
3767
3768     if (!last && first)
3769         last = first;
3770     else if (!first && last)
3771         first = last;
3772     else if (first)
3773         first->op_sibling = last;
3774     listop->op_first = first;
3775     listop->op_last = last;
3776     if (type == OP_LIST) {
3777         OP* const pushop = newOP(OP_PUSHMARK, 0);
3778         pushop->op_sibling = first;
3779         listop->op_first = pushop;
3780         listop->op_flags |= OPf_KIDS;
3781         if (!last)
3782             listop->op_last = pushop;
3783     }
3784
3785     return CHECKOP(type, listop);
3786 }
3787
3788 /*
3789 =for apidoc Am|OP *|newOP|I32 type|I32 flags
3790
3791 Constructs, checks, and returns an op of any base type (any type that
3792 has no extra fields).  I<type> is the opcode.  I<flags> gives the
3793 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
3794 of C<op_private>.
3795
3796 =cut
3797 */
3798
3799 OP *
3800 Perl_newOP(pTHX_ I32 type, I32 flags)
3801 {
3802     dVAR;
3803     OP *o;
3804
3805     if (type == -OP_ENTEREVAL) {
3806         type = OP_ENTEREVAL;
3807         flags |= OPpEVAL_BYTES<<8;
3808     }
3809
3810     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
3811         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
3812         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
3813         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
3814
3815     NewOp(1101, o, 1, OP);
3816     o->op_type = (OPCODE)type;
3817     o->op_ppaddr = PL_ppaddr[type];
3818     o->op_flags = (U8)flags;
3819     o->op_latefree = 0;
3820     o->op_latefreed = 0;
3821     o->op_attached = 0;
3822
3823     o->op_next = o;
3824     o->op_private = (U8)(0 | (flags >> 8));
3825     if (PL_opargs[type] & OA_RETSCALAR)
3826         scalar(o);
3827     if (PL_opargs[type] & OA_TARGET)
3828         o->op_targ = pad_alloc(type, SVs_PADTMP);
3829     return CHECKOP(type, o);
3830 }
3831
3832 /*
3833 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
3834
3835 Constructs, checks, and returns an op of any unary type.  I<type> is
3836 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
3837 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
3838 bits, the eight bits of C<op_private>, except that the bit with value 1
3839 is automatically set.  I<first> supplies an optional op to be the direct
3840 child of the unary op; it is consumed by this function and become part
3841 of the constructed op tree.
3842
3843 =cut
3844 */
3845
3846 OP *
3847 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
3848 {
3849     dVAR;
3850     UNOP *unop;
3851
3852     if (type == -OP_ENTEREVAL) {
3853         type = OP_ENTEREVAL;
3854         flags |= OPpEVAL_BYTES<<8;
3855     }
3856
3857     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
3858         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
3859         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
3860         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
3861         || type == OP_SASSIGN
3862         || type == OP_ENTERTRY
3863         || type == OP_NULL );
3864
3865     if (!first)
3866         first = newOP(OP_STUB, 0);
3867     if (PL_opargs[type] & OA_MARK)
3868         first = force_list(first);
3869
3870     NewOp(1101, unop, 1, UNOP);
3871     unop->op_type = (OPCODE)type;
3872     unop->op_ppaddr = PL_ppaddr[type];
3873     unop->op_first = first;
3874     unop->op_flags = (U8)(flags | OPf_KIDS);
3875     unop->op_private = (U8)(1 | (flags >> 8));
3876     unop = (UNOP*) CHECKOP(type, unop);
3877     if (unop->op_next)
3878         return (OP*)unop;
3879
3880     return fold_constants(op_integerize(op_std_init((OP *) unop)));
3881 }
3882
3883 /*
3884 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
3885
3886 Constructs, checks, and returns an op of any binary type.  I<type>
3887 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
3888 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
3889 the eight bits of C<op_private>, except that the bit with value 1 or
3890 2 is automatically set as required.  I<first> and I<last> supply up to
3891 two ops to be the direct children of the binary op; they are consumed
3892 by this function and become part of the constructed op tree.
3893
3894 =cut
3895 */
3896
3897 OP *
3898 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
3899 {
3900     dVAR;
3901     BINOP *binop;
3902
3903     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
3904         || type == OP_SASSIGN || type == OP_NULL );
3905
3906     NewOp(1101, binop, 1, BINOP);
3907
3908     if (!first)
3909         first = newOP(OP_NULL, 0);
3910
3911     binop->op_type = (OPCODE)type;
3912     binop->op_ppaddr = PL_ppaddr[type];
3913     binop->op_first = first;
3914     binop->op_flags = (U8)(flags | OPf_KIDS);
3915     if (!last) {
3916         last = first;
3917         binop->op_private = (U8)(1 | (flags >> 8));
3918     }
3919     else {
3920         binop->op_private = (U8)(2 | (flags >> 8));
3921         first->op_sibling = last;
3922     }
3923
3924     binop = (BINOP*)CHECKOP(type, binop);
3925     if (binop->op_next || binop->op_type != (OPCODE)type)
3926         return (OP*)binop;
3927
3928     binop->op_last = binop->op_first->op_sibling;
3929
3930     return fold_constants(op_integerize(op_std_init((OP *)binop)));
3931 }
3932
3933 static int uvcompare(const void *a, const void *b)
3934     __attribute__nonnull__(1)
3935     __attribute__nonnull__(2)
3936     __attribute__pure__;
3937 static int uvcompare(const void *a, const void *b)
3938 {
3939     if (*((const UV *)a) < (*(const UV *)b))
3940         return -1;
3941     if (*((const UV *)a) > (*(const UV *)b))
3942         return 1;
3943     if (*((const UV *)a+1) < (*(const UV *)b+1))
3944         return -1;
3945     if (*((const UV *)a+1) > (*(const UV *)b+1))
3946         return 1;
3947     return 0;
3948 }
3949
3950 static OP *
3951 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
3952 {
3953     dVAR;
3954     SV * const tstr = ((SVOP*)expr)->op_sv;
3955     SV * const rstr =
3956 #ifdef PERL_MAD
3957                         (repl->op_type == OP_NULL)
3958                             ? ((SVOP*)((LISTOP*)repl)->op_first)->op_sv :
3959 #endif
3960                               ((SVOP*)repl)->op_sv;
3961     STRLEN tlen;
3962     STRLEN rlen;
3963     const U8 *t = (U8*)SvPV_const(tstr, tlen);
3964     const U8 *r = (U8*)SvPV_const(rstr, rlen);
3965     register I32 i;
3966     register I32 j;
3967     I32 grows = 0;
3968     register short *tbl;
3969
3970     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
3971     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
3972     I32 del              = o->op_private & OPpTRANS_DELETE;
3973     SV* swash;
3974
3975     PERL_ARGS_ASSERT_PMTRANS;
3976
3977     PL_hints |= HINT_BLOCK_SCOPE;
3978
3979     if (SvUTF8(tstr))
3980         o->op_private |= OPpTRANS_FROM_UTF;
3981
3982     if (SvUTF8(rstr))
3983         o->op_private |= OPpTRANS_TO_UTF;
3984
3985     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
3986         SV* const listsv = newSVpvs("# comment\n");
3987         SV* transv = NULL;
3988         const U8* tend = t + tlen;
3989         const U8* rend = r + rlen;
3990         STRLEN ulen;
3991         UV tfirst = 1;
3992         UV tlast = 0;
3993         IV tdiff;
3994         UV rfirst = 1;
3995         UV rlast = 0;
3996         IV rdiff;
3997         IV diff;
3998         I32 none = 0;
3999         U32 max = 0;
4000         I32 bits;
4001         I32 havefinal = 0;
4002         U32 final = 0;
4003         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
4004         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
4005         U8* tsave = NULL;
4006         U8* rsave = NULL;
4007         const U32 flags = UTF8_ALLOW_DEFAULT;
4008
4009         if (!from_utf) {
4010             STRLEN len = tlen;
4011             t = tsave = bytes_to_utf8(t, &len);
4012             tend = t + len;
4013         }
4014         if (!to_utf && rlen) {
4015             STRLEN len = rlen;
4016             r = rsave = bytes_to_utf8(r, &len);
4017             rend = r + len;
4018         }
4019
4020 /* There are several snags with this code on EBCDIC:
4021    1. 0xFF is a legal UTF-EBCDIC byte (there are no illegal bytes).
4022    2. scan_const() in toke.c has encoded chars in native encoding which makes
4023       ranges at least in EBCDIC 0..255 range the bottom odd.
4024 */
4025
4026         if (complement) {
4027             U8 tmpbuf[UTF8_MAXBYTES+1];
4028             UV *cp;
4029             UV nextmin = 0;
4030             Newx(cp, 2*tlen, UV);
4031             i = 0;
4032             transv = newSVpvs("");
4033             while (t < tend) {
4034                 cp[2*i] = utf8n_to_uvuni(t, tend-t, &ulen, flags);
4035                 t += ulen;
4036                 if (t < tend && NATIVE_TO_UTF(*t) == 0xff) {
4037                     t++;
4038                     cp[2*i+1] = utf8n_to_uvuni(t, tend-t, &ulen, flags);
4039                     t += ulen;
4040                 }
4041                 else {
4042                  cp[2*i+1] = cp[2*i];
4043                 }
4044                 i++;
4045             }
4046             qsort(cp, i, 2*sizeof(UV), uvcompare);
4047             for (j = 0; j < i; j++) {
4048                 UV  val = cp[2*j];
4049                 diff = val - nextmin;
4050                 if (diff > 0) {
4051                     t = uvuni_to_utf8(tmpbuf,nextmin);
4052                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4053                     if (diff > 1) {
4054                         U8  range_mark = UTF_TO_NATIVE(0xff);
4055                         t = uvuni_to_utf8(tmpbuf, val - 1);
4056                         sv_catpvn(transv, (char *)&range_mark, 1);
4057                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4058                     }
4059                 }
4060                 val = cp[2*j+1];
4061                 if (val >= nextmin)
4062                     nextmin = val + 1;
4063             }
4064             t = uvuni_to_utf8(tmpbuf,nextmin);
4065             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4066             {
4067                 U8 range_mark = UTF_TO_NATIVE(0xff);
4068                 sv_catpvn(transv, (char *)&range_mark, 1);
4069             }
4070             t = uvuni_to_utf8(tmpbuf, 0x7fffffff);
4071             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4072             t = (const U8*)SvPVX_const(transv);
4073             tlen = SvCUR(transv);
4074             tend = t + tlen;
4075             Safefree(cp);
4076         }
4077         else if (!rlen && !del) {
4078             r = t; rlen = tlen; rend = tend;
4079         }
4080         if (!squash) {
4081                 if ((!rlen && !del) || t == r ||
4082                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
4083                 {
4084                     o->op_private |= OPpTRANS_IDENTICAL;
4085                 }
4086         }
4087
4088         while (t < tend || tfirst <= tlast) {
4089             /* see if we need more "t" chars */
4090             if (tfirst > tlast) {
4091                 tfirst = (I32)utf8n_to_uvuni(t, tend - t, &ulen, flags);
4092                 t += ulen;
4093                 if (t < tend && NATIVE_TO_UTF(*t) == 0xff) {    /* illegal utf8 val indicates range */
4094                     t++;
4095                     tlast = (I32)utf8n_to_uvuni(t, tend - t, &ulen, flags);
4096                     t += ulen;
4097                 }
4098                 else
4099                     tlast = tfirst;
4100             }
4101
4102             /* now see if we need more "r" chars */
4103             if (rfirst > rlast) {
4104                 if (r < rend) {
4105                     rfirst = (I32)utf8n_to_uvuni(r, rend - r, &ulen, flags);
4106                     r += ulen;
4107                     if (r < rend && NATIVE_TO_UTF(*r) == 0xff) {        /* illegal utf8 val indicates range */
4108                         r++;
4109                         rlast = (I32)utf8n_to_uvuni(r, rend - r, &ulen, flags);
4110                         r += ulen;
4111                     }
4112                     else
4113                         rlast = rfirst;
4114                 }
4115                 else {
4116                     if (!havefinal++)
4117                         final = rlast;
4118                     rfirst = rlast = 0xffffffff;
4119                 }
4120             }
4121
4122             /* now see which range will peter our first, if either. */
4123             tdiff = tlast - tfirst;
4124             rdiff = rlast - rfirst;
4125
4126             if (tdiff <= rdiff)
4127                 diff = tdiff;
4128             else
4129                 diff = rdiff;
4130
4131             if (rfirst == 0xffffffff) {
4132                 diff = tdiff;   /* oops, pretend rdiff is infinite */
4133                 if (diff > 0)
4134                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
4135                                    (long)tfirst, (long)tlast);
4136                 else
4137                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
4138             }
4139             else {
4140                 if (diff > 0)
4141                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
4142                                    (long)tfirst, (long)(tfirst + diff),
4143                                    (long)rfirst);
4144                 else
4145                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
4146                                    (long)tfirst, (long)rfirst);
4147
4148                 if (rfirst + diff > max)
4149                     max = rfirst + diff;
4150                 if (!grows)
4151                     grows = (tfirst < rfirst &&
4152                              UNISKIP(tfirst) < UNISKIP(rfirst + diff));
4153                 rfirst += diff + 1;
4154             }
4155             tfirst += diff + 1;
4156         }
4157
4158         none = ++max;
4159         if (del)
4160             del = ++max;
4161
4162         if (max > 0xffff)
4163             bits = 32;
4164         else if (max > 0xff)
4165             bits = 16;
4166         else
4167             bits = 8;
4168
4169         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
4170 #ifdef USE_ITHREADS
4171         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVs_PADTMP);
4172         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
4173         PAD_SETSV(cPADOPo->op_padix, swash);
4174         SvPADTMP_on(swash);
4175         SvREADONLY_on(swash);
4176 #else
4177         cSVOPo->op_sv = swash;
4178 #endif
4179         SvREFCNT_dec(listsv);
4180         SvREFCNT_dec(transv);
4181
4182         if (!del && havefinal && rlen)
4183             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
4184                            newSVuv((UV)final), 0);
4185
4186         if (grows)
4187             o->op_private |= OPpTRANS_GROWS;
4188
4189         Safefree(tsave);
4190         Safefree(rsave);
4191
4192 #ifdef PERL_MAD
4193         op_getmad(expr,o,'e');
4194         op_getmad(repl,o,'r');
4195 #else
4196         op_free(expr);
4197         op_free(repl);
4198 #endif
4199         return o;
4200     }
4201
4202     tbl = (short*)PerlMemShared_calloc(
4203         (o->op_private & OPpTRANS_COMPLEMENT) &&
4204             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
4205         sizeof(short));
4206     cPVOPo->op_pv = (char*)tbl;
4207     if (complement) {
4208         for (i = 0; i < (I32)tlen; i++)
4209             tbl[t[i]] = -1;
4210         for (i = 0, j = 0; i < 256; i++) {
4211             if (!tbl[i]) {
4212                 if (j >= (I32)rlen) {
4213                     if (del)
4214                         tbl[i] = -2;
4215                     else if (rlen)
4216                         tbl[i] = r[j-1];
4217                     else
4218                         tbl[i] = (short)i;
4219                 }
4220                 else {
4221                     if (i < 128 && r[j] >= 128)
4222                         grows = 1;
4223                     tbl[i] = r[j++];
4224                 }
4225             }
4226         }
4227         if (!del) {
4228             if (!rlen) {
4229                 j = rlen;
4230                 if (!squash)
4231                     o->op_private |= OPpTRANS_IDENTICAL;
4232             }
4233             else if (j >= (I32)rlen)
4234                 j = rlen - 1;
4235             else {
4236                 tbl = 
4237                     (short *)
4238                     PerlMemShared_realloc(tbl,
4239                                           (0x101+rlen-j) * sizeof(short));
4240                 cPVOPo->op_pv = (char*)tbl;
4241             }
4242             tbl[0x100] = (short)(rlen - j);
4243             for (i=0; i < (I32)rlen - j; i++)
4244                 tbl[0x101+i] = r[j+i];
4245         }
4246     }
4247     else {
4248         if (!rlen && !del) {
4249             r = t; rlen = tlen;
4250             if (!squash)
4251                 o->op_private |= OPpTRANS_IDENTICAL;
4252         }
4253         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
4254             o->op_private |= OPpTRANS_IDENTICAL;
4255         }
4256         for (i = 0; i < 256; i++)
4257             tbl[i] = -1;
4258         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
4259             if (j >= (I32)rlen) {
4260                 if (del) {
4261                     if (tbl[t[i]] == -1)
4262                         tbl[t[i]] = -2;
4263                     continue;
4264                 }
4265                 --j;
4266             }
4267             if (tbl[t[i]] == -1) {
4268                 if (t[i] < 128 && r[j] >= 128)
4269                     grows = 1;
4270                 tbl[t[i]] = r[j];
4271             }
4272         }
4273     }
4274
4275     if(del && rlen == tlen) {
4276         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
4277     } else if(rlen > tlen) {
4278         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
4279     }
4280
4281     if (grows)
4282         o->op_private |= OPpTRANS_GROWS;
4283 #ifdef PERL_MAD
4284     op_getmad(expr,o,'e');
4285     op_getmad(repl,o,'r');
4286 #else
4287     op_free(expr);
4288     op_free(repl);
4289 #endif
4290
4291     return o;
4292 }
4293
4294 /*
4295 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
4296
4297 Constructs, checks, and returns an op of any pattern matching type.
4298 I<type> is the opcode.  I<flags> gives the eight bits of C<op_flags>
4299 and, shifted up eight bits, the eight bits of C<op_private>.
4300
4301 =cut
4302 */
4303
4304 OP *
4305 Perl_newPMOP(pTHX_ I32 type, I32 flags)
4306 {
4307     dVAR;
4308     PMOP *pmop;
4309
4310     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP);
4311
4312     NewOp(1101, pmop, 1, PMOP);
4313     pmop->op_type = (OPCODE)type;
4314     pmop->op_ppaddr = PL_ppaddr[type];
4315     pmop->op_flags = (U8)flags;
4316     pmop->op_private = (U8)(0 | (flags >> 8));
4317
4318     if (PL_hints & HINT_RE_TAINT)
4319         pmop->op_pmflags |= PMf_RETAINT;
4320     if (IN_LOCALE_COMPILETIME) {
4321         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
4322     }
4323     else if ((! (PL_hints & HINT_BYTES))
4324                 /* Both UNI_8_BIT and locale :not_characters imply Unicode */
4325              && (PL_hints & (HINT_UNI_8_BIT|HINT_LOCALE_NOT_CHARS)))
4326     {
4327         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
4328     }
4329     if (PL_hints & HINT_RE_FLAGS) {
4330         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
4331          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
4332         );
4333         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
4334         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
4335          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
4336         );
4337         if (reflags && SvOK(reflags)) {
4338             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
4339         }
4340     }
4341
4342
4343 #ifdef USE_ITHREADS
4344     assert(SvPOK(PL_regex_pad[0]));
4345     if (SvCUR(PL_regex_pad[0])) {
4346         /* Pop off the "packed" IV from the end.  */
4347         SV *const repointer_list = PL_regex_pad[0];
4348         const char *p = SvEND(repointer_list) - sizeof(IV);
4349         const IV offset = *((IV*)p);
4350
4351         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
4352
4353         SvEND_set(repointer_list, p);
4354
4355         pmop->op_pmoffset = offset;
4356         /* This slot should be free, so assert this:  */
4357         assert(PL_regex_pad[offset] == &PL_sv_undef);
4358     } else {
4359         SV * const repointer = &PL_sv_undef;
4360         av_push(PL_regex_padav, repointer);
4361         pmop->op_pmoffset = av_len(PL_regex_padav);
4362         PL_regex_pad = AvARRAY(PL_regex_padav);
4363     }
4364 #endif
4365
4366     return CHECKOP(type, pmop);
4367 }
4368
4369 /* Given some sort of match op o, and an expression expr containing a
4370  * pattern, either compile expr into a regex and attach it to o (if it's
4371  * constant), or convert expr into a runtime regcomp op sequence (if it's
4372  * not)
4373  *
4374  * isreg indicates that the pattern is part of a regex construct, eg
4375  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
4376  * split "pattern", which aren't. In the former case, expr will be a list
4377  * if the pattern contains more than one term (eg /a$b/) or if it contains
4378  * a replacement, ie s/// or tr///.
4379  *
4380  * When the pattern has been compiled within a new anon CV (for
4381  * qr/(?{...})/ ), then floor indicates the savestack level just before
4382  * the new sub was created
4383  */
4384
4385 OP *
4386 Perl_pmruntime(pTHX_ OP *o, OP *expr, bool isreg, I32 floor)
4387 {
4388     dVAR;
4389     PMOP *pm;
4390     LOGOP *rcop;
4391     I32 repl_has_vars = 0;
4392     OP* repl = NULL;
4393     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
4394     bool is_compiletime;
4395     bool has_code;
4396
4397     PERL_ARGS_ASSERT_PMRUNTIME;
4398
4399     /* for s/// and tr///, last element in list is the replacement; pop it */
4400
4401     if (is_trans || o->op_type == OP_SUBST) {
4402         OP* kid;
4403         repl = cLISTOPx(expr)->op_last;
4404         kid = cLISTOPx(expr)->op_first;
4405         while (kid->op_sibling != repl)
4406             kid = kid->op_sibling;
4407         kid->op_sibling = NULL;
4408         cLISTOPx(expr)->op_last = kid;
4409     }
4410
4411     /* for TRANS, convert LIST/PUSH/CONST into CONST, and pass to pmtrans() */
4412
4413     if (is_trans) {
4414         OP* const oe = expr;
4415         assert(expr->op_type == OP_LIST);
4416         assert(cLISTOPx(expr)->op_first->op_type == OP_PUSHMARK);
4417         assert(cLISTOPx(expr)->op_first->op_sibling == cLISTOPx(expr)->op_last);
4418         expr = cLISTOPx(oe)->op_last;
4419         cLISTOPx(oe)->op_first->op_sibling = NULL;
4420         cLISTOPx(oe)->op_last = NULL;
4421         op_free(oe);
4422
4423         return pmtrans(o, expr, repl);
4424     }
4425
4426     /* find whether we have any runtime or code elements;
4427      * at the same time, temporarily set the op_next of each DO block;
4428      * then when we LINKLIST, this will cause the DO blocks to be excluded
4429      * from the op_next chain (and from having LINKLIST recursively
4430      * applied to them). We fix up the DOs specially later */
4431
4432     is_compiletime = 1;
4433     has_code = 0;
4434     if (expr->op_type == OP_LIST) {
4435         OP *o;
4436         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
4437             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
4438                 has_code = 1;
4439                 assert(!o->op_next && o->op_sibling);
4440                 o->op_next = o->op_sibling;
4441             }
4442             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
4443                 is_compiletime = 0;
4444         }
4445     }
4446     else if (expr->op_type != OP_CONST)
4447         is_compiletime = 0;
4448
4449     LINKLIST(expr);
4450
4451     /* fix up DO blocks; treat each one as a separate little sub */
4452
4453     if (expr->op_type == OP_LIST) {
4454         OP *o;
4455         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
4456             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
4457                 continue;
4458             o->op_next = NULL; /* undo temporary hack from above */
4459             scalar(o);
4460             LINKLIST(o);
4461             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
4462                 LISTOP *leave = cLISTOPx(cLISTOPo->op_first);
4463                 /* skip ENTER */
4464                 assert(leave->op_first->op_type == OP_ENTER);
4465                 assert(leave->op_first->op_sibling);
4466                 o->op_next = leave->op_first->op_sibling;
4467                 /* skip LEAVE */
4468                 assert(leave->op_flags & OPf_KIDS);
4469                 assert(leave->op_last->op_next = (OP*)leave);
4470                 leave->op_next = NULL; /* stop on last op */
4471                 op_null((OP*)leave);
4472             }
4473             else {
4474                 /* skip SCOPE */
4475                 OP *scope = cLISTOPo->op_first;
4476                 assert(scope->op_type == OP_SCOPE);
4477                 assert(scope->op_flags & OPf_KIDS);
4478                 scope->op_next = NULL; /* stop on last op */
4479                 op_null(scope);
4480             }
4481             /* have to peep the DOs individually as we've removed it from
4482              * the op_next chain */
4483             CALL_PEEP(o);
4484             if (is_compiletime)
4485                 /* runtime finalizes as part of finalizing whole tree */
4486                 finalize_optree(o);
4487         }
4488     }
4489
4490     PL_hints |= HINT_BLOCK_SCOPE;
4491     pm = (PMOP*)o;
4492     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
4493
4494     if (is_compiletime) {
4495         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
4496         regexp_engine const *eng = current_re_engine();
4497
4498         if (o->op_flags & OPf_SPECIAL)
4499             rx_flags |= RXf_SPLIT;
4500
4501         if (!has_code || !eng->op_comp) {
4502             /* compile-time simple constant pattern */
4503
4504             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
4505                 /* whoops! we guessed that a qr// had a code block, but we
4506                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
4507                  * that isn't required now. Note that we have to be pretty
4508                  * confident that nothing used that CV's pad while the
4509                  * regex was parsed */
4510                 assert(AvFILLp(PL_comppad) == 0); /* just @_ */
4511                 /* But we know that one op is using this CV's slab. */
4512                 cv_forget_slab(PL_compcv);
4513                 LEAVE_SCOPE(floor);
4514                 pm->op_pmflags &= ~PMf_HAS_CV;
4515             }
4516
4517             PM_SETRE(pm,
4518                 eng->op_comp
4519                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4520                                         rx_flags, pm->op_pmflags)
4521                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4522                                         rx_flags, pm->op_pmflags)
4523             );
4524 #ifdef PERL_MAD
4525             op_getmad(expr,(OP*)pm,'e');
4526 #else
4527             op_free(expr);
4528 #endif
4529         }
4530         else {
4531             /* compile-time pattern that includes literal code blocks */
4532             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4533                         rx_flags,
4534                         (pm->op_pmflags |
4535                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
4536                     );
4537             PM_SETRE(pm, re);
4538             if (pm->op_pmflags & PMf_HAS_CV) {
4539                 CV *cv;
4540                 /* this QR op (and the anon sub we embed it in) is never
4541                  * actually executed. It's just a placeholder where we can
4542                  * squirrel away expr in op_code_list without the peephole
4543                  * optimiser etc processing it for a second time */
4544                 OP *qr = newPMOP(OP_QR, 0);
4545                 ((PMOP*)qr)->op_code_list = expr;
4546
4547                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
4548                 SvREFCNT_inc_simple_void(PL_compcv);
4549                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
4550                 ((struct regexp *)SvANY(re))->qr_anoncv = cv;
4551
4552                 /* attach the anon CV to the pad so that
4553                  * pad_fixup_inner_anons() can find it */
4554                 (void)pad_add_anon(cv, o->op_type);
4555                 SvREFCNT_inc_simple_void(cv);
4556             }
4557             else {
4558                 pm->op_code_list = expr;
4559             }
4560         }
4561     }
4562     else {
4563         /* runtime pattern: build chain of regcomp etc ops */
4564         bool reglist;
4565         PADOFFSET cv_targ = 0;
4566
4567         reglist = isreg && expr->op_type == OP_LIST;
4568         if (reglist)
4569             op_null(expr);
4570
4571         if (has_code) {
4572             pm->op_code_list = expr;
4573             /* don't free op_code_list; its ops are embedded elsewhere too */
4574             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
4575         }
4576
4577         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
4578          * to allow its op_next to be pointed past the regcomp and
4579          * preceding stacking ops;
4580          * OP_REGCRESET is there to reset taint before executing the
4581          * stacking ops */
4582         if (pm->op_pmflags & PMf_KEEP || PL_tainting)
4583             expr = newUNOP((PL_tainting ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
4584
4585         if (pm->op_pmflags & PMf_HAS_CV) {
4586             /* we have a runtime qr with literal code. This means
4587              * that the qr// has been wrapped in a new CV, which
4588              * means that runtime consts, vars etc will have been compiled
4589              * against a new pad. So... we need to execute those ops
4590              * within the environment of the new CV. So wrap them in a call
4591              * to a new anon sub. i.e. for
4592              *
4593              *     qr/a$b(?{...})/,
4594              *
4595              * we build an anon sub that looks like
4596              *
4597              *     sub { "a", $b, '(?{...})' }
4598              *
4599              * and call it, passing the returned list to regcomp.
4600              * Or to put it another way, the list of ops that get executed
4601              * are:
4602              *
4603              *     normal              PMf_HAS_CV
4604              *     ------              -------------------
4605              *                         pushmark (for regcomp)
4606              *                         pushmark (for entersub)
4607              *                         pushmark (for refgen)
4608              *                         anoncode
4609              *                         refgen
4610              *                         entersub
4611              *     regcreset                  regcreset
4612              *     pushmark                   pushmark
4613              *     const("a")                 const("a")
4614              *     gvsv(b)                    gvsv(b)
4615              *     const("(?{...})")          const("(?{...})")
4616              *                                leavesub
4617              *     regcomp             regcomp
4618              */
4619
4620             SvREFCNT_inc_simple_void(PL_compcv);
4621             /* these lines are just an unrolled newANONATTRSUB */
4622             expr = newSVOP(OP_ANONCODE, 0,
4623                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
4624             cv_targ = expr->op_targ;
4625             expr = newUNOP(OP_REFGEN, 0, expr);
4626
4627             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr))));
4628         }
4629
4630         NewOp(1101, rcop, 1, LOGOP);
4631         rcop->op_type = OP_REGCOMP;
4632         rcop->op_ppaddr = PL_ppaddr[OP_REGCOMP];
4633         rcop->op_first = scalar(expr);
4634         rcop->op_flags |= OPf_KIDS
4635                             | ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
4636                             | (reglist ? OPf_STACKED : 0);
4637         rcop->op_private = 0;
4638         rcop->op_other = o;
4639         rcop->op_targ = cv_targ;
4640
4641         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
4642         if (PL_hints & HINT_RE_EVAL) PL_cv_has_eval = 1;
4643
4644         /* establish postfix order */
4645         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
4646             LINKLIST(expr);
4647             rcop->op_next = expr;
4648             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
4649         }
4650         else {
4651             rcop->op_next = LINKLIST(expr);
4652             expr->op_next = (OP*)rcop;
4653         }
4654
4655         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
4656     }
4657
4658     if (repl) {
4659         OP *curop;
4660         if (pm->op_pmflags & PMf_EVAL) {
4661             curop = NULL;
4662             if (CopLINE(PL_curcop) < (line_t)PL_parser->multi_end)
4663                 CopLINE_set(PL_curcop, (line_t)PL_parser->multi_end);
4664         }
4665         else if (repl->op_type == OP_CONST)
4666             curop = repl;
4667         else {
4668             OP *lastop = NULL;
4669             for (curop = LINKLIST(repl); curop!=repl; curop = LINKLIST(curop)) {
4670                 if (curop->op_type == OP_SCOPE
4671                         || curop->op_type == OP_LEAVE
4672                         || (PL_opargs[curop->op_type] & OA_DANGEROUS)) {
4673                     if (curop->op_type == OP_GV) {
4674                         GV * const gv = cGVOPx_gv(curop);
4675                         repl_has_vars = 1;
4676                         if (strchr("&`'123456789+-\016\022", *GvENAME(gv)))
4677                             break;
4678                     }
4679                     else if (curop->op_type == OP_RV2CV)
4680                         break;
4681                     else if (curop->op_type == OP_RV2SV ||
4682                              curop->op_type == OP_RV2AV ||
4683                              curop->op_type == OP_RV2HV ||
4684                              curop->op_type == OP_RV2GV) {
4685                         if (lastop && lastop->op_type != OP_GV) /*funny deref?*/
4686                             break;
4687                     }
4688                     else if (curop->op_type == OP_PADSV ||
4689                              curop->op_type == OP_PADAV ||
4690                              curop->op_type == OP_PADHV ||
4691                              curop->op_type == OP_PADANY)
4692                     {
4693                         repl_has_vars = 1;
4694                     }
4695                     else if (curop->op_type == OP_PUSHRE)
4696                         NOOP; /* Okay here, dangerous in newASSIGNOP */
4697                     else
4698                         break;
4699                 }
4700                 lastop = curop;
4701             }
4702         }
4703         if (curop == repl
4704             && !(repl_has_vars
4705                  && (!PM_GETRE(pm)
4706                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
4707         {
4708             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
4709             op_prepend_elem(o->op_type, scalar(repl), o);
4710         }
4711         else {
4712             if (curop == repl && !PM_GETRE(pm)) { /* Has variables. */
4713                 pm->op_pmflags |= PMf_MAYBE_CONST;
4714             }
4715             NewOp(1101, rcop, 1, LOGOP);
4716             rcop->op_type = OP_SUBSTCONT;
4717             rcop->op_ppaddr = PL_ppaddr[OP_SUBSTCONT];
4718             rcop->op_first = scalar(repl);
4719             rcop->op_flags |= OPf_KIDS;
4720             rcop->op_private = 1;
4721             rcop->op_other = o;
4722
4723             /* establish postfix order */
4724             rcop->op_next = LINKLIST(repl);
4725             repl->op_next = (OP*)rcop;
4726
4727             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
4728             assert(!(pm->op_pmflags & PMf_ONCE));
4729             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
4730             rcop->op_next = 0;
4731         }
4732     }
4733
4734     return (OP*)pm;
4735 }
4736
4737 /*
4738 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
4739
4740 Constructs, checks, and returns an op of any type that involves an
4741 embedded SV.  I<type> is the opcode.  I<flags> gives the eight bits
4742 of C<op_flags>.  I<sv> gives the SV to embed in the op; this function
4743 takes ownership of one reference to it.
4744
4745 =cut
4746 */
4747
4748 OP *
4749 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
4750 {
4751     dVAR;
4752     SVOP *svop;
4753
4754     PERL_ARGS_ASSERT_NEWSVOP;
4755
4756     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
4757         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
4758         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP);
4759
4760     NewOp(1101, svop, 1, SVOP);
4761     svop->op_type = (OPCODE)type;
4762     svop->op_ppaddr = PL_ppaddr[type];
4763     svop->op_sv = sv;
4764     svop->op_next = (OP*)svop;
4765     svop->op_flags = (U8)flags;
4766     svop->op_private = (U8)(0 | (flags >> 8));
4767     if (PL_opargs[type] & OA_RETSCALAR)
4768         scalar((OP*)svop);
4769     if (PL_opargs[type] & OA_TARGET)
4770         svop->op_targ = pad_alloc(type, SVs_PADTMP);
4771     return CHECKOP(type, svop);
4772 }
4773
4774 #ifdef USE_ITHREADS
4775
4776 /*
4777 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
4778
4779 Constructs, checks, and returns an op of any type that involves a
4780 reference to a pad element.  I<type> is the opcode.  I<flags> gives the
4781 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
4782 is populated with I<sv>; this function takes ownership of one reference
4783 to it.
4784
4785 This function only exists if Perl has been compiled to use ithreads.
4786
4787 =cut
4788 */
4789
4790 OP *
4791 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
4792 {
4793     dVAR;
4794     PADOP *padop;
4795
4796     PERL_ARGS_ASSERT_NEWPADOP;
4797
4798     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
4799         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
4800         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP);
4801
4802     NewOp(1101, padop, 1, PADOP);
4803     padop->op_type = (OPCODE)type;
4804     padop->op_ppaddr = PL_ppaddr[type];
4805     padop->op_padix = pad_alloc(type, SVs_PADTMP);
4806     SvREFCNT_dec(PAD_SVl(padop->op_padix));
4807     PAD_SETSV(padop->op_padix, sv);
4808     assert(sv);
4809     SvPADTMP_on(sv);
4810     padop->op_next = (OP*)padop;
4811     padop->op_flags = (U8)flags;
4812     if (PL_opargs[type] & OA_RETSCALAR)
4813         scalar((OP*)padop);
4814     if (PL_opargs[type] & OA_TARGET)
4815         padop->op_targ = pad_alloc(type, SVs_PADTMP);
4816     return CHECKOP(type, padop);
4817 }
4818
4819 #endif /* !USE_ITHREADS */
4820
4821 /*
4822 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
4823
4824 Constructs, checks, and returns an op of any type that involves an
4825 embedded reference to a GV.  I<type> is the opcode.  I<flags> gives the
4826 eight bits of C<op_flags>.  I<gv> identifies the GV that the op should
4827 reference; calling this function does not transfer ownership of any
4828 reference to it.
4829
4830 =cut
4831 */
4832
4833 OP *
4834 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
4835 {
4836     dVAR;
4837
4838     PERL_ARGS_ASSERT_NEWGVOP;
4839
4840 #ifdef USE_ITHREADS
4841     GvIN_PAD_on(gv);
4842     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
4843 #else
4844     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
4845 #endif
4846 }
4847
4848 /*
4849 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
4850
4851 Constructs, checks, and returns an op of any type that involves an
4852 embedded C-level pointer (PV).  I<type> is the opcode.  I<flags> gives
4853 the eight bits of C<op_flags>.  I<pv> supplies the C-level pointer, which
4854 must have been allocated using L</PerlMemShared_malloc>; the memory will
4855 be freed when the op is destroyed.
4856
4857 =cut
4858 */
4859
4860 OP *