This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regen/ebcdic.pl: Move code to function
[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  * Note that during the build of miniperl, a temporary copy of this file
26  * is made, called opmini.c.
27  *
28  * A Perl program is compiled into a tree of OP nodes. Each op contains:
29  *  * structural OP pointers to its children and siblings (op_sibling,
30  *    op_first etc) that define the tree structure;
31  *  * execution order OP pointers (op_next, plus sometimes op_other,
32  *    op_lastop  etc) that define the execution sequence plus variants;
33  *  * a pointer to the C "pp" function that would execute the op;
34  *  * any data specific to that op.
35  * For example, an OP_CONST op points to the pp_const() function and to an
36  * SV containing the constant value. When pp_const() is executed, its job
37  * is to push that SV onto the stack.
38  *
39  * OPs are mainly created by the newFOO() functions, which are mainly
40  * called from the parser (in perly.y) as the code is parsed. For example
41  * the Perl code $a + $b * $c would cause the equivalent of the following
42  * to be called (oversimplifying a bit):
43  *
44  *  newBINOP(OP_ADD, flags,
45  *      newSVREF($a),
46  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
47  *  )
48  *
49  * As the parser reduces low-level rules, it creates little op subtrees;
50  * as higher-level rules are resolved, these subtrees get joined together
51  * as branches on a bigger subtree, until eventually a top-level rule like
52  * a subroutine definition is reduced, at which point there is one large
53  * parse tree left.
54  *
55  * The execution order pointers (op_next) are generated as the subtrees
56  * are joined together. Consider this sub-expression: A*B + C/D: at the
57  * point when it's just been parsed, the op tree looks like:
58  *
59  *   [+]
60  *    |
61  *   [*]------[/]
62  *    |        |
63  *    A---B    C---D
64  *
65  * with the intended execution order being:
66  *
67  *   [PREV] => A => B => [*] => C => D => [/] =>  [+] => [NEXT]
68  *
69  * At this point all the nodes' op_next pointers will have been set,
70  * except that:
71  *    * we don't know what the [NEXT] node will be yet;
72  *    * we don't know what the [PREV] node will be yet, but when it gets
73  *      created and needs its op_next set, it needs to be set to point to
74  *      A, which is non-obvious.
75  * To handle both those cases, we temporarily set the top node's
76  * op_next to point to the first node to be executed in this subtree (A in
77  * this case). This means that initially a subtree's op_next chain,
78  * starting from the top node, will visit each node in execution sequence
79  * then point back at the top node.
80  * When we embed this subtree in a larger tree, its top op_next is used
81  * to get the start node, then is set to point to its new neighbour.
82  * For example the two separate [*],A,B and [/],C,D subtrees would
83  * initially have had:
84  *   [*] => A;  A => B;  B => [*]
85  * and
86  *   [/] => C;  C => D;  D => [/]
87  * When these two subtrees were joined together to make the [+] subtree,
88  * [+]'s op_next was set to [*]'s op_next, i.e. A; then [*]'s op_next was
89  * set to point to [/]'s op_next, i.e. C.
90  *
91  * This op_next linking is done by the LINKLIST() macro and its underlying
92  * op_linklist() function. Given a top-level op, if its op_next is
93  * non-null, it's already been linked, so leave it. Otherwise link it with
94  * its children as described above, possibly recursively if any of the
95  * children have a null op_next.
96  *
97  * In summary: given a subtree, its top-level node's op_next will either
98  * be:
99  *   NULL: the subtree hasn't been LINKLIST()ed yet;
100  *   fake: points to the start op for this subtree;
101  *   real: once the subtree has been embedded into a larger tree
102  */
103
104 /*
105
106 Here's an older description from Larry.
107
108 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
109
110     A bottom-up pass
111     A top-down pass
112     An execution-order pass
113
114 The bottom-up pass is represented by all the "newOP" routines and
115 the ck_ routines.  The bottom-upness is actually driven by yacc.
116 So at the point that a ck_ routine fires, we have no idea what the
117 context is, either upward in the syntax tree, or either forward or
118 backward in the execution order.  (The bottom-up parser builds that
119 part of the execution order it knows about, but if you follow the "next"
120 links around, you'll find it's actually a closed loop through the
121 top level node.)
122
123 Whenever the bottom-up parser gets to a node that supplies context to
124 its components, it invokes that portion of the top-down pass that applies
125 to that part of the subtree (and marks the top node as processed, so
126 if a node further up supplies context, it doesn't have to take the
127 plunge again).  As a particular subcase of this, as the new node is
128 built, it takes all the closed execution loops of its subcomponents
129 and links them into a new closed loop for the higher level node.  But
130 it's still not the real execution order.
131
132 The actual execution order is not known till we get a grammar reduction
133 to a top-level unit like a subroutine or file that will be called by
134 "name" rather than via a "next" pointer.  At that point, we can call
135 into peep() to do that code's portion of the 3rd pass.  It has to be
136 recursive, but it's recursive on basic blocks, not on tree nodes.
137 */
138
139 /* To implement user lexical pragmas, there needs to be a way at run time to
140    get the compile time state of %^H for that block.  Storing %^H in every
141    block (or even COP) would be very expensive, so a different approach is
142    taken.  The (running) state of %^H is serialised into a tree of HE-like
143    structs.  Stores into %^H are chained onto the current leaf as a struct
144    refcounted_he * with the key and the value.  Deletes from %^H are saved
145    with a value of PL_sv_placeholder.  The state of %^H at any point can be
146    turned back into a regular HV by walking back up the tree from that point's
147    leaf, ignoring any key you've already seen (placeholder or not), storing
148    the rest into the HV structure, then removing the placeholders. Hence
149    memory is only used to store the %^H deltas from the enclosing COP, rather
150    than the entire %^H on each COP.
151
152    To cause actions on %^H to write out the serialisation records, it has
153    magic type 'H'. This magic (itself) does nothing, but its presence causes
154    the values to gain magic type 'h', which has entries for set and clear.
155    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
156    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
157    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
158    it will be correctly restored when any inner compiling scope is exited.
159 */
160
161 #include "EXTERN.h"
162 #define PERL_IN_OP_C
163 #include "perl.h"
164 #include "keywords.h"
165 #include "feature.h"
166 #include "regcomp.h"
167
168 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
169 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
170 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
171
172 static const char array_passed_to_stat[] = "Array passed to stat will be coerced to a scalar";
173
174 /* Used to avoid recursion through the op tree in scalarvoid() and
175    op_free()
176 */
177
178 #define dDEFER_OP  \
179     SSize_t defer_stack_alloc = 0; \
180     SSize_t defer_ix = -1; \
181     OP **defer_stack = NULL;
182 #define DEFER_OP_CLEANUP Safefree(defer_stack)
183 #define DEFERRED_OP_STEP 100
184 #define DEFER_OP(o) \
185   STMT_START { \
186     if (UNLIKELY(defer_ix == (defer_stack_alloc-1))) {    \
187         defer_stack_alloc += DEFERRED_OP_STEP; \
188         assert(defer_stack_alloc > 0); \
189         Renew(defer_stack, defer_stack_alloc, OP *); \
190     } \
191     defer_stack[++defer_ix] = o; \
192   } STMT_END
193 #define DEFER_REVERSE(count)                            \
194     STMT_START {                                        \
195         UV cnt = (count);                               \
196         if (cnt > 1) {                                  \
197             OP **top = defer_stack + defer_ix;          \
198             /* top - (cnt) + 1 isn't safe here */       \
199             OP **bottom = top - (cnt - 1);              \
200             OP *tmp;                                    \
201             assert(bottom >= defer_stack);              \
202             while (top > bottom) {                      \
203                 tmp = *top;                             \
204                 *top-- = *bottom;                       \
205                 *bottom++ = tmp;                        \
206             }                                           \
207         }                                               \
208     } STMT_END;
209
210 #define POP_DEFERRED_OP() (defer_ix >= 0 ? defer_stack[defer_ix--] : (OP *)NULL)
211
212 /* remove any leading "empty" ops from the op_next chain whose first
213  * node's address is stored in op_p. Store the updated address of the
214  * first node in op_p.
215  */
216
217 STATIC void
218 S_prune_chain_head(OP** op_p)
219 {
220     while (*op_p
221         && (   (*op_p)->op_type == OP_NULL
222             || (*op_p)->op_type == OP_SCOPE
223             || (*op_p)->op_type == OP_SCALAR
224             || (*op_p)->op_type == OP_LINESEQ)
225     )
226         *op_p = (*op_p)->op_next;
227 }
228
229
230 /* See the explanatory comments above struct opslab in op.h. */
231
232 #ifdef PERL_DEBUG_READONLY_OPS
233 #  define PERL_SLAB_SIZE 128
234 #  define PERL_MAX_SLAB_SIZE 4096
235 #  include <sys/mman.h>
236 #endif
237
238 #ifndef PERL_SLAB_SIZE
239 #  define PERL_SLAB_SIZE 64
240 #endif
241 #ifndef PERL_MAX_SLAB_SIZE
242 #  define PERL_MAX_SLAB_SIZE 2048
243 #endif
244
245 /* rounds up to nearest pointer */
246 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
247 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
248
249 static OPSLAB *
250 S_new_slab(pTHX_ size_t sz)
251 {
252 #ifdef PERL_DEBUG_READONLY_OPS
253     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
254                                    PROT_READ|PROT_WRITE,
255                                    MAP_ANON|MAP_PRIVATE, -1, 0);
256     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
257                           (unsigned long) sz, slab));
258     if (slab == MAP_FAILED) {
259         perror("mmap failed");
260         abort();
261     }
262     slab->opslab_size = (U16)sz;
263 #else
264     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
265 #endif
266 #ifndef WIN32
267     /* The context is unused in non-Windows */
268     PERL_UNUSED_CONTEXT;
269 #endif
270     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
271     return slab;
272 }
273
274 /* requires double parens and aTHX_ */
275 #define DEBUG_S_warn(args)                                             \
276     DEBUG_S(                                                            \
277         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
278     )
279
280 void *
281 Perl_Slab_Alloc(pTHX_ size_t sz)
282 {
283     OPSLAB *slab;
284     OPSLAB *slab2;
285     OPSLOT *slot;
286     OP *o;
287     size_t opsz, space;
288
289     /* We only allocate ops from the slab during subroutine compilation.
290        We find the slab via PL_compcv, hence that must be non-NULL. It could
291        also be pointing to a subroutine which is now fully set up (CvROOT()
292        pointing to the top of the optree for that sub), or a subroutine
293        which isn't using the slab allocator. If our sanity checks aren't met,
294        don't use a slab, but allocate the OP directly from the heap.  */
295     if (!PL_compcv || CvROOT(PL_compcv)
296      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
297     {
298         o = (OP*)PerlMemShared_calloc(1, sz);
299         goto gotit;
300     }
301
302     /* While the subroutine is under construction, the slabs are accessed via
303        CvSTART(), to avoid needing to expand PVCV by one pointer for something
304        unneeded at runtime. Once a subroutine is constructed, the slabs are
305        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
306        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
307        details.  */
308     if (!CvSTART(PL_compcv)) {
309         CvSTART(PL_compcv) =
310             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
311         CvSLABBED_on(PL_compcv);
312         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
313     }
314     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
315
316     opsz = SIZE_TO_PSIZE(sz);
317     sz = opsz + OPSLOT_HEADER_P;
318
319     /* The slabs maintain a free list of OPs. In particular, constant folding
320        will free up OPs, so it makes sense to re-use them where possible. A
321        freed up slot is used in preference to a new allocation.  */
322     if (slab->opslab_freed) {
323         OP **too = &slab->opslab_freed;
324         o = *too;
325         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", (void*)o, (void*)slab));
326         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
327             DEBUG_S_warn((aTHX_ "Alas! too small"));
328             o = *(too = &o->op_next);
329             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
330         }
331         if (o) {
332             *too = o->op_next;
333             Zero(o, opsz, I32 *);
334             o->op_slabbed = 1;
335             goto gotit;
336         }
337     }
338
339 #define INIT_OPSLOT \
340             slot->opslot_slab = slab;                   \
341             slot->opslot_next = slab2->opslab_first;    \
342             slab2->opslab_first = slot;                 \
343             o = &slot->opslot_op;                       \
344             o->op_slabbed = 1
345
346     /* The partially-filled slab is next in the chain. */
347     slab2 = slab->opslab_next ? slab->opslab_next : slab;
348     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
349         /* Remaining space is too small. */
350
351         /* If we can fit a BASEOP, add it to the free chain, so as not
352            to waste it. */
353         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
354             slot = &slab2->opslab_slots;
355             INIT_OPSLOT;
356             o->op_type = OP_FREED;
357             o->op_next = slab->opslab_freed;
358             slab->opslab_freed = o;
359         }
360
361         /* Create a new slab.  Make this one twice as big. */
362         slot = slab2->opslab_first;
363         while (slot->opslot_next) slot = slot->opslot_next;
364         slab2 = S_new_slab(aTHX_
365                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
366                                         ? PERL_MAX_SLAB_SIZE
367                                         : (DIFF(slab2, slot)+1)*2);
368         slab2->opslab_next = slab->opslab_next;
369         slab->opslab_next = slab2;
370     }
371     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
372
373     /* Create a new op slot */
374     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
375     assert(slot >= &slab2->opslab_slots);
376     if (DIFF(&slab2->opslab_slots, slot)
377          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
378         slot = &slab2->opslab_slots;
379     INIT_OPSLOT;
380     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", (void*)o, (void*)slab));
381
382   gotit:
383     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
384     assert(!o->op_moresib);
385     assert(!o->op_sibparent);
386
387     return (void *)o;
388 }
389
390 #undef INIT_OPSLOT
391
392 #ifdef PERL_DEBUG_READONLY_OPS
393 void
394 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
395 {
396     PERL_ARGS_ASSERT_SLAB_TO_RO;
397
398     if (slab->opslab_readonly) return;
399     slab->opslab_readonly = 1;
400     for (; slab; slab = slab->opslab_next) {
401         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
402                               (unsigned long) slab->opslab_size, slab));*/
403         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
404             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
405                              (unsigned long)slab->opslab_size, errno);
406     }
407 }
408
409 void
410 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
411 {
412     OPSLAB *slab2;
413
414     PERL_ARGS_ASSERT_SLAB_TO_RW;
415
416     if (!slab->opslab_readonly) return;
417     slab2 = slab;
418     for (; slab2; slab2 = slab2->opslab_next) {
419         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
420                               (unsigned long) size, slab2));*/
421         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
422                      PROT_READ|PROT_WRITE)) {
423             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
424                              (unsigned long)slab2->opslab_size, errno);
425         }
426     }
427     slab->opslab_readonly = 0;
428 }
429
430 #else
431 #  define Slab_to_rw(op)    NOOP
432 #endif
433
434 /* This cannot possibly be right, but it was copied from the old slab
435    allocator, to which it was originally added, without explanation, in
436    commit 083fcd5. */
437 #ifdef NETWARE
438 #    define PerlMemShared PerlMem
439 #endif
440
441 /* make freed ops die if they're inadvertently executed */
442 #ifdef DEBUGGING
443 static OP *
444 S_pp_freed(pTHX)
445 {
446     DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
447 }
448 #endif
449
450 void
451 Perl_Slab_Free(pTHX_ void *op)
452 {
453     OP * const o = (OP *)op;
454     OPSLAB *slab;
455
456     PERL_ARGS_ASSERT_SLAB_FREE;
457
458 #ifdef DEBUGGING
459     o->op_ppaddr = S_pp_freed;
460 #endif
461
462     if (!o->op_slabbed) {
463         if (!o->op_static)
464             PerlMemShared_free(op);
465         return;
466     }
467
468     slab = OpSLAB(o);
469     /* If this op is already freed, our refcount will get screwy. */
470     assert(o->op_type != OP_FREED);
471     o->op_type = OP_FREED;
472     o->op_next = slab->opslab_freed;
473     slab->opslab_freed = o;
474     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", (void*)o, (void*)slab));
475     OpslabREFCNT_dec_padok(slab);
476 }
477
478 void
479 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
480 {
481     const bool havepad = !!PL_comppad;
482     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
483     if (havepad) {
484         ENTER;
485         PAD_SAVE_SETNULLPAD();
486     }
487     opslab_free(slab);
488     if (havepad) LEAVE;
489 }
490
491 void
492 Perl_opslab_free(pTHX_ OPSLAB *slab)
493 {
494     OPSLAB *slab2;
495     PERL_ARGS_ASSERT_OPSLAB_FREE;
496     PERL_UNUSED_CONTEXT;
497     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
498     assert(slab->opslab_refcnt == 1);
499     do {
500         slab2 = slab->opslab_next;
501 #ifdef DEBUGGING
502         slab->opslab_refcnt = ~(size_t)0;
503 #endif
504 #ifdef PERL_DEBUG_READONLY_OPS
505         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
506                                                (void*)slab));
507         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
508             perror("munmap failed");
509             abort();
510         }
511 #else
512         PerlMemShared_free(slab);
513 #endif
514         slab = slab2;
515     } while (slab);
516 }
517
518 void
519 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
520 {
521     OPSLAB *slab2;
522 #ifdef DEBUGGING
523     size_t savestack_count = 0;
524 #endif
525     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
526     slab2 = slab;
527     do {
528         OPSLOT *slot;
529         for (slot = slab2->opslab_first;
530              slot->opslot_next;
531              slot = slot->opslot_next) {
532             if (slot->opslot_op.op_type != OP_FREED
533              && !(slot->opslot_op.op_savefree
534 #ifdef DEBUGGING
535                   && ++savestack_count
536 #endif
537                  )
538             ) {
539                 assert(slot->opslot_op.op_slabbed);
540                 op_free(&slot->opslot_op);
541                 if (slab->opslab_refcnt == 1) goto free;
542             }
543         }
544     } while ((slab2 = slab2->opslab_next));
545     /* > 1 because the CV still holds a reference count. */
546     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
547 #ifdef DEBUGGING
548         assert(savestack_count == slab->opslab_refcnt-1);
549 #endif
550         /* Remove the CV’s reference count. */
551         slab->opslab_refcnt--;
552         return;
553     }
554    free:
555     opslab_free(slab);
556 }
557
558 #ifdef PERL_DEBUG_READONLY_OPS
559 OP *
560 Perl_op_refcnt_inc(pTHX_ OP *o)
561 {
562     if(o) {
563         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
564         if (slab && slab->opslab_readonly) {
565             Slab_to_rw(slab);
566             ++o->op_targ;
567             Slab_to_ro(slab);
568         } else {
569             ++o->op_targ;
570         }
571     }
572     return o;
573
574 }
575
576 PADOFFSET
577 Perl_op_refcnt_dec(pTHX_ OP *o)
578 {
579     PADOFFSET result;
580     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
581
582     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
583
584     if (slab && slab->opslab_readonly) {
585         Slab_to_rw(slab);
586         result = --o->op_targ;
587         Slab_to_ro(slab);
588     } else {
589         result = --o->op_targ;
590     }
591     return result;
592 }
593 #endif
594 /*
595  * In the following definition, the ", (OP*)0" is just to make the compiler
596  * think the expression is of the right type: croak actually does a Siglongjmp.
597  */
598 #define CHECKOP(type,o) \
599     ((PL_op_mask && PL_op_mask[type])                           \
600      ? ( op_free((OP*)o),                                       \
601          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
602          (OP*)0 )                                               \
603      : PL_check[type](aTHX_ (OP*)o))
604
605 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
606
607 #define OpTYPE_set(o,type) \
608     STMT_START {                                \
609         o->op_type = (OPCODE)type;              \
610         o->op_ppaddr = PL_ppaddr[type];         \
611     } STMT_END
612
613 STATIC OP *
614 S_no_fh_allowed(pTHX_ OP *o)
615 {
616     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
617
618     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
619                  OP_DESC(o)));
620     return o;
621 }
622
623 STATIC OP *
624 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
625 {
626     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
627     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
628     return o;
629 }
630  
631 STATIC OP *
632 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
633 {
634     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
635
636     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
637     return o;
638 }
639
640 STATIC void
641 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
642 {
643     PERL_ARGS_ASSERT_BAD_TYPE_PV;
644
645     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
646                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
647 }
648
649 /* remove flags var, its unused in all callers, move to to right end since gv
650   and kid are always the same */
651 STATIC void
652 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
653 {
654     SV * const namesv = cv_name((CV *)gv, NULL, 0);
655     PERL_ARGS_ASSERT_BAD_TYPE_GV;
656  
657     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
658                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
659 }
660
661 STATIC void
662 S_no_bareword_allowed(pTHX_ OP *o)
663 {
664     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
665
666     qerror(Perl_mess(aTHX_
667                      "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
668                      SVfARG(cSVOPo_sv)));
669     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
670 }
671
672 /* "register" allocation */
673
674 PADOFFSET
675 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
676 {
677     PADOFFSET off;
678     const bool is_our = (PL_parser->in_my == KEY_our);
679
680     PERL_ARGS_ASSERT_ALLOCMY;
681
682     if (flags & ~SVf_UTF8)
683         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
684                    (UV)flags);
685
686     /* complain about "my $<special_var>" etc etc */
687     if (   len
688         && !(  is_our
689             || isALPHA(name[1])
690             || (   (flags & SVf_UTF8)
691                 && isIDFIRST_utf8_safe((U8 *)name+1, name + len))
692             || (name[1] == '_' && len > 2)))
693     {
694         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
695          && isASCII(name[1])
696          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
697             /* diag_listed_as: Can't use global %s in "%s" */
698             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
699                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
700                               PL_parser->in_my == KEY_state ? "state" : "my"));
701         } else {
702             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
703                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
704         }
705     }
706
707     /* allocate a spare slot and store the name in that slot */
708
709     off = pad_add_name_pvn(name, len,
710                        (is_our ? padadd_OUR :
711                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
712                     PL_parser->in_my_stash,
713                     (is_our
714                         /* $_ is always in main::, even with our */
715                         ? (PL_curstash && !memEQs(name,len,"$_")
716                             ? PL_curstash
717                             : PL_defstash)
718                         : NULL
719                     )
720     );
721     /* anon sub prototypes contains state vars should always be cloned,
722      * otherwise the state var would be shared between anon subs */
723
724     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
725         CvCLONE_on(PL_compcv);
726
727     return off;
728 }
729
730 /*
731 =head1 Optree Manipulation Functions
732
733 =for apidoc alloccopstash
734
735 Available only under threaded builds, this function allocates an entry in
736 C<PL_stashpad> for the stash passed to it.
737
738 =cut
739 */
740
741 #ifdef USE_ITHREADS
742 PADOFFSET
743 Perl_alloccopstash(pTHX_ HV *hv)
744 {
745     PADOFFSET off = 0, o = 1;
746     bool found_slot = FALSE;
747
748     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
749
750     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
751
752     for (; o < PL_stashpadmax; ++o) {
753         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
754         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
755             found_slot = TRUE, off = o;
756     }
757     if (!found_slot) {
758         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
759         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
760         off = PL_stashpadmax;
761         PL_stashpadmax += 10;
762     }
763
764     PL_stashpad[PL_stashpadix = off] = hv;
765     return off;
766 }
767 #endif
768
769 /* free the body of an op without examining its contents.
770  * Always use this rather than FreeOp directly */
771
772 static void
773 S_op_destroy(pTHX_ OP *o)
774 {
775     FreeOp(o);
776 }
777
778 /* Destructor */
779
780 /*
781 =for apidoc Am|void|op_free|OP *o
782
783 Free an op.  Only use this when an op is no longer linked to from any
784 optree.
785
786 =cut
787 */
788
789 void
790 Perl_op_free(pTHX_ OP *o)
791 {
792     dVAR;
793     OPCODE type;
794     dDEFER_OP;
795
796     do {
797
798         /* Though ops may be freed twice, freeing the op after its slab is a
799            big no-no. */
800         assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
801         /* During the forced freeing of ops after compilation failure, kidops
802            may be freed before their parents. */
803         if (!o || o->op_type == OP_FREED)
804             continue;
805
806         type = o->op_type;
807
808         /* an op should only ever acquire op_private flags that we know about.
809          * If this fails, you may need to fix something in regen/op_private.
810          * Don't bother testing if:
811          *   * the op_ppaddr doesn't match the op; someone may have
812          *     overridden the op and be doing strange things with it;
813          *   * we've errored, as op flags are often left in an
814          *     inconsistent state then. Note that an error when
815          *     compiling the main program leaves PL_parser NULL, so
816          *     we can't spot faults in the main code, only
817          *     evaled/required code */
818 #ifdef DEBUGGING
819         if (   o->op_ppaddr == PL_ppaddr[o->op_type]
820             && PL_parser
821             && !PL_parser->error_count)
822         {
823             assert(!(o->op_private & ~PL_op_private_valid[type]));
824         }
825 #endif
826
827         if (o->op_private & OPpREFCOUNTED) {
828             switch (type) {
829             case OP_LEAVESUB:
830             case OP_LEAVESUBLV:
831             case OP_LEAVEEVAL:
832             case OP_LEAVE:
833             case OP_SCOPE:
834             case OP_LEAVEWRITE:
835                 {
836                 PADOFFSET refcnt;
837                 OP_REFCNT_LOCK;
838                 refcnt = OpREFCNT_dec(o);
839                 OP_REFCNT_UNLOCK;
840                 if (refcnt) {
841                     /* Need to find and remove any pattern match ops from the list
842                        we maintain for reset().  */
843                     find_and_forget_pmops(o);
844                     continue;
845                 }
846                 }
847                 break;
848             default:
849                 break;
850             }
851         }
852
853         /* Call the op_free hook if it has been set. Do it now so that it's called
854          * at the right time for refcounted ops, but still before all of the kids
855          * are freed. */
856         CALL_OPFREEHOOK(o);
857
858         if (o->op_flags & OPf_KIDS) {
859             OP *kid, *nextkid;
860             for (kid = cUNOPo->op_first; kid; kid = nextkid) {
861                 nextkid = OpSIBLING(kid); /* Get before next freeing kid */
862                 if (!kid || kid->op_type == OP_FREED)
863                     /* During the forced freeing of ops after
864                        compilation failure, kidops may be freed before
865                        their parents. */
866                     continue;
867                 if (!(kid->op_flags & OPf_KIDS))
868                     /* If it has no kids, just free it now */
869                     op_free(kid);
870                 else
871                     DEFER_OP(kid);
872             }
873         }
874         if (type == OP_NULL)
875             type = (OPCODE)o->op_targ;
876
877         if (o->op_slabbed)
878             Slab_to_rw(OpSLAB(o));
879
880         /* COP* is not cleared by op_clear() so that we may track line
881          * numbers etc even after null() */
882         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
883             cop_free((COP*)o);
884         }
885
886         op_clear(o);
887         FreeOp(o);
888         if (PL_op == o)
889             PL_op = NULL;
890     } while ( (o = POP_DEFERRED_OP()) );
891
892     DEFER_OP_CLEANUP;
893 }
894
895 /* S_op_clear_gv(): free a GV attached to an OP */
896
897 STATIC
898 #ifdef USE_ITHREADS
899 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
900 #else
901 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
902 #endif
903 {
904
905     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
906             || o->op_type == OP_MULTIDEREF)
907 #ifdef USE_ITHREADS
908                 && PL_curpad
909                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
910 #else
911                 ? (GV*)(*svp) : NULL;
912 #endif
913     /* It's possible during global destruction that the GV is freed
914        before the optree. Whilst the SvREFCNT_inc is happy to bump from
915        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
916        will trigger an assertion failure, because the entry to sv_clear
917        checks that the scalar is not already freed.  A check of for
918        !SvIS_FREED(gv) turns out to be invalid, because during global
919        destruction the reference count can be forced down to zero
920        (with SVf_BREAK set).  In which case raising to 1 and then
921        dropping to 0 triggers cleanup before it should happen.  I
922        *think* that this might actually be a general, systematic,
923        weakness of the whole idea of SVf_BREAK, in that code *is*
924        allowed to raise and lower references during global destruction,
925        so any *valid* code that happens to do this during global
926        destruction might well trigger premature cleanup.  */
927     bool still_valid = gv && SvREFCNT(gv);
928
929     if (still_valid)
930         SvREFCNT_inc_simple_void(gv);
931 #ifdef USE_ITHREADS
932     if (*ixp > 0) {
933         pad_swipe(*ixp, TRUE);
934         *ixp = 0;
935     }
936 #else
937     SvREFCNT_dec(*svp);
938     *svp = NULL;
939 #endif
940     if (still_valid) {
941         int try_downgrade = SvREFCNT(gv) == 2;
942         SvREFCNT_dec_NN(gv);
943         if (try_downgrade)
944             gv_try_downgrade(gv);
945     }
946 }
947
948
949 void
950 Perl_op_clear(pTHX_ OP *o)
951 {
952
953     dVAR;
954
955     PERL_ARGS_ASSERT_OP_CLEAR;
956
957     switch (o->op_type) {
958     case OP_NULL:       /* Was holding old type, if any. */
959         /* FALLTHROUGH */
960     case OP_ENTERTRY:
961     case OP_ENTEREVAL:  /* Was holding hints. */
962     case OP_ARGDEFELEM: /* Was holding signature index. */
963         o->op_targ = 0;
964         break;
965     default:
966         if (!(o->op_flags & OPf_REF)
967             || (PL_check[o->op_type] != Perl_ck_ftst))
968             break;
969         /* FALLTHROUGH */
970     case OP_GVSV:
971     case OP_GV:
972     case OP_AELEMFAST:
973 #ifdef USE_ITHREADS
974             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
975 #else
976             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
977 #endif
978         break;
979     case OP_METHOD_REDIR:
980     case OP_METHOD_REDIR_SUPER:
981 #ifdef USE_ITHREADS
982         if (cMETHOPx(o)->op_rclass_targ) {
983             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
984             cMETHOPx(o)->op_rclass_targ = 0;
985         }
986 #else
987         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
988         cMETHOPx(o)->op_rclass_sv = NULL;
989 #endif
990         /* FALLTHROUGH */
991     case OP_METHOD_NAMED:
992     case OP_METHOD_SUPER:
993         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
994         cMETHOPx(o)->op_u.op_meth_sv = NULL;
995 #ifdef USE_ITHREADS
996         if (o->op_targ) {
997             pad_swipe(o->op_targ, 1);
998             o->op_targ = 0;
999         }
1000 #endif
1001         break;
1002     case OP_CONST:
1003     case OP_HINTSEVAL:
1004         SvREFCNT_dec(cSVOPo->op_sv);
1005         cSVOPo->op_sv = NULL;
1006 #ifdef USE_ITHREADS
1007         /** Bug #15654
1008           Even if op_clear does a pad_free for the target of the op,
1009           pad_free doesn't actually remove the sv that exists in the pad;
1010           instead it lives on. This results in that it could be reused as 
1011           a target later on when the pad was reallocated.
1012         **/
1013         if(o->op_targ) {
1014           pad_swipe(o->op_targ,1);
1015           o->op_targ = 0;
1016         }
1017 #endif
1018         break;
1019     case OP_DUMP:
1020     case OP_GOTO:
1021     case OP_NEXT:
1022     case OP_LAST:
1023     case OP_REDO:
1024         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1025             break;
1026         /* FALLTHROUGH */
1027     case OP_TRANS:
1028     case OP_TRANSR:
1029         if (   (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1030             && (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)))
1031         {
1032 #ifdef USE_ITHREADS
1033             if (cPADOPo->op_padix > 0) {
1034                 pad_swipe(cPADOPo->op_padix, TRUE);
1035                 cPADOPo->op_padix = 0;
1036             }
1037 #else
1038             SvREFCNT_dec(cSVOPo->op_sv);
1039             cSVOPo->op_sv = NULL;
1040 #endif
1041         }
1042         else {
1043             PerlMemShared_free(cPVOPo->op_pv);
1044             cPVOPo->op_pv = NULL;
1045         }
1046         break;
1047     case OP_SUBST:
1048         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1049         goto clear_pmop;
1050
1051     case OP_SPLIT:
1052         if (     (o->op_private & OPpSPLIT_ASSIGN) /* @array  = split */
1053             && !(o->op_flags & OPf_STACKED))       /* @{expr} = split */
1054         {
1055             if (o->op_private & OPpSPLIT_LEX)
1056                 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1057             else
1058 #ifdef USE_ITHREADS
1059                 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1060 #else
1061                 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1062 #endif
1063         }
1064         /* FALLTHROUGH */
1065     case OP_MATCH:
1066     case OP_QR:
1067     clear_pmop:
1068         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1069             op_free(cPMOPo->op_code_list);
1070         cPMOPo->op_code_list = NULL;
1071         forget_pmop(cPMOPo);
1072         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1073         /* we use the same protection as the "SAFE" version of the PM_ macros
1074          * here since sv_clean_all might release some PMOPs
1075          * after PL_regex_padav has been cleared
1076          * and the clearing of PL_regex_padav needs to
1077          * happen before sv_clean_all
1078          */
1079 #ifdef USE_ITHREADS
1080         if(PL_regex_pad) {        /* We could be in destruction */
1081             const IV offset = (cPMOPo)->op_pmoffset;
1082             ReREFCNT_dec(PM_GETRE(cPMOPo));
1083             PL_regex_pad[offset] = &PL_sv_undef;
1084             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1085                            sizeof(offset));
1086         }
1087 #else
1088         ReREFCNT_dec(PM_GETRE(cPMOPo));
1089         PM_SETRE(cPMOPo, NULL);
1090 #endif
1091
1092         break;
1093
1094     case OP_ARGCHECK:
1095         PerlMemShared_free(cUNOP_AUXo->op_aux);
1096         break;
1097
1098     case OP_MULTICONCAT:
1099         {
1100             UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1101             /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1102              * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1103              * utf8 shared strings */
1104             char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1105             char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1106             if (p1)
1107                 PerlMemShared_free(p1);
1108             if (p2 && p1 != p2)
1109                 PerlMemShared_free(p2);
1110             PerlMemShared_free(aux);
1111         }
1112         break;
1113
1114     case OP_MULTIDEREF:
1115         {
1116             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1117             UV actions = items->uv;
1118             bool last = 0;
1119             bool is_hash = FALSE;
1120
1121             while (!last) {
1122                 switch (actions & MDEREF_ACTION_MASK) {
1123
1124                 case MDEREF_reload:
1125                     actions = (++items)->uv;
1126                     continue;
1127
1128                 case MDEREF_HV_padhv_helem:
1129                     is_hash = TRUE;
1130                     /* FALLTHROUGH */
1131                 case MDEREF_AV_padav_aelem:
1132                     pad_free((++items)->pad_offset);
1133                     goto do_elem;
1134
1135                 case MDEREF_HV_gvhv_helem:
1136                     is_hash = TRUE;
1137                     /* FALLTHROUGH */
1138                 case MDEREF_AV_gvav_aelem:
1139 #ifdef USE_ITHREADS
1140                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1141 #else
1142                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1143 #endif
1144                     goto do_elem;
1145
1146                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1147                     is_hash = TRUE;
1148                     /* FALLTHROUGH */
1149                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1150 #ifdef USE_ITHREADS
1151                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1152 #else
1153                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1154 #endif
1155                     goto do_vivify_rv2xv_elem;
1156
1157                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1158                     is_hash = TRUE;
1159                     /* FALLTHROUGH */
1160                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1161                     pad_free((++items)->pad_offset);
1162                     goto do_vivify_rv2xv_elem;
1163
1164                 case MDEREF_HV_pop_rv2hv_helem:
1165                 case MDEREF_HV_vivify_rv2hv_helem:
1166                     is_hash = TRUE;
1167                     /* FALLTHROUGH */
1168                 do_vivify_rv2xv_elem:
1169                 case MDEREF_AV_pop_rv2av_aelem:
1170                 case MDEREF_AV_vivify_rv2av_aelem:
1171                 do_elem:
1172                     switch (actions & MDEREF_INDEX_MASK) {
1173                     case MDEREF_INDEX_none:
1174                         last = 1;
1175                         break;
1176                     case MDEREF_INDEX_const:
1177                         if (is_hash) {
1178 #ifdef USE_ITHREADS
1179                             /* see RT #15654 */
1180                             pad_swipe((++items)->pad_offset, 1);
1181 #else
1182                             SvREFCNT_dec((++items)->sv);
1183 #endif
1184                         }
1185                         else
1186                             items++;
1187                         break;
1188                     case MDEREF_INDEX_padsv:
1189                         pad_free((++items)->pad_offset);
1190                         break;
1191                     case MDEREF_INDEX_gvsv:
1192 #ifdef USE_ITHREADS
1193                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1194 #else
1195                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1196 #endif
1197                         break;
1198                     }
1199
1200                     if (actions & MDEREF_FLAG_last)
1201                         last = 1;
1202                     is_hash = FALSE;
1203
1204                     break;
1205
1206                 default:
1207                     assert(0);
1208                     last = 1;
1209                     break;
1210
1211                 } /* switch */
1212
1213                 actions >>= MDEREF_SHIFT;
1214             } /* while */
1215
1216             /* start of malloc is at op_aux[-1], where the length is
1217              * stored */
1218             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1219         }
1220         break;
1221     }
1222
1223     if (o->op_targ > 0) {
1224         pad_free(o->op_targ);
1225         o->op_targ = 0;
1226     }
1227 }
1228
1229 STATIC void
1230 S_cop_free(pTHX_ COP* cop)
1231 {
1232     PERL_ARGS_ASSERT_COP_FREE;
1233
1234     CopFILE_free(cop);
1235     if (! specialWARN(cop->cop_warnings))
1236         PerlMemShared_free(cop->cop_warnings);
1237     cophh_free(CopHINTHASH_get(cop));
1238     if (PL_curcop == cop)
1239        PL_curcop = NULL;
1240 }
1241
1242 STATIC void
1243 S_forget_pmop(pTHX_ PMOP *const o)
1244 {
1245     HV * const pmstash = PmopSTASH(o);
1246
1247     PERL_ARGS_ASSERT_FORGET_PMOP;
1248
1249     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1250         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1251         if (mg) {
1252             PMOP **const array = (PMOP**) mg->mg_ptr;
1253             U32 count = mg->mg_len / sizeof(PMOP**);
1254             U32 i = count;
1255
1256             while (i--) {
1257                 if (array[i] == o) {
1258                     /* Found it. Move the entry at the end to overwrite it.  */
1259                     array[i] = array[--count];
1260                     mg->mg_len = count * sizeof(PMOP**);
1261                     /* Could realloc smaller at this point always, but probably
1262                        not worth it. Probably worth free()ing if we're the
1263                        last.  */
1264                     if(!count) {
1265                         Safefree(mg->mg_ptr);
1266                         mg->mg_ptr = NULL;
1267                     }
1268                     break;
1269                 }
1270             }
1271         }
1272     }
1273     if (PL_curpm == o) 
1274         PL_curpm = NULL;
1275 }
1276
1277 STATIC void
1278 S_find_and_forget_pmops(pTHX_ OP *o)
1279 {
1280     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1281
1282     if (o->op_flags & OPf_KIDS) {
1283         OP *kid = cUNOPo->op_first;
1284         while (kid) {
1285             switch (kid->op_type) {
1286             case OP_SUBST:
1287             case OP_SPLIT:
1288             case OP_MATCH:
1289             case OP_QR:
1290                 forget_pmop((PMOP*)kid);
1291             }
1292             find_and_forget_pmops(kid);
1293             kid = OpSIBLING(kid);
1294         }
1295     }
1296 }
1297
1298 /*
1299 =for apidoc Am|void|op_null|OP *o
1300
1301 Neutralizes an op when it is no longer needed, but is still linked to from
1302 other ops.
1303
1304 =cut
1305 */
1306
1307 void
1308 Perl_op_null(pTHX_ OP *o)
1309 {
1310     dVAR;
1311
1312     PERL_ARGS_ASSERT_OP_NULL;
1313
1314     if (o->op_type == OP_NULL)
1315         return;
1316     op_clear(o);
1317     o->op_targ = o->op_type;
1318     OpTYPE_set(o, OP_NULL);
1319 }
1320
1321 void
1322 Perl_op_refcnt_lock(pTHX)
1323   PERL_TSA_ACQUIRE(PL_op_mutex)
1324 {
1325 #ifdef USE_ITHREADS
1326     dVAR;
1327 #endif
1328     PERL_UNUSED_CONTEXT;
1329     OP_REFCNT_LOCK;
1330 }
1331
1332 void
1333 Perl_op_refcnt_unlock(pTHX)
1334   PERL_TSA_RELEASE(PL_op_mutex)
1335 {
1336 #ifdef USE_ITHREADS
1337     dVAR;
1338 #endif
1339     PERL_UNUSED_CONTEXT;
1340     OP_REFCNT_UNLOCK;
1341 }
1342
1343
1344 /*
1345 =for apidoc op_sibling_splice
1346
1347 A general function for editing the structure of an existing chain of
1348 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1349 you to delete zero or more sequential nodes, replacing them with zero or
1350 more different nodes.  Performs the necessary op_first/op_last
1351 housekeeping on the parent node and op_sibling manipulation on the
1352 children.  The last deleted node will be marked as as the last node by
1353 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1354
1355 Note that op_next is not manipulated, and nodes are not freed; that is the
1356 responsibility of the caller.  It also won't create a new list op for an
1357 empty list etc; use higher-level functions like op_append_elem() for that.
1358
1359 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1360 the splicing doesn't affect the first or last op in the chain.
1361
1362 C<start> is the node preceding the first node to be spliced.  Node(s)
1363 following it will be deleted, and ops will be inserted after it.  If it is
1364 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1365 beginning.
1366
1367 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1368 If -1 or greater than or equal to the number of remaining kids, all
1369 remaining kids are deleted.
1370
1371 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1372 If C<NULL>, no nodes are inserted.
1373
1374 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1375 deleted.
1376
1377 For example:
1378
1379     action                    before      after         returns
1380     ------                    -----       -----         -------
1381
1382                               P           P
1383     splice(P, A, 2, X-Y-Z)    |           |             B-C
1384                               A-B-C-D     A-X-Y-Z-D
1385
1386                               P           P
1387     splice(P, NULL, 1, X-Y)   |           |             A
1388                               A-B-C-D     X-Y-B-C-D
1389
1390                               P           P
1391     splice(P, NULL, 3, NULL)  |           |             A-B-C
1392                               A-B-C-D     D
1393
1394                               P           P
1395     splice(P, B, 0, X-Y)      |           |             NULL
1396                               A-B-C-D     A-B-X-Y-C-D
1397
1398
1399 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1400 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1401
1402 =cut
1403 */
1404
1405 OP *
1406 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1407 {
1408     OP *first;
1409     OP *rest;
1410     OP *last_del = NULL;
1411     OP *last_ins = NULL;
1412
1413     if (start)
1414         first = OpSIBLING(start);
1415     else if (!parent)
1416         goto no_parent;
1417     else
1418         first = cLISTOPx(parent)->op_first;
1419
1420     assert(del_count >= -1);
1421
1422     if (del_count && first) {
1423         last_del = first;
1424         while (--del_count && OpHAS_SIBLING(last_del))
1425             last_del = OpSIBLING(last_del);
1426         rest = OpSIBLING(last_del);
1427         OpLASTSIB_set(last_del, NULL);
1428     }
1429     else
1430         rest = first;
1431
1432     if (insert) {
1433         last_ins = insert;
1434         while (OpHAS_SIBLING(last_ins))
1435             last_ins = OpSIBLING(last_ins);
1436         OpMAYBESIB_set(last_ins, rest, NULL);
1437     }
1438     else
1439         insert = rest;
1440
1441     if (start) {
1442         OpMAYBESIB_set(start, insert, NULL);
1443     }
1444     else {
1445         assert(parent);
1446         cLISTOPx(parent)->op_first = insert;
1447         if (insert)
1448             parent->op_flags |= OPf_KIDS;
1449         else
1450             parent->op_flags &= ~OPf_KIDS;
1451     }
1452
1453     if (!rest) {
1454         /* update op_last etc */
1455         U32 type;
1456         OP *lastop;
1457
1458         if (!parent)
1459             goto no_parent;
1460
1461         /* ought to use OP_CLASS(parent) here, but that can't handle
1462          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1463          * either */
1464         type = parent->op_type;
1465         if (type == OP_CUSTOM) {
1466             dTHX;
1467             type = XopENTRYCUSTOM(parent, xop_class);
1468         }
1469         else {
1470             if (type == OP_NULL)
1471                 type = parent->op_targ;
1472             type = PL_opargs[type] & OA_CLASS_MASK;
1473         }
1474
1475         lastop = last_ins ? last_ins : start ? start : NULL;
1476         if (   type == OA_BINOP
1477             || type == OA_LISTOP
1478             || type == OA_PMOP
1479             || type == OA_LOOP
1480         )
1481             cLISTOPx(parent)->op_last = lastop;
1482
1483         if (lastop)
1484             OpLASTSIB_set(lastop, parent);
1485     }
1486     return last_del ? first : NULL;
1487
1488   no_parent:
1489     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1490 }
1491
1492 /*
1493 =for apidoc op_parent
1494
1495 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1496
1497 =cut
1498 */
1499
1500 OP *
1501 Perl_op_parent(OP *o)
1502 {
1503     PERL_ARGS_ASSERT_OP_PARENT;
1504     while (OpHAS_SIBLING(o))
1505         o = OpSIBLING(o);
1506     return o->op_sibparent;
1507 }
1508
1509 /* replace the sibling following start with a new UNOP, which becomes
1510  * the parent of the original sibling; e.g.
1511  *
1512  *  op_sibling_newUNOP(P, A, unop-args...)
1513  *
1514  *  P              P
1515  *  |      becomes |
1516  *  A-B-C          A-U-C
1517  *                   |
1518  *                   B
1519  *
1520  * where U is the new UNOP.
1521  *
1522  * parent and start args are the same as for op_sibling_splice();
1523  * type and flags args are as newUNOP().
1524  *
1525  * Returns the new UNOP.
1526  */
1527
1528 STATIC OP *
1529 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1530 {
1531     OP *kid, *newop;
1532
1533     kid = op_sibling_splice(parent, start, 1, NULL);
1534     newop = newUNOP(type, flags, kid);
1535     op_sibling_splice(parent, start, 0, newop);
1536     return newop;
1537 }
1538
1539
1540 /* lowest-level newLOGOP-style function - just allocates and populates
1541  * the struct. Higher-level stuff should be done by S_new_logop() /
1542  * newLOGOP(). This function exists mainly to avoid op_first assignment
1543  * being spread throughout this file.
1544  */
1545
1546 LOGOP *
1547 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1548 {
1549     dVAR;
1550     LOGOP *logop;
1551     OP *kid = first;
1552     NewOp(1101, logop, 1, LOGOP);
1553     OpTYPE_set(logop, type);
1554     logop->op_first = first;
1555     logop->op_other = other;
1556     if (first)
1557         logop->op_flags = OPf_KIDS;
1558     while (kid && OpHAS_SIBLING(kid))
1559         kid = OpSIBLING(kid);
1560     if (kid)
1561         OpLASTSIB_set(kid, (OP*)logop);
1562     return logop;
1563 }
1564
1565
1566 /* Contextualizers */
1567
1568 /*
1569 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1570
1571 Applies a syntactic context to an op tree representing an expression.
1572 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1573 or C<G_VOID> to specify the context to apply.  The modified op tree
1574 is returned.
1575
1576 =cut
1577 */
1578
1579 OP *
1580 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1581 {
1582     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1583     switch (context) {
1584         case G_SCALAR: return scalar(o);
1585         case G_ARRAY:  return list(o);
1586         case G_VOID:   return scalarvoid(o);
1587         default:
1588             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1589                        (long) context);
1590     }
1591 }
1592
1593 /*
1594
1595 =for apidoc Am|OP*|op_linklist|OP *o
1596 This function is the implementation of the L</LINKLIST> macro.  It should
1597 not be called directly.
1598
1599 =cut
1600 */
1601
1602 OP *
1603 Perl_op_linklist(pTHX_ OP *o)
1604 {
1605     OP *first;
1606
1607     PERL_ARGS_ASSERT_OP_LINKLIST;
1608
1609     if (o->op_next)
1610         return o->op_next;
1611
1612     /* establish postfix order */
1613     first = cUNOPo->op_first;
1614     if (first) {
1615         OP *kid;
1616         o->op_next = LINKLIST(first);
1617         kid = first;
1618         for (;;) {
1619             OP *sibl = OpSIBLING(kid);
1620             if (sibl) {
1621                 kid->op_next = LINKLIST(sibl);
1622                 kid = sibl;
1623             } else {
1624                 kid->op_next = o;
1625                 break;
1626             }
1627         }
1628     }
1629     else
1630         o->op_next = o;
1631
1632     return o->op_next;
1633 }
1634
1635 static OP *
1636 S_scalarkids(pTHX_ OP *o)
1637 {
1638     if (o && o->op_flags & OPf_KIDS) {
1639         OP *kid;
1640         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1641             scalar(kid);
1642     }
1643     return o;
1644 }
1645
1646 STATIC OP *
1647 S_scalarboolean(pTHX_ OP *o)
1648 {
1649     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1650
1651     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1652          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1653         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1654          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1655          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1656         if (ckWARN(WARN_SYNTAX)) {
1657             const line_t oldline = CopLINE(PL_curcop);
1658
1659             if (PL_parser && PL_parser->copline != NOLINE) {
1660                 /* This ensures that warnings are reported at the first line
1661                    of the conditional, not the last.  */
1662                 CopLINE_set(PL_curcop, PL_parser->copline);
1663             }
1664             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1665             CopLINE_set(PL_curcop, oldline);
1666         }
1667     }
1668     return scalar(o);
1669 }
1670
1671 static SV *
1672 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1673 {
1674     assert(o);
1675     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1676            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1677     {
1678         const char funny  = o->op_type == OP_PADAV
1679                          || o->op_type == OP_RV2AV ? '@' : '%';
1680         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1681             GV *gv;
1682             if (cUNOPo->op_first->op_type != OP_GV
1683              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1684                 return NULL;
1685             return varname(gv, funny, 0, NULL, 0, subscript_type);
1686         }
1687         return
1688             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1689     }
1690 }
1691
1692 static SV *
1693 S_op_varname(pTHX_ const OP *o)
1694 {
1695     return S_op_varname_subscript(aTHX_ o, 1);
1696 }
1697
1698 static void
1699 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1700 { /* or not so pretty :-) */
1701     if (o->op_type == OP_CONST) {
1702         *retsv = cSVOPo_sv;
1703         if (SvPOK(*retsv)) {
1704             SV *sv = *retsv;
1705             *retsv = sv_newmortal();
1706             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1707                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1708         }
1709         else if (!SvOK(*retsv))
1710             *retpv = "undef";
1711     }
1712     else *retpv = "...";
1713 }
1714
1715 static void
1716 S_scalar_slice_warning(pTHX_ const OP *o)
1717 {
1718     OP *kid;
1719     const bool h = o->op_type == OP_HSLICE
1720                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1721     const char lbrack =
1722         h ? '{' : '[';
1723     const char rbrack =
1724         h ? '}' : ']';
1725     SV *name;
1726     SV *keysv = NULL; /* just to silence compiler warnings */
1727     const char *key = NULL;
1728
1729     if (!(o->op_private & OPpSLICEWARNING))
1730         return;
1731     if (PL_parser && PL_parser->error_count)
1732         /* This warning can be nonsensical when there is a syntax error. */
1733         return;
1734
1735     kid = cLISTOPo->op_first;
1736     kid = OpSIBLING(kid); /* get past pushmark */
1737     /* weed out false positives: any ops that can return lists */
1738     switch (kid->op_type) {
1739     case OP_BACKTICK:
1740     case OP_GLOB:
1741     case OP_READLINE:
1742     case OP_MATCH:
1743     case OP_RV2AV:
1744     case OP_EACH:
1745     case OP_VALUES:
1746     case OP_KEYS:
1747     case OP_SPLIT:
1748     case OP_LIST:
1749     case OP_SORT:
1750     case OP_REVERSE:
1751     case OP_ENTERSUB:
1752     case OP_CALLER:
1753     case OP_LSTAT:
1754     case OP_STAT:
1755     case OP_READDIR:
1756     case OP_SYSTEM:
1757     case OP_TMS:
1758     case OP_LOCALTIME:
1759     case OP_GMTIME:
1760     case OP_ENTEREVAL:
1761         return;
1762     }
1763
1764     /* Don't warn if we have a nulled list either. */
1765     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1766         return;
1767
1768     assert(OpSIBLING(kid));
1769     name = S_op_varname(aTHX_ OpSIBLING(kid));
1770     if (!name) /* XS module fiddling with the op tree */
1771         return;
1772     S_op_pretty(aTHX_ kid, &keysv, &key);
1773     assert(SvPOK(name));
1774     sv_chop(name,SvPVX(name)+1);
1775     if (key)
1776        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1777         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1778                    "Scalar value @%" SVf "%c%s%c better written as $%" SVf
1779                    "%c%s%c",
1780                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1781                     lbrack, key, rbrack);
1782     else
1783        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1784         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1785                    "Scalar value @%" SVf "%c%" SVf "%c better written as $%"
1786                     SVf "%c%" SVf "%c",
1787                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1788                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1789 }
1790
1791 OP *
1792 Perl_scalar(pTHX_ OP *o)
1793 {
1794     OP *kid;
1795
1796     /* assumes no premature commitment */
1797     if (!o || (PL_parser && PL_parser->error_count)
1798          || (o->op_flags & OPf_WANT)
1799          || o->op_type == OP_RETURN)
1800     {
1801         return o;
1802     }
1803
1804     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1805
1806     switch (o->op_type) {
1807     case OP_REPEAT:
1808         scalar(cBINOPo->op_first);
1809         if (o->op_private & OPpREPEAT_DOLIST) {
1810             kid = cLISTOPx(cUNOPo->op_first)->op_first;
1811             assert(kid->op_type == OP_PUSHMARK);
1812             if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1813                 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1814                 o->op_private &=~ OPpREPEAT_DOLIST;
1815             }
1816         }
1817         break;
1818     case OP_OR:
1819     case OP_AND:
1820     case OP_COND_EXPR:
1821         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
1822             scalar(kid);
1823         break;
1824         /* FALLTHROUGH */
1825     case OP_SPLIT:
1826     case OP_MATCH:
1827     case OP_QR:
1828     case OP_SUBST:
1829     case OP_NULL:
1830     default:
1831         if (o->op_flags & OPf_KIDS) {
1832             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
1833                 scalar(kid);
1834         }
1835         break;
1836     case OP_LEAVE:
1837     case OP_LEAVETRY:
1838         kid = cLISTOPo->op_first;
1839         scalar(kid);
1840         kid = OpSIBLING(kid);
1841     do_kids:
1842         while (kid) {
1843             OP *sib = OpSIBLING(kid);
1844             if (sib && kid->op_type != OP_LEAVEWHEN
1845              && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
1846                 || (  sib->op_targ != OP_NEXTSTATE
1847                    && sib->op_targ != OP_DBSTATE  )))
1848                 scalarvoid(kid);
1849             else
1850                 scalar(kid);
1851             kid = sib;
1852         }
1853         PL_curcop = &PL_compiling;
1854         break;
1855     case OP_SCOPE:
1856     case OP_LINESEQ:
1857     case OP_LIST:
1858         kid = cLISTOPo->op_first;
1859         goto do_kids;
1860     case OP_SORT:
1861         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1862         break;
1863     case OP_KVHSLICE:
1864     case OP_KVASLICE:
1865     {
1866         /* Warn about scalar context */
1867         const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1868         const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1869         SV *name;
1870         SV *keysv;
1871         const char *key = NULL;
1872
1873         /* This warning can be nonsensical when there is a syntax error. */
1874         if (PL_parser && PL_parser->error_count)
1875             break;
1876
1877         if (!ckWARN(WARN_SYNTAX)) break;
1878
1879         kid = cLISTOPo->op_first;
1880         kid = OpSIBLING(kid); /* get past pushmark */
1881         assert(OpSIBLING(kid));
1882         name = S_op_varname(aTHX_ OpSIBLING(kid));
1883         if (!name) /* XS module fiddling with the op tree */
1884             break;
1885         S_op_pretty(aTHX_ kid, &keysv, &key);
1886         assert(SvPOK(name));
1887         sv_chop(name,SvPVX(name)+1);
1888         if (key)
1889   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1890             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1891                        "%%%" SVf "%c%s%c in scalar context better written "
1892                        "as $%" SVf "%c%s%c",
1893                         SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1894                         lbrack, key, rbrack);
1895         else
1896   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1897             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1898                        "%%%" SVf "%c%" SVf "%c in scalar context better "
1899                        "written as $%" SVf "%c%" SVf "%c",
1900                         SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1901                         SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1902     }
1903     }
1904     return o;
1905 }
1906
1907 OP *
1908 Perl_scalarvoid(pTHX_ OP *arg)
1909 {
1910     dVAR;
1911     OP *kid;
1912     SV* sv;
1913     OP *o = arg;
1914     dDEFER_OP;
1915
1916     PERL_ARGS_ASSERT_SCALARVOID;
1917
1918     do {
1919         U8 want;
1920         SV *useless_sv = NULL;
1921         const char* useless = NULL;
1922
1923         if (o->op_type == OP_NEXTSTATE
1924             || o->op_type == OP_DBSTATE
1925             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1926                                           || o->op_targ == OP_DBSTATE)))
1927             PL_curcop = (COP*)o;                /* for warning below */
1928
1929         /* assumes no premature commitment */
1930         want = o->op_flags & OPf_WANT;
1931         if ((want && want != OPf_WANT_SCALAR)
1932             || (PL_parser && PL_parser->error_count)
1933             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1934         {
1935             continue;
1936         }
1937
1938         if ((o->op_private & OPpTARGET_MY)
1939             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1940         {
1941             /* newASSIGNOP has already applied scalar context, which we
1942                leave, as if this op is inside SASSIGN.  */
1943             continue;
1944         }
1945
1946         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1947
1948         switch (o->op_type) {
1949         default:
1950             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1951                 break;
1952             /* FALLTHROUGH */
1953         case OP_REPEAT:
1954             if (o->op_flags & OPf_STACKED)
1955                 break;
1956             if (o->op_type == OP_REPEAT)
1957                 scalar(cBINOPo->op_first);
1958             goto func_ops;
1959         case OP_CONCAT:
1960             if ((o->op_flags & OPf_STACKED) &&
1961                     !(o->op_private & OPpCONCAT_NESTED))
1962                 break;
1963             goto func_ops;
1964         case OP_SUBSTR:
1965             if (o->op_private == 4)
1966                 break;
1967             /* FALLTHROUGH */
1968         case OP_WANTARRAY:
1969         case OP_GV:
1970         case OP_SMARTMATCH:
1971         case OP_AV2ARYLEN:
1972         case OP_REF:
1973         case OP_REFGEN:
1974         case OP_SREFGEN:
1975         case OP_DEFINED:
1976         case OP_HEX:
1977         case OP_OCT:
1978         case OP_LENGTH:
1979         case OP_VEC:
1980         case OP_INDEX:
1981         case OP_RINDEX:
1982         case OP_SPRINTF:
1983         case OP_KVASLICE:
1984         case OP_KVHSLICE:
1985         case OP_UNPACK:
1986         case OP_PACK:
1987         case OP_JOIN:
1988         case OP_LSLICE:
1989         case OP_ANONLIST:
1990         case OP_ANONHASH:
1991         case OP_SORT:
1992         case OP_REVERSE:
1993         case OP_RANGE:
1994         case OP_FLIP:
1995         case OP_FLOP:
1996         case OP_CALLER:
1997         case OP_FILENO:
1998         case OP_EOF:
1999         case OP_TELL:
2000         case OP_GETSOCKNAME:
2001         case OP_GETPEERNAME:
2002         case OP_READLINK:
2003         case OP_TELLDIR:
2004         case OP_GETPPID:
2005         case OP_GETPGRP:
2006         case OP_GETPRIORITY:
2007         case OP_TIME:
2008         case OP_TMS:
2009         case OP_LOCALTIME:
2010         case OP_GMTIME:
2011         case OP_GHBYNAME:
2012         case OP_GHBYADDR:
2013         case OP_GHOSTENT:
2014         case OP_GNBYNAME:
2015         case OP_GNBYADDR:
2016         case OP_GNETENT:
2017         case OP_GPBYNAME:
2018         case OP_GPBYNUMBER:
2019         case OP_GPROTOENT:
2020         case OP_GSBYNAME:
2021         case OP_GSBYPORT:
2022         case OP_GSERVENT:
2023         case OP_GPWNAM:
2024         case OP_GPWUID:
2025         case OP_GGRNAM:
2026         case OP_GGRGID:
2027         case OP_GETLOGIN:
2028         case OP_PROTOTYPE:
2029         case OP_RUNCV:
2030         func_ops:
2031             useless = OP_DESC(o);
2032             break;
2033
2034         case OP_GVSV:
2035         case OP_PADSV:
2036         case OP_PADAV:
2037         case OP_PADHV:
2038         case OP_PADANY:
2039         case OP_AELEM:
2040         case OP_AELEMFAST:
2041         case OP_AELEMFAST_LEX:
2042         case OP_ASLICE:
2043         case OP_HELEM:
2044         case OP_HSLICE:
2045             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2046                 /* Otherwise it's "Useless use of grep iterator" */
2047                 useless = OP_DESC(o);
2048             break;
2049
2050         case OP_SPLIT:
2051             if (!(o->op_private & OPpSPLIT_ASSIGN))
2052                 useless = OP_DESC(o);
2053             break;
2054
2055         case OP_NOT:
2056             kid = cUNOPo->op_first;
2057             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2058                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2059                 goto func_ops;
2060             }
2061             useless = "negative pattern binding (!~)";
2062             break;
2063
2064         case OP_SUBST:
2065             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2066                 useless = "non-destructive substitution (s///r)";
2067             break;
2068
2069         case OP_TRANSR:
2070             useless = "non-destructive transliteration (tr///r)";
2071             break;
2072
2073         case OP_RV2GV:
2074         case OP_RV2SV:
2075         case OP_RV2AV:
2076         case OP_RV2HV:
2077             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2078                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2079                 useless = "a variable";
2080             break;
2081
2082         case OP_CONST:
2083             sv = cSVOPo_sv;
2084             if (cSVOPo->op_private & OPpCONST_STRICT)
2085                 no_bareword_allowed(o);
2086             else {
2087                 if (ckWARN(WARN_VOID)) {
2088                     NV nv;
2089                     /* don't warn on optimised away booleans, eg
2090                      * use constant Foo, 5; Foo || print; */
2091                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2092                         useless = NULL;
2093                     /* the constants 0 and 1 are permitted as they are
2094                        conventionally used as dummies in constructs like
2095                        1 while some_condition_with_side_effects;  */
2096                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2097                         useless = NULL;
2098                     else if (SvPOK(sv)) {
2099                         SV * const dsv = newSVpvs("");
2100                         useless_sv
2101                             = Perl_newSVpvf(aTHX_
2102                                             "a constant (%s)",
2103                                             pv_pretty(dsv, SvPVX_const(sv),
2104                                                       SvCUR(sv), 32, NULL, NULL,
2105                                                       PERL_PV_PRETTY_DUMP
2106                                                       | PERL_PV_ESCAPE_NOCLEAR
2107                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2108                         SvREFCNT_dec_NN(dsv);
2109                     }
2110                     else if (SvOK(sv)) {
2111                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2112                     }
2113                     else
2114                         useless = "a constant (undef)";
2115                 }
2116             }
2117             op_null(o);         /* don't execute or even remember it */
2118             break;
2119
2120         case OP_POSTINC:
2121             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2122             break;
2123
2124         case OP_POSTDEC:
2125             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2126             break;
2127
2128         case OP_I_POSTINC:
2129             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2130             break;
2131
2132         case OP_I_POSTDEC:
2133             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2134             break;
2135
2136         case OP_SASSIGN: {
2137             OP *rv2gv;
2138             UNOP *refgen, *rv2cv;
2139             LISTOP *exlist;
2140
2141             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2142                 break;
2143
2144             rv2gv = ((BINOP *)o)->op_last;
2145             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2146                 break;
2147
2148             refgen = (UNOP *)((BINOP *)o)->op_first;
2149
2150             if (!refgen || (refgen->op_type != OP_REFGEN
2151                             && refgen->op_type != OP_SREFGEN))
2152                 break;
2153
2154             exlist = (LISTOP *)refgen->op_first;
2155             if (!exlist || exlist->op_type != OP_NULL
2156                 || exlist->op_targ != OP_LIST)
2157                 break;
2158
2159             if (exlist->op_first->op_type != OP_PUSHMARK
2160                 && exlist->op_first != exlist->op_last)
2161                 break;
2162
2163             rv2cv = (UNOP*)exlist->op_last;
2164
2165             if (rv2cv->op_type != OP_RV2CV)
2166                 break;
2167
2168             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2169             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2170             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2171
2172             o->op_private |= OPpASSIGN_CV_TO_GV;
2173             rv2gv->op_private |= OPpDONT_INIT_GV;
2174             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2175
2176             break;
2177         }
2178
2179         case OP_AASSIGN: {
2180             inplace_aassign(o);
2181             break;
2182         }
2183
2184         case OP_OR:
2185         case OP_AND:
2186             kid = cLOGOPo->op_first;
2187             if (kid->op_type == OP_NOT
2188                 && (kid->op_flags & OPf_KIDS)) {
2189                 if (o->op_type == OP_AND) {
2190                     OpTYPE_set(o, OP_OR);
2191                 } else {
2192                     OpTYPE_set(o, OP_AND);
2193                 }
2194                 op_null(kid);
2195             }
2196             /* FALLTHROUGH */
2197
2198         case OP_DOR:
2199         case OP_COND_EXPR:
2200         case OP_ENTERGIVEN:
2201         case OP_ENTERWHEN:
2202             for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2203                 if (!(kid->op_flags & OPf_KIDS))
2204                     scalarvoid(kid);
2205                 else
2206                     DEFER_OP(kid);
2207         break;
2208
2209         case OP_NULL:
2210             if (o->op_flags & OPf_STACKED)
2211                 break;
2212             /* FALLTHROUGH */
2213         case OP_NEXTSTATE:
2214         case OP_DBSTATE:
2215         case OP_ENTERTRY:
2216         case OP_ENTER:
2217             if (!(o->op_flags & OPf_KIDS))
2218                 break;
2219             /* FALLTHROUGH */
2220         case OP_SCOPE:
2221         case OP_LEAVE:
2222         case OP_LEAVETRY:
2223         case OP_LEAVELOOP:
2224         case OP_LINESEQ:
2225         case OP_LEAVEGIVEN:
2226         case OP_LEAVEWHEN:
2227         kids:
2228             for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2229                 if (!(kid->op_flags & OPf_KIDS))
2230                     scalarvoid(kid);
2231                 else
2232                     DEFER_OP(kid);
2233             break;
2234         case OP_LIST:
2235             /* If the first kid after pushmark is something that the padrange
2236                optimisation would reject, then null the list and the pushmark.
2237             */
2238             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2239                 && (  !(kid = OpSIBLING(kid))
2240                       || (  kid->op_type != OP_PADSV
2241                             && kid->op_type != OP_PADAV
2242                             && kid->op_type != OP_PADHV)
2243                       || kid->op_private & ~OPpLVAL_INTRO
2244                       || !(kid = OpSIBLING(kid))
2245                       || (  kid->op_type != OP_PADSV
2246                             && kid->op_type != OP_PADAV
2247                             && kid->op_type != OP_PADHV)
2248                       || kid->op_private & ~OPpLVAL_INTRO)
2249             ) {
2250                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2251                 op_null(o); /* NULL the list */
2252             }
2253             goto kids;
2254         case OP_ENTEREVAL:
2255             scalarkids(o);
2256             break;
2257         case OP_SCALAR:
2258             scalar(o);
2259             break;
2260         }
2261
2262         if (useless_sv) {
2263             /* mortalise it, in case warnings are fatal.  */
2264             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2265                            "Useless use of %" SVf " in void context",
2266                            SVfARG(sv_2mortal(useless_sv)));
2267         }
2268         else if (useless) {
2269             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2270                            "Useless use of %s in void context",
2271                            useless);
2272         }
2273     } while ( (o = POP_DEFERRED_OP()) );
2274
2275     DEFER_OP_CLEANUP;
2276
2277     return arg;
2278 }
2279
2280 static OP *
2281 S_listkids(pTHX_ OP *o)
2282 {
2283     if (o && o->op_flags & OPf_KIDS) {
2284         OP *kid;
2285         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2286             list(kid);
2287     }
2288     return o;
2289 }
2290
2291 OP *
2292 Perl_list(pTHX_ OP *o)
2293 {
2294     OP *kid;
2295
2296     /* assumes no premature commitment */
2297     if (!o || (o->op_flags & OPf_WANT)
2298          || (PL_parser && PL_parser->error_count)
2299          || o->op_type == OP_RETURN)
2300     {
2301         return o;
2302     }
2303
2304     if ((o->op_private & OPpTARGET_MY)
2305         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2306     {
2307         return o;                               /* As if inside SASSIGN */
2308     }
2309
2310     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2311
2312     switch (o->op_type) {
2313     case OP_FLOP:
2314         list(cBINOPo->op_first);
2315         break;
2316     case OP_REPEAT:
2317         if (o->op_private & OPpREPEAT_DOLIST
2318          && !(o->op_flags & OPf_STACKED))
2319         {
2320             list(cBINOPo->op_first);
2321             kid = cBINOPo->op_last;
2322             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2323              && SvIVX(kSVOP_sv) == 1)
2324             {
2325                 op_null(o); /* repeat */
2326                 op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2327                 /* const (rhs): */
2328                 op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2329             }
2330         }
2331         break;
2332     case OP_OR:
2333     case OP_AND:
2334     case OP_COND_EXPR:
2335         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2336             list(kid);
2337         break;
2338     default:
2339     case OP_MATCH:
2340     case OP_QR:
2341     case OP_SUBST:
2342     case OP_NULL:
2343         if (!(o->op_flags & OPf_KIDS))
2344             break;
2345         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2346             list(cBINOPo->op_first);
2347             return gen_constant_list(o);
2348         }
2349         listkids(o);
2350         break;
2351     case OP_LIST:
2352         listkids(o);
2353         if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2354             op_null(cUNOPo->op_first); /* NULL the pushmark */
2355             op_null(o); /* NULL the list */
2356         }
2357         break;
2358     case OP_LEAVE:
2359     case OP_LEAVETRY:
2360         kid = cLISTOPo->op_first;
2361         list(kid);
2362         kid = OpSIBLING(kid);
2363     do_kids:
2364         while (kid) {
2365             OP *sib = OpSIBLING(kid);
2366             if (sib && kid->op_type != OP_LEAVEWHEN)
2367                 scalarvoid(kid);
2368             else
2369                 list(kid);
2370             kid = sib;
2371         }
2372         PL_curcop = &PL_compiling;
2373         break;
2374     case OP_SCOPE:
2375     case OP_LINESEQ:
2376         kid = cLISTOPo->op_first;
2377         goto do_kids;
2378     }
2379     return o;
2380 }
2381
2382 static OP *
2383 S_scalarseq(pTHX_ OP *o)
2384 {
2385     if (o) {
2386         const OPCODE type = o->op_type;
2387
2388         if (type == OP_LINESEQ || type == OP_SCOPE ||
2389             type == OP_LEAVE || type == OP_LEAVETRY)
2390         {
2391             OP *kid, *sib;
2392             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2393                 if ((sib = OpSIBLING(kid))
2394                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2395                     || (  sib->op_targ != OP_NEXTSTATE
2396                        && sib->op_targ != OP_DBSTATE  )))
2397                 {
2398                     scalarvoid(kid);
2399                 }
2400             }
2401             PL_curcop = &PL_compiling;
2402         }
2403         o->op_flags &= ~OPf_PARENS;
2404         if (PL_hints & HINT_BLOCK_SCOPE)
2405             o->op_flags |= OPf_PARENS;
2406     }
2407     else
2408         o = newOP(OP_STUB, 0);
2409     return o;
2410 }
2411
2412 STATIC OP *
2413 S_modkids(pTHX_ OP *o, I32 type)
2414 {
2415     if (o && o->op_flags & OPf_KIDS) {
2416         OP *kid;
2417         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2418             op_lvalue(kid, type);
2419     }
2420     return o;
2421 }
2422
2423
2424 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2425  * const fields. Also, convert CONST keys to HEK-in-SVs.
2426  * rop is the op that retrieves the hash;
2427  * key_op is the first key
2428  */
2429
2430 STATIC void
2431 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op)
2432 {
2433     PADNAME *lexname;
2434     GV **fields;
2435     bool check_fields;
2436
2437     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2438     if (rop) {
2439         if (rop->op_first->op_type == OP_PADSV)
2440             /* @$hash{qw(keys here)} */
2441             rop = (UNOP*)rop->op_first;
2442         else {
2443             /* @{$hash}{qw(keys here)} */
2444             if (rop->op_first->op_type == OP_SCOPE
2445                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2446                 {
2447                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2448                 }
2449             else
2450                 rop = NULL;
2451         }
2452     }
2453
2454     lexname = NULL; /* just to silence compiler warnings */
2455     fields  = NULL; /* just to silence compiler warnings */
2456
2457     check_fields =
2458             rop
2459          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2460              SvPAD_TYPED(lexname))
2461          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2462          && isGV(*fields) && GvHV(*fields);
2463
2464     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2465         SV **svp, *sv;
2466         if (key_op->op_type != OP_CONST)
2467             continue;
2468         svp = cSVOPx_svp(key_op);
2469
2470         /* make sure it's not a bareword under strict subs */
2471         if (key_op->op_private & OPpCONST_BARE &&
2472             key_op->op_private & OPpCONST_STRICT)
2473         {
2474             no_bareword_allowed((OP*)key_op);
2475         }
2476
2477         /* Make the CONST have a shared SV */
2478         if (   !SvIsCOW_shared_hash(sv = *svp)
2479             && SvTYPE(sv) < SVt_PVMG
2480             && SvOK(sv)
2481             && !SvROK(sv))
2482         {
2483             SSize_t keylen;
2484             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2485             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2486             SvREFCNT_dec_NN(sv);
2487             *svp = nsv;
2488         }
2489
2490         if (   check_fields
2491             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2492         {
2493             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2494                         "in variable %" PNf " of type %" HEKf,
2495                         SVfARG(*svp), PNfARG(lexname),
2496                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2497         }
2498     }
2499 }
2500
2501 /* info returned by S_sprintf_is_multiconcatable() */
2502
2503 struct sprintf_ismc_info {
2504     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2505     char  *start;     /* start of raw format string */
2506     char  *end;       /* bytes after end of raw format string */
2507     STRLEN total_len; /* total length (in bytes) of format string, not
2508                          including '%s' and  half of '%%' */
2509     STRLEN variant;   /* number of bytes by which total_len_p would grow
2510                          if upgraded to utf8 */
2511     bool   utf8;      /* whether the format is utf8 */
2512 };
2513
2514
2515 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2516  * i.e. its format argument is a const string with only '%s' and '%%'
2517  * formats, and the number of args is known, e.g.
2518  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2519  * but not
2520  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2521  *
2522  * If successful, the sprintf_ismc_info struct pointed to by info will be
2523  * populated.
2524  */
2525
2526 STATIC bool
2527 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2528 {
2529     OP    *pm, *constop, *kid;
2530     SV    *sv;
2531     char  *s, *e, *p;
2532     SSize_t nargs, nformats;
2533     STRLEN cur, total_len, variant;
2534     bool   utf8;
2535
2536     /* if sprintf's behaviour changes, die here so that someone
2537      * can decide whether to enhance this function or skip optimising
2538      * under those new circumstances */
2539     assert(!(o->op_flags & OPf_STACKED));
2540     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2541     assert(!(o->op_private & ~OPpARG4_MASK));
2542
2543     pm = cUNOPo->op_first;
2544     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2545         return FALSE;
2546     constop = OpSIBLING(pm);
2547     if (!constop || constop->op_type != OP_CONST)
2548         return FALSE;
2549     sv = cSVOPx_sv(constop);
2550     if (SvMAGICAL(sv) || !SvPOK(sv))
2551         return FALSE;
2552
2553     s = SvPV(sv, cur);
2554     e = s + cur;
2555
2556     /* Scan format for %% and %s and work out how many %s there are.
2557      * Abandon if other format types are found.
2558      */
2559
2560     nformats  = 0;
2561     total_len = 0;
2562     variant   = 0;
2563
2564     for (p = s; p < e; p++) {
2565         if (*p != '%') {
2566             total_len++;
2567             if (!UTF8_IS_INVARIANT(*p))
2568                 variant++;
2569             continue;
2570         }
2571         p++;
2572         if (p >= e)
2573             return FALSE; /* lone % at end gives "Invalid conversion" */
2574         if (*p == '%')
2575             total_len++;
2576         else if (*p == 's')
2577             nformats++;
2578         else
2579             return FALSE;
2580     }
2581
2582     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2583         return FALSE;
2584
2585     utf8 = cBOOL(SvUTF8(sv));
2586     if (utf8)
2587         variant = 0;
2588
2589     /* scan args; they must all be in scalar cxt */
2590
2591     nargs = 0;
2592     kid = OpSIBLING(constop);
2593
2594     while (kid) {
2595         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2596             return FALSE;
2597         nargs++;
2598         kid = OpSIBLING(kid);
2599     }
2600
2601     if (nargs != nformats)
2602         return FALSE; /* e.g. sprintf("%s%s", $a); */
2603
2604
2605     info->nargs      = nargs;
2606     info->start      = s;
2607     info->end        = e;
2608     info->total_len  = total_len;
2609     info->variant    = variant;
2610     info->utf8       = utf8;
2611
2612     return TRUE;
2613 }
2614
2615
2616
2617 /* S_maybe_multiconcat():
2618  *
2619  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2620  * convert it (and its children) into an OP_MULTICONCAT. See the code
2621  * comments just before pp_multiconcat() for the full details of what
2622  * OP_MULTICONCAT supports.
2623  *
2624  * Basically we're looking for an optree with a chain of OP_CONCATS down
2625  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2626  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2627  *
2628  *      $x = "$a$b-$c"
2629  *
2630  *  looks like
2631  *
2632  *      SASSIGN
2633  *         |
2634  *      STRINGIFY   -- PADSV[$x]
2635  *         |
2636  *         |
2637  *      ex-PUSHMARK -- CONCAT/S
2638  *                        |
2639  *                     CONCAT/S  -- PADSV[$d]
2640  *                        |
2641  *                     CONCAT    -- CONST["-"]
2642  *                        |
2643  *                     PADSV[$a] -- PADSV[$b]
2644  *
2645  * Note that at this stage the OP_SASSIGN may have already been optimised
2646  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2647  */
2648
2649 STATIC void
2650 S_maybe_multiconcat(pTHX_ OP *o)
2651 {
2652     dVAR;
2653     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2654     OP *topop;       /* the top-most op in the concat tree (often equals o,
2655                         unless there are assign/stringify ops above it */
2656     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2657     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2658     OP *targetop;    /* the op corresponding to target=... or target.=... */
2659     OP *stringop;    /* the OP_STRINGIFY op, if any */
2660     OP *nextop;      /* used for recreating the op_next chain without consts */
2661     OP *kid;         /* general-purpose op pointer */
2662     UNOP_AUX_item *aux;
2663     UNOP_AUX_item *lenp;
2664     char *const_str, *p;
2665     struct sprintf_ismc_info sprintf_info;
2666
2667                      /* store info about each arg in args[];
2668                       * toparg is the highest used slot; argp is a general
2669                       * pointer to args[] slots */
2670     struct {
2671         void *p;      /* initially points to const sv (or null for op);
2672                          later, set to SvPV(constsv), with ... */
2673         STRLEN len;   /* ... len set to SvPV(..., len) */
2674     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2675
2676     SSize_t nargs  = 0;
2677     SSize_t nconst = 0;
2678     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2679     STRLEN variant;
2680     bool utf8 = FALSE;
2681     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2682                                  the last-processed arg will the LHS of one,
2683                                  as args are processed in reverse order */
2684     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2685     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2686     U8 flags          = 0;   /* what will become the op_flags and ... */
2687     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2688     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2689     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2690     bool prev_was_const = FALSE; /* previous arg was a const */
2691
2692     /* -----------------------------------------------------------------
2693      * Phase 1:
2694      *
2695      * Examine the optree non-destructively to determine whether it's
2696      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2697      * information about the optree in args[].
2698      */
2699
2700     argp     = args;
2701     targmyop = NULL;
2702     targetop = NULL;
2703     stringop = NULL;
2704     topop    = o;
2705     parentop = o;
2706
2707     assert(   o->op_type == OP_SASSIGN
2708            || o->op_type == OP_CONCAT
2709            || o->op_type == OP_SPRINTF
2710            || o->op_type == OP_STRINGIFY);
2711
2712     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2713
2714     /* first see if, at the top of the tree, there is an assign,
2715      * append and/or stringify */
2716
2717     if (topop->op_type == OP_SASSIGN) {
2718         /* expr = ..... */
2719         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2720             return;
2721         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2722             return;
2723         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2724
2725         parentop = topop;
2726         topop = cBINOPo->op_first;
2727         targetop = OpSIBLING(topop);
2728         if (!targetop) /* probably some sort of syntax error */
2729             return;
2730     }
2731     else if (   topop->op_type == OP_CONCAT
2732              && (topop->op_flags & OPf_STACKED)
2733              && (!(topop->op_private & OPpCONCAT_NESTED))
2734             )
2735     {
2736         /* expr .= ..... */
2737
2738         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
2739          * decide what to do about it */
2740         assert(!(o->op_private & OPpTARGET_MY));
2741
2742         /* barf on unknown flags */
2743         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
2744         private_flags |= OPpMULTICONCAT_APPEND;
2745         targetop = cBINOPo->op_first;
2746         parentop = topop;
2747         topop    = OpSIBLING(targetop);
2748
2749         /* $x .= <FOO> gets optimised to rcatline instead */
2750         if (topop->op_type == OP_READLINE)
2751             return;
2752     }
2753
2754     if (targetop) {
2755         /* Can targetop (the LHS) if it's a padsv, be be optimised
2756          * away and use OPpTARGET_MY instead?
2757          */
2758         if (    (targetop->op_type == OP_PADSV)
2759             && !(targetop->op_private & OPpDEREF)
2760             && !(targetop->op_private & OPpPAD_STATE)
2761                /* we don't support 'my $x .= ...' */
2762             && (   o->op_type == OP_SASSIGN
2763                 || !(targetop->op_private & OPpLVAL_INTRO))
2764         )
2765             is_targable = TRUE;
2766     }
2767
2768     if (topop->op_type == OP_STRINGIFY) {
2769         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
2770             return;
2771         stringop = topop;
2772
2773         /* barf on unknown flags */
2774         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
2775
2776         if ((topop->op_private & OPpTARGET_MY)) {
2777             if (o->op_type == OP_SASSIGN)
2778                 return; /* can't have two assigns */
2779             targmyop = topop;
2780         }
2781
2782         private_flags |= OPpMULTICONCAT_STRINGIFY;
2783         parentop = topop;
2784         topop = cBINOPx(topop)->op_first;
2785         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
2786         topop = OpSIBLING(topop);
2787     }
2788
2789     if (topop->op_type == OP_SPRINTF) {
2790         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
2791             return;
2792         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
2793             nargs     = sprintf_info.nargs;
2794             total_len = sprintf_info.total_len;
2795             variant   = sprintf_info.variant;
2796             utf8      = sprintf_info.utf8;
2797             is_sprintf = TRUE;
2798             private_flags |= OPpMULTICONCAT_FAKE;
2799             toparg = argp;
2800             /* we have an sprintf op rather than a concat optree.
2801              * Skip most of the code below which is associated with
2802              * processing that optree. We also skip phase 2, determining
2803              * whether its cost effective to optimise, since for sprintf,
2804              * multiconcat is *always* faster */
2805             goto create_aux;
2806         }
2807         /* note that even if the sprintf itself isn't multiconcatable,
2808          * the expression as a whole may be, e.g. in
2809          *    $x .= sprintf("%d",...)
2810          * the sprintf op will be left as-is, but the concat/S op may
2811          * be upgraded to multiconcat
2812          */
2813     }
2814     else if (topop->op_type == OP_CONCAT) {
2815         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
2816             return;
2817
2818         if ((topop->op_private & OPpTARGET_MY)) {
2819             if (o->op_type == OP_SASSIGN || targmyop)
2820                 return; /* can't have two assigns */
2821             targmyop = topop;
2822         }
2823     }
2824
2825     /* Is it safe to convert a sassign/stringify/concat op into
2826      * a multiconcat? */
2827     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
2828     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
2829     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
2830     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
2831     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
2832                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
2833     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
2834                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
2835
2836     /* Now scan the down the tree looking for a series of
2837      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
2838      * stacked). For example this tree:
2839      *
2840      *     |
2841      *   CONCAT/STACKED
2842      *     |
2843      *   CONCAT/STACKED -- EXPR5
2844      *     |
2845      *   CONCAT/STACKED -- EXPR4
2846      *     |
2847      *   CONCAT -- EXPR3
2848      *     |
2849      *   EXPR1  -- EXPR2
2850      *
2851      * corresponds to an expression like
2852      *
2853      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
2854      *
2855      * Record info about each EXPR in args[]: in particular, whether it is
2856      * a stringifiable OP_CONST and if so what the const sv is.
2857      *
2858      * The reason why the last concat can't be STACKED is the difference
2859      * between
2860      *
2861      *    ((($a .= $a) .= $a) .= $a) .= $a
2862      *
2863      * and
2864      *    $a . $a . $a . $a . $a
2865      *
2866      * The main difference between the optrees for those two constructs
2867      * is the presence of the last STACKED. As well as modifying $a,
2868      * the former sees the changed $a between each concat, so if $s is
2869      * initially 'a', the first returns 'a' x 16, while the latter returns
2870      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
2871      */
2872
2873     kid = topop;
2874
2875     for (;;) {
2876         OP *argop;
2877         SV *sv;
2878         bool last = FALSE;
2879
2880         if (    kid->op_type == OP_CONCAT
2881             && !kid_is_last
2882         ) {
2883             OP *k1, *k2;
2884             k1 = cUNOPx(kid)->op_first;
2885             k2 = OpSIBLING(k1);
2886             /* shouldn't happen except maybe after compile err? */
2887             if (!k2)
2888                 return;
2889
2890             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
2891             if (kid->op_private & OPpTARGET_MY)
2892                 kid_is_last = TRUE;
2893
2894             stacked_last = (kid->op_flags & OPf_STACKED);
2895             if (!stacked_last)
2896                 kid_is_last = TRUE;
2897
2898             kid   = k1;
2899             argop = k2;
2900         }
2901         else {
2902             argop = kid;
2903             last = TRUE;
2904         }
2905
2906         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
2907             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
2908         {
2909             /* At least two spare slots are needed to decompose both
2910              * concat args. If there are no slots left, continue to
2911              * examine the rest of the optree, but don't push new values
2912              * on args[]. If the optree as a whole is legal for conversion
2913              * (in particular that the last concat isn't STACKED), then
2914              * the first PERL_MULTICONCAT_MAXARG elements of the optree
2915              * can be converted into an OP_MULTICONCAT now, with the first
2916              * child of that op being the remainder of the optree -
2917              * which may itself later be converted to a multiconcat op
2918              * too.
2919              */
2920             if (last) {
2921                 /* the last arg is the rest of the optree */
2922                 argp++->p = NULL;
2923                 nargs++;
2924             }
2925         }
2926         else if (   argop->op_type == OP_CONST
2927             && ((sv = cSVOPx_sv(argop)))
2928             /* defer stringification until runtime of 'constant'
2929              * things that might stringify variantly, e.g. the radix
2930              * point of NVs, or overloaded RVs */
2931             && (SvPOK(sv) || SvIOK(sv))
2932             && (!SvGMAGICAL(sv))
2933         ) {
2934             argp++->p = sv;
2935             utf8   |= cBOOL(SvUTF8(sv));
2936             nconst++;
2937             if (prev_was_const)
2938                 /* this const may be demoted back to a plain arg later;
2939                  * make sure we have enough arg slots left */
2940                 nadjconst++;
2941             prev_was_const = !prev_was_const;
2942         }
2943         else {
2944             argp++->p = NULL;
2945             nargs++;
2946             prev_was_const = FALSE;
2947         }
2948
2949         if (last)
2950             break;
2951     }
2952
2953     toparg = argp - 1;
2954
2955     if (stacked_last)
2956         return; /* we don't support ((A.=B).=C)...) */
2957
2958     /* look for two adjacent consts and don't fold them together:
2959      *     $o . "a" . "b"
2960      * should do
2961      *     $o->concat("a")->concat("b")
2962      * rather than
2963      *     $o->concat("ab")
2964      * (but $o .=  "a" . "b" should still fold)
2965      */
2966     {
2967         bool seen_nonconst = FALSE;
2968         for (argp = toparg; argp >= args; argp--) {
2969             if (argp->p == NULL) {
2970                 seen_nonconst = TRUE;
2971                 continue;
2972             }
2973             if (!seen_nonconst)
2974                 continue;
2975             if (argp[1].p) {
2976                 /* both previous and current arg were constants;
2977                  * leave the current OP_CONST as-is */
2978                 argp->p = NULL;
2979                 nconst--;
2980                 nargs++;
2981             }
2982         }
2983     }
2984
2985     /* -----------------------------------------------------------------
2986      * Phase 2:
2987      *
2988      * At this point we have determined that the optree *can* be converted
2989      * into a multiconcat. Having gathered all the evidence, we now decide
2990      * whether it *should*.
2991      */
2992
2993
2994     /* we need at least one concat action, e.g.:
2995      *
2996      *  Y . Z
2997      *  X = Y . Z
2998      *  X .= Y
2999      *
3000      * otherwise we could be doing something like $x = "foo", which
3001      * if treated as as a concat, would fail to COW.
3002      */
3003     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3004         return;
3005
3006     /* Benchmarking seems to indicate that we gain if:
3007      * * we optimise at least two actions into a single multiconcat
3008      *    (e.g concat+concat, sassign+concat);
3009      * * or if we can eliminate at least 1 OP_CONST;
3010      * * or if we can eliminate a padsv via OPpTARGET_MY
3011      */
3012
3013     if (
3014            /* eliminated at least one OP_CONST */
3015            nconst >= 1
3016            /* eliminated an OP_SASSIGN */
3017         || o->op_type == OP_SASSIGN
3018            /* eliminated an OP_PADSV */
3019         || (!targmyop && is_targable)
3020     )
3021         /* definitely a net gain to optimise */
3022         goto optimise;
3023
3024     /* ... if not, what else? */
3025
3026     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3027      * multiconcat is faster (due to not creating a temporary copy of
3028      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3029      * faster.
3030      */
3031     if (   nconst == 0
3032          && nargs == 2
3033          && targmyop
3034          && topop->op_type == OP_CONCAT
3035     ) {
3036         PADOFFSET t = targmyop->op_targ;
3037         OP *k1 = cBINOPx(topop)->op_first;
3038         OP *k2 = cBINOPx(topop)->op_last;
3039         if (   k2->op_type == OP_PADSV
3040             && k2->op_targ == t
3041             && (   k1->op_type != OP_PADSV
3042                 || k1->op_targ != t)
3043         )
3044             goto optimise;
3045     }
3046
3047     /* need at least two concats */
3048     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3049         return;
3050
3051
3052
3053     /* -----------------------------------------------------------------
3054      * Phase 3:
3055      *
3056      * At this point the optree has been verified as ok to be optimised
3057      * into an OP_MULTICONCAT. Now start changing things.
3058      */
3059
3060    optimise:
3061
3062     /* stringify all const args and determine utf8ness */
3063
3064     variant = 0;
3065     for (argp = args; argp <= toparg; argp++) {
3066         SV *sv = (SV*)argp->p;
3067         if (!sv)
3068             continue; /* not a const op */
3069         if (utf8 && !SvUTF8(sv))
3070             sv_utf8_upgrade_nomg(sv);
3071         argp->p = SvPV_nomg(sv, argp->len);
3072         total_len += argp->len;
3073         
3074         /* see if any strings would grow if converted to utf8 */
3075         if (!utf8) {
3076             char *p    = (char*)argp->p;
3077             STRLEN len = argp->len;
3078             while (len--) {
3079                 U8 c = *p++;
3080                 if (!UTF8_IS_INVARIANT(c))
3081                     variant++;
3082             }
3083         }
3084     }
3085
3086     /* create and populate aux struct */
3087
3088   create_aux:
3089
3090     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3091                     sizeof(UNOP_AUX_item)
3092                     *  (
3093                            PERL_MULTICONCAT_HEADER_SIZE
3094                          + ((nargs + 1) * (variant ? 2 : 1))
3095                         )
3096                     );
3097     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3098
3099     /* Extract all the non-const expressions from the concat tree then
3100      * dispose of the old tree, e.g. convert the tree from this:
3101      *
3102      *  o => SASSIGN
3103      *         |
3104      *       STRINGIFY   -- TARGET
3105      *         |
3106      *       ex-PUSHMARK -- CONCAT
3107      *                        |
3108      *                      CONCAT -- EXPR5
3109      *                        |
3110      *                      CONCAT -- EXPR4
3111      *                        |
3112      *                      CONCAT -- EXPR3
3113      *                        |
3114      *                      EXPR1  -- EXPR2
3115      *
3116      *
3117      * to:
3118      *
3119      *  o => MULTICONCAT
3120      *         |
3121      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3122      *
3123      * except that if EXPRi is an OP_CONST, it's discarded.
3124      *
3125      * During the conversion process, EXPR ops are stripped from the tree
3126      * and unshifted onto o. Finally, any of o's remaining original
3127      * childen are discarded and o is converted into an OP_MULTICONCAT.
3128      *
3129      * In this middle of this, o may contain both: unshifted args on the
3130      * left, and some remaining original args on the right. lastkidop
3131      * is set to point to the right-most unshifted arg to delineate
3132      * between the two sets.
3133      */
3134
3135
3136     if (is_sprintf) {
3137         /* create a copy of the format with the %'s removed, and record
3138          * the sizes of the const string segments in the aux struct */
3139         char *q, *oldq;
3140         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3141
3142         p    = sprintf_info.start;
3143         q    = const_str;
3144         oldq = q;
3145         for (; p < sprintf_info.end; p++) {
3146             if (*p == '%') {
3147                 p++;
3148                 if (*p != '%') {
3149                     (lenp++)->ssize = q - oldq;
3150                     oldq = q;
3151                     continue;
3152                 }
3153             }
3154             *q++ = *p;
3155         }
3156         lenp->ssize = q - oldq;
3157         assert((STRLEN)(q - const_str) == total_len);
3158
3159         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3160          * may or may not be topop) The pushmark and const ops need to be
3161          * kept in case they're an op_next entry point.
3162          */
3163         lastkidop = cLISTOPx(topop)->op_last;
3164         kid = cUNOPx(topop)->op_first; /* pushmark */
3165         op_null(kid);
3166         op_null(OpSIBLING(kid));       /* const */
3167         if (o != topop) {
3168             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3169             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3170             lastkidop->op_next = o;
3171         }
3172     }
3173     else {
3174         p = const_str;
3175         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3176
3177         lenp->ssize = -1;
3178
3179         /* Concatenate all const strings into const_str.
3180          * Note that args[] contains the RHS args in reverse order, so
3181          * we scan args[] from top to bottom to get constant strings
3182          * in L-R order
3183          */
3184         for (argp = toparg; argp >= args; argp--) {
3185             if (!argp->p)
3186                 /* not a const op */
3187                 (++lenp)->ssize = -1;
3188             else {
3189                 STRLEN l = argp->len;
3190                 Copy(argp->p, p, l, char);
3191                 p += l;
3192                 if (lenp->ssize == -1)
3193                     lenp->ssize = l;
3194                 else
3195                     lenp->ssize += l;
3196             }
3197         }
3198
3199         kid = topop;
3200         nextop = o;
3201         lastkidop = NULL;
3202
3203         for (argp = args; argp <= toparg; argp++) {
3204             /* only keep non-const args, except keep the first-in-next-chain
3205              * arg no matter what it is (but nulled if OP_CONST), because it
3206              * may be the entry point to this subtree from the previous
3207              * op_next.
3208              */
3209             bool last = (argp == toparg);
3210             OP *prev;
3211
3212             /* set prev to the sibling *before* the arg to be cut out,
3213              * e.g. when cutting EXPR:
3214              *
3215              *         |
3216              * kid=  CONCAT
3217              *         |
3218              * prev= CONCAT -- EXPR
3219              *         |
3220              */
3221             if (argp == args && kid->op_type != OP_CONCAT) {
3222                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3223                  * so the expression to be cut isn't kid->op_last but
3224                  * kid itself */
3225                 OP *o1, *o2;
3226                 /* find the op before kid */
3227                 o1 = NULL;
3228                 o2 = cUNOPx(parentop)->op_first;
3229                 while (o2 && o2 != kid) {
3230                     o1 = o2;
3231                     o2 = OpSIBLING(o2);
3232                 }
3233                 assert(o2 == kid);
3234                 prev = o1;
3235                 kid  = parentop;
3236             }
3237             else if (kid == o && lastkidop)
3238                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3239             else
3240                 prev = last ? NULL : cUNOPx(kid)->op_first;
3241
3242             if (!argp->p || last) {
3243                 /* cut RH op */
3244                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3245                 /* and unshift to front of o */
3246                 op_sibling_splice(o, NULL, 0, aop);
3247                 /* record the right-most op added to o: later we will
3248                  * free anything to the right of it */
3249                 if (!lastkidop)
3250                     lastkidop = aop;
3251                 aop->op_next = nextop;
3252                 if (last) {
3253                     if (argp->p)
3254                         /* null the const at start of op_next chain */
3255                         op_null(aop);
3256                 }
3257                 else if (prev)
3258                     nextop = prev->op_next;
3259             }
3260
3261             /* the last two arguments are both attached to the same concat op */
3262             if (argp < toparg - 1)
3263                 kid = prev;
3264         }
3265     }
3266
3267     /* Populate the aux struct */
3268
3269     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3270     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3271     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3272     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3273     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3274
3275     /* if variant > 0, calculate a variant const string and lengths where
3276      * the utf8 version of the string will take 'variant' more bytes than
3277      * the plain one. */
3278
3279     if (variant) {
3280         char              *p = const_str;
3281         STRLEN          ulen = total_len + variant;
3282         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3283         UNOP_AUX_item *ulens = lens + (nargs + 1);
3284         char             *up = (char*)PerlMemShared_malloc(ulen);
3285         SSize_t            n;
3286
3287         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3288         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3289
3290         for (n = 0; n < (nargs + 1); n++) {
3291             SSize_t i;
3292             char * orig_up = up;
3293             for (i = (lens++)->ssize; i > 0; i--) {
3294                 U8 c = *p++;
3295                 append_utf8_from_native_byte(c, (U8**)&up);
3296             }
3297             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3298         }
3299     }
3300
3301     if (stringop) {
3302         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3303          * that op's first child - an ex-PUSHMARK - because the op_next of
3304          * the previous op may point to it (i.e. it's the entry point for
3305          * the o optree)
3306          */
3307         OP *pmop =
3308             (stringop == o)
3309                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3310                 : op_sibling_splice(stringop, NULL, 1, NULL);
3311         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3312         op_sibling_splice(o, NULL, 0, pmop);
3313         if (!lastkidop)
3314             lastkidop = pmop;
3315     }
3316
3317     /* Optimise 
3318      *    target  = A.B.C...
3319      *    target .= A.B.C...
3320      */
3321
3322     if (targetop) {
3323         assert(!targmyop);
3324
3325         if (o->op_type == OP_SASSIGN) {
3326             /* Move the target subtree from being the last of o's children
3327              * to being the last of o's preserved children.
3328              * Note the difference between 'target = ...' and 'target .= ...':
3329              * for the former, target is executed last; for the latter,
3330              * first.
3331              */
3332             kid = OpSIBLING(lastkidop);
3333             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3334             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3335             lastkidop->op_next = kid->op_next;
3336             lastkidop = targetop;
3337         }
3338         else {
3339             /* Move the target subtree from being the first of o's
3340              * original children to being the first of *all* o's children.
3341              */
3342             if (lastkidop) {
3343                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3344                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3345             }
3346             else {
3347                 /* if the RHS of .= doesn't contain a concat (e.g.
3348                  * $x .= "foo"), it gets missed by the "strip ops from the
3349                  * tree and add to o" loop earlier */
3350                 assert(topop->op_type != OP_CONCAT);
3351                 if (stringop) {
3352                     /* in e.g. $x .= "$y", move the $y expression
3353                      * from being a child of OP_STRINGIFY to being the
3354                      * second child of the OP_CONCAT
3355                      */
3356                     assert(cUNOPx(stringop)->op_first == topop);
3357                     op_sibling_splice(stringop, NULL, 1, NULL);
3358                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3359                 }
3360                 assert(topop == OpSIBLING(cBINOPo->op_first));
3361                 if (toparg->p)
3362                     op_null(topop);
3363                 lastkidop = topop;
3364             }
3365         }
3366
3367         if (is_targable) {
3368             /* optimise
3369              *  my $lex  = A.B.C...
3370              *     $lex  = A.B.C...
3371              *     $lex .= A.B.C...
3372              * The original padsv op is kept but nulled in case it's the
3373              * entry point for the optree (which it will be for
3374              * '$lex .=  ... '
3375              */
3376             private_flags |= OPpTARGET_MY;
3377             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3378             o->op_targ = targetop->op_targ;
3379             targetop->op_targ = 0;
3380             op_null(targetop);
3381         }
3382         else
3383             flags |= OPf_STACKED;
3384     }
3385     else if (targmyop) {
3386         private_flags |= OPpTARGET_MY;
3387         if (o != targmyop) {
3388             o->op_targ = targmyop->op_targ;
3389             targmyop->op_targ = 0;
3390         }
3391     }
3392
3393     /* detach the emaciated husk of the sprintf/concat optree and free it */
3394     for (;;) {
3395         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3396         if (!kid)
3397             break;
3398         op_free(kid);
3399     }
3400
3401     /* and convert o into a multiconcat */
3402
3403     o->op_flags        = (flags|OPf_KIDS|stacked_last
3404                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3405     o->op_private      = private_flags;
3406     o->op_type         = OP_MULTICONCAT;
3407     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3408     cUNOP_AUXo->op_aux = aux;
3409 }
3410
3411
3412 /* do all the final processing on an optree (e.g. running the peephole
3413  * optimiser on it), then attach it to cv (if cv is non-null)
3414  */
3415
3416 static void
3417 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3418 {
3419     OP **startp;
3420
3421     /* XXX for some reason, evals, require and main optrees are
3422      * never attached to their CV; instead they just hang off
3423      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3424      * and get manually freed when appropriate */
3425     if (cv)
3426         startp = &CvSTART(cv);
3427     else
3428         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3429
3430     *startp = start;
3431     optree->op_private |= OPpREFCOUNTED;
3432     OpREFCNT_set(optree, 1);
3433     optimize_optree(optree);
3434     CALL_PEEP(*startp);
3435     finalize_optree(optree);
3436     S_prune_chain_head(startp);
3437
3438     if (cv) {
3439         /* now that optimizer has done its work, adjust pad values */
3440         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3441                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3442     }
3443 }
3444
3445
3446 /*
3447 =for apidoc optimize_optree
3448
3449 This function applies some optimisations to the optree in top-down order.
3450 It is called before the peephole optimizer, which processes ops in
3451 execution order. Note that finalize_optree() also does a top-down scan,
3452 but is called *after* the peephole optimizer.
3453
3454 =cut
3455 */
3456
3457 void
3458 Perl_optimize_optree(pTHX_ OP* o)
3459 {
3460     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3461
3462     ENTER;
3463     SAVEVPTR(PL_curcop);
3464
3465     optimize_op(o);
3466
3467     LEAVE;
3468 }
3469
3470
3471 /* helper for optimize_optree() which optimises on op then recurses
3472  * to optimise any children.
3473  */
3474
3475 STATIC void
3476 S_optimize_op(pTHX_ OP* o)
3477 {
3478     dDEFER_OP;
3479
3480     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3481     do {
3482         assert(o->op_type != OP_FREED);
3483
3484         switch (o->op_type) {
3485         case OP_NEXTSTATE:
3486         case OP_DBSTATE:
3487             PL_curcop = ((COP*)o);              /* for warnings */
3488             break;
3489
3490
3491         case OP_CONCAT:
3492         case OP_SASSIGN:
3493         case OP_STRINGIFY:
3494         case OP_SPRINTF:
3495             S_maybe_multiconcat(aTHX_ o);
3496             break;
3497
3498         case OP_SUBST:
3499             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
3500                 DEFER_OP(cPMOPo->op_pmreplrootu.op_pmreplroot);
3501             break;
3502
3503         default:
3504             break;
3505         }
3506
3507         if (o->op_flags & OPf_KIDS) {
3508             OP *kid;
3509             IV child_count = 0;
3510             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
3511                 DEFER_OP(kid);
3512                 ++child_count;
3513             }
3514             DEFER_REVERSE(child_count);
3515         }
3516     } while ( ( o = POP_DEFERRED_OP() ) );
3517
3518     DEFER_OP_CLEANUP;
3519 }
3520
3521
3522 /*
3523 =for apidoc finalize_optree
3524
3525 This function finalizes the optree.  Should be called directly after
3526 the complete optree is built.  It does some additional
3527 checking which can't be done in the normal C<ck_>xxx functions and makes
3528 the tree thread-safe.
3529
3530 =cut
3531 */
3532 void
3533 Perl_finalize_optree(pTHX_ OP* o)
3534 {
3535     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3536
3537     ENTER;
3538     SAVEVPTR(PL_curcop);
3539
3540     finalize_op(o);
3541
3542     LEAVE;
3543 }
3544
3545 #ifdef USE_ITHREADS
3546 /* Relocate sv to the pad for thread safety.
3547  * Despite being a "constant", the SV is written to,
3548  * for reference counts, sv_upgrade() etc. */
3549 PERL_STATIC_INLINE void
3550 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3551 {
3552     PADOFFSET ix;
3553     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3554     if (!*svp) return;
3555     ix = pad_alloc(OP_CONST, SVf_READONLY);
3556     SvREFCNT_dec(PAD_SVl(ix));
3557     PAD_SETSV(ix, *svp);
3558     /* XXX I don't know how this isn't readonly already. */
3559     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3560     *svp = NULL;
3561     *targp = ix;
3562 }
3563 #endif
3564
3565 /*
3566 =for apidoc s|OP*|traverse_op_tree|OP* top|OP* o
3567
3568 Return the next op in a depth-first traversal of the op tree,
3569 returning NULL when the traversal is complete.
3570
3571 The initial call must supply the root of the tree as both top and o.
3572
3573 For now it's static, but it may be exposed to the API in the future.
3574
3575 =cut
3576 */
3577
3578 STATIC OP*
3579 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3580     OP *sib;
3581
3582     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3583
3584     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3585         return cUNOPo->op_first;
3586     }
3587     else if ((sib = OpSIBLING(o))) {
3588         return sib;
3589     }
3590     else {
3591         OP *parent = o->op_sibparent;
3592         assert(!(o->op_moresib));
3593         while (parent && parent != top) {
3594             OP *sib = OpSIBLING(parent);
3595             if (sib)
3596                 return sib;
3597             parent = parent->op_sibparent;
3598         }
3599
3600         return NULL;
3601     }
3602 }
3603
3604 STATIC void
3605 S_finalize_op(pTHX_ OP* o)
3606 {
3607     OP * const top = o;
3608     PERL_ARGS_ASSERT_FINALIZE_OP;
3609
3610     do {
3611         assert(o->op_type != OP_FREED);
3612
3613         switch (o->op_type) {
3614         case OP_NEXTSTATE:
3615         case OP_DBSTATE:
3616             PL_curcop = ((COP*)o);              /* for warnings */
3617             break;
3618         case OP_EXEC:
3619             if (OpHAS_SIBLING(o)) {
3620                 OP *sib = OpSIBLING(o);
3621                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3622                     && ckWARN(WARN_EXEC)
3623                     && OpHAS_SIBLING(sib))
3624                 {
3625                     const OPCODE type = OpSIBLING(sib)->op_type;
3626                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3627                         const line_t oldline = CopLINE(PL_curcop);
3628                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3629                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3630                             "Statement unlikely to be reached");
3631                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3632                             "\t(Maybe you meant system() when you said exec()?)\n");
3633                         CopLINE_set(PL_curcop, oldline);
3634                     }
3635                 }
3636             }
3637             break;
3638
3639         case OP_GV:
3640             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3641                 GV * const gv = cGVOPo_gv;
3642                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
3643                     /* XXX could check prototype here instead of just carping */
3644                     SV * const sv = sv_newmortal();
3645                     gv_efullname3(sv, gv, NULL);
3646                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3647                                 "%" SVf "() called too early to check prototype",
3648                                 SVfARG(sv));
3649                 }
3650             }
3651             break;
3652
3653         case OP_CONST:
3654             if (cSVOPo->op_private & OPpCONST_STRICT)
3655                 no_bareword_allowed(o);
3656 #ifdef USE_ITHREADS
3657             /* FALLTHROUGH */
3658         case OP_HINTSEVAL:
3659             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
3660 #endif
3661             break;
3662
3663 #ifdef USE_ITHREADS
3664             /* Relocate all the METHOP's SVs to the pad for thread safety. */
3665         case OP_METHOD_NAMED:
3666         case OP_METHOD_SUPER:
3667         case OP_METHOD_REDIR:
3668         case OP_METHOD_REDIR_SUPER:
3669             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
3670             break;
3671 #endif
3672
3673         case OP_HELEM: {
3674             UNOP *rop;
3675             SVOP *key_op;
3676             OP *kid;
3677
3678             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
3679                 break;
3680
3681             rop = (UNOP*)((BINOP*)o)->op_first;
3682
3683             goto check_keys;
3684
3685             case OP_HSLICE:
3686                 S_scalar_slice_warning(aTHX_ o);
3687                 /* FALLTHROUGH */
3688
3689             case OP_KVHSLICE:
3690                 kid = OpSIBLING(cLISTOPo->op_first);
3691             if (/* I bet there's always a pushmark... */
3692                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
3693                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
3694             {
3695                 break;
3696             }
3697
3698             key_op = (SVOP*)(kid->op_type == OP_CONST
3699                              ? kid
3700                              : OpSIBLING(kLISTOP->op_first));
3701
3702             rop = (UNOP*)((LISTOP*)o)->op_last;
3703
3704         check_keys:
3705             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
3706                 rop = NULL;
3707             S_check_hash_fields_and_hekify(aTHX_ rop, key_op);
3708             break;
3709         }
3710         case OP_NULL:
3711             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
3712                 break;
3713             /* FALLTHROUGH */
3714         case OP_ASLICE:
3715             S_scalar_slice_warning(aTHX_ o);
3716             break;
3717
3718         case OP_SUBST: {
3719             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
3720                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3721             break;
3722         }
3723         default:
3724             break;
3725         }
3726
3727 #ifdef DEBUGGING
3728         if (o->op_flags & OPf_KIDS) {
3729             OP *kid;
3730
3731             /* check that op_last points to the last sibling, and that
3732              * the last op_sibling/op_sibparent field points back to the
3733              * parent, and that the only ops with KIDS are those which are
3734              * entitled to them */
3735             U32 type = o->op_type;
3736             U32 family;
3737             bool has_last;
3738
3739             if (type == OP_NULL) {
3740                 type = o->op_targ;
3741                 /* ck_glob creates a null UNOP with ex-type GLOB
3742                  * (which is a list op. So pretend it wasn't a listop */
3743                 if (type == OP_GLOB)
3744                     type = OP_NULL;
3745             }
3746             family = PL_opargs[type] & OA_CLASS_MASK;
3747
3748             has_last = (   family == OA_BINOP
3749                         || family == OA_LISTOP
3750                         || family == OA_PMOP
3751                         || family == OA_LOOP
3752                        );
3753             assert(  has_last /* has op_first and op_last, or ...
3754                   ... has (or may have) op_first: */
3755                   || family == OA_UNOP
3756                   || family == OA_UNOP_AUX
3757                   || family == OA_LOGOP
3758                   || family == OA_BASEOP_OR_UNOP
3759                   || family == OA_FILESTATOP
3760                   || family == OA_LOOPEXOP
3761                   || family == OA_METHOP
3762                   || type == OP_CUSTOM
3763                   || type == OP_NULL /* new_logop does this */
3764                   );
3765
3766             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
3767                 if (!OpHAS_SIBLING(kid)) {
3768                     if (has_last)
3769                         assert(kid == cLISTOPo->op_last);
3770                     assert(kid->op_sibparent == o);
3771                 }
3772             }
3773         }
3774 #endif
3775     } while (( o = traverse_op_tree(top, o)) != NULL);
3776 }
3777
3778 /*
3779 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
3780
3781 Propagate lvalue ("modifiable") context to an op and its children.
3782 C<type> represents the context type, roughly based on the type of op that
3783 would do the modifying, although C<local()> is represented by C<OP_NULL>,
3784 because it has no op type of its own (it is signalled by a flag on
3785 the lvalue op).
3786
3787 This function detects things that can't be modified, such as C<$x+1>, and
3788 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
3789 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
3790
3791 It also flags things that need to behave specially in an lvalue context,
3792 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
3793
3794 =cut
3795 */
3796
3797 static void
3798 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
3799 {
3800     CV *cv = PL_compcv;
3801     PadnameLVALUE_on(pn);
3802     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
3803         cv = CvOUTSIDE(cv);
3804         /* RT #127786: cv can be NULL due to an eval within the DB package
3805          * called from an anon sub - anon subs don't have CvOUTSIDE() set
3806          * unless they contain an eval, but calling eval within DB
3807          * pretends the eval was done in the caller's scope.
3808          */
3809         if (!cv)
3810             break;
3811         assert(CvPADLIST(cv));
3812         pn =
3813            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
3814         assert(PadnameLEN(pn));
3815         PadnameLVALUE_on(pn);
3816     }
3817 }
3818
3819 static bool
3820 S_vivifies(const OPCODE type)
3821 {
3822     switch(type) {
3823     case OP_RV2AV:     case   OP_ASLICE:
3824     case OP_RV2HV:     case OP_KVASLICE:
3825     case OP_RV2SV:     case   OP_HSLICE:
3826     case OP_AELEMFAST: case OP_KVHSLICE:
3827     case OP_HELEM:
3828     case OP_AELEM:
3829         return 1;
3830     }
3831     return 0;
3832 }
3833
3834 static void
3835 S_lvref(pTHX_ OP *o, I32 type)
3836 {
3837     dVAR;
3838     OP *kid;
3839     switch (o->op_type) {
3840     case OP_COND_EXPR:
3841         for (kid = OpSIBLING(cUNOPo->op_first); kid;
3842              kid = OpSIBLING(kid))
3843             S_lvref(aTHX_ kid, type);
3844         /* FALLTHROUGH */
3845     case OP_PUSHMARK:
3846         return;
3847     case OP_RV2AV:
3848         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
3849         o->op_flags |= OPf_STACKED;
3850         if (o->op_flags & OPf_PARENS) {
3851             if (o->op_private & OPpLVAL_INTRO) {
3852                  yyerror(Perl_form(aTHX_ "Can't modify reference to "
3853                       "localized parenthesized array in list assignment"));
3854                 return;
3855             }
3856           slurpy:
3857             OpTYPE_set(o, OP_LVAVREF);
3858             o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
3859             o->op_flags |= OPf_MOD|OPf_REF;
3860             return;
3861         }
3862         o->op_private |= OPpLVREF_AV;
3863         goto checkgv;
3864     case OP_RV2CV:
3865         kid = cUNOPo->op_first;
3866         if (kid->op_type == OP_NULL)
3867             kid = cUNOPx(OpSIBLING(kUNOP->op_first))
3868                 ->op_first;
3869         o->op_private = OPpLVREF_CV;
3870         if (kid->op_type == OP_GV)
3871             o->op_flags |= OPf_STACKED;
3872         else if (kid->op_type == OP_PADCV) {
3873             o->op_targ = kid->op_targ;
3874             kid->op_targ = 0;
3875             op_free(cUNOPo->op_first);
3876             cUNOPo->op_first = NULL;
3877             o->op_flags &=~ OPf_KIDS;
3878         }
3879         else goto badref;
3880         break;
3881     case OP_RV2HV:
3882         if (o->op_flags & OPf_PARENS) {
3883           parenhash:
3884             yyerror(Perl_form(aTHX_ "Can't modify reference to "
3885                                  "parenthesized hash in list assignment"));
3886                 return;
3887         }
3888         o->op_private |= OPpLVREF_HV;
3889         /* FALLTHROUGH */
3890     case OP_RV2SV:
3891       checkgv:
3892         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
3893         o->op_flags |= OPf_STACKED;
3894         break;
3895     case OP_PADHV:
3896         if (o->op_flags & OPf_PARENS) goto parenhash;
3897         o->op_private |= OPpLVREF_HV;
3898         /* FALLTHROUGH */
3899     case OP_PADSV:
3900         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
3901         break;
3902     case OP_PADAV:
3903         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
3904         if (o->op_flags & OPf_PARENS) goto slurpy;
3905         o->op_private |= OPpLVREF_AV;
3906         break;
3907     case OP_AELEM:
3908     case OP_HELEM:
3909         o->op_private |= OPpLVREF_ELEM;
3910         o->op_flags   |= OPf_STACKED;
3911         break;
3912     case OP_ASLICE:
3913     case OP_HSLICE:
3914         OpTYPE_set(o, OP_LVREFSLICE);
3915         o->op_private &= OPpLVAL_INTRO;
3916         return;
3917     case OP_NULL:
3918         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
3919             goto badref;
3920         else if (!(o->op_flags & OPf_KIDS))
3921             return;
3922         if (o->op_targ != OP_LIST) {
3923             S_lvref(aTHX_ cBINOPo->op_first, type);
3924             return;
3925         }
3926         /* FALLTHROUGH */
3927     case OP_LIST:
3928         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid)) {
3929             assert((kid->op_flags & OPf_WANT) != OPf_WANT_VOID);
3930             S_lvref(aTHX_ kid, type);
3931         }
3932         return;
3933     case OP_STUB:
3934         if (o->op_flags & OPf_PARENS)
3935             return;
3936         /* FALLTHROUGH */
3937     default:
3938       badref:
3939         /* diag_listed_as: Can't modify reference to %s in %s assignment */
3940         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
3941                      o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
3942                       ? "do block"
3943                       : OP_DESC(o),
3944                      PL_op_desc[type]));
3945         return;
3946     }
3947     OpTYPE_set(o, OP_LVREF);
3948     o->op_private &=
3949         OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
3950     if (type == OP_ENTERLOOP)
3951         o->op_private |= OPpLVREF_ITER;
3952 }
3953
3954 PERL_STATIC_INLINE bool
3955 S_potential_mod_type(I32 type)
3956 {
3957     /* Types that only potentially result in modification.  */
3958     return type == OP_GREPSTART || type == OP_ENTERSUB
3959         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
3960 }
3961
3962 OP *
3963 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
3964 {
3965     dVAR;
3966     OP *kid;
3967     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
3968     int localize = -1;
3969
3970     if (!o || (PL_parser && PL_parser->error_count))
3971         return o;
3972
3973     if ((o->op_private & OPpTARGET_MY)
3974         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
3975     {
3976         return o;
3977     }
3978
3979     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
3980
3981     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
3982
3983     switch (o->op_type) {
3984     case OP_UNDEF:
3985         PL_modcount++;
3986         return o;
3987     case OP_STUB:
3988         if ((o->op_flags & OPf_PARENS))
3989             break;
3990         goto nomod;
3991     case OP_ENTERSUB:
3992         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
3993             !(o->op_flags & OPf_STACKED)) {
3994             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
3995             assert(cUNOPo->op_first->op_type == OP_NULL);
3996             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
3997             break;
3998         }
3999         else {                          /* lvalue subroutine call */
4000             o->op_private |= OPpLVAL_INTRO;
4001             PL_modcount = RETURN_UNLIMITED_NUMBER;
4002             if (S_potential_mod_type(type)) {
4003                 o->op_private |= OPpENTERSUB_INARGS;
4004                 break;
4005             }
4006             else {                      /* Compile-time error message: */
4007                 OP *kid = cUNOPo->op_first;
4008                 CV *cv;
4009                 GV *gv;
4010                 SV *namesv;
4011
4012                 if (kid->op_type != OP_PUSHMARK) {
4013                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4014                         Perl_croak(aTHX_
4015                                 "panic: unexpected lvalue entersub "
4016                                 "args: type/targ %ld:%" UVuf,
4017                                 (long)kid->op_type, (UV)kid->op_targ);
4018                     kid = kLISTOP->op_first;
4019                 }
4020                 while (OpHAS_SIBLING(kid))
4021                     kid = OpSIBLING(kid);
4022                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4023                     break;      /* Postpone until runtime */
4024                 }
4025
4026                 kid = kUNOP->op_first;
4027                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4028                     kid = kUNOP->op_first;
4029                 if (kid->op_type == OP_NULL)
4030                     Perl_croak(aTHX_
4031                                "Unexpected constant lvalue entersub "
4032                                "entry via type/targ %ld:%" UVuf,
4033                                (long)kid->op_type, (UV)kid->op_targ);
4034                 if (kid->op_type != OP_GV) {
4035                     break;
4036                 }
4037
4038                 gv = kGVOP_gv;
4039                 cv = isGV(gv)
4040                     ? GvCV(gv)
4041                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4042                         ? MUTABLE_CV(SvRV(gv))
4043                         : NULL;
4044                 if (!cv)
4045                     break;
4046                 if (CvLVALUE(cv))
4047                     break;
4048                 if (flags & OP_LVALUE_NO_CROAK)
4049                     return NULL;
4050
4051                 namesv = cv_name(cv, NULL, 0);
4052                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4053                                      "subroutine call of &%" SVf " in %s",
4054                                      SVfARG(namesv), PL_op_desc[type]),
4055                            SvUTF8(namesv));
4056                 return o;
4057             }
4058         }
4059         /* FALLTHROUGH */
4060     default:
4061       nomod:
4062         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4063         /* grep, foreach, subcalls, refgen */
4064         if (S_potential_mod_type(type))
4065             break;
4066         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4067                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4068                       ? "do block"
4069                       : OP_DESC(o)),
4070                      type ? PL_op_desc[type] : "local"));
4071         return o;
4072
4073     case OP_PREINC:
4074     case OP_PREDEC:
4075     case OP_POW:
4076     case OP_MULTIPLY:
4077     case OP_DIVIDE:
4078     case OP_MODULO:
4079     case OP_ADD:
4080     case OP_SUBTRACT:
4081     case OP_CONCAT:
4082     case OP_LEFT_SHIFT:
4083     case OP_RIGHT_SHIFT:
4084     case OP_BIT_AND:
4085     case OP_BIT_XOR:
4086     case OP_BIT_OR:
4087     case OP_I_MULTIPLY:
4088     case OP_I_DIVIDE:
4089     case OP_I_MODULO:
4090     case OP_I_ADD:
4091     case OP_I_SUBTRACT:
4092         if (!(o->op_flags & OPf_STACKED))
4093             goto nomod;
4094         PL_modcount++;
4095         break;
4096
4097     case OP_REPEAT:
4098         if (o->op_flags & OPf_STACKED) {
4099             PL_modcount++;
4100             break;
4101         }
4102         if (!(o->op_private & OPpREPEAT_DOLIST))
4103             goto nomod;
4104         else {
4105             const I32 mods = PL_modcount;
4106             modkids(cBINOPo->op_first, type);
4107             if (type != OP_AASSIGN)
4108                 goto nomod;
4109             kid = cBINOPo->op_last;
4110             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4111                 const IV iv = SvIV(kSVOP_sv);
4112                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4113                     PL_modcount =
4114                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4115             }
4116             else
4117                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4118         }
4119         break;
4120
4121     case OP_COND_EXPR:
4122         localize = 1;
4123         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
4124             op_lvalue(kid, type);
4125         break;
4126
4127     case OP_RV2AV:
4128     case OP_RV2HV:
4129         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4130            PL_modcount = RETURN_UNLIMITED_NUMBER;
4131            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4132               fiable since some contexts need to know.  */
4133            o->op_flags |= OPf_MOD;
4134            return o;
4135         }
4136         /* FALLTHROUGH */
4137     case OP_RV2GV:
4138         if (scalar_mod_type(o, type))
4139             goto nomod;
4140         ref(cUNOPo->op_first, o->op_type);
4141         /* FALLTHROUGH */
4142     case OP_ASLICE:
4143     case OP_HSLICE:
4144         localize = 1;
4145         /* FALLTHROUGH */
4146     case OP_AASSIGN:
4147         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4148         if (type == OP_LEAVESUBLV && (
4149                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4150              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4151            ))
4152             o->op_private |= OPpMAYBE_LVSUB;
4153         /* FALLTHROUGH */
4154     case OP_NEXTSTATE:
4155     case OP_DBSTATE:
4156        PL_modcount = RETURN_UNLIMITED_NUMBER;
4157         break;
4158     case OP_KVHSLICE:
4159     case OP_KVASLICE:
4160     case OP_AKEYS:
4161         if (type == OP_LEAVESUBLV)
4162             o->op_private |= OPpMAYBE_LVSUB;
4163         goto nomod;
4164     case OP_AVHVSWITCH:
4165         if (type == OP_LEAVESUBLV
4166          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4167             o->op_private |= OPpMAYBE_LVSUB;
4168         goto nomod;
4169     case OP_AV2ARYLEN:
4170         PL_hints |= HINT_BLOCK_SCOPE;
4171         if (type == OP_LEAVESUBLV)
4172             o->op_private |= OPpMAYBE_LVSUB;
4173         PL_modcount++;
4174         break;
4175     case OP_RV2SV:
4176         ref(cUNOPo->op_first, o->op_type);
4177         localize = 1;
4178         /* FALLTHROUGH */
4179     case OP_GV:
4180         PL_hints |= HINT_BLOCK_SCOPE;
4181         /* FALLTHROUGH */
4182     case OP_SASSIGN:
4183     case OP_ANDASSIGN:
4184     case OP_ORASSIGN:
4185     case OP_DORASSIGN:
4186         PL_modcount++;
4187         break;
4188
4189     case OP_AELEMFAST:
4190     case OP_AELEMFAST_LEX:
4191         localize = -1;
4192         PL_modcount++;
4193         break;
4194
4195     case OP_PADAV:
4196     case OP_PADHV:
4197        PL_modcount = RETURN_UNLIMITED_NUMBER;
4198         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4199         {
4200            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4201               fiable since some contexts need to know.  */
4202             o->op_flags |= OPf_MOD;
4203             return o;
4204         }
4205         if (scalar_mod_type(o, type))
4206             goto nomod;
4207         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4208           && type == OP_LEAVESUBLV)
4209             o->op_private |= OPpMAYBE_LVSUB;
4210         /* FALLTHROUGH */
4211     case OP_PADSV:
4212         PL_modcount++;
4213         if (!type) /* local() */
4214             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4215                               PNfARG(PAD_COMPNAME(o->op_targ)));
4216         if (!(o->op_private & OPpLVAL_INTRO)
4217          || (  type != OP_SASSIGN && type != OP_AASSIGN
4218             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4219             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4220         break;
4221
4222     case OP_PUSHMARK:
4223         localize = 0;
4224         break;
4225
4226     case OP_KEYS:
4227         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4228             goto nomod;
4229         goto lvalue_func;
4230     case OP_SUBSTR:
4231         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4232             goto nomod;
4233         /* FALLTHROUGH */
4234     case OP_POS:
4235     case OP_VEC:
4236       lvalue_func:
4237         if (type == OP_LEAVESUBLV)
4238             o->op_private |= OPpMAYBE_LVSUB;
4239         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4240             /* substr and vec */
4241             /* If this op is in merely potential (non-fatal) modifiable
4242                context, then apply OP_ENTERSUB context to
4243                the kid op (to avoid croaking).  Other-
4244                wise pass this op’s own type so the correct op is mentioned
4245                in error messages.  */
4246             op_lvalue(OpSIBLING(cBINOPo->op_first),
4247                       S_potential_mod_type(type)
4248                         ? (I32)OP_ENTERSUB
4249                         : o->op_type);
4250         }
4251         break;
4252
4253     case OP_AELEM:
4254     case OP_HELEM:
4255         ref(cBINOPo->op_first, o->op_type);
4256         if (type == OP_ENTERSUB &&
4257              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4258             o->op_private |= OPpLVAL_DEFER;
4259         if (type == OP_LEAVESUBLV)
4260             o->op_private |= OPpMAYBE_LVSUB;
4261         localize = 1;
4262         PL_modcount++;
4263         break;
4264
4265     case OP_LEAVE:
4266     case OP_LEAVELOOP:
4267         o->op_private |= OPpLVALUE;
4268         /* FALLTHROUGH */
4269     case OP_SCOPE:
4270     case OP_ENTER:
4271     case OP_LINESEQ:
4272         localize = 0;
4273         if (o->op_flags & OPf_KIDS)
4274             op_lvalue(cLISTOPo->op_last, type);
4275         break;
4276
4277     case OP_NULL:
4278         localize = 0;
4279         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4280             goto nomod;
4281         else if (!(o->op_flags & OPf_KIDS))
4282             break;
4283
4284         if (o->op_targ != OP_LIST) {
4285             OP *sib = OpSIBLING(cLISTOPo->op_first);
4286             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4287              * that looks like
4288              *
4289              *   null
4290              *      arg
4291              *      trans
4292              *
4293              * compared with things like OP_MATCH which have the argument
4294              * as a child:
4295              *
4296              *   match
4297              *      arg
4298              *
4299              * so handle specially to correctly get "Can't modify" croaks etc
4300              */
4301
4302             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4303             {
4304                 /* this should trigger a "Can't modify transliteration" err */
4305                 op_lvalue(sib, type);
4306             }
4307             op_lvalue(cBINOPo->op_first, type);
4308             break;
4309         }
4310         /* FALLTHROUGH */
4311     case OP_LIST:
4312         localize = 0;
4313         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4314             /* elements might be in void context because the list is
4315                in scalar context or because they are attribute sub calls */
4316             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
4317                 op_lvalue(kid, type);
4318         break;
4319
4320     case OP_COREARGS:
4321         return o;
4322
4323     case OP_AND:
4324     case OP_OR:
4325         if (type == OP_LEAVESUBLV
4326          || !S_vivifies(cLOGOPo->op_first->op_type))
4327             op_lvalue(cLOGOPo->op_first, type);
4328         if (type == OP_LEAVESUBLV
4329          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4330             op_lvalue(OpSIBLING(cLOGOPo->op_first), type);
4331         goto nomod;
4332
4333     case OP_SREFGEN:
4334         if (type == OP_NULL) { /* local */
4335           local_refgen:
4336             if (!FEATURE_MYREF_IS_ENABLED)
4337                 Perl_croak(aTHX_ "The experimental declared_refs "
4338                                  "feature is not enabled");
4339             Perl_ck_warner_d(aTHX_
4340                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4341                     "Declaring references is experimental");
4342             op_lvalue(cUNOPo->op_first, OP_NULL);
4343             return o;
4344         }
4345         if (type != OP_AASSIGN && type != OP_SASSIGN
4346          && type != OP_ENTERLOOP)
4347             goto nomod;
4348         /* Don’t bother applying lvalue context to the ex-list.  */
4349         kid = cUNOPx(cUNOPo->op_first)->op_first;
4350         assert (!OpHAS_SIBLING(kid));
4351         goto kid_2lvref;
4352     case OP_REFGEN:
4353         if (type == OP_NULL) /* local */
4354             goto local_refgen;
4355         if (type != OP_AASSIGN) goto nomod;
4356         kid = cUNOPo->op_first;
4357       kid_2lvref:
4358         {
4359             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4360             S_lvref(aTHX_ kid, type);
4361             if (!PL_parser || PL_parser->error_count == ec) {
4362                 if (!FEATURE_REFALIASING_IS_ENABLED)
4363                     Perl_croak(aTHX_
4364                        "Experimental aliasing via reference not enabled");
4365                 Perl_ck_warner_d(aTHX_
4366                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4367                                 "Aliasing via reference is experimental");
4368             }
4369         }
4370         if (o->op_type == OP_REFGEN)
4371             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4372         op_null(o);
4373         return o;
4374
4375     case OP_SPLIT:
4376         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4377             /* This is actually @array = split.  */
4378             PL_modcount = RETURN_UNLIMITED_NUMBER;
4379             break;
4380         }
4381         goto nomod;
4382
4383     case OP_SCALAR:
4384         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4385         goto nomod;
4386     }
4387
4388     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4389        their argument is a filehandle; thus \stat(".") should not set
4390        it. AMS 20011102 */
4391     if (type == OP_REFGEN &&
4392         PL_check[o->op_type] == Perl_ck_ftst)
4393         return o;
4394
4395     if (type != OP_LEAVESUBLV)
4396         o->op_flags |= OPf_MOD;
4397
4398     if (type == OP_AASSIGN || type == OP_SASSIGN)
4399         o->op_flags |= OPf_SPECIAL
4400                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4401     else if (!type) { /* local() */
4402         switch (localize) {
4403         case 1:
4404             o->op_private |= OPpLVAL_INTRO;
4405             o->op_flags &= ~OPf_SPECIAL;
4406             PL_hints |= HINT_BLOCK_SCOPE;
4407             break;
4408         case 0:
4409             break;
4410         case -1:
4411             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4412                            "Useless localization of %s", OP_DESC(o));
4413         }
4414     }
4415     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4416              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4417         o->op_flags |= OPf_REF;
4418     return o;
4419 }
4420
4421 STATIC bool
4422 S_scalar_mod_type(const OP *o, I32 type)
4423 {
4424     switch (type) {
4425     case OP_POS:
4426     case OP_SASSIGN:
4427         if (o && o->op_type == OP_RV2GV)
4428             return FALSE;
4429         /* FALLTHROUGH */
4430     case OP_PREINC:
4431     case OP_PREDEC:
4432     case OP_POSTINC:
4433     case OP_POSTDEC:
4434     case OP_I_PREINC:
4435     case OP_I_PREDEC:
4436     case OP_I_POSTINC:
4437     case OP_I_POSTDEC:
4438     case OP_POW:
4439     case OP_MULTIPLY:
4440     case OP_DIVIDE:
4441     case OP_MODULO:
4442     case OP_REPEAT:
4443     case OP_ADD:
4444     case OP_SUBTRACT:
4445     case OP_I_MULTIPLY:
4446     case OP_I_DIVIDE:
4447     case OP_I_MODULO:
4448     case OP_I_ADD:
4449     case OP_I_SUBTRACT:
4450     case OP_LEFT_SHIFT:
4451     case OP_RIGHT_SHIFT:
4452     case OP_BIT_AND:
4453     case OP_BIT_XOR:
4454     case OP_BIT_OR:
4455     case OP_NBIT_AND:
4456     case OP_NBIT_XOR:
4457     case OP_NBIT_OR:
4458     case OP_SBIT_AND:
4459     case OP_SBIT_XOR:
4460     case OP_SBIT_OR:
4461     case OP_CONCAT:
4462     case OP_SUBST:
4463     case OP_TRANS:
4464     case OP_TRANSR:
4465     case OP_READ:
4466     case OP_SYSREAD:
4467     case OP_RECV:
4468     case OP_ANDASSIGN:
4469     case OP_ORASSIGN:
4470     case OP_DORASSIGN:
4471     case OP_VEC:
4472     case OP_SUBSTR:
4473         return TRUE;
4474     default:
4475         return FALSE;
4476     }
4477 }
4478
4479 STATIC bool
4480 S_is_handle_constructor(const OP *o, I32 numargs)
4481 {
4482     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4483
4484     switch (o->op_type) {
4485     case OP_PIPE_OP:
4486     case OP_SOCKPAIR:
4487         if (numargs == 2)
4488             return TRUE;
4489         /* FALLTHROUGH */
4490     case OP_SYSOPEN:
4491     case OP_OPEN:
4492     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4493     case OP_SOCKET:
4494     case OP_OPEN_DIR:
4495     case OP_ACCEPT:
4496         if (numargs == 1)
4497             return TRUE;
4498         /* FALLTHROUGH */
4499     default:
4500         return FALSE;
4501     }
4502 }
4503
4504 static OP *
4505 S_refkids(pTHX_ OP *o, I32 type)
4506 {
4507     if (o && o->op_flags & OPf_KIDS) {
4508         OP *kid;
4509         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4510             ref(kid, type);
4511     }
4512     return o;
4513 }
4514
4515 OP *
4516 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4517 {
4518     dVAR;
4519     OP *kid;
4520
4521     PERL_ARGS_ASSERT_DOREF;
4522
4523     if (PL_parser && PL_parser->error_count)
4524         return o;
4525
4526     switch (o->op_type) {
4527     case OP_ENTERSUB:
4528         if ((type == OP_EXISTS || type == OP_DEFINED) &&
4529             !(o->op_flags & OPf_STACKED)) {
4530             OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4531             assert(cUNOPo->op_first->op_type == OP_NULL);
4532             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
4533             o->op_flags |= OPf_SPECIAL;
4534         }
4535         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4536             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4537                               : type == OP_RV2HV ? OPpDEREF_HV
4538                               : OPpDEREF_SV);
4539             o->op_flags |= OPf_MOD;
4540         }
4541
4542         break;
4543
4544     case OP_COND_EXPR:
4545         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
4546             doref(kid, type, set_op_ref);
4547         break;
4548     case OP_RV2SV:
4549         if (type == OP_DEFINED)
4550             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
4551         doref(cUNOPo->op_first, o->op_type, set_op_ref);
4552         /* FALLTHROUGH */
4553     case OP_PADSV:
4554         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4555             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4556                               : type == OP_RV2HV ? OPpDEREF_HV
4557                               : OPpDEREF_SV);
4558             o->op_flags |= OPf_MOD;
4559         }
4560         break;
4561
4562     case OP_RV2AV:
4563     case OP_RV2HV:
4564         if (set_op_ref)
4565             o->op_flags |= OPf_REF;
4566         /* FALLTHROUGH */
4567     case OP_RV2GV:
4568         if (type == OP_DEFINED)
4569             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
4570         doref(cUNOPo->op_first, o->op_type, set_op_ref);
4571         break;
4572
4573     case OP_PADAV:
4574     case OP_PADHV:
4575         if (set_op_ref)
4576             o->op_flags |= OPf_REF;
4577         break;
4578
4579     case OP_SCALAR:
4580     case OP_NULL:
4581         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
4582             break;
4583         doref(cBINOPo->op_first, type, set_op_ref);
4584         break;
4585     case OP_AELEM:
4586     case OP_HELEM:
4587         doref(cBINOPo->op_first, o->op_type, set_op_ref);
4588         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4589             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4590                               : type == OP_RV2HV ? OPpDEREF_HV
4591                               : OPpDEREF_SV);
4592             o->op_flags |= OPf_MOD;
4593         }
4594         break;
4595
4596     case OP_SCOPE:
4597     case OP_LEAVE:
4598         set_op_ref = FALSE;
4599         /* FALLTHROUGH */
4600     case OP_ENTER:
4601     case OP_LIST:
4602         if (!(o->op_flags & OPf_KIDS))
4603             break;
4604         doref(cLISTOPo->op_last, type, set_op_ref);
4605         break;
4606     default:
4607         break;
4608     }
4609     return scalar(o);
4610
4611 }
4612
4613 STATIC OP *
4614 S_dup_attrlist(pTHX_ OP *o)
4615 {
4616     OP *rop;
4617
4618     PERL_ARGS_ASSERT_DUP_ATTRLIST;
4619
4620     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
4621      * where the first kid is OP_PUSHMARK and the remaining ones
4622      * are OP_CONST.  We need to push the OP_CONST values.
4623      */
4624     if (o->op_type == OP_CONST)
4625         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
4626     else {
4627         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
4628         rop = NULL;
4629         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
4630             if (o->op_type == OP_CONST)
4631                 rop = op_append_elem(OP_LIST, rop,
4632                                   newSVOP(OP_CONST, o->op_flags,
4633                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
4634         }
4635     }
4636     return rop;
4637 }
4638
4639 STATIC void
4640 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
4641 {
4642     PERL_ARGS_ASSERT_APPLY_ATTRS;
4643     {
4644         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
4645
4646         /* fake up C<use attributes $pkg,$rv,@attrs> */
4647
4648 #define ATTRSMODULE "attributes"
4649 #define ATTRSMODULE_PM "attributes.pm"
4650
4651         Perl_load_module(
4652           aTHX_ PERL_LOADMOD_IMPORT_OPS,
4653           newSVpvs(ATTRSMODULE),
4654           NULL,
4655           op_prepend_elem(OP_LIST,
4656                           newSVOP(OP_CONST, 0, stashsv),
4657                           op_prepend_elem(OP_LIST,
4658                                           newSVOP(OP_CONST, 0,
4659                                                   newRV(target)),
4660                                           dup_attrlist(attrs))));
4661     }
4662 }
4663
4664 STATIC void
4665 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
4666 {
4667     OP *pack, *imop, *arg;
4668     SV *meth, *stashsv, **svp;
4669
4670     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
4671
4672     if (!attrs)
4673         return;
4674
4675     assert(target->op_type == OP_PADSV ||
4676            target->op_type == OP_PADHV ||
4677            target->op_type == OP_PADAV);
4678
4679     /* Ensure that attributes.pm is loaded. */
4680     /* Don't force the C<use> if we don't need it. */
4681     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
4682     if (svp && *svp != &PL_sv_undef)
4683         NOOP;   /* already in %INC */
4684     else
4685         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
4686                                newSVpvs(ATTRSMODULE), NULL);
4687
4688     /* Need package name for method call. */
4689     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
4690
4691     /* Build up the real arg-list. */
4692     stashsv = newSVhek(HvNAME_HEK(stash));
4693
4694     arg = newOP(OP_PADSV, 0);
4695     arg->op_targ = target->op_targ;
4696     arg = op_prepend_elem(OP_LIST,
4697                        newSVOP(OP_CONST, 0, stashsv),
4698                        op_prepend_elem(OP_LIST,
4699                                     newUNOP(OP_REFGEN, 0,
4700                                             arg),
4701                                     dup_attrlist(attrs)));
4702
4703     /* Fake up a method call to import */
4704     meth = newSVpvs_share("import");
4705     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
4706                    op_append_elem(OP_LIST,
4707                                op_prepend_elem(OP_LIST, pack, arg),
4708                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
4709
4710     /* Combine the ops. */
4711     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
4712 }
4713
4714 /*
4715 =notfor apidoc apply_attrs_string
4716
4717 Attempts to apply a list of attributes specified by the C<attrstr> and
4718 C<len> arguments to the subroutine identified by the C<cv> argument which
4719 is expected to be associated with the package identified by the C<stashpv>
4720 argument (see L<attributes>).  It gets this wrong, though, in that it
4721 does not correctly identify the boundaries of the individual attribute
4722 specifications within C<attrstr>.  This is not really intended for the
4723 public API, but has to be listed here for systems such as AIX which
4724 need an explicit export list for symbols.  (It's called from XS code
4725 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
4726 to respect attribute syntax properly would be welcome.
4727
4728 =cut
4729 */
4730
4731 void
4732 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
4733                         const char *attrstr, STRLEN len)
4734 {
4735     OP *attrs = NULL;
4736
4737     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
4738
4739     if (!len) {
4740         len = strlen(attrstr);
4741     }
4742
4743     while (len) {
4744         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
4745         if (len) {
4746             const char * const sstr = attrstr;
4747             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
4748             attrs = op_append_elem(OP_LIST, attrs,
4749                                 newSVOP(OP_CONST, 0,
4750                                         newSVpvn(sstr, attrstr-sstr)));
4751         }
4752     }
4753
4754     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
4755                      newSVpvs(ATTRSMODULE),
4756                      NULL, op_prepend_elem(OP_LIST,
4757                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
4758                                   op_prepend_elem(OP_LIST,
4759                                                newSVOP(OP_CONST, 0,
4760                                                        newRV(MUTABLE_SV(cv))),
4761                                                attrs)));
4762 }
4763
4764 STATIC void
4765 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
4766                         bool curstash)
4767 {
4768     OP *new_proto = NULL;
4769     STRLEN pvlen;
4770     char *pv;
4771     OP *o;
4772
4773     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
4774
4775     if (!*attrs)
4776         return;
4777
4778     o = *attrs;
4779     if (o->op_type == OP_CONST) {
4780         pv = SvPV(cSVOPo_sv, pvlen);
4781         if (memBEGINs(pv, pvlen, "prototype(")) {
4782             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
4783             SV ** const tmpo = cSVOPx_svp(o);
4784             SvREFCNT_dec(cSVOPo_sv);
4785             *tmpo = tmpsv;
4786             new_proto = o;
4787             *attrs = NULL;
4788         }
4789     } else if (o->op_type == OP_LIST) {
4790         OP * lasto;
4791         assert(o->op_flags & OPf_KIDS);
4792         lasto = cLISTOPo->op_first;
4793         assert(lasto->op_type == OP_PUSHMARK);
4794         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
4795             if (o->op_type == OP_CONST) {
4796                 pv = SvPV(cSVOPo_sv, pvlen);
4797                 if (memBEGINs(pv, pvlen, "prototype(")) {
4798                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
4799                     SV ** const tmpo = cSVOPx_svp(o);
4800                     SvREFCNT_dec(cSVOPo_sv);
4801                     *tmpo = tmpsv;
4802                     if (new_proto && ckWARN(WARN_MISC)) {
4803                         STRLEN new_len;
4804                         const char * newp = SvPV(cSVOPo_sv, new_len);
4805                         Perl_warner(aTHX_ packWARN(WARN_MISC),
4806                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
4807                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
4808                         op_free(new_proto);
4809                     }
4810                     else if (new_proto)
4811                         op_free(new_proto);
4812                     new_proto = o;
4813                     /* excise new_proto from the list */
4814                     op_sibling_splice(*attrs, lasto, 1, NULL);
4815                     o = lasto;
4816                     continue;
4817                 }
4818             }
4819             lasto = o;
4820         }
4821         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
4822            would get pulled in with no real need */
4823         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
4824             op_free(*attrs);
4825             *attrs = NULL;
4826         }
4827     }
4828
4829     if (new_proto) {
4830         SV *svname;
4831         if (isGV(name)) {
4832             svname = sv_newmortal();
4833             gv_efullname3(svname, name, NULL);
4834         }
4835         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
4836             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
4837         else
4838             svname = (SV *)name;
4839         if (ckWARN(WARN_ILLEGALPROTO))
4840             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
4841                                  curstash);
4842         if (*proto && ckWARN(WARN_PROTOTYPE)) {
4843             STRLEN old_len, new_len;
4844             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
4845             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
4846
4847             if (curstash && svname == (SV *)name
4848              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
4849                 svname = sv_2mortal(newSVsv(PL_curstname));
4850                 sv_catpvs(svname, "::");
4851                 sv_catsv(svname, (SV *)name);
4852             }
4853
4854             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
4855                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
4856                 " in %" SVf,
4857                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
4858                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
4859                 SVfARG(svname));
4860         }
4861         if (*proto)
4862             op_free(*proto);
4863         *proto = new_proto;
4864     }
4865 }
4866
4867 static void
4868 S_cant_declare(pTHX_ OP *o)
4869 {
4870     if (o->op_type == OP_NULL
4871      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
4872         o = cUNOPo->op_first;
4873     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
4874                              o->op_type == OP_NULL
4875                                && o->op_flags & OPf_SPECIAL
4876                                  ? "do block"
4877                                  : OP_DESC(o),
4878                              PL_parser->in_my == KEY_our   ? "our"   :
4879                              PL_parser->in_my == KEY_state ? "state" :
4880                                                              "my"));
4881 }
4882
4883 STATIC OP *
4884 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
4885 {
4886     I32 type;
4887     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
4888
4889     PERL_ARGS_ASSERT_MY_KID;
4890
4891     if (!o || (PL_parser && PL_parser->error_count))
4892         return o;
4893
4894     type = o->op_type;
4895
4896     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
4897         OP *kid;
4898         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4899             my_kid(kid, attrs, imopsp);
4900         return o;
4901     } else if (type == OP_UNDEF || type == OP_STUB) {
4902         return o;
4903     } else if (type == OP_RV2SV ||      /* "our" declaration */
4904                type == OP_RV2AV ||
4905                type == OP_RV2HV) {
4906         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
4907             S_cant_declare(aTHX_ o);
4908         } else if (attrs) {
4909             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
4910             assert(PL_parser);
4911             PL_parser->in_my = FALSE;
4912             PL_parser->in_my_stash = NULL;
4913             apply_attrs(GvSTASH(gv),
4914                         (type == OP_RV2SV ? GvSVn(gv) :
4915                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
4916                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
4917                         attrs);
4918         }
4919         o->op_private |= OPpOUR_INTRO;
4920         return o;
4921     }
4922     else if (type == OP_REFGEN || type == OP_SREFGEN) {
4923         if (!FEATURE_MYREF_IS_ENABLED)
4924             Perl_croak(aTHX_ "The experimental declared_refs "
4925                              "feature is not enabled");
4926         Perl_ck_warner_d(aTHX_
4927              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4928             "Declaring references is experimental");
4929         /* Kid is a nulled OP_LIST, handled above.  */
4930         my_kid(cUNOPo->op_first, attrs, imopsp);
4931         return o;
4932     }
4933     else if (type != OP_PADSV &&
4934              type != OP_PADAV &&
4935              type != OP_PADHV &&
4936              type != OP_PUSHMARK)
4937     {
4938         S_cant_declare(aTHX_ o);
4939         return o;
4940     }
4941     else if (attrs && type != OP_PUSHMARK) {
4942         HV *stash;
4943
4944         assert(PL_parser);
4945         PL_parser->in_my = FALSE;
4946         PL_parser->in_my_stash = NULL;
4947
4948         /* check for C<my Dog $spot> when deciding package */
4949         stash = PAD_COMPNAME_TYPE(o->op_targ);
4950         if (!stash)
4951             stash = PL_curstash;
4952         apply_attrs_my(stash, o, attrs, imopsp);
4953     }
4954     o->op_flags |= OPf_MOD;
4955     o->op_private |= OPpLVAL_INTRO;
4956     if (stately)
4957         o->op_private |= OPpPAD_STATE;
4958     return o;
4959 }
4960
4961 OP *
4962 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
4963 {
4964     OP *rops;
4965     int maybe_scalar = 0;
4966
4967     PERL_ARGS_ASSERT_MY_ATTRS;
4968
4969 /* [perl #17376]: this appears to be premature, and results in code such as
4970    C< our(%x); > executing in list mode rather than void mode */
4971 #if 0
4972     if (o->op_flags & OPf_PARENS)
4973         list(o);
4974     else
4975         maybe_scalar = 1;
4976 #else
4977     maybe_scalar = 1;
4978 #endif
4979     if (attrs)
4980         SAVEFREEOP(attrs);
4981     rops = NULL;
4982     o = my_kid(o, attrs, &rops);
4983     if (rops) {
4984         if (maybe_scalar && o->op_type == OP_PADSV) {
4985             o = scalar(op_append_list(OP_LIST, rops, o));
4986             o->op_private |= OPpLVAL_INTRO;
4987         }
4988         else {
4989             /* The listop in rops might have a pushmark at the beginning,
4990                which will mess up list assignment. */
4991             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
4992             if (rops->op_type == OP_LIST && 
4993                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
4994             {
4995                 OP * const pushmark = lrops->op_first;
4996                 /* excise pushmark */
4997                 op_sibling_splice(rops, NULL, 1, NULL);
4998                 op_free(pushmark);
4999             }
5000             o = op_append_list(OP_LIST, o, rops);
5001         }
5002     }
5003     PL_parser->in_my = FALSE;
5004     PL_parser->in_my_stash = NULL;
5005     return o;
5006 }
5007
5008 OP *
5009 Perl_sawparens(pTHX_ OP *o)
5010 {
5011     PERL_UNUSED_CONTEXT;
5012     if (o)
5013         o->op_flags |= OPf_PARENS;
5014     return o;
5015 }
5016
5017 OP *
5018 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5019 {
5020     OP *o;
5021     bool ismatchop = 0;
5022     const OPCODE ltype = left->op_type;
5023     const OPCODE rtype = right->op_type;
5024
5025     PERL_ARGS_ASSERT_BIND_MATCH;
5026
5027     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5028           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5029     {
5030       const char * const desc
5031           = PL_op_desc[(
5032                           rtype == OP_SUBST || rtype == OP_TRANS
5033                        || rtype == OP_TRANSR
5034                        )
5035                        ? (int)rtype : OP_MATCH];
5036       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5037       SV * const name =
5038         S_op_varname(aTHX_ left);
5039       if (name)
5040         Perl_warner(aTHX_ packWARN(WARN_MISC),
5041              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5042              desc, SVfARG(name), SVfARG(name));
5043       else {
5044         const char * const sample = (isary
5045              ? "@array" : "%hash");
5046         Perl_warner(aTHX_ packWARN(WARN_MISC),
5047              "Applying %s to %s will act on scalar(%s)",
5048              desc, sample, sample);
5049       }
5050     }
5051
5052     if (rtype == OP_CONST &&
5053         cSVOPx(right)->op_private & OPpCONST_BARE &&
5054         cSVOPx(right)->op_private & OPpCONST_STRICT)
5055     {
5056         no_bareword_allowed(right);
5057     }
5058
5059     /* !~ doesn't make sense with /r, so error on it for now */
5060     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5061         type == OP_NOT)
5062         /* diag_listed_as: Using !~ with %s doesn't make sense */
5063         yyerror("Using !~ with s///r doesn't make sense");
5064     if (rtype == OP_TRANSR && type == OP_NOT)
5065         /* diag_listed_as: Using !~ with %s doesn't make sense */
5066         yyerror("Using !~ with tr///r doesn't make sense");
5067
5068     ismatchop = (rtype == OP_MATCH ||
5069                  rtype == OP_SUBST ||
5070                  rtype == OP_TRANS || rtype == OP_TRANSR)
5071              && !(right->op_flags & OPf_SPECIAL);
5072     if (ismatchop && right->op_private & OPpTARGET_MY) {
5073         right->op_targ = 0;
5074         right->op_private &= ~OPpTARGET_MY;
5075     }
5076     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5077         if (left->op_type == OP_PADSV
5078          && !(left->op_private & OPpLVAL_INTRO))
5079         {
5080             right->op_targ = left->op_targ;
5081             op_free(left);
5082             o = right;
5083         }
5084         else {
5085             right->op_flags |= OPf_STACKED;
5086             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5087             ! (rtype == OP_TRANS &&
5088                right->op_private & OPpTRANS_IDENTICAL) &&
5089             ! (rtype == OP_SUBST &&
5090                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5091                 left = op_lvalue(left, rtype);
5092             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5093                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5094             else
5095                 o = op_prepend_elem(rtype, scalar(left), right);
5096         }
5097         if (type == OP_NOT)
5098             return newUNOP(OP_NOT, 0, scalar(o));
5099         return o;
5100     }
5101     else
5102         return bind_match(type, left,
5103                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5104 }
5105
5106 OP *
5107 Perl_invert(pTHX_ OP *o)
5108 {
5109     if (!o)
5110         return NULL;
5111     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5112 }
5113
5114 /*
5115 =for apidoc Amx|OP *|op_scope|OP *o
5116
5117 Wraps up an op tree with some additional ops so that at runtime a dynamic
5118 scope will be created.  The original ops run in the new dynamic scope,
5119 and then, provided that they exit normally, the scope will be unwound.
5120 The additional ops used to create and unwind the dynamic scope will
5121 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5122 instead if the ops are simple enough to not need the full dynamic scope
5123 structure.
5124
5125 =cut
5126 */
5127
5128 OP *
5129 Perl_op_scope(pTHX_ OP *o)
5130 {
5131     dVAR;
5132     if (o) {
5133         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5134             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
5135             OpTYPE_set(o, OP_LEAVE);
5136         }
5137         else if (o->op_type == OP_LINESEQ) {
5138             OP *kid;
5139             OpTYPE_set(o, OP_SCOPE);
5140             kid = ((LISTOP*)o)->op_first;
5141             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5142                 op_null(kid);
5143
5144                 /* The following deals with things like 'do {1 for 1}' */
5145                 kid = OpSIBLING(kid);
5146                 if (kid &&
5147                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5148                     op_null(kid);
5149             }
5150         }
5151         else
5152             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5153     }
5154     return o;
5155 }
5156
5157 OP *
5158 Perl_op_unscope(pTHX_ OP *o)
5159 {
5160     if (o && o->op_type == OP_LINESEQ) {
5161         OP *kid = cLISTOPo->op_first;
5162         for(; kid; kid = OpSIBLING(kid))
5163             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5164                 op_null(kid);
5165     }
5166     return o;
5167 }
5168
5169 /*
5170 =for apidoc Am|int|block_start|int full
5171
5172 Handles compile-time scope entry.
5173 Arranges for hints to be restored on block
5174 exit and also handles pad sequence numbers to make lexical variables scope
5175 right.  Returns a savestack index for use with C<block_end>.
5176
5177 =cut
5178 */
5179
5180 int
5181 Perl_block_start(pTHX_ int full)
5182 {
5183     const int retval = PL_savestack_ix;
5184
5185     PL_compiling.cop_seq = PL_cop_seqmax;
5186     COP_SEQMAX_INC;
5187     pad_block_start(full);
5188     SAVEHINTS();
5189     PL_hints &= ~HINT_BLOCK_SCOPE;
5190     SAVECOMPILEWARNINGS();
5191     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5192     SAVEI32(PL_compiling.cop_seq);
5193     PL_compiling.cop_seq = 0;
5194
5195     CALL_BLOCK_HOOKS(bhk_start, full);
5196
5197     return retval;
5198 }
5199
5200 /*
5201 =for apidoc Am|OP *|block_end|I32 floor|OP *seq
5202
5203 Handles compile-time scope exit.  C<floor>
5204 is the savestack index returned by
5205 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5206 possibly modified.
5207
5208 =cut
5209 */
5210
5211 OP*
5212 Perl_block_end(pTHX_ I32 floor, OP *seq)
5213 {
5214     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5215     OP* retval = scalarseq(seq);
5216     OP *o;
5217
5218     /* XXX Is the null PL_parser check necessary here? */
5219     assert(PL_parser); /* Let’s find out under debugging builds.  */
5220     if (PL_parser && PL_parser->parsed_sub) {
5221         o = newSTATEOP(0, NULL, NULL);
5222         op_null(o);
5223         retval = op_append_elem(OP_LINESEQ, retval, o);
5224     }
5225
5226     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5227
5228     LEAVE_SCOPE(floor);
5229     if (needblockscope)
5230         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5231     o = pad_leavemy();
5232
5233     if (o) {
5234         /* pad_leavemy has created a sequence of introcv ops for all my
5235            subs declared in the block.  We have to replicate that list with
5236            clonecv ops, to deal with this situation:
5237
5238                sub {
5239                    my sub s1;
5240                    my sub s2;
5241                    sub s1 { state sub foo { \&s2 } }
5242                }->()
5243
5244            Originally, I was going to have introcv clone the CV and turn
5245            off the stale flag.  Since &s1 is declared before &s2, the
5246            introcv op for &s1 is executed (on sub entry) before the one for
5247            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5248            cloned, since it is a state sub) closes over &s2 and expects
5249            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5250            then &s2 is still marked stale.  Since &s1 is not active, and
5251            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5252            ble will not stay shared’ warning.  Because it is the same stub
5253            that will be used when the introcv op for &s2 is executed, clos-
5254            ing over it is safe.  Hence, we have to turn off the stale flag
5255            on all lexical subs in the block before we clone any of them.
5256            Hence, having introcv clone the sub cannot work.  So we create a
5257            list of ops like this:
5258
5259                lineseq
5260                   |
5261                   +-- introcv
5262                   |
5263                   +-- introcv
5264                   |
5265                   +-- introcv
5266                   |
5267                   .
5268                   .
5269                   .
5270                   |
5271                   +-- clonecv
5272                   |
5273                   +-- clonecv
5274                   |
5275                   +-- clonecv
5276                   |
5277                   .
5278                   .
5279                   .
5280          */
5281         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5282         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5283         for (;; kid = OpSIBLING(kid)) {
5284             OP *newkid = newOP(OP_CLONECV, 0);
5285             newkid->op_targ = kid->op_targ;
5286             o = op_append_elem(OP_LINESEQ, o, newkid);
5287             if (kid == last) break;
5288         }
5289         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5290     }
5291
5292     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5293
5294     return retval;
5295 }
5296
5297 /*
5298 =head1 Compile-time scope hooks
5299
5300 =for apidoc Aox||blockhook_register
5301
5302 Register a set of hooks to be called when the Perl lexical scope changes
5303 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5304
5305 =cut
5306 */
5307
5308 void
5309 Perl_blockhook_register(pTHX_ BHK *hk)
5310 {
5311     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5312
5313     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5314 }
5315
5316 void
5317 Perl_newPROG(pTHX_ OP *o)
5318 {
5319     OP *start;
5320
5321     PERL_ARGS_ASSERT_NEWPROG;
5322
5323     if (PL_in_eval) {
5324         PERL_CONTEXT *cx;
5325         I32 i;
5326         if (PL_eval_root)
5327                 return;
5328         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5329                                ((PL_in_eval & EVAL_KEEPERR)
5330                                 ? OPf_SPECIAL : 0), o);
5331
5332         cx = CX_CUR();
5333         assert(CxTYPE(cx) == CXt_EVAL);
5334
5335         if ((cx->blk_gimme & G_WANT) == G_VOID)
5336             scalarvoid(PL_eval_root);
5337         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
5338             list(PL_eval_root);
5339         else
5340             scalar(PL_eval_root);
5341
5342         start = op_linklist(PL_eval_root);
5343         PL_eval_root->op_next = 0;
5344         i = PL_savestack_ix;
5345         SAVEFREEOP(o);
5346         ENTER;
5347         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5348         LEAVE;
5349         PL_savestack_ix = i;
5350     }
5351     else {
5352         if (o->op_type == OP_STUB) {
5353             /* This block is entered if nothing is compiled for the main
5354                program. This will be the case for an genuinely empty main
5355                program, or one which only has BEGIN blocks etc, so already
5356                run and freed.
5357
5358                Historically (5.000) the guard above was !o. However, commit
5359                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5360                c71fccf11fde0068, changed perly.y so that newPROG() is now
5361                called with the output of block_end(), which returns a new
5362                OP_STUB for the case of an empty optree. ByteLoader (and
5363                maybe other things) also take this path, because they set up
5364                PL_main_start and PL_main_root directly, without generating an
5365                optree.
5366
5367                If the parsing the main program aborts (due to parse errors,
5368                or due to BEGIN or similar calling exit), then newPROG()
5369                isn't even called, and hence this code path and its cleanups
5370                are skipped. This shouldn't make a make a difference:
5371                * a non-zero return from perl_parse is a failure, and
5372                  perl_destruct() should be called immediately.
5373                * however, if exit(0) is called during the parse, then
5374                  perl_parse() returns 0, and perl_run() is called. As
5375                  PL_main_start will be NULL, perl_run() will return
5376                  promptly, and the exit code will remain 0.
5377             */
5378
5379             PL_comppad_name = 0;
5380             PL_compcv = 0;
5381             S_op_destroy(aTHX_ o);
5382             return;
5383         }
5384         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5385         PL_curcop = &PL_compiling;
5386         start = LINKLIST(PL_main_root);
5387         PL_main_root->op_next = 0;
5388         S_process_optree(aTHX_ NULL, PL_main_root, start);
5389         cv_forget_slab(PL_compcv);
5390         PL_compcv = 0;
5391
5392         /* Register with debugger */
5393         if (PERLDB_INTER) {
5394             CV * const cv = get_cvs("DB::postponed", 0);
5395             if (cv) {
5396                 dSP;
5397                 PUSHMARK(SP);
5398                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
5399                 PUTBACK;
5400                 call_sv(MUTABLE_SV(cv), G_DISCARD);
5401             }
5402         }
5403     }
5404 }
5405
5406 OP *
5407 Perl_localize(pTHX_ OP *o, I32 lex)
5408 {
5409     PERL_ARGS_ASSERT_LOCALIZE;
5410
5411     if (o->op_flags & OPf_PARENS)
5412 /* [perl #17376]: this appears to be premature, and results in code such as
5413    C< our(%x); > executing in list mode rather than void mode */
5414 #if 0
5415         list(o);
5416 #else
5417         NOOP;
5418 #endif
5419     else {
5420         if ( PL_parser->bufptr > PL_parser->oldbufptr
5421             && PL_parser->bufptr[-1] == ','
5422             && ckWARN(WARN_PARENTHESIS))
5423         {
5424             char *s = PL_parser->bufptr;
5425             bool sigil = FALSE;
5426
5427             /* some heuristics to detect a potential error */
5428             while (*s && (strchr(", \t\n", *s)))
5429                 s++;
5430
5431             while (1) {
5432                 if (*s && (strchr("@$%", *s) || (!lex && *s == '*'))
5433                        && *++s
5434                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
5435                     s++;
5436                     sigil = TRUE;
5437                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
5438                         s++;
5439                     while (*s && (strchr(", \t\n", *s)))
5440                         s++;
5441                 }
5442                 else
5443                     break;
5444             }
5445             if (sigil && (*s == ';' || *s == '=')) {
5446                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
5447                                 "Parentheses missing around \"%s\" list",
5448                                 lex
5449                                     ? (PL_parser->in_my == KEY_our
5450                                         ? "our"
5451                                         : PL_parser->in_my == KEY_state
5452                                             ? "state"
5453                                             : "my")
5454                                     : "local");
5455             }
5456         }
5457     }
5458     if (lex)
5459         o = my(o);
5460     else
5461         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
5462     PL_parser->in_my = FALSE;
5463     PL_parser->in_my_stash = NULL;
5464     return o;
5465 }
5466
5467 OP *
5468 Perl_jmaybe(pTHX_ OP *o)
5469 {
5470     PERL_ARGS_ASSERT_JMAYBE;
5471
5472     if (o->op_type == OP_LIST) {
5473         OP * const o2
5474             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
5475         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
5476     }
5477     return o;
5478 }
5479
5480 PERL_STATIC_INLINE OP *
5481 S_op_std_init(pTHX_ OP *o)
5482 {
5483     I32 type = o->op_type;
5484
5485     PERL_ARGS_ASSERT_OP_STD_INIT;
5486
5487     if (PL_opargs[type] & OA_RETSCALAR)
5488         scalar(o);
5489     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
5490         o->op_targ = pad_alloc(type, SVs_PADTMP);
5491
5492     return o;
5493 }
5494
5495 PERL_STATIC_INLINE OP *
5496 S_op_integerize(pTHX_ OP *o)
5497 {
5498     I32 type = o->op_type;
5499
5500     PERL_ARGS_ASSERT_OP_INTEGERIZE;
5501
5502     /* integerize op. */
5503     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
5504     {
5505         dVAR;
5506         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
5507     }
5508
5509     if (type == OP_NEGATE)
5510         /* XXX might want a ck_negate() for this */
5511         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
5512
5513     return o;
5514 }
5515
5516 /* This function exists solely to provide a scope to limit
5517    setjmp/longjmp() messing with auto variables.
5518  */
5519 PERL_STATIC_INLINE int
5520 S_fold_constants_eval(pTHX) {
5521     int ret = 0;
5522     dJMPENV;
5523
5524     JMPENV_PUSH(ret);
5525
5526     if (ret == 0) {
5527         CALLRUNOPS(aTHX);
5528     }
5529
5530     JMPENV_POP;
5531
5532     return ret;
5533 }
5534
5535 static OP *
5536 S_fold_constants(pTHX_ OP *const o)
5537 {
5538     dVAR;
5539     OP *curop;
5540     OP *newop;
5541     I32 type = o->op_type;
5542     bool is_stringify;
5543     SV *sv = NULL;
5544     int ret = 0;
5545     OP *old_next;
5546     SV * const oldwarnhook = PL_warnhook;
5547     SV * const olddiehook  = PL_diehook;
5548     COP not_compiling;
5549     U8 oldwarn = PL_dowarn;
5550     I32 old_cxix;
5551
5552     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
5553
5554     if (!(PL_opargs[type] & OA_FOLDCONST))
5555         goto nope;
5556
5557     switch (type) {
5558     case OP_UCFIRST:
5559     case OP_LCFIRST:
5560     case OP_UC:
5561     case OP_LC:
5562     case OP_FC:
5563 #ifdef USE_LOCALE_CTYPE
5564         if (IN_LC_COMPILETIME(LC_CTYPE))
5565             goto nope;
5566 #endif
5567         break;
5568     case OP_SLT:
5569     case OP_SGT:
5570     case OP_SLE:
5571     case OP_SGE:
5572     case OP_SCMP:
5573 #ifdef USE_LOCALE_COLLATE
5574         if (IN_LC_COMPILETIME(LC_COLLATE))
5575             goto nope;
5576 #endif
5577         break;
5578     case OP_SPRINTF:
5579         /* XXX what about the numeric ops? */
5580 #ifdef USE_LOCALE_NUMERIC
5581         if (IN_LC_COMPILETIME(LC_NUMERIC))
5582             goto nope;
5583 #endif
5584         break;
5585     case OP_PACK:
5586         if (!OpHAS_SIBLING(cLISTOPo->op_first)
5587           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
5588             goto nope;
5589         {
5590             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
5591             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
5592             {
5593                 const char *s = SvPVX_const(sv);
5594                 while (s < SvEND(sv)) {
5595                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
5596                     s++;
5597                 }
5598             }
5599         }
5600         break;
5601     case OP_REPEAT:
5602         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
5603         break;
5604     case OP_SREFGEN:
5605         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
5606          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
5607             goto nope;
5608     }
5609
5610     if (PL_parser && PL_parser->error_count)
5611         goto nope;              /* Don't try to run w/ errors */
5612
5613     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
5614         switch (curop->op_type) {
5615         case OP_CONST:
5616             if (   (curop->op_private & OPpCONST_BARE)
5617                 && (curop->op_private & OPpCONST_STRICT)) {
5618                 no_bareword_allowed(curop);
5619                 goto nope;
5620             }
5621             /* FALLTHROUGH */
5622         case OP_LIST:
5623         case OP_SCALAR:
5624         case OP_NULL:
5625         case OP_PUSHMARK:
5626             /* Foldable; move to next op in list */
5627             break;
5628
5629         default:
5630             /* No other op types are considered foldable */
5631             goto nope;
5632         }
5633     }
5634
5635     curop = LINKLIST(o);
5636     old_next = o->op_next;
5637     o->op_next = 0;
5638     PL_op = curop;
5639
5640     old_cxix = cxstack_ix;
5641     create_eval_scope(NULL, G_FAKINGEVAL);
5642
5643     /* Verify that we don't need to save it:  */
5644     assert(PL_curcop == &PL_compiling);
5645     StructCopy(&PL_compiling, &not_compiling, COP);
5646     PL_curcop = &not_compiling;
5647     /* The above ensures that we run with all the correct hints of the
5648        currently compiling COP, but that IN_PERL_RUNTIME is true. */
5649     assert(IN_PERL_RUNTIME);
5650     PL_warnhook = PERL_WARNHOOK_FATAL;
5651     PL_diehook  = NULL;
5652
5653     /* Effective $^W=1.  */
5654     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
5655         PL_dowarn |= G_WARN_ON;
5656
5657     ret = S_fold_constants_eval(aTHX);
5658
5659     switch (ret) {
5660     case 0:
5661         sv = *(PL_stack_sp--);
5662         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
5663             pad_swipe(o->op_targ,  FALSE);
5664         }
5665         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
5666             SvREFCNT_inc_simple_void(sv);
5667             SvTEMP_off(sv);
5668         }
5669         else { assert(SvIMMORTAL(sv)); }
5670         break;
5671     case 3:
5672         /* Something tried to die.  Abandon constant folding.  */
5673         /* Pretend the error never happened.  */
5674         CLEAR_ERRSV();
5675         o->op_next = old_next;
5676         break;
5677     default:
5678         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
5679         PL_warnhook = oldwarnhook;
5680         PL_diehook  = olddiehook;
5681         /* XXX note that this croak may fail as we've already blown away
5682          * the stack - eg any nested evals */
5683         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
5684     }
5685     PL_dowarn   = oldwarn;
5686     PL_warnhook = oldwarnhook;
5687     PL_diehook  = olddiehook;
5688     PL_curcop = &PL_compiling;
5689
5690     /* if we croaked, depending on how we croaked the eval scope
5691      * may or may not have already been popped */
5692     if (cxstack_ix > old_cxix) {
5693         assert(cxstack_ix == old_cxix + 1);
5694         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
5695         delete_eval_scope();
5696     }
5697     if (ret)
5698         goto nope;
5699
5700     /* OP_STRINGIFY and constant folding are used to implement qq.
5701        Here the constant folding is an implementation detail that we
5702        want to hide.  If the stringify op is itself already marked
5703        folded, however, then it is actually a folded join.  */
5704     is_stringify = type == OP_STRINGIFY && !o->op_folded;
5705     op_free(o);
5706     assert(sv);
5707     if (is_stringify)
5708         SvPADTMP_off(sv);
5709     else if (!SvIMMORTAL(sv)) {
5710         SvPADTMP_on(sv);
5711         SvREADONLY_on(sv);
5712     }
5713     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
5714     if (!is_stringify) newop->op_folded = 1;
5715     return newop;
5716
5717  nope:
5718     return o;
5719 }
5720
5721 static OP *
5722 S_gen_constant_list(pTHX_ OP *o)
5723 {
5724     dVAR;
5725     OP *curop, *old_next;
5726     SV * const oldwarnhook = PL_warnhook;
5727     SV * const olddiehook  = PL_diehook;
5728     COP *old_curcop;
5729     U8 oldwarn = PL_dowarn;
5730     SV **svp;
5731     AV *av;
5732     I32 old_cxix;
5733     COP not_compiling;
5734     int ret = 0;
5735     dJMPENV;
5736     bool op_was_null;
5737
5738     list(o);
5739     if (PL_parser && PL_parser->error_count)
5740         return o;               /* Don't attempt to run with errors */
5741
5742     curop = LINKLIST(o);
5743     old_next = o->op_next;
5744     o->op_next = 0;
5745     op_was_null = o->op_type == OP_NULL;
5746     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
5747         o->op_type = OP_CUSTOM;
5748     CALL_PEEP(curop);
5749     if (op_was_null)
5750         o->op_type = OP_NULL;
5751     S_prune_chain_head(&curop);
5752     PL_op = curop;
5753
5754     old_cxix = cxstack_ix;
5755     create_eval_scope(NULL, G_FAKINGEVAL);
5756
5757     old_curcop = PL_curcop;
5758     StructCopy(old_curcop, &not_compiling, COP);
5759     PL_curcop = &not_compiling;
5760     /* The above ensures that we run with all the correct hints of the
5761        current COP, but that IN_PERL_RUNTIME is true. */
5762     assert(IN_PERL_RUNTIME);
5763     PL_warnhook = PERL_WARNHOOK_FATAL;
5764     PL_diehook  = NULL;
5765     JMPENV_PUSH(ret);
5766
5767     /* Effective $^W=1.  */
5768     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
5769         PL_dowarn |= G_WARN_ON;
5770
5771     switch (ret) {
5772     case 0:
5773 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
5774         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
5775 #endif
5776         Perl_pp_pushmark(aTHX);
5777         CALLRUNOPS(aTHX);
5778         PL_op = curop;
5779         assert (!(curop->op_flags & OPf_SPECIAL));
5780         assert(curop->op_type == OP_RANGE);
5781         Perl_pp_anonlist(aTHX);
5782         break;
5783     case 3:
5784         CLEAR_ERRSV();
5785         o->op_next = old_next;
5786         break;
5787     default:
5788         JMPENV_POP;
5789         PL_warnhook = oldwarnhook;
5790         PL_diehook = olddiehook;
5791         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
5792             ret);
5793     }
5794
5795     JMPENV_POP;
5796     PL_dowarn = oldwarn;
5797     PL_warnhook = oldwarnhook;
5798     PL_diehook = olddiehook;
5799     PL_curcop = old_curcop;
5800
5801     if (cxstack_ix > old_cxix) {
5802         assert(cxstack_ix == old_cxix + 1);
5803         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
5804         delete_eval_scope();
5805     }
5806     if (ret)
5807         return o;
5808
5809     OpTYPE_set(o, OP_RV2AV);
5810     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
5811     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
5812     o->op_opt = 0;              /* needs to be revisited in rpeep() */
5813     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
5814
5815     /* replace subtree with an OP_CONST */
5816     curop = ((UNOP*)o)->op_first;
5817     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
5818     op_free(curop);
5819
5820     if (AvFILLp(av) != -1)
5821         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
5822         {
5823             SvPADTMP_on(*svp);
5824             SvREADONLY_on(*svp);
5825         }
5826     LINKLIST(o);
5827     return list(o);
5828 }
5829
5830 /*
5831 =head1 Optree Manipulation Functions
5832 */
5833
5834 /* List constructors */
5835
5836 /*
5837 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
5838
5839 Append an item to the list of ops contained directly within a list-type
5840 op, returning the lengthened list.  C<first> is the list-type op,
5841 and C<last> is the op to append to the list.  C<optype> specifies the
5842 intended opcode for the list.  If C<first> is not already a list of the
5843 right type, it will be upgraded into one.  If either C<first> or C<last>
5844 is null, the other is returned unchanged.
5845
5846 =cut
5847 */
5848
5849 OP *
5850 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
5851 {
5852     if (!first)
5853         return last;
5854
5855     if (!last)
5856         return first;
5857
5858     if (first->op_type != (unsigned)type
5859         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
5860     {
5861         return newLISTOP(type, 0, first, last);
5862     }
5863
5864     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
5865     first->op_flags |= OPf_KIDS;
5866     return first;
5867 }
5868
5869 /*
5870 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
5871
5872 Concatenate the lists of ops contained directly within two list-type ops,
5873 returning the combined list.  C<first> and C<last> are the list-type ops
5874 to concatenate.  C<optype> specifies the intended opcode for the list.
5875 If either C<first> or C<last> is not already a list of the right type,
5876 it will be upgraded into one.  If either C<first> or C<last> is null,
5877 the other is returned unchanged.
5878
5879 =cut
5880 */
5881
5882 OP *
5883 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
5884 {
5885     if (!first)
5886         return last;
5887
5888     if (!last)
5889         return first;
5890
5891     if (first->op_type != (unsigned)type)
5892         return op_prepend_elem(type, first, last);
5893
5894     if (last->op_type != (unsigned)type)
5895         return op_append_elem(type, first, last);
5896
5897     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
5898     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
5899     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
5900     first->op_flags |= (last->op_flags & OPf_KIDS);
5901
5902     S_op_destroy(aTHX_ last);
5903
5904     return first;
5905 }
5906
5907 /*
5908 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
5909
5910 Prepend an item to the list of ops contained directly within a list-type
5911 op, returning the lengthened list.  C<first> is the op to prepend to the
5912 list, and C<last> is the list-type op.  C<optype> specifies the intended
5913 opcode for the list.  If C<last> is not already a list of the right type,
5914 it will be upgraded into one.  If either C<first> or C<last> is null,
5915 the other is returned unchanged.
5916
5917 =cut
5918 */
5919
5920 OP *
5921 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
5922 {
5923     if (!first)
5924         return last;
5925
5926     if (!last)
5927         return first;
5928
5929     if (last->op_type == (unsigned)type) {
5930         if (type == OP_LIST) {  /* already a PUSHMARK there */
5931             /* insert 'first' after pushmark */
5932             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
5933             if (!(first->op_flags & OPf_PARENS))
5934                 last->op_flags &= ~OPf_PARENS;
5935         }
5936         else
5937             op_sibling_splice(last, NULL, 0, first);
5938         last->op_flags |= OPf_KIDS;
5939         return last;
5940     }
5941
5942     return newLISTOP(type, 0, first, last);
5943 }
5944
5945 /*
5946 =for apidoc Am|OP *|op_convert_list|I32 type|I32 flags|OP *o
5947
5948 Converts C<o> into a list op if it is not one already, and then converts it
5949 into the specified C<type>, calling its check function, allocating a target if
5950 it needs one, and folding constants.
5951
5952 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
5953 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
5954 C<op_convert_list> to make it the right type.
5955
5956 =cut
5957 */
5958
5959 OP *
5960 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
5961 {
5962     dVAR;
5963     if (type < 0) type = -type, flags |= OPf_SPECIAL;
5964     if (!o || o->op_type != OP_LIST)
5965         o = force_list(o, 0);
5966     else
5967     {
5968         o->op_flags &= ~OPf_WANT;
5969         o->op_private &= ~OPpLVAL_INTRO;
5970     }
5971
5972     if (!(PL_opargs[type] & OA_MARK))
5973         op_null(cLISTOPo->op_first);
5974     else {
5975         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
5976         if (kid2 && kid2->op_type == OP_COREARGS) {
5977             op_null(cLISTOPo->op_first);
5978             kid2->op_private |= OPpCOREARGS_PUSHMARK;
5979         }
5980     }
5981
5982     if (type != OP_SPLIT)
5983         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
5984          * ck_split() create a real PMOP and leave the op's type as listop
5985          * for now. Otherwise op_free() etc will crash.
5986          */
5987         OpTYPE_set(o, type);
5988
5989     o->op_flags |= flags;
5990     if (flags & OPf_FOLDED)
5991         o->op_folded = 1;
5992
5993     o = CHECKOP(type, o);
5994     if (o->op_type != (unsigned)type)
5995         return o;
5996
5997     return fold_constants(op_integerize(op_std_init(o)));
5998 }
5999
6000 /* Constructors */
6001
6002
6003 /*
6004 =head1 Optree construction
6005
6006 =for apidoc Am|OP *|newNULLLIST
6007
6008 Constructs, checks, and returns a new C<stub> op, which represents an
6009 empty list expression.
6010
6011 =cut
6012 */
6013
6014 OP *
6015 Perl_newNULLLIST(pTHX)
6016 {
6017     return newOP(OP_STUB, 0);
6018 }
6019
6020 /* promote o and any siblings to be a list if its not already; i.e.
6021  *
6022  *  o - A - B
6023  *
6024  * becomes
6025  *
6026  *  list
6027  *    |
6028  *  pushmark - o - A - B
6029  *
6030  * If nullit it true, the list op is nulled.
6031  */
6032
6033 static OP *
6034 S_force_list(pTHX_ OP *o, bool nullit)
6035 {
6036     if (!o || o->op_type != OP_LIST) {
6037         OP *rest = NULL;
6038         if (o) {
6039             /* manually detach any siblings then add them back later */
6040             rest = OpSIBLING(o);
6041             OpLASTSIB_set(o, NULL);
6042         }
6043         o = newLISTOP(OP_LIST, 0, o, NULL);
6044         if (rest)
6045             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6046     }
6047     if (nullit)
6048         op_null(o);
6049     return o;
6050 }
6051
6052 /*
6053 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
6054
6055 Constructs, checks, and returns an op of any list type.  C<type> is
6056 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6057 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6058 supply up to two ops to be direct children of the list op; they are
6059 consumed by this function and become part of the constructed op tree.
6060
6061 For most list operators, the check function expects all the kid ops to be
6062 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6063 appropriate.  What you want to do in that case is create an op of type
6064 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6065 See L</op_convert_list> for more information.
6066
6067
6068 =cut
6069 */
6070
6071 OP *
6072 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6073 {
6074     dVAR;
6075     LISTOP *listop;
6076
6077     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6078         || type == OP_CUSTOM);
6079
6080     NewOp(1101, listop, 1, LISTOP);
6081
6082     OpTYPE_set(listop, type);
6083     if (first || last)
6084         flags |= OPf_KIDS;
6085     listop->op_flags = (U8)flags;
6086
6087     if (!last && first)
6088         last = first;
6089     else if (!first && last)
6090         first = last;
6091     else if (first)
6092         OpMORESIB_set(first, last);
6093     listop->op_first = first;
6094     listop->op_last = last;
6095     if (type == OP_LIST) {
6096         OP* const pushop = newOP(OP_PUSHMARK, 0);
6097         OpMORESIB_set(pushop, first);
6098         listop->op_first = pushop;
6099         listop->op_flags |= OPf_KIDS;
6100         if (!last)
6101             listop->op_last = pushop;
6102     }
6103     if (listop->op_last)
6104         OpLASTSIB_set(listop->op_last, (OP*)listop);
6105
6106     return CHECKOP(type, listop);
6107 }
6108
6109 /*
6110 =for apidoc Am|OP *|newOP|I32 type|I32 flags
6111
6112 Constructs, checks, and returns an op of any base type (any type that
6113 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6114 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6115 of C<op_private>.
6116
6117 =cut
6118 */
6119
6120 OP *
6121 Perl_newOP(pTHX_ I32 type, I32 flags)
6122 {
6123     dVAR;
6124     OP *o;
6125
6126     if (type == -OP_ENTEREVAL) {
6127         type = OP_ENTEREVAL;
6128         flags |= OPpEVAL_BYTES<<8;
6129     }
6130
6131     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6132         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6133         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6134         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6135
6136     NewOp(1101, o, 1, OP);
6137     OpTYPE_set(o, type);
6138     o->op_flags = (U8)flags;
6139
6140     o->op_next = o;
6141     o->op_private = (U8)(0 | (flags >> 8));
6142     if (PL_opargs[type] & OA_RETSCALAR)
6143         scalar(o);
6144     if (PL_opargs[type] & OA_TARGET)
6145         o->op_targ = pad_alloc(type, SVs_PADTMP);
6146     return CHECKOP(type, o);
6147 }
6148
6149 /*
6150 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
6151
6152 Constructs, checks, and returns an op of any unary type.  C<type> is
6153 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6154 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6155 bits, the eight bits of C<op_private>, except that the bit with value 1
6156 is automatically set.  C<first> supplies an optional op to be the direct
6157 child of the unary op; it is consumed by this function and become part
6158 of the constructed op tree.
6159
6160 =cut
6161 */
6162
6163 OP *
6164 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6165 {
6166     dVAR;
6167     UNOP *unop;
6168
6169     if (type == -OP_ENTEREVAL) {
6170         type = OP_ENTEREVAL;
6171         flags |= OPpEVAL_BYTES<<8;
6172     }
6173
6174     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6175         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6176         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6177         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6178         || type == OP_SASSIGN
6179         || type == OP_ENTERTRY
6180         || type == OP_CUSTOM
6181         || type == OP_NULL );
6182
6183     if (!first)
6184         first = newOP(OP_STUB, 0);
6185     if (PL_opargs[type] & OA_MARK)
6186         first = force_list(first, 1);
6187
6188     NewOp(1101, unop, 1, UNOP);
6189     OpTYPE_set(unop, type);
6190     unop->op_first = first;
6191     unop->op_flags = (U8)(flags | OPf_KIDS);
6192     unop->op_private = (U8)(1 | (flags >> 8));
6193
6194     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6195         OpLASTSIB_set(first, (OP*)unop);
6196
6197     unop = (UNOP*) CHECKOP(type, unop);
6198     if (unop->op_next)
6199         return (OP*)unop;
6200
6201     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6202 }
6203
6204 /*
6205 =for apidoc newUNOP_AUX
6206
6207 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6208 initialised to C<aux>
6209
6210 =cut
6211 */
6212
6213 OP *
6214 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6215 {
6216     dVAR;
6217     UNOP_AUX *unop;
6218
6219     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6220         || type == OP_CUSTOM);
6221
6222     NewOp(1101, unop, 1, UNOP_AUX);
6223     unop->op_type = (OPCODE)type;
6224     unop->op_ppaddr = PL_ppaddr[type];
6225     unop->op_first = first;
6226     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6227     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6228     unop->op_aux = aux;
6229
6230     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6231         OpLASTSIB_set(first, (OP*)unop);
6232
6233     unop = (UNOP_AUX*) CHECKOP(type, unop);
6234
6235     return op_std_init((OP *) unop);
6236 }
6237
6238 /*
6239 =for apidoc Am|OP *|newMETHOP|I32 type|I32 flags|OP *first
6240
6241 Constructs, checks, and returns an op of method type with a method name
6242 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6243 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6244 and, shifted up eight bits, the eight bits of C<op_private>, except that
6245 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6246 op which evaluates method name; it is consumed by this function and
6247 become part of the constructed op tree.
6248 Supported optypes: C<OP_METHOD>.
6249
6250 =cut
6251 */
6252
6253 static OP*
6254 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6255     dVAR;
6256     METHOP *methop;
6257
6258     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6259         || type == OP_CUSTOM);
6260
6261     NewOp(1101, methop, 1, METHOP);
6262     if (dynamic_meth) {
6263         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
6264         methop->op_flags = (U8)(flags | OPf_KIDS);
6265         methop->op_u.op_first = dynamic_meth;
6266         methop->op_private = (U8)(1 | (flags >> 8));
6267
6268         if (!OpHAS_SIBLING(dynamic_meth))
6269             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6270     }
6271     else {
6272         assert(const_meth);
6273         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6274         methop->op_u.op_meth_sv = const_meth;
6275         methop->op_private = (U8)(0 | (flags >> 8));
6276         methop->op_next = (OP*)methop;
6277     }
6278
6279 #ifdef USE_ITHREADS
6280     methop->op_rclass_targ = 0;
6281 #else
6282     methop->op_rclass_sv = NULL;
6283 #endif
6284
6285     OpTYPE_set(methop, type);
6286     return CHECKOP(type, methop);
6287 }
6288
6289 OP *
6290 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6291     PERL_ARGS_ASSERT_NEWMETHOP;
6292     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6293 }
6294
6295 /*
6296 =for apidoc Am|OP *|newMETHOP_named|I32 type|I32 flags|SV *const_meth
6297
6298 Constructs, checks, and returns an op of method type with a constant
6299 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6300 C<op_flags>, and, shifted up eight bits, the eight bits of
6301 C<op_private>.  C<const_meth> supplies a constant method name;
6302 it must be a shared COW string.
6303 Supported optypes: C<OP_METHOD_NAMED>.
6304
6305 =cut
6306 */
6307
6308 OP *
6309 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6310     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6311     return newMETHOP_internal(type, flags, NULL, const_meth);
6312 }
6313
6314 /*
6315 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
6316
6317 Constructs, checks, and returns an op of any binary type.  C<type>
6318 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6319 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6320 the eight bits of C<op_private>, except that the bit with value 1 or
6321 2 is automatically set as required.  C<first> and C<last> supply up to
6322 two ops to be the direct children of the binary op; they are consumed
6323 by this function and become part of the constructed op tree.
6324
6325 =cut
6326 */
6327
6328 OP *
6329 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6330 {
6331     dVAR;
6332     BINOP *binop;
6333
6334     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6335         || type == OP_NULL || type == OP_CUSTOM);
6336
6337     NewOp(1101, binop, 1, BINOP);
6338
6339     if (!first)
6340         first = newOP(OP_NULL, 0);
6341
6342     OpTYPE_set(binop, type);
6343     binop->op_first = first;
6344     binop->op_flags = (U8)(flags | OPf_KIDS);
6345     if (!last) {
6346         last = first;
6347         binop->op_private = (U8)(1 | (flags >> 8));
6348     }
6349     else {
6350         binop->op_private = (U8)(2 | (flags >> 8));
6351         OpMORESIB_set(first, last);
6352     }
6353
6354     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6355         OpLASTSIB_set(last, (OP*)binop);
6356
6357     binop->op_last = OpSIBLING(binop->op_first);
6358     if (binop->op_last)
6359         OpLASTSIB_set(binop->op_last, (OP*)binop);
6360
6361     binop = (BINOP*)CHECKOP(type, binop);
6362     if (binop->op_next || binop->op_type != (OPCODE)type)
6363         return (OP*)binop;
6364
6365     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6366 }
6367
6368 /* Helper function for S_pmtrans(): comparison function to sort an array
6369  * of codepoint range pairs. Sorts by start point, or if equal, by end
6370  * point */
6371
6372 static int uvcompare(const void *a, const void *b)
6373     __attribute__nonnull__(1)
6374     __attribute__nonnull__(2)
6375     __attribute__pure__;
6376 static int uvcompare(const void *a, const void *b)
6377 {
6378     if (*((const UV *)a) < (*(const UV *)b))
6379         return -1;
6380     if (*((const UV *)a) > (*(const UV *)b))
6381         return 1;
6382     if (*((const UV *)a+1) < (*(const UV *)b+1))
6383         return -1;
6384     if (*((const UV *)a+1) > (*(const UV *)b+1))
6385         return 1;
6386     return 0;
6387 }
6388
6389 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
6390  * containing the search and replacement strings, assemble into
6391  * a translation table attached as o->op_pv.
6392  * Free expr and repl.
6393  * It expects the toker to have already set the
6394  *   OPpTRANS_COMPLEMENT
6395  *   OPpTRANS_SQUASH
6396  *   OPpTRANS_DELETE
6397  * flags as appropriate; this function may add
6398  *   OPpTRANS_FROM_UTF
6399  *   OPpTRANS_TO_UTF
6400  *   OPpTRANS_IDENTICAL
6401  *   OPpTRANS_GROWS
6402  * flags
6403  */
6404
6405 static OP *
6406 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
6407 {
6408     SV * const tstr = ((SVOP*)expr)->op_sv;
6409     SV * const rstr = ((SVOP*)repl)->op_sv;
6410     STRLEN tlen;
6411     STRLEN rlen;
6412     const U8 *t = (U8*)SvPV_const(tstr, tlen);
6413     const U8 *r = (U8*)SvPV_const(rstr, rlen);
6414     Size_t i, j;
6415     bool grows = FALSE;
6416     OPtrans_map *tbl;
6417     SSize_t struct_size; /* malloced size of table struct */
6418
6419     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
6420     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
6421     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
6422     SV* swash;
6423
6424     PERL_ARGS_ASSERT_PMTRANS;
6425
6426     PL_hints |= HINT_BLOCK_SCOPE;
6427
6428     if (SvUTF8(tstr))
6429         o->op_private |= OPpTRANS_FROM_UTF;
6430
6431     if (SvUTF8(rstr))
6432         o->op_private |= OPpTRANS_TO_UTF;
6433
6434     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
6435
6436         /* for utf8 translations, op_sv will be set to point to a swash
6437          * containing codepoint ranges. This is done by first assembling
6438          * a textual representation of the ranges in listsv then compiling
6439          * it using swash_init(). For more details of the textual format,
6440          * see L<perlunicode.pod/"User-Defined Character Properties"> .
6441          */
6442
6443         SV* const listsv = newSVpvs("# comment\n");
6444         SV* transv = NULL;
6445         const U8* tend = t + tlen;
6446         const U8* rend = r + rlen;
6447         STRLEN ulen;
6448         UV tfirst = 1;
6449         UV tlast = 0;
6450         IV tdiff;
6451         STRLEN tcount = 0;
6452         UV rfirst = 1;
6453         UV rlast = 0;
6454         IV rdiff;
6455         STRLEN rcount = 0;
6456         IV diff;
6457         I32 none = 0;
6458         U32 max = 0;
6459         I32 bits;
6460         I32 havefinal = 0;
6461         U32 final = 0;
6462         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
6463         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
6464         U8* tsave = NULL;
6465         U8* rsave = NULL;
6466         const U32 flags = UTF8_ALLOW_DEFAULT;
6467
6468         if (!from_utf) {
6469             STRLEN len = tlen;
6470             t = tsave = bytes_to_utf8(t, &len);
6471             tend = t + len;
6472         }
6473         if (!to_utf && rlen) {
6474             STRLEN len = rlen;
6475             r = rsave = bytes_to_utf8(r, &len);
6476             rend = r + len;
6477         }
6478
6479 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
6480  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
6481  * odd.  */
6482
6483         if (complement) {
6484             /* utf8 and /c:
6485              * replace t/tlen/tend with a version that has the ranges
6486              * complemented
6487              */
6488             U8 tmpbuf[UTF8_MAXBYTES+1];
6489             UV *cp;
6490             UV nextmin = 0;
6491             Newx(cp, 2*tlen, UV);
6492             i = 0;
6493             transv = newSVpvs("");
6494
6495             /* convert search string into array of (start,end) range
6496              * codepoint pairs stored in cp[]. Most "ranges" will start
6497              * and end at the same char */
6498             while (t < tend) {
6499                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
6500                 t += ulen;
6501                 /* the toker converts X-Y into (X, ILLEGAL_UTF8_BYTE, Y) */
6502                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
6503                     t++;
6504                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
6505                     t += ulen;
6506                 }
6507                 else {
6508                  cp[2*i+1] = cp[2*i];
6509                 }
6510                 i++;
6511             }
6512
6513             /* sort the ranges */
6514             qsort(cp, i, 2*sizeof(UV), uvcompare);
6515
6516             /* Create a utf8 string containing the complement of the
6517              * codepoint ranges. For example if cp[] contains [A,B], [C,D],
6518              * then transv will contain the equivalent of:
6519              * join '', map chr, 0,     ILLEGAL_UTF8_BYTE, A - 1,
6520              *                   B + 1, ILLEGAL_UTF8_BYTE, C - 1,
6521              *                   D + 1, ILLEGAL_UTF8_BYTE, 0x7fffffff;
6522              * A range of a single char skips the ILLEGAL_UTF8_BYTE and
6523              * end cp.
6524              */
6525             for (j = 0; j < i; j++) {
6526                 UV  val = cp[2*j];
6527                 diff = val - nextmin;
6528                 if (diff > 0) {
6529                     t = uvchr_to_utf8(tmpbuf,nextmin);
6530                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6531                     if (diff > 1) {
6532                         U8  range_mark = ILLEGAL_UTF8_BYTE;
6533                         t = uvchr_to_utf8(tmpbuf, val - 1);
6534                         sv_catpvn(transv, (char *)&range_mark, 1);
6535                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6536                     }
6537                 }
6538                 val = cp[2*j+1];
6539                 if (val >= nextmin)
6540                     nextmin = val + 1;
6541             }
6542
6543             t = uvchr_to_utf8(tmpbuf,nextmin);
6544             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6545             {
6546                 U8 range_mark = ILLEGAL_UTF8_BYTE;
6547                 sv_catpvn(transv, (char *)&range_mark, 1);
6548             }
6549             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
6550             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6551             t = (const U8*)SvPVX_const(transv);
6552             tlen = SvCUR(transv);
6553             tend = t + tlen;
6554             Safefree(cp);
6555         }
6556         else if (!rlen && !del) {
6557             r = t; rlen = tlen; rend = tend;
6558         }
6559
6560         if (!squash) {
6561                 if ((!rlen && !del) || t == r ||
6562                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
6563                 {
6564                     o->op_private |= OPpTRANS_IDENTICAL;
6565                 }
6566         }
6567
6568         /* extract char ranges from t and r and append them to listsv */
6569
6570         while (t < tend || tfirst <= tlast) {
6571             /* see if we need more "t" chars */
6572             if (tfirst > tlast) {
6573                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
6574                 t += ulen;
6575                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
6576                     t++;
6577                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
6578                     t += ulen;
6579                 }
6580                 else
6581                     tlast = tfirst;
6582             }
6583
6584             /* now see if we need more "r" chars */
6585             if (rfirst > rlast) {
6586                 if (r < rend) {
6587                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
6588                     r += ulen;
6589                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
6590                         r++;
6591                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
6592                         r += ulen;
6593                     }
6594                     else
6595                         rlast = rfirst;
6596                 }
6597                 else {
6598                     if (!havefinal++)
6599                         final = rlast;
6600                     rfirst = rlast = 0xffffffff;
6601                 }
6602             }
6603
6604             /* now see which range will peter out first, if either. */
6605             tdiff = tlast - tfirst;
6606             rdiff = rlast - rfirst;
6607             tcount += tdiff + 1;
6608             rcount += rdiff + 1;
6609
6610             if (tdiff <= rdiff)
6611                 diff = tdiff;
6612             else
6613                 diff = rdiff;
6614
6615             if (rfirst == 0xffffffff) {
6616                 diff = tdiff;   /* oops, pretend rdiff is infinite */
6617                 if (diff > 0)
6618                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
6619                                    (long)tfirst, (long)tlast);
6620                 else
6621                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
6622             }
6623             else {
6624                 if (diff > 0)
6625                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
6626                                    (long)tfirst, (long)(tfirst + diff),
6627                                    (long)rfirst);
6628                 else
6629                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
6630                                    (long)tfirst, (long)rfirst);
6631
6632                 if (rfirst + diff > max)
6633                     max = rfirst + diff;
6634                 if (!grows)
6635                     grows = (tfirst < rfirst &&
6636                              UVCHR_SKIP(tfirst) < UVCHR_SKIP(rfirst + diff));
6637                 rfirst += diff + 1;
6638             }
6639             tfirst += diff + 1;
6640         }
6641
6642         /* compile listsv into a swash and attach to o */
6643
6644         none = ++max;
6645         if (del)
6646             ++max;
6647
6648         if (max > 0xffff)
6649             bits = 32;
6650         else if (max > 0xff)
6651             bits = 16;
6652         else
6653             bits = 8;
6654
6655         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
6656 #ifdef USE_ITHREADS
6657         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
6658         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
6659         PAD_SETSV(cPADOPo->op_padix, swash);
6660         SvPADTMP_on(swash);
6661         SvREADONLY_on(swash);
6662 #else
6663         cSVOPo->op_sv = swash;
6664 #endif
6665         SvREFCNT_dec(listsv);
6666         SvREFCNT_dec(transv);
6667
6668         if (!del && havefinal && rlen)
6669             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
6670                            newSVuv((UV)final), 0);
6671
6672         Safefree(tsave);
6673         Safefree(rsave);
6674
6675         tlen = tcount;
6676         rlen = rcount;
6677         if (r < rend)
6678             rlen++;
6679         else if (rlast == 0xffffffff)
6680             rlen = 0;
6681
6682         goto warnins;
6683     }
6684
6685     /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
6686      * table. Entries with the value -1 indicate chars not to be
6687      * translated, while -2 indicates a search char without a
6688      * corresponding replacement char under /d.
6689      *
6690      * Normally, the table has 256 slots. However, in the presence of
6691      * /c, the search charlist has an implicit \x{100}-\x{7fffffff}
6692      * added, and if there are enough replacement chars to start pairing
6693      * with the \x{100},... search chars, then a larger (> 256) table
6694      * is allocated.
6695      *
6696      * In addition, regardless of whether under /c, an extra slot at the
6697      * end is used to store the final repeating char, or -3 under an empty
6698      * replacement list, or -2 under /d; which makes the runtime code
6699      * easier.
6700      *
6701      * The toker will have already expanded char ranges in t and r.
6702      */
6703
6704     /* Initially allocate 257-slot table: 256 for basic (non /c) usage,
6705      * plus final slot for repeat/-2/-3. Later we realloc if excess > * 0.
6706      * The OPtrans_map struct already contains one slot; hence the -1.
6707      */
6708     struct_size = sizeof(OPtrans_map) + (256 - 1 + 1)*sizeof(short);
6709     tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
6710     tbl->size = 256;
6711     cPVOPo->op_pv = (char*)tbl;
6712
6713     if (complement) {
6714         Size_t excess;
6715
6716         /* in this branch, j is a count of 'consumed' (i.e. paired off
6717          * with a search char) replacement chars (so j <= rlen always)
6718          */
6719         for (i = 0; i < tlen; i++)
6720             tbl->map[t[i]] = -1;
6721
6722         for (i = 0, j = 0; i < 256; i++) {
6723             if (!tbl->map[i]) {
6724                 if (j == rlen) {
6725                     if (del)
6726                         tbl->map[i] = -2;
6727                     else if (rlen)
6728                         tbl->map[i] = r[j-1];
6729                     else
6730                         tbl->map[i] = (short)i;
6731                 }
6732                 else {
6733                     tbl->map[i] = r[j++];
6734                 }
6735                 if (   tbl->map[i] >= 0
6736                     &&  UVCHR_IS_INVARIANT((UV)i)
6737                     && !UVCHR_IS_INVARIANT((UV)(tbl->map[i]))
6738                 )
6739                     grows = TRUE;
6740             }
6741         }
6742
6743         ASSUME(j <= rlen);
6744         excess = rlen - j;
6745
6746         if (excess) {
6747             /* More replacement chars than search chars:
6748              * store excess replacement chars at end of main table.
6749              */
6750
6751             struct_size += excess;
6752             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
6753                         struct_size + excess * sizeof(short));
6754             tbl->size += excess;
6755             cPVOPo->op_pv = (char*)tbl;
6756
6757             for (i = 0; i < excess; i++)
6758                 tbl->map[i + 256] = r[j+i];
6759         }
6760         else {
6761             /* no more replacement chars than search chars */
6762             if (!rlen && !del && !squash)
6763                 o->op_private |= OPpTRANS_IDENTICAL;
6764         }
6765
6766         tbl->map[tbl->size] = del ? -2 : rlen ? r[rlen - 1] : -3;
6767     }
6768     else {
6769         if (!rlen && !del) {
6770             r = t; rlen = tlen;
6771             if (!squash)
6772                 o->op_private |= OPpTRANS_IDENTICAL;
6773         }
6774         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
6775             o->op_private |= OPpTRANS_IDENTICAL;
6776         }
6777
6778         for (i = 0; i < 256; i++)
6779             tbl->map[i] = -1;
6780         for (i = 0, j = 0; i < tlen; i++,j++) {
6781             if (j >= rlen) {
6782                 if (del) {
6783                     if (tbl->map[t[i]] == -1)
6784                         tbl->map[t[i]] = -2;
6785                     continue;
6786                 }
6787                 --j;
6788             }
6789             if (tbl->map[t[i]] == -1) {
6790                 if (     UVCHR_IS_INVARIANT(t[i])
6791                     && ! UVCHR_IS_INVARIANT(r[j]))
6792                     grows = TRUE;
6793                 tbl->map[t[i]] = r[j];
6794             }
6795         }
6796         tbl->map[tbl->size] = del ? -1 : rlen ? -1 : -3;
6797     }
6798
6799     /* both non-utf8 and utf8 code paths end up here */
6800
6801   warnins:
6802     if(del && rlen == tlen) {
6803         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
6804     } else if(rlen > tlen && !complement) {
6805         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
6806     }
6807
6808     if (grows)
6809         o->op_private |= OPpTRANS_GROWS;
6810     op_free(expr);
6811     op_free(repl);
6812
6813     return o;
6814 }
6815
6816
6817 /*
6818 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
6819
6820 Constructs, checks, and returns an op of any pattern matching type.
6821 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
6822 and, shifted up eight bits, the eight bits of C<op_private>.
6823
6824 =cut
6825 */
6826
6827 OP *
6828 Perl_newPMOP(pTHX_ I32 type, I32 flags)
6829 {
6830     dVAR;
6831     PMOP *pmop;
6832
6833     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
6834         || type == OP_CUSTOM);
6835
6836     NewOp(1101, pmop, 1, PMOP);
6837     OpTYPE_set(pmop, type);
6838     pmop->op_flags = (U8)flags;
6839     pmop->op_private = (U8)(0 | (flags >> 8));
6840     if (PL_opargs[type] & OA_RETSCALAR)
6841         scalar((OP *)pmop);
6842
6843     if (PL_hints & HINT_RE_TAINT)
6844         pmop->op_pmflags |= PMf_RETAINT;
6845 #ifdef USE_LOCALE_CTYPE
6846     if (IN_LC_COMPILETIME(LC_CTYPE)) {
6847         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
6848     }
6849     else
6850 #endif
6851          if (IN_UNI_8_BIT) {
6852         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
6853     }
6854     if (PL_hints & HINT_RE_FLAGS) {
6855         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
6856          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
6857         );
6858         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
6859         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
6860          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
6861         );
6862         if (reflags && SvOK(reflags)) {
6863             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
6864         }
6865     }
6866
6867
6868 #ifdef USE_ITHREADS
6869     assert(SvPOK(PL_regex_pad[0]));
6870     if (SvCUR(PL_regex_pad[0])) {
6871         /* Pop off the "packed" IV from the end.  */
6872         SV *const repointer_list = PL_regex_pad[0];
6873         const char *p = SvEND(repointer_list) - sizeof(IV);
6874         const IV offset = *((IV*)p);
6875
6876         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
6877
6878         SvEND_set(repointer_list, p);
6879
6880         pmop->op_pmoffset = offset;
6881         /* This slot should be free, so assert this:  */
6882         assert(PL_regex_pad[offset] == &PL_sv_undef);
6883     } else {
6884         SV * const repointer = &PL_sv_undef;
6885         av_push(PL_regex_padav, repointer);
6886         pmop->op_pmoffset = av_tindex(PL_regex_padav);
6887         PL_regex_pad = AvARRAY(PL_regex_padav);
6888     }
6889 #endif
6890
6891     return CHECKOP(type, pmop);
6892 }
6893
6894 static void
6895 S_set_haseval(pTHX)
6896 {
6897     PADOFFSET i = 1;
6898     PL_cv_has_eval = 1;
6899     /* Any pad names in scope are potentially lvalues.  */
6900     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
6901         PADNAME *pn = PAD_COMPNAME_SV(i);
6902         if (!pn || !PadnameLEN(pn))
6903             continue;
6904         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
6905             S_mark_padname_lvalue(aTHX_ pn);
6906     }
6907 }
6908
6909 /* Given some sort of match op o, and an expression expr containing a
6910  * pattern, either compile expr into a regex and attach it to o (if it's
6911  * constant), or convert expr into a runtime regcomp op sequence (if it's
6912  * not)
6913  *
6914  * Flags currently has 2 bits of meaning:
6915  * 1: isreg indicates that the pattern is part of a regex construct, eg
6916  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
6917  * split "pattern", which aren't. In the former case, expr will be a list
6918  * if the pattern contains more than one term (eg /a$b/).
6919  * 2: The pattern is for a split.
6920  *
6921  * When the pattern has been compiled within a new anon CV (for
6922  * qr/(?{...})/ ), then floor indicates the savestack level just before
6923  * the new sub was created
6924  */
6925
6926 OP *
6927 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
6928 {
6929     PMOP *pm;
6930     LOGOP *rcop;
6931     I32 repl_has_vars = 0;
6932     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
6933     bool is_compiletime;
6934     bool has_code;
6935     bool isreg    = cBOOL(flags & 1);
6936     bool is_split = cBOOL(flags & 2);
6937
6938     PERL_ARGS_ASSERT_PMRUNTIME;
6939
6940     if (is_trans) {
6941         return pmtrans(o, expr, repl);
6942     }
6943
6944     /* find whether we have any runtime or code elements;
6945      * at the same time, temporarily set the op_next of each DO block;
6946      * then when we LINKLIST, this will cause the DO blocks to be excluded
6947      * from the op_next chain (and from having LINKLIST recursively
6948      * applied to them). We fix up the DOs specially later */
6949
6950     is_compiletime = 1;
6951     has_code = 0;
6952     if (expr->op_type == OP_LIST) {
6953         OP *o;
6954         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
6955             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
6956                 has_code = 1;
6957                 assert(!o->op_next);
6958                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
6959                     assert(PL_parser && PL_parser->error_count);
6960                     /* This can happen with qr/ (?{(^{})/.  Just fake up
6961                        the op we were expecting to see, to avoid crashing
6962                        elsewhere.  */
6963                     op_sibling_splice(expr, o, 0,
6964                                       newSVOP(OP_CONST, 0, &PL_sv_no));
6965                 }
6966                 o->op_next = OpSIBLING(o);
6967             }
6968             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
6969                 is_compiletime = 0;
6970         }
6971     }
6972     else if (expr->op_type != OP_CONST)
6973         is_compiletime = 0;
6974
6975     LINKLIST(expr);
6976
6977     /* fix up DO blocks; treat each one as a separate little sub;
6978      * also, mark any arrays as LIST/REF */
6979
6980     if (expr->op_type == OP_LIST) {
6981         OP *o;
6982         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
6983
6984             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
6985                 assert( !(o->op_flags  & OPf_WANT));
6986                 /* push the array rather than its contents. The regex
6987                  * engine will retrieve and join the elements later */
6988                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
6989                 continue;
6990             }
6991
6992             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
6993                 continue;
6994             o->op_next = NULL; /* undo temporary hack from above */
6995             scalar(o);
6996             LINKLIST(o);
6997             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
6998                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
6999                 /* skip ENTER */
7000                 assert(leaveop->op_first->op_type == OP_ENTER);
7001                 assert(OpHAS_SIBLING(leaveop->op_first));
7002                 o->op_next = OpSIBLING(leaveop->op_first);
7003                 /* skip leave */
7004                 assert(leaveop->op_flags & OPf_KIDS);
7005                 assert(leaveop->op_last->op_next == (OP*)leaveop);
7006                 leaveop->op_next = NULL; /* stop on last op */
7007                 op_null((OP*)leaveop);
7008             }
7009             else {
7010                 /* skip SCOPE */
7011                 OP *scope = cLISTOPo->op_first;
7012                 assert(scope->op_type == OP_SCOPE);
7013                 assert(scope->op_flags & OPf_KIDS);
7014                 scope->op_next = NULL; /* stop on last op */
7015                 op_null(scope);
7016             }
7017
7018             /* XXX optimize_optree() must be called on o before
7019              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
7020              * currently cope with a peephole-optimised optree.
7021              * Calling optimize_optree() here ensures that condition
7022              * is met, but may mean optimize_optree() is applied
7023              * to the same optree later (where hopefully it won't do any
7024              * harm as it can't convert an op to multiconcat if it's
7025              * already been converted */
7026             optimize_optree(o);
7027
7028             /* have to peep the DOs individually as we've removed it from
7029              * the op_next chain */
7030             CALL_PEEP(o);
7031             S_prune_chain_head(&(o->op_next));
7032             if (is_compiletime)
7033                 /* runtime finalizes as part of finalizing whole tree */
7034                 finalize_optree(o);
7035         }
7036     }
7037     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
7038         assert( !(expr->op_flags  & OPf_WANT));
7039         /* push the array rather than its contents. The regex
7040          * engine will retrieve and join the elements later */
7041         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
7042     }
7043
7044     PL_hints |= HINT_BLOCK_SCOPE;
7045     pm = (PMOP*)o;
7046     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
7047
7048     if (is_compiletime) {
7049         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
7050         regexp_engine const *eng = current_re_engine();
7051
7052         if (is_split) {
7053             /* make engine handle split ' ' specially */
7054             pm->op_pmflags |= PMf_SPLIT;
7055             rx_flags |= RXf_SPLIT;
7056         }
7057
7058         /* Skip compiling if parser found an error for this pattern */
7059         if (pm->op_pmflags & PMf_HAS_ERROR) {
7060             return o;
7061         }
7062
7063         if (!has_code || !eng->op_comp) {
7064             /* compile-time simple constant pattern */
7065
7066             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
7067                 /* whoops! we guessed that a qr// had a code block, but we
7068                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
7069                  * that isn't required now. Note that we have to be pretty
7070                  * confident that nothing used that CV's pad while the
7071                  * regex was parsed, except maybe op targets for \Q etc.
7072                  * If there were any op targets, though, they should have
7073                  * been stolen by constant folding.
7074                  */
7075 #ifdef DEBUGGING
7076                 SSize_t i = 0;
7077                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
7078                 while (++i <= AvFILLp(PL_comppad)) {
7079 #  ifdef USE_PAD_RESET
7080                     /* under USE_PAD_RESET, pad swipe replaces a swiped
7081                      * folded constant with a fresh padtmp */
7082                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
7083 #  else
7084                     assert(!PL_curpad[i]);
7085 #  endif
7086                 }
7087 #endif
7088                 /* But we know that one op is using this CV's slab. */
7089                 cv_forget_slab(PL_compcv);
7090                 LEAVE_SCOPE(floor);
7091                 pm->op_pmflags &= ~PMf_HAS_CV;
7092             }
7093
7094             PM_SETRE(pm,
7095                 eng->op_comp
7096                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7097                                         rx_flags, pm->op_pmflags)
7098                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7099                                         rx_flags, pm->op_pmflags)
7100             );
7101             op_free(expr);
7102         }
7103         else {
7104             /* compile-time pattern that includes literal code blocks */
7105             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7106                         rx_flags,
7107                         (pm->op_pmflags |
7108                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
7109                     );
7110             PM_SETRE(pm, re);
7111             if (pm->op_pmflags & PMf_HAS_CV) {
7112                 CV *cv;
7113                 /* this QR op (and the anon sub we embed it in) is never
7114                  * actually executed. It's just a placeholder where we can
7115                  * squirrel away expr in op_code_list without the peephole
7116                  * optimiser etc processing it for a second time */
7117                 OP *qr = newPMOP(OP_QR, 0);
7118                 ((PMOP*)qr)->op_code_list = expr;
7119
7120                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
7121                 SvREFCNT_inc_simple_void(PL_compcv);
7122                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
7123                 ReANY(re)->qr_anoncv = cv;
7124
7125                 /* attach the anon CV to the pad so that
7126                  * pad_fixup_inner_anons() can find it */
7127                 (void)pad_add_anon(cv, o->op_type);
7128                 SvREFCNT_inc_simple_void(cv);
7129             }
7130             else {
7131                 pm->op_code_list = expr;
7132             }
7133         }
7134     }
7135     else {
7136         /* runtime pattern: build chain of regcomp etc ops */
7137         bool reglist;
7138         PADOFFSET cv_targ = 0;
7139
7140         reglist = isreg && expr->op_type == OP_LIST;
7141         if (reglist)
7142             op_null(expr);
7143
7144         if (has_code) {
7145             pm->op_code_list = expr;
7146             /* don't free op_code_list; its ops are embedded elsewhere too */
7147             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
7148         }
7149
7150         if (is_split)
7151             /* make engine handle split ' ' specially */
7152             pm->op_pmflags |= PMf_SPLIT;
7153
7154         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
7155          * to allow its op_next to be pointed past the regcomp and
7156          * preceding stacking ops;
7157          * OP_REGCRESET is there to reset taint before executing the
7158          * stacking ops */
7159         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
7160             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
7161
7162         if (pm->op_pmflags & PMf_HAS_CV) {
7163             /* we have a runtime qr with literal code. This means
7164              * that the qr// has been wrapped in a new CV, which
7165              * means that runtime consts, vars etc will have been compiled
7166              * against a new pad. So... we need to execute those ops
7167              * within the environment of the new CV. So wrap them in a call
7168              * to a new anon sub. i.e. for
7169              *
7170              *     qr/a$b(?{...})/,
7171              *
7172              * we build an anon sub that looks like
7173              *
7174              *     sub { "a", $b, '(?{...})' }
7175              *
7176              * and call it, passing the returned list to regcomp.
7177              * Or to put it another way, the list of ops that get executed
7178              * are:
7179              *
7180              *     normal              PMf_HAS_CV
7181              *     ------              -------------------
7182              *                         pushmark (for regcomp)
7183              *                         pushmark (for entersub)
7184              *                         anoncode
7185              *                         srefgen
7186              *                         entersub
7187              *     regcreset                  regcreset
7188              *     pushmark                   pushmark
7189              *     const("a")                 const("a")
7190              *     gvsv(b)                    gvsv(b)
7191              *     const("(?{...})")          const("(?{...})")
7192              *                                leavesub
7193              *     regcomp             regcomp
7194              */
7195
7196             SvREFCNT_inc_simple_void(PL_compcv);
7197             CvLVALUE_on(PL_compcv);
7198             /* these lines are just an unrolled newANONATTRSUB */
7199             expr = newSVOP(OP_ANONCODE, 0,
7200                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
7201             cv_targ = expr->op_targ;
7202             expr = newUNOP(OP_REFGEN, 0, expr);
7203
7204             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
7205         }
7206
7207         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
7208         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
7209                            | (reglist ? OPf_STACKED : 0);
7210         rcop->op_targ = cv_targ;
7211
7212         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
7213         if (PL_hints & HINT_RE_EVAL)
7214             S_set_haseval(aTHX);
7215
7216         /* establish postfix order */
7217         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
7218             LINKLIST(expr);
7219             rcop->op_next = expr;
7220             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
7221         }
7222         else {
7223             rcop->op_next = LINKLIST(expr);
7224             expr->op_next = (OP*)rcop;
7225         }
7226
7227         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
7228     }
7229
7230     if (repl) {
7231         OP *curop = repl;
7232         bool konst;
7233         /* If we are looking at s//.../e with a single statement, get past
7234            the implicit do{}. */
7235         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
7236              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
7237              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
7238          {
7239             OP *sib;
7240             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
7241             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
7242              && !OpHAS_SIBLING(sib))
7243                 curop = sib;
7244         }
7245         if (curop->op_type == OP_CONST)
7246             konst = TRUE;
7247         else if (( (curop->op_type == OP_RV2SV ||
7248                     curop->op_type == OP_RV2AV ||
7249                     curop->op_type == OP_RV2HV ||
7250                     curop->op_type == OP_RV2GV)
7251                    && cUNOPx(curop)->op_first
7252                    && cUNOPx(curop)->op_first->op_type == OP_GV )
7253                 || curop->op_type == OP_PADSV
7254                 || curop->op_type == OP_PADAV
7255                 || curop->op_type == OP_PADHV
7256                 || curop->op_type == OP_PADANY) {
7257             repl_has_vars = 1;
7258             konst = TRUE;
7259         }
7260         else konst = FALSE;
7261         if (konst
7262             && !(repl_has_vars
7263                  && (!PM_GETRE(pm)
7264                      || !RX_PRELEN(PM_GETRE(pm))
7265                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
7266         {
7267             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
7268             op_prepend_elem(o->op_type, scalar(repl), o);
7269         }
7270         else {
7271             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
7272             rcop->op_private = 1;
7273
7274             /* establish postfix order */
7275             rcop->op_next = LINKLIST(repl);
7276             repl->op_next = (OP*)rcop;
7277
7278             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
7279             assert(!(pm->op_pmflags & PMf_ONCE));
7280             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
7281             rcop->op_next = 0;
7282         }
7283     }
7284
7285     return (OP*)pm;
7286 }
7287
7288 /*
7289 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
7290
7291 Constructs, checks, and returns an op of any type that involves an
7292 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
7293 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
7294 takes ownership of one reference to it.
7295
7296 =cut
7297 */
7298
7299 OP *
7300 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
7301 {
7302     dVAR;
7303     SVOP *svop;
7304
7305     PERL_ARGS_ASSERT_NEWSVOP;
7306
7307     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
7308         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7309         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
7310         || type == OP_CUSTOM);
7311
7312     NewOp(1101, svop, 1, SVOP);
7313     OpTYPE_set(svop, type);
7314     svop->op_sv = sv;
7315     svop->op_next = (OP*)svop;
7316     svop->op_flags = (U8)flags;
7317     svop->op_private = (U8)(0 | (flags >> 8));
7318     if (PL_opargs[type] & OA_RETSCALAR)
7319         scalar((OP*)svop);
7320     if (PL_opargs[type] & OA_TARGET)
7321         svop->op_targ = pad_alloc(type, SVs_PADTMP);
7322     return CHECKOP(type, svop);
7323 }
7324
7325 /*
7326 =for apidoc Am|OP *|newDEFSVOP|
7327
7328 Constructs and returns an op to access C<$_>.
7329
7330 =cut
7331 */
7332
7333 OP *
7334 Perl_newDEFSVOP(pTHX)
7335 {
7336         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
7337 }
7338
7339 #ifdef USE_ITHREADS
7340
7341 /*
7342 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
7343
7344 Constructs, checks, and returns an op of any type that involves a
7345 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
7346 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
7347 is populated with C<sv>; this function takes ownership of one reference
7348 to it.
7349
7350 This function only exists if Perl has been compiled to use ithreads.
7351
7352 =cut
7353 */
7354
7355 OP *
7356 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
7357 {
7358     dVAR;
7359     PADOP *padop;
7360
7361     PERL_ARGS_ASSERT_NEWPADOP;
7362
7363     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
7364         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7365         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
7366         || type == OP_CUSTOM);
7367
7368     NewOp(1101, padop, 1, PADOP);
7369     OpTYPE_set(padop, type);
7370     padop->op_padix =
7371         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
7372     SvREFCNT_dec(PAD_SVl(padop->op_padix));
7373     PAD_SETSV(padop->op_padix, sv);
7374     assert(sv);
7375     padop->op_next = (OP*)padop;
7376     padop->op_flags = (U8)flags;
7377     if (PL_opargs[type] & OA_RETSCALAR)
7378         scalar((OP*)padop);
7379     if (PL_opargs[type] & OA_TARGET)
7380         padop->op_targ = pad_alloc(type, SVs_PADTMP);
7381     return CHECKOP(type, padop);
7382 }
7383
7384 #endif /* USE_ITHREADS */
7385
7386 /*
7387 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
7388
7389 Constructs, checks, and returns an op of any type that involves an
7390 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
7391 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
7392 reference; calling this function does not transfer ownership of any
7393 reference to it.
7394
7395 =cut
7396 */
7397
7398 OP *
7399 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
7400 {
7401     PERL_ARGS_ASSERT_NEWGVOP;
7402
7403 #ifdef USE_ITHREADS
7404     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
7405 #else
7406     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
7407 #endif
7408 }
7409
7410 /*
7411 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
7412
7413 Constructs, checks, and returns an op of any type that involves an
7414 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
7415 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
7416 Depending on the op type, the memory referenced by C<pv> may be freed
7417 when the op is destroyed.  If the op is of a freeing type, C<pv> must
7418 have been allocated using C<PerlMemShared_malloc>.
7419
7420 =cut
7421 */
7422
7423 OP *
7424 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
7425 {
7426     dVAR;
7427     const bool utf8 = cBOOL(flags & SVf_UTF8);
7428     PVOP *pvop;
7429
7430     flags &= ~SVf_UTF8;
7431
7432     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7433         || type == OP_RUNCV || type == OP_CUSTOM
7434         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
7435
7436     NewOp(1101, pvop, 1, PVOP);
7437     OpTYPE_set(pvop, type);
7438     pvop->op_pv = pv;
7439     pvop->op_next = (OP*)pvop;
7440     pvop->op_flags = (U8)flags;
7441     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
7442     if (PL_opargs[type] & OA_RETSCALAR)
7443         scalar((OP*)pvop);
7444     if (PL_opargs[type] & OA_TARGET)
7445         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
7446     return CHECKOP(type, pvop);
7447 }
7448
7449 void
7450 Perl_package(pTHX_ OP *o)
7451 {
7452     SV *const sv = cSVOPo->op_sv;
7453
7454     PERL_ARGS_ASSERT_PACKAGE;
7455
7456     SAVEGENERICSV(PL_curstash);
7457     save_item(PL_curstname);
7458
7459     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
7460
7461     sv_setsv(PL_curstname, sv);
7462
7463     PL_hints |= HINT_BLOCK_SCOPE;
7464     PL_parser->copline = NOLINE;
7465
7466     op_free(o);
7467 }
7468
7469 void
7470 Perl_package_version( pTHX_ OP *v )
7471 {
7472     U32 savehints = PL_hints;
7473     PERL_ARGS_ASSERT_PACKAGE_VERSION;
7474     PL_hints &= ~HINT_STRICT_VARS;
7475     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
7476     PL_hints = savehints;
7477     op_free(v);
7478 }
7479
7480 void
7481 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
7482 {
7483     OP *pack;
7484     OP *imop;
7485     OP *veop;
7486     SV *use_version = NULL;
7487
7488     PERL_ARGS_ASSERT_UTILIZE;
7489
7490     if (idop->op_type != OP_CONST)
7491         Perl_croak(aTHX_ "Module name must be constant");
7492
7493     veop = NULL;
7494
7495     if (version) {
7496         SV * const vesv = ((SVOP*)version)->op_sv;
7497
7498         if (!arg && !SvNIOKp(vesv)) {
7499             arg = version;
7500         }
7501         else {
7502             OP *pack;
7503             SV *meth;
7504
7505             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
7506                 Perl_croak(aTHX_ "Version number must be a constant number");
7507
7508             /* Make copy of idop so we don't free it twice */
7509             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
7510
7511             /* Fake up a method call to VERSION */
7512             meth = newSVpvs_share("VERSION");
7513             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
7514                             op_append_elem(OP_LIST,
7515                                         op_prepend_elem(OP_LIST, pack, version),
7516                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
7517         }
7518     }
7519
7520     /* Fake up an import/unimport */
7521     if (arg && arg->op_type == OP_STUB) {
7522         imop = arg;             /* no import on explicit () */
7523     }
7524     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
7525         imop = NULL;            /* use 5.0; */
7526         if (aver)
7527             use_version = ((SVOP*)idop)->op_sv;
7528         else
7529             idop->op_private |= OPpCONST_NOVER;
7530     }
7531     else {
7532         SV *meth;
7533
7534         /* Make copy of idop so we don't free it twice */
7535         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
7536
7537         /* Fake up a method call to import/unimport */
7538         meth = aver
7539             ? newSVpvs_share("import") : newSVpvs_share("unimport");
7540         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
7541                        op_append_elem(OP_LIST,
7542                                    op_prepend_elem(OP_LIST, pack, arg),
7543                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
7544                        ));
7545     }
7546
7547     /* Fake up the BEGIN {}, which does its thing immediately. */
7548     newATTRSUB(floor,
7549         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
7550         NULL,
7551         NULL,
7552         op_append_elem(OP_LINESEQ,
7553             op_append_elem(OP_LINESEQ,
7554                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
7555                 newSTATEOP(0, NULL, veop)),
7556             newSTATEOP(0, NULL, imop) ));
7557
7558     if (use_version) {
7559         /* Enable the
7560          * feature bundle that corresponds to the required version. */
7561         use_version = sv_2mortal(new_version(use_version));
7562         S_enable_feature_bundle(aTHX_ use_version);
7563
7564         /* If a version >= 5.11.0 is requested, strictures are on by default! */
7565         if (vcmp(use_version,
7566                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
7567             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
7568                 PL_hints |= HINT_STRICT_REFS;
7569             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
7570                 PL_hints |= HINT_STRICT_SUBS;
7571             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
7572                 PL_hints |= HINT_STRICT_VARS;
7573         }
7574         /* otherwise they are off */
7575         else {
7576             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
7577                 PL_hints &= ~HINT_STRICT_REFS;
7578             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
7579                 PL_hints &= ~HINT_STRICT_SUBS;
7580             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
7581                 PL_hints &= ~HINT_STRICT_VARS;
7582         }
7583     }
7584
7585     /* The "did you use incorrect case?" warning used to be here.
7586      * The problem is that on case-insensitive filesystems one
7587      * might get false positives for "use" (and "require"):
7588      * "use Strict" or "require CARP" will work.  This causes
7589      * portability problems for the script: in case-strict
7590      * filesystems the script will stop working.
7591      *
7592      * The "incorrect case" warning checked whether "use Foo"
7593      * imported "Foo" to your namespace, but that is wrong, too:
7594      * there is no requirement nor promise in the language that
7595      * a Foo.pm should or would contain anything in package "Foo".
7596      *
7597      * There is very little Configure-wise that can be done, either:
7598      * the case-sensitivity of the build filesystem of Perl does not
7599      * help in guessing the case-sensitivity of the runtime environment.
7600      */
7601
7602     PL_hints |= HINT_BLOCK_SCOPE;
7603     PL_parser->copline = NOLINE;
7604     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
7605 }
7606
7607 /*
7608 =head1 Embedding Functions
7609
7610 =for apidoc load_module
7611
7612 Loads the module whose name is pointed to by the string part of C<name>.
7613 Note that the actual module name, not its filename, should be given.
7614 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
7615 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
7616 trailing arguments can be used to specify arguments to the module's C<import()>
7617 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
7618 on the flags. The flags argument is a bitwise-ORed collection of any of
7619 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
7620 (or 0 for no flags).
7621
7622 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
7623 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
7624 the trailing optional arguments may be omitted entirely. Otherwise, if
7625 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
7626 exactly one C<OP*>, containing the op tree that produces the relevant import
7627 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
7628 will be used as import arguments; and the list must be terminated with C<(SV*)
7629 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
7630 set, the trailing C<NULL> pointer is needed even if no import arguments are
7631 desired. The reference count for each specified C<SV*> argument is
7632 decremented. In addition, the C<name> argument is modified.
7633
7634 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
7635 than C<use>.
7636
7637 =cut */
7638
7639 void
7640 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
7641 {
7642     va_list args;
7643
7644     PERL_ARGS_ASSERT_LOAD_MODULE;
7645
7646     va_start(args, ver);
7647     vload_module(flags, name, ver, &args);
7648     va_end(args);
7649 }
7650
7651 #ifdef PERL_IMPLICIT_CONTEXT
7652 void
7653 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
7654 {
7655     dTHX;
7656     va_list args;
7657     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
7658     va_start(args, ver);
7659     vload_module(flags, name, ver, &args);
7660     va_end(args);
7661 }
7662 #endif
7663
7664 void
7665 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
7666 {
7667     OP *veop, *imop;
7668     OP * const modname = newSVOP(OP_CONST, 0, name);
7669
7670     PERL_ARGS_ASSERT_VLOAD_MODULE;
7671
7672     modname->op_private |= OPpCONST_BARE;
7673     if (ver) {
7674         veop = newSVOP(OP_CONST, 0, ver);
7675     }
7676     else
7677         veop = NULL;
7678     if (flags & PERL_LOADMOD_NOIMPORT) {
7679         imop = sawparens(newNULLLIST());
7680     }
7681     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
7682         imop = va_arg(*args, OP*);
7683     }
7684     else {
7685         SV *sv;
7686         imop = NULL;
7687         sv = va_arg(*args, SV*);
7688         while (sv) {
7689             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
7690             sv = va_arg(*args, SV*);
7691         }
7692     }
7693
7694     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
7695      * that it has a PL_parser to play with while doing that, and also
7696      * that it doesn't mess with any existing parser, by creating a tmp
7697      * new parser with lex_start(). This won't actually be used for much,
7698      * since pp_require() will create another parser for the real work.
7699      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
7700
7701     ENTER;
7702     SAVEVPTR(PL_curcop);
7703     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
7704     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
7705             veop, modname, imop);
7706     LEAVE;
7707 }
7708
7709 PERL_STATIC_INLINE OP *
7710 S_new_entersubop(pTHX_ GV *gv, OP *arg)
7711 {
7712     return newUNOP(OP_ENTERSUB, OPf_STACKED,
7713                    newLISTOP(OP_LIST, 0, arg,
7714                              newUNOP(OP_RV2CV, 0,
7715                                      newGVOP(OP_GV, 0, gv))));
7716 }
7717
7718 OP *
7719 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
7720 {
7721     OP *doop;
7722     GV *gv;
7723
7724     PERL_ARGS_ASSERT_DOFILE;
7725
7726     if (!force_builtin && (gv = gv_override("do", 2))) {
7727         doop = S_new_entersubop(aTHX_ gv, term);
7728     }
7729     else {
7730         doop = newUNOP(OP_DOFILE, 0, scalar(term));
7731     }
7732     return doop;
7733 }
7734
7735 /*
7736 =head1 Optree construction
7737
7738 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
7739
7740 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
7741 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
7742 be set automatically, and, shifted up eight bits, the eight bits of
7743 C<op_private>, except that the bit with value 1 or 2 is automatically
7744 set as required.  C<listval> and C<subscript> supply the parameters of
7745 the slice; they are consumed by this function and become part of the
7746 constructed op tree.
7747
7748 =cut
7749 */
7750
7751 OP *
7752 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
7753 {
7754     return newBINOP(OP_LSLICE, flags,
7755             list(force_list(subscript, 1)),
7756             list(force_list(listval,   1)) );
7757 }
7758
7759 #define ASSIGN_LIST   1
7760 #define ASSIGN_REF    2
7761
7762 STATIC I32
7763 S_assignment_type(pTHX_ const OP *o)
7764 {
7765     unsigned type;
7766     U8 flags;
7767     U8 ret;
7768
7769     if (!o)
7770         return TRUE;
7771
7772     if (o->op_type == OP_SREFGEN)
7773     {
7774         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
7775         type = kid->op_type;
7776         flags = o->op_flags | kid->op_flags;
7777         if (!(flags & OPf_PARENS)
7778           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
7779               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
7780             return ASSIGN_REF;
7781         ret = ASSIGN_REF;
7782     } else {
7783         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
7784             o = cUNOPo->op_first;
7785         flags = o->op_flags;
7786         type = o->op_type;
7787         ret = 0;
7788     }
7789
7790     if (type == OP_COND_EXPR) {
7791         OP * const sib = OpSIBLING(cLOGOPo->op_first);
7792         const I32 t = assignment_type(sib);
7793         const I32 f = assignment_type(OpSIBLING(sib));
7794
7795         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
7796             return ASSIGN_LIST;
7797         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
7798             yyerror("Assignment to both a list and a scalar");
7799         return FALSE;
7800     }
7801
7802     if (type == OP_LIST &&
7803         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
7804         o->op_private & OPpLVAL_INTRO)
7805         return ret;
7806
7807     if (type == OP_LIST || flags & OPf_PARENS ||
7808         type == OP_RV2AV || type == OP_RV2HV ||
7809         type == OP_ASLICE || type == OP_HSLICE ||
7810         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
7811         return TRUE;
7812
7813     if (type == OP_PADAV || type == OP_PADHV)
7814         return TRUE;
7815
7816     if (type == OP_RV2SV)
7817         return ret;
7818
7819     return ret;
7820 }
7821
7822 static OP *
7823 S_newONCEOP(pTHX_ OP *initop, OP *padop)
7824 {
7825     dVAR;
7826     const PADOFFSET target = padop->op_targ;
7827     OP *const other = newOP(OP_PADSV,
7828                             padop->op_flags
7829                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
7830     OP *const first = newOP(OP_NULL, 0);
7831     OP *const nullop = newCONDOP(0, first, initop, other);
7832     /* XXX targlex disabled for now; see ticket #124160
7833         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
7834      */
7835     OP *const condop = first->op_next;
7836
7837     OpTYPE_set(condop, OP_ONCE);
7838     other->op_targ = target;
7839     nullop->op_flags |= OPf_WANT_SCALAR;
7840
7841     /* Store the initializedness of state vars in a separate
7842        pad entry.  */
7843     condop->op_targ =
7844       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
7845     /* hijacking PADSTALE for uninitialized state variables */
7846     SvPADSTALE_on(PAD_SVl(condop->op_targ));
7847
7848     return nullop;
7849 }
7850
7851 /*
7852 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
7853
7854 Constructs, checks, and returns an assignment op.  C<left> and C<right>
7855 supply the parameters of the assignment; they are consumed by this
7856 function and become part of the constructed op tree.
7857
7858 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
7859 a suitable conditional optree is constructed.  If C<optype> is the opcode
7860 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
7861 performs the binary operation and assigns the result to the left argument.
7862 Either way, if C<optype> is non-zero then C<flags> has no effect.
7863
7864 If C<optype> is zero, then a plain scalar or list assignment is
7865 constructed.  Which type of assignment it is is automatically determined.
7866 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
7867 will be set automatically, and, shifted up eight bits, the eight bits
7868 of C<op_private>, except that the bit with value 1 or 2 is automatically
7869 set as required.
7870
7871 =cut
7872 */
7873
7874 OP *
7875 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
7876 {
7877     OP *o;
7878     I32 assign_type;
7879
7880     if (optype) {
7881         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
7882             right = scalar(right);
7883             return newLOGOP(optype, 0,
7884                 op_lvalue(scalar(left), optype),
7885                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
7886         }
7887         else {
7888             return newBINOP(optype, OPf_STACKED,
7889                 op_lvalue(scalar(left), optype), scalar(right));
7890         }
7891     }
7892
7893     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
7894         OP *state_var_op = NULL;
7895         static const char no_list_state[] = "Initialization of state variables"
7896             " in list currently forbidden";
7897         OP *curop;
7898
7899         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
7900             left->op_private &= ~ OPpSLICEWARNING;
7901
7902         PL_modcount = 0;
7903         left = op_lvalue(left, OP_AASSIGN);
7904         curop = list(force_list(left, 1));
7905         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
7906         o->op_private = (U8)(0 | (flags >> 8));
7907
7908         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
7909         {
7910             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
7911             if (!(left->op_flags & OPf_PARENS) &&
7912                     lop->op_type == OP_PUSHMARK &&
7913                     (vop = OpSIBLING(lop)) &&
7914                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
7915                     !(vop->op_flags & OPf_PARENS) &&
7916                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
7917                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
7918                     (eop = OpSIBLING(vop)) &&
7919                     eop->op_type == OP_ENTERSUB &&
7920                     !OpHAS_SIBLING(eop)) {
7921                 state_var_op = vop;
7922             } else {
7923                 while (lop) {
7924                     if ((lop->op_type == OP_PADSV ||
7925                          lop->op_type == OP_PADAV ||
7926                          lop->op_type == OP_PADHV ||
7927                          lop->op_type == OP_PADANY)
7928                       && (lop->op_private & OPpPAD_STATE)
7929                     )
7930                         yyerror(no_list_state);
7931                     lop = OpSIBLING(lop);
7932                 }
7933             }
7934         }
7935         else if (  (left->op_private & OPpLVAL_INTRO)
7936                 && (left->op_private & OPpPAD_STATE)
7937                 && (   left->op_type == OP_PADSV
7938                     || left->op_type == OP_PADAV
7939                     || left->op_type == OP_PADHV
7940                     || left->op_type == OP_PADANY)
7941         ) {
7942                 /* All single variable list context state assignments, hence
7943                    state ($a) = ...
7944                    (state $a) = ...
7945                    state @a = ...
7946                    state (@a) = ...
7947                    (state @a) = ...
7948                    state %a = ...
7949                    state (%a) = ...
7950                    (state %a) = ...
7951                 */
7952                 if (left->op_flags & OPf_PARENS)
7953                     yyerror(no_list_state);
7954                 else
7955                     state_var_op = left;
7956         }
7957
7958         /* optimise @a = split(...) into:
7959         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
7960         * @a, my @a, local @a:  split(...)          (where @a is attached to
7961         *                                            the split op itself)
7962         */
7963
7964         if (   right
7965             && right->op_type == OP_SPLIT
7966             /* don't do twice, e.g. @b = (@a = split) */
7967             && !(right->op_private & OPpSPLIT_ASSIGN))
7968         {
7969             OP *gvop = NULL;
7970
7971             if (   (  left->op_type == OP_RV2AV
7972                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
7973                 || left->op_type == OP_PADAV)
7974             {
7975                 /* @pkg or @lex or local @pkg' or 'my @lex' */
7976                 OP *tmpop;
7977                 if (gvop) {
7978 #ifdef USE_ITHREADS
7979                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
7980                         = cPADOPx(gvop)->op_padix;
7981                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
7982 #else
7983                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
7984                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
7985                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
7986 #endif
7987                     right->op_private |=
7988                         left->op_private & OPpOUR_INTRO;
7989                 }
7990                 else {
7991                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
7992                     left->op_targ = 0;  /* steal it */
7993                     right->op_private |= OPpSPLIT_LEX;
7994                 }
7995                 right->op_private |= left->op_private & OPpLVAL_INTRO;
7996
7997               detach_split:
7998                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
7999                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
8000                 assert(OpSIBLING(tmpop) == right);
8001                 assert(!OpHAS_SIBLING(right));
8002                 /* detach the split subtreee from the o tree,
8003                  * then free the residual o tree */
8004                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
8005                 op_free(o);                     /* blow off assign */
8006                 right->op_private |= OPpSPLIT_ASSIGN;
8007                 right->op_flags &= ~OPf_WANT;
8008                         /* "I don't know and I don't care." */
8009                 return right;
8010             }
8011             else if (left->op_type == OP_RV2AV) {
8012                 /* @{expr} */
8013
8014                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
8015                 assert(OpSIBLING(pushop) == left);
8016                 /* Detach the array ...  */
8017                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
8018                 /* ... and attach it to the split.  */
8019                 op_sibling_splice(right, cLISTOPx(right)->op_last,
8020                                   0, left);
8021                 right->op_flags |= OPf_STACKED;
8022                 /* Detach split and expunge aassign as above.  */
8023                 goto detach_split;
8024             }
8025             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
8026                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
8027             {
8028                 /* convert split(...,0) to split(..., PL_modcount+1) */
8029                 SV ** const svp =
8030                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
8031                 SV * const sv = *svp;
8032                 if (SvIOK(sv) && SvIVX(sv) == 0)
8033                 {
8034                   if (right->op_private & OPpSPLIT_IMPLIM) {
8035                     /* our own SV, created in ck_split */
8036                     SvREADONLY_off(sv);
8037                     sv_setiv(sv, PL_modcount+1);
8038                   }
8039                   else {
8040                     /* SV may belong to someone else */
8041                     SvREFCNT_dec(sv);
8042                     *svp = newSViv(PL_modcount+1);
8043                   }
8044                 }
8045             }
8046         }
8047
8048         if (state_var_op)
8049             o = S_newONCEOP(aTHX_ o, state_var_op);
8050         return o;
8051     }
8052     if (assign_type == ASSIGN_REF)
8053         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
8054     if (!right)
8055         right = newOP(OP_UNDEF, 0);
8056     if (right->op_type == OP_READLINE) {
8057         right->op_flags |= OPf_STACKED;
8058         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
8059                 scalar(right));
8060     }
8061     else {
8062         o = newBINOP(OP_SASSIGN, flags,
8063             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
8064     }
8065     return o;
8066 }
8067
8068 /*
8069 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
8070
8071 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
8072 but will be a C<dbstate> op if debugging is enabled for currently-compiled
8073 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
8074 If C<label> is non-null, it supplies the name of a label to attach to
8075 the state op; this function takes ownership of the memory pointed at by
8076 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
8077 for the state op.
8078
8079 If C<o> is null, the state op is returned.  Otherwise the state op is
8080 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
8081 is consumed by this function and becomes part of the returned op tree.
8082
8083 =cut
8084 */
8085
8086 OP *
8087 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
8088 {
8089     dVAR;
8090     const U32 seq = intro_my();
8091     const U32 utf8 = flags & SVf_UTF8;
8092     COP *cop;
8093
8094     PL_parser->parsed_sub = 0;
8095
8096     flags &= ~SVf_UTF8;
8097
8098     NewOp(1101, cop, 1, COP);
8099     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
8100         OpTYPE_set(cop, OP_DBSTATE);
8101     }
8102     else {
8103         OpTYPE_set(cop, OP_NEXTSTATE);
8104     }
8105     cop->op_flags = (U8)flags;
8106     CopHINTS_set(cop, PL_hints);
8107 #ifdef VMS
8108     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
8109 #endif
8110     cop->op_next = (OP*)cop;
8111
8112     cop->cop_seq = seq;
8113     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8114     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
8115     if (label) {
8116         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
8117
8118         PL_hints |= HINT_BLOCK_SCOPE;
8119         /* It seems that we need to defer freeing this pointer, as other parts
8120            of the grammar end up wanting to copy it after this op has been
8121            created. */
8122         SAVEFREEPV(label);
8123     }
8124
8125     if (PL_parser->preambling != NOLINE) {
8126         CopLINE_set(cop, PL_parser->preambling);
8127         PL_parser->copline = NOLINE;
8128     }
8129     else if (PL_parser->copline == NOLINE)
8130         CopLINE_set(cop, CopLINE(PL_curcop));
8131     else {
8132         CopLINE_set(cop, PL_parser->copline);
8133         PL_parser->copline = NOLINE;
8134     }
8135 #ifdef USE_ITHREADS
8136     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
8137 #else
8138     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
8139 #endif
8140     CopSTASH_set(cop, PL_curstash);
8141
8142     if (cop->op_type == OP_DBSTATE) {
8143         /* this line can have a breakpoint - store the cop in IV */
8144         AV *av = CopFILEAVx(PL_curcop);
8145         if (av) {
8146             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
8147             if (svp && *svp != &PL_sv_undef ) {
8148                 (void)SvIOK_on(*svp);
8149                 SvIV_set(*svp, PTR2IV(cop));
8150             }
8151         }
8152     }
8153
8154     if (flags & OPf_SPECIAL)
8155         op_null((OP*)cop);
8156     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
8157 }
8158
8159 /*
8160 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
8161
8162 Constructs, checks, and returns a logical (flow control) op.  C<type>
8163 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
8164 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
8165 the eight bits of C<op_private>, except that the bit with value 1 is
8166 automatically set.  C<first> supplies the expression controlling the
8167 flow, and C<other> supplies the side (alternate) chain of ops; they are
8168 consumed by this function and become part of the constructed op tree.
8169
8170 =cut
8171 */
8172
8173 OP *
8174 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
8175 {
8176     PERL_ARGS_ASSERT_NEWLOGOP;
8177
8178     return new_logop(type, flags, &first, &other);
8179 }
8180
8181 STATIC OP *
8182 S_search_const(pTHX_ OP *o)
8183 {
8184     PERL_ARGS_ASSERT_SEARCH_CONST;
8185
8186     switch (o->op_type) {
8187         case OP_CONST:
8188             return o;
8189         case OP_NULL:
8190             if (o->op_flags & OPf_KIDS)
8191                 return search_const(cUNOPo->op_first);
8192             break;
8193         case OP_LEAVE:
8194         case OP_SCOPE:
8195         case OP_LINESEQ:
8196         {
8197             OP *kid;
8198             if (!(o->op_flags & OPf_KIDS))
8199                 return NULL;
8200             kid = cLISTOPo->op_first;
8201             do {
8202                 switch (kid->op_type) {
8203                     case OP_ENTER:
8204                     case OP_NULL:
8205                     case OP_NEXTSTATE:
8206                         kid = OpSIBLING(kid);
8207                         break;
8208                     default:
8209                         if (kid != cLISTOPo->op_last)
8210                             return NULL;
8211                         goto last;
8212                 }
8213             } while (kid);
8214             if (!kid)
8215                 kid = cLISTOPo->op_last;
8216           last:
8217             return search_const(kid);
8218         }
8219     }
8220
8221     return NULL;
8222 }
8223
8224 STATIC OP *
8225 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
8226 {
8227     dVAR;
8228     LOGOP *logop;
8229     OP *o;
8230     OP *first;
8231     OP *other;
8232     OP *cstop = NULL;
8233     int prepend_not = 0;
8234
8235     PERL_ARGS_ASSERT_NEW_LOGOP;
8236
8237     first = *firstp;
8238     other = *otherp;
8239
8240     /* [perl #59802]: Warn about things like "return $a or $b", which
8241        is parsed as "(return $a) or $b" rather than "return ($a or
8242        $b)".  NB: This also applies to xor, which is why we do it
8243        here.
8244      */
8245     switch (first->op_type) {
8246     case OP_NEXT:
8247     case OP_LAST:
8248     case OP_REDO:
8249         /* XXX: Perhaps we should emit a stronger warning for these.
8250            Even with the high-precedence operator they don't seem to do
8251            anything sensible.
8252
8253            But until we do, fall through here.
8254          */
8255     case OP_RETURN:
8256     case OP_EXIT:
8257     case OP_DIE:
8258     case OP_GOTO:
8259         /* XXX: Currently we allow people to "shoot themselves in the
8260            foot" by explicitly writing "(return $a) or $b".
8261
8262            Warn unless we are looking at the result from folding or if
8263            the programmer explicitly grouped the operators like this.
8264            The former can occur with e.g.
8265
8266                 use constant FEATURE => ( $] >= ... );
8267                 sub { not FEATURE and return or do_stuff(); }
8268          */
8269         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
8270             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
8271                            "Possible precedence issue with control flow operator");
8272         /* XXX: Should we optimze this to "return $a;" (i.e. remove
8273            the "or $b" part)?
8274         */
8275         break;
8276     }
8277
8278     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
8279         return newBINOP(type, flags, scalar(first), scalar(other));
8280
8281     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
8282         || type == OP_CUSTOM);
8283
8284     scalarboolean(first);
8285
8286     /* search for a constant op that could let us fold the test */
8287     if ((cstop = search_const(first))) {
8288         if (cstop->op_private & OPpCONST_STRICT)
8289             no_bareword_allowed(cstop);
8290         else if ((cstop->op_private & OPpCONST_BARE))
8291                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
8292         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
8293             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
8294             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
8295             /* Elide the (constant) lhs, since it can't affect the outcome */
8296             *firstp = NULL;
8297             if (other->op_type == OP_CONST)
8298                 other->op_private |= OPpCONST_SHORTCIRCUIT;
8299             op_free(first);
8300             if (other->op_type == OP_LEAVE)
8301                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
8302             else if (other->op_type == OP_MATCH
8303                   || other->op_type == OP_SUBST
8304                   || other->op_type == OP_TRANSR
8305                   || other->op_type == OP_TRANS)
8306                 /* Mark the op as being unbindable with =~ */
8307                 other->op_flags |= OPf_SPECIAL;
8308
8309             other->op_folded = 1;
8310             return other;
8311         }
8312         else {
8313             /* Elide the rhs, since the outcome is entirely determined by
8314              * the (constant) lhs */
8315
8316             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
8317             const OP *o2 = other;
8318             if ( ! (o2->op_type == OP_LIST
8319                     && (( o2 = cUNOPx(o2)->op_first))
8320                     && o2->op_type == OP_PUSHMARK
8321                     && (( o2 = OpSIBLING(o2))) )
8322             )
8323                 o2 = other;
8324             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
8325                         || o2->op_type == OP_PADHV)
8326                 && o2->op_private & OPpLVAL_INTRO
8327                 && !(o2->op_private & OPpPAD_STATE))
8328             {
8329         Perl_croak(aTHX_ "This use of my() in false conditional is "
8330                           "no longer allowed");
8331             }
8332
8333             *otherp = NULL;
8334             if (cstop->op_type == OP_CONST)
8335                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
8336             op_free(other);
8337             return first;
8338         }
8339     }
8340     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
8341         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
8342     {
8343         const OP * const k1 = ((UNOP*)first)->op_first;
8344         const OP * const k2 = OpSIBLING(k1);
8345         OPCODE warnop = 0;
8346         switch (first->op_type)
8347         {
8348         case OP_NULL:
8349             if (k2 && k2->op_type == OP_READLINE
8350                   && (k2->op_flags & OPf_STACKED)
8351                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8352             {
8353                 warnop = k2->op_type;
8354             }
8355             break;
8356
8357         case OP_SASSIGN:
8358             if (k1->op_type == OP_READDIR
8359                   || k1->op_type == OP_GLOB
8360                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8361                  || k1->op_type == OP_EACH
8362                  || k1->op_type == OP_AEACH)
8363             {
8364                 warnop = ((k1->op_type == OP_NULL)
8365                           ? (OPCODE)k1->op_targ : k1->op_type);
8366             }
8367             break;
8368         }
8369         if (warnop) {
8370             const line_t oldline = CopLINE(PL_curcop);
8371             /* This ensures that warnings are reported at the first line
8372                of the construction, not the last.  */
8373             CopLINE_set(PL_curcop, PL_parser->copline);
8374             Perl_warner(aTHX_ packWARN(WARN_MISC),
8375                  "Value of %s%s can be \"0\"; test with defined()",
8376                  PL_op_desc[warnop],
8377                  ((warnop == OP_READLINE || warnop == OP_GLOB)
8378                   ? " construct" : "() operator"));
8379             CopLINE_set(PL_curcop, oldline);
8380         }
8381     }
8382
8383     /* optimize AND and OR ops that have NOTs as children */
8384     if (first->op_type == OP_NOT
8385         && (first->op_flags & OPf_KIDS)
8386         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
8387             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
8388         ) {
8389         if (type == OP_AND || type == OP_OR) {
8390             if (type == OP_AND)
8391                 type = OP_OR;
8392             else
8393                 type = OP_AND;
8394             op_null(first);
8395             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
8396                 op_null(other);
8397                 prepend_not = 1; /* prepend a NOT op later */
8398             }
8399         }
8400     }
8401
8402     logop = alloc_LOGOP(type, first, LINKLIST(other));
8403     logop->op_flags |= (U8)flags;
8404     logop->op_private = (U8)(1 | (flags >> 8));
8405
8406     /* establish postfix order */
8407     logop->op_next = LINKLIST(first);
8408     first->op_next = (OP*)logop;
8409     assert(!OpHAS_SIBLING(first));
8410     op_sibling_splice((OP*)logop, first, 0, other);
8411
8412     CHECKOP(type,logop);
8413
8414     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
8415                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
8416                 (OP*)logop);
8417     other->op_next = o;
8418
8419     return o;
8420 }
8421
8422 /*
8423 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
8424
8425 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
8426 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
8427 will be set automatically, and, shifted up eight bits, the eight bits of
8428 C<op_private>, except that the bit with value 1 is automatically set.
8429 C<first> supplies the expression selecting between the two branches,
8430 and C<trueop> and C<falseop> supply the branches; they are consumed by
8431 this function and become part of the constructed op tree.
8432
8433 =cut
8434 */
8435
8436 OP *
8437 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
8438 {
8439     dVAR;
8440     LOGOP *logop;
8441     OP *start;
8442     OP *o;
8443     OP *cstop;
8444
8445     PERL_ARGS_ASSERT_NEWCONDOP;
8446
8447     if (!falseop)
8448         return newLOGOP(OP_AND, 0, first, trueop);
8449     if (!trueop)
8450         return newLOGOP(OP_OR, 0, first, falseop);
8451
8452     scalarboolean(first);
8453     if ((cstop = search_const(first))) {
8454         /* Left or right arm of the conditional?  */
8455         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
8456         OP *live = left ? trueop : falseop;
8457         OP *const dead = left ? falseop : trueop;
8458         if (cstop->op_private & OPpCONST_BARE &&
8459             cstop->op_private & OPpCONST_STRICT) {
8460             no_bareword_allowed(cstop);
8461         }
8462         op_free(first);
8463         op_free(dead);
8464         if (live->op_type == OP_LEAVE)
8465             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
8466         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
8467               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
8468             /* Mark the op as being unbindable with =~ */
8469             live->op_flags |= OPf_SPECIAL;
8470         live->op_folded = 1;
8471         return live;
8472     }
8473     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
8474     logop->op_flags |= (U8)flags;
8475     logop->op_private = (U8)(1 | (flags >> 8));
8476     logop->op_next = LINKLIST(falseop);
8477
8478     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
8479             logop);
8480
8481     /* establish postfix order */
8482     start = LINKLIST(first);
8483     first->op_next = (OP*)logop;
8484
8485     /* make first, trueop, falseop siblings */
8486     op_sibling_splice((OP*)logop, first,  0, trueop);
8487     op_sibling_splice((OP*)logop, trueop, 0, falseop);
8488
8489     o = newUNOP(OP_NULL, 0, (OP*)logop);
8490
8491     trueop->op_next = falseop->op_next = o;
8492
8493     o->op_next = start;
8494     return o;
8495 }
8496
8497 /*
8498 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
8499
8500 Constructs and returns a C<range> op, with subordinate C<flip> and
8501 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
8502 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
8503 for both the C<flip> and C<range> ops, except that the bit with value
8504 1 is automatically set.  C<left> and C<right> supply the expressions
8505 controlling the endpoints of the range; they are consumed by this function
8506 and become part of the constructed op tree.
8507
8508 =cut
8509 */
8510
8511 OP *
8512 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
8513 {
8514     LOGOP *range;
8515     OP *flip;
8516     OP *flop;
8517     OP *leftstart;
8518     OP *o;
8519
8520     PERL_ARGS_ASSERT_NEWRANGE;
8521
8522     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
8523     range->op_flags = OPf_KIDS;
8524     leftstart = LINKLIST(left);
8525     range->op_private = (U8)(1 | (flags >> 8));
8526
8527     /* make left and right siblings */
8528     op_sibling_splice((OP*)range, left, 0, right);
8529
8530     range->op_next = (OP*)range;
8531     flip = newUNOP(OP_FLIP, flags, (OP*)range);
8532     flop = newUNOP(OP_FLOP, 0, flip);
8533     o = newUNOP(OP_NULL, 0, flop);
8534     LINKLIST(flop);
8535     range->op_next = leftstart;
8536
8537     left->op_next = flip;
8538     right->op_next = flop;
8539
8540     range->op_targ =
8541         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
8542     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
8543     flip->op_targ =
8544         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
8545     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
8546     SvPADTMP_on(PAD_SV(flip->op_targ));
8547
8548     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
8549     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
8550
8551     /* check barewords before they might be optimized aways */
8552     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
8553         no_bareword_allowed(left);
8554     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
8555         no_bareword_allowed(right);
8556
8557     flip->op_next = o;
8558     if (!flip->op_private || !flop->op_private)
8559         LINKLIST(o);            /* blow off optimizer unless constant */
8560
8561     return o;
8562 }
8563
8564 /*
8565 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
8566
8567 Constructs, checks, and returns an op tree expressing a loop.  This is
8568 only a loop in the control flow through the op tree; it does not have
8569 the heavyweight loop structure that allows exiting the loop by C<last>
8570 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
8571 top-level op, except that some bits will be set automatically as required.
8572 C<expr> supplies the expression controlling loop iteration, and C<block>
8573 supplies the body of the loop; they are consumed by this function and
8574 become part of the constructed op tree.  C<debuggable> is currently
8575 unused and should always be 1.
8576
8577 =cut
8578 */
8579
8580 OP *
8581 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
8582 {
8583     OP* listop;
8584     OP* o;
8585     const bool once = block && block->op_flags & OPf_SPECIAL &&
8586                       block->op_type == OP_NULL;
8587
8588     PERL_UNUSED_ARG(debuggable);
8589
8590     if (expr) {
8591         if (once && (
8592               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
8593            || (  expr->op_type == OP_NOT
8594               && cUNOPx(expr)->op_first->op_type == OP_CONST
8595               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
8596               )
8597            ))
8598             /* Return the block now, so that S_new_logop does not try to
8599                fold it away. */
8600             return block;       /* do {} while 0 does once */
8601         if (expr->op_type == OP_READLINE
8602             || expr->op_type == OP_READDIR
8603             || expr->op_type == OP_GLOB
8604             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
8605             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
8606             expr = newUNOP(OP_DEFINED, 0,
8607                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
8608         } else if (expr->op_flags & OPf_KIDS) {
8609             const OP * const k1 = ((UNOP*)expr)->op_first;
8610             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
8611             switch (expr->op_type) {
8612               case OP_NULL:
8613                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
8614                       && (k2->op_flags & OPf_STACKED)
8615                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8616                     expr = newUNOP(OP_DEFINED, 0, expr);
8617                 break;
8618
8619               case OP_SASSIGN:
8620                 if (k1 && (k1->op_type == OP_READDIR
8621                       || k1->op_type == OP_GLOB
8622                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8623                      || k1->op_type == OP_EACH
8624                      || k1->op_type == OP_AEACH))
8625                     expr = newUNOP(OP_DEFINED, 0, expr);
8626                 break;
8627             }
8628         }
8629     }
8630
8631     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
8632      * op, in listop. This is wrong. [perl #27024] */
8633     if (!block)
8634         block = newOP(OP_NULL, 0);
8635     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
8636     o = new_logop(OP_AND, 0, &expr, &listop);
8637
8638     if (once) {
8639         ASSUME(listop);
8640     }
8641
8642     if (listop)
8643         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
8644
8645     if (once && o != listop)
8646     {
8647         assert(cUNOPo->op_first->op_type == OP_AND
8648             || cUNOPo->op_first->op_type == OP_OR);
8649         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
8650     }
8651
8652     if (o == listop)
8653         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
8654
8655     o->op_flags |= flags;
8656     o = op_scope(o);
8657     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
8658     return o;
8659 }
8660
8661 /*
8662 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
8663
8664 Constructs, checks, and returns an op tree expressing a C<while> loop.
8665 This is a heavyweight loop, with structure that allows exiting the loop
8666 by C<last> and suchlike.
8667
8668 C<loop> is an optional preconstructed C<enterloop> op to use in the
8669 loop; if it is null then a suitable op will be constructed automatically.
8670 C<expr> supplies the loop's controlling expression.  C<block> supplies the
8671 main body of the loop, and C<cont> optionally supplies a C<continue> block
8672 that operates as a second half of the body.  All of these optree inputs
8673 are consumed by this function and become part of the constructed op tree.
8674
8675 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
8676 op and, shifted up eight bits, the eight bits of C<op_private> for
8677 the C<leaveloop> op, except that (in both cases) some bits will be set
8678 automatically.  C<debuggable> is currently unused and should always be 1.
8679 C<has_my> can be supplied as true to force the
8680 loop body to be enclosed in its own scope.
8681
8682 =cut
8683 */
8684
8685 OP *
8686 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
8687         OP *expr, OP *block, OP *cont, I32 has_my)
8688 {
8689     dVAR;
8690     OP *redo;
8691     OP *next = NULL;
8692     OP *listop;
8693     OP *o;
8694     U8 loopflags = 0;
8695
8696     PERL_UNUSED_ARG(debuggable);
8697
8698     if (expr) {
8699         if (expr->op_type == OP_READLINE
8700          || expr->op_type == OP_READDIR
8701          || expr->op_type == OP_GLOB
8702          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
8703                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
8704             expr = newUNOP(OP_DEFINED, 0,
8705                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
8706         } else if (expr->op_flags & OPf_KIDS) {
8707             const OP * const k1 = ((UNOP*)expr)->op_first;
8708             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
8709             switch (expr->op_type) {
8710               case OP_NULL:
8711                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
8712                       && (k2->op_flags & OPf_STACKED)
8713                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8714                     expr = newUNOP(OP_DEFINED, 0, expr);
8715                 break;
8716
8717               case OP_SASSIGN:
8718                 if (k1 && (k1->op_type == OP_READDIR
8719                       || k1->op_type == OP_GLOB
8720                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8721                      || k1->op_type == OP_EACH
8722                      || k1->op_type == OP_AEACH))
8723                     expr = newUNOP(OP_DEFINED, 0, expr);
8724                 break;
8725             }
8726         }
8727     }
8728
8729     if (!block)
8730         block = newOP(OP_NULL, 0);
8731     else if (cont || has_my) {
8732         block = op_scope(block);
8733     }
8734
8735     if (cont) {
8736         next = LINKLIST(cont);
8737     }
8738     if (expr) {
8739         OP * const unstack = newOP(OP_UNSTACK, 0);
8740         if (!next)
8741             next = unstack;
8742         cont = op_append_elem(OP_LINESEQ, cont, unstack);
8743     }
8744
8745     assert(block);
8746     listop = op_append_list(OP_LINESEQ, block, cont);
8747     assert(listop);
8748     redo = LINKLIST(listop);
8749
8750     if (expr) {
8751         scalar(listop);
8752         o = new_logop(OP_AND, 0, &expr, &listop);
8753         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
8754             op_free((OP*)loop);
8755             return expr;                /* listop already freed by new_logop */
8756         }
8757         if (listop)
8758             ((LISTOP*)listop)->op_last->op_next =
8759                 (o == listop ? redo : LINKLIST(o));
8760     }
8761     else
8762         o = listop;
8763
8764     if (!loop) {
8765         NewOp(1101,loop,1,LOOP);
8766         OpTYPE_set(loop, OP_ENTERLOOP);
8767         loop->op_private = 0;
8768         loop->op_next = (OP*)loop;
8769     }
8770
8771     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
8772
8773     loop->op_redoop = redo;
8774     loop->op_lastop = o;
8775     o->op_private |= loopflags;
8776
8777     if (next)
8778         loop->op_nextop = next;
8779     else
8780         loop->op_nextop = o;
8781
8782     o->op_flags |= flags;
8783     o->op_private |= (flags >> 8);
8784     return o;
8785 }
8786
8787 /*
8788 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
8789
8790 Constructs, checks, and returns an op tree expressing a C<foreach>
8791 loop (iteration through a list of values).  This is a heavyweight loop,
8792 with structure that allows exiting the loop by C<last> and suchlike.
8793
8794 C<sv> optionally supplies the variable that will be aliased to each
8795 item in turn; if null, it defaults to C<$_>.
8796 C<expr> supplies the list of values to iterate over.  C<block> supplies
8797 the main body of the loop, and C<cont> optionally supplies a C<continue>
8798 block that operates as a second half of the body.  All of these optree
8799 inputs are consumed by this function and become part of the constructed
8800 op tree.
8801
8802 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
8803 op and, shifted up eight bits, the eight bits of C<op_private> for
8804 the C<leaveloop> op, except that (in both cases) some bits will be set
8805 automatically.
8806
8807 =cut
8808 */
8809
8810 OP *
8811 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
8812 {
8813     dVAR;
8814     LOOP *loop;
8815     OP *wop;
8816     PADOFFSET padoff = 0;
8817     I32 iterflags = 0;
8818     I32 iterpflags = 0;
8819
8820     PERL_ARGS_ASSERT_NEWFOROP;
8821
8822     if (sv) {
8823         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
8824             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
8825             OpTYPE_set(sv, OP_RV2GV);
8826
8827             /* The op_type check is needed to prevent a possible segfault
8828              * if the loop variable is undeclared and 'strict vars' is in
8829              * effect. This is illegal but is nonetheless parsed, so we
8830              * may reach this point with an OP_CONST where we're expecting
8831              * an OP_GV.
8832              */
8833             if (cUNOPx(sv)->op_first->op_type == OP_GV
8834              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
8835                 iterpflags |= OPpITER_DEF;
8836         }
8837         else if (sv->op_type == OP_PADSV) { /* private variable */
8838             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
8839             padoff = sv->op_targ;
8840             sv->op_targ = 0;
8841             op_free(sv);
8842             sv = NULL;
8843             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
8844         }
8845         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
8846             NOOP;
8847         else
8848             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
8849         if (padoff) {
8850             PADNAME * const pn = PAD_COMPNAME(padoff);
8851             const char * const name = PadnamePV(pn);
8852
8853             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
8854                 iterpflags |= OPpITER_DEF;
8855         }
8856     }
8857     else {
8858         sv = newGVOP(OP_GV, 0, PL_defgv);
8859         iterpflags |= OPpITER_DEF;
8860     }
8861
8862     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
8863         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
8864         iterflags |= OPf_STACKED;
8865     }
8866     else if (expr->op_type == OP_NULL &&
8867              (expr->op_flags & OPf_KIDS) &&
8868              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
8869     {
8870         /* Basically turn for($x..$y) into the same as for($x,$y), but we
8871          * set the STACKED flag to indicate that these values are to be
8872          * treated as min/max values by 'pp_enteriter'.
8873          */
8874         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
8875         LOGOP* const range = (LOGOP*) flip->op_first;
8876         OP* const left  = range->op_first;
8877         OP* const right = OpSIBLING(left);
8878         LISTOP* listop;
8879
8880         range->op_flags &= ~OPf_KIDS;
8881         /* detach range's children */
8882         op_sibling_splice((OP*)range, NULL, -1, NULL);
8883
8884         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
8885         listop->op_first->op_next = range->op_next;
8886         left->op_next = range->op_other;
8887         right->op_next = (OP*)listop;
8888         listop->op_next = listop->op_first;
8889
8890         op_free(expr);
8891         expr = (OP*)(listop);
8892         op_null(expr);
8893         iterflags |= OPf_STACKED;
8894     }
8895     else {
8896         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
8897     }
8898
8899     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
8900                                   op_append_elem(OP_LIST, list(expr),
8901                                                  scalar(sv)));
8902     assert(!loop->op_next);
8903     /* for my  $x () sets OPpLVAL_INTRO;
8904      * for our $x () sets OPpOUR_INTRO */
8905     loop->op_private = (U8)iterpflags;
8906     if (loop->op_slabbed
8907      && DIFF(loop, OpSLOT(loop)->opslot_next)
8908          < SIZE_TO_PSIZE(sizeof(LOOP)))
8909     {
8910         LOOP *tmp;
8911         NewOp(1234,tmp,1,LOOP);
8912         Copy(loop,tmp,1,LISTOP);
8913         assert(loop->op_last->op_sibparent == (OP*)loop);
8914         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
8915         S_op_destroy(aTHX_ (OP*)loop);
8916         loop = tmp;
8917     }
8918     else if (!loop->op_slabbed)
8919     {
8920         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
8921         OpLASTSIB_set(loop->op_last, (OP*)loop);
8922     }
8923     loop->op_targ = padoff;
8924     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
8925     return wop;
8926 }
8927
8928 /*
8929 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
8930
8931 Constructs, checks, and returns a loop-exiting op (such as C<goto>
8932 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
8933 determining the target of the op; it is consumed by this function and
8934 becomes part of the constructed op tree.
8935
8936 =cut
8937 */
8938
8939 OP*
8940 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
8941 {
8942     OP *o = NULL;
8943
8944     PERL_ARGS_ASSERT_NEWLOOPEX;
8945
8946     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
8947         || type == OP_CUSTOM);
8948
8949     if (type != OP_GOTO) {
8950         /* "last()" means "last" */
8951         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
8952             o = newOP(type, OPf_SPECIAL);
8953         }
8954     }
8955     else {
8956         /* Check whether it's going to be a goto &function */
8957         if (label->op_type == OP_ENTERSUB
8958                 && !(label->op_flags & OPf_STACKED))
8959             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
8960     }
8961
8962     /* Check for a constant argument */
8963     if (label->op_type == OP_CONST) {
8964             SV * const sv = ((SVOP *)label)->op_sv;
8965             STRLEN l;
8966             const char *s = SvPV_const(sv,l);
8967             if (l == strlen(s)) {
8968                 o = newPVOP(type,
8969                             SvUTF8(((SVOP*)label)->op_sv),
8970                             savesharedpv(
8971                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
8972             }
8973     }
8974     
8975     /* If we have already created an op, we do not need the label. */
8976     if (o)
8977                 op_free(label);
8978     else o = newUNOP(type, OPf_STACKED, label);
8979
8980     PL_hints |= HINT_BLOCK_SCOPE;
8981     return o;
8982 }
8983
8984 /* if the condition is a literal array or hash
8985    (or @{ ... } etc), make a reference to it.
8986  */
8987 STATIC OP *
8988 S_ref_array_or_hash(pTHX_ OP *cond)
8989 {
8990     if (cond
8991     && (cond->op_type == OP_RV2AV
8992     ||  cond->op_type == OP_PADAV
8993     ||  cond->op_type == OP_RV2HV
8994     ||  cond->op_type == OP_PADHV))
8995
8996         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
8997
8998     else if(cond
8999     && (cond->op_type == OP_ASLICE
9000     ||  cond->op_type == OP_KVASLICE
9001     ||  cond->op_type == OP_HSLICE
9002     ||  cond->op_type == OP_KVHSLICE)) {
9003
9004         /* anonlist now needs a list from this op, was previously used in
9005          * scalar context */
9006         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
9007         cond->op_flags |= OPf_WANT_LIST;
9008
9009         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
9010     }
9011
9012     else
9013         return cond;
9014 }
9015
9016 /* These construct the optree fragments representing given()
9017    and when() blocks.
9018
9019    entergiven and enterwhen are LOGOPs; the op_other pointer
9020    points up to the associated leave op. We need this so we
9021    can put it in the context and make break/continue work.
9022    (Also, of course, pp_enterwhen will jump straight to
9023    op_other if the match fails.)
9024  */
9025
9026 STATIC OP *
9027 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
9028                    I32 enter_opcode, I32 leave_opcode,
9029                    PADOFFSET entertarg)
9030 {
9031     dVAR;
9032     LOGOP *enterop;
9033     OP *o;
9034
9035     PERL_ARGS_ASSERT_NEWGIVWHENOP;
9036     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
9037
9038     enterop = alloc_LOGOP(enter_opcode, block, NULL);
9039     enterop->op_targ = 0;
9040     enterop->op_private = 0;
9041
9042     o = newUNOP(leave_opcode, 0, (OP *) enterop);
9043
9044     if (cond) {
9045         /* prepend cond if we have one */
9046         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
9047
9048         o->op_next = LINKLIST(cond);
9049         cond->op_next = (OP *) enterop;
9050     }
9051     else {
9052         /* This is a default {} block */
9053         enterop->op_flags |= OPf_SPECIAL;
9054         o      ->op_flags |= OPf_SPECIAL;
9055
9056         o->op_next = (OP *) enterop;
9057     }
9058
9059     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
9060                                        entergiven and enterwhen both
9061                                        use ck_null() */
9062
9063     enterop->op_next = LINKLIST(block);
9064     block->op_next = enterop->op_other = o;
9065
9066     return o;
9067 }
9068
9069 /* Does this look like a boolean operation? For these purposes
9070    a boolean operation is:
9071      - a subroutine call [*]
9072      - a logical connective
9073      - a comparison operator
9074      - a filetest operator, with the exception of -s -M -A -C
9075      - defined(), exists() or eof()
9076      - /$re/ or $foo =~ /$re/
9077    
9078    [*] possibly surprising
9079  */
9080 STATIC bool
9081 S_looks_like_bool(pTHX_ const OP *o)
9082 {
9083     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
9084
9085     switch(o->op_type) {
9086         case OP_OR:
9087         case OP_DOR:
9088             return looks_like_bool(cLOGOPo->op_first);
9089
9090         case OP_AND:
9091         {
9092             OP* sibl = OpSIBLING(cLOGOPo->op_first);
9093             ASSUME(sibl);
9094             return (
9095                 looks_like_bool(cLOGOPo->op_first)
9096              && looks_like_bool(sibl));
9097         }
9098
9099         case OP_NULL:
9100         case OP_SCALAR:
9101             return (
9102                 o->op_flags & OPf_KIDS
9103             && looks_like_bool(cUNOPo->op_first));
9104
9105         case OP_ENTERSUB:
9106
9107         case OP_NOT:    case OP_XOR:
9108
9109         case OP_EQ:     case OP_NE:     case OP_LT:
9110         case OP_GT:     case OP_LE:     case OP_GE:
9111
9112         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
9113         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
9114
9115         case OP_SEQ:    case OP_SNE:    case OP_SLT:
9116         case OP_SGT:    case OP_SLE:    case OP_SGE:
9117         
9118         case OP_SMARTMATCH:
9119         
9120         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
9121         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
9122         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
9123         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
9124         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
9125         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
9126         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
9127         case OP_FTTEXT:   case OP_FTBINARY:
9128         
9129         case OP_DEFINED: case OP_EXISTS:
9130         case OP_MATCH:   case OP_EOF:
9131
9132         case OP_FLOP:
9133
9134             return TRUE;
9135
9136         case OP_INDEX:
9137         case OP_RINDEX:
9138             /* optimised-away (index() != -1) or similar comparison */
9139             if (o->op_private & OPpTRUEBOOL)
9140                 return TRUE;
9141             return FALSE;
9142         
9143         case OP_CONST:
9144             /* Detect comparisons that have been optimized away */
9145             if (cSVOPo->op_sv == &PL_sv_yes
9146             ||  cSVOPo->op_sv == &PL_sv_no)
9147             
9148                 return TRUE;
9149             else
9150                 return FALSE;
9151         /* FALLTHROUGH */
9152         default:
9153             return FALSE;
9154     }
9155 }
9156
9157 /*
9158 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
9159
9160 Constructs, checks, and returns an op tree expressing a C<given> block.
9161 C<cond> supplies the expression to whose value C<$_> will be locally
9162 aliased, and C<block> supplies the body of the C<given> construct; they
9163 are consumed by this function and become part of the constructed op tree.
9164 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
9165
9166 =cut
9167 */
9168
9169 OP *
9170 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
9171 {
9172     PERL_ARGS_ASSERT_NEWGIVENOP;
9173     PERL_UNUSED_ARG(defsv_off);
9174
9175     assert(!defsv_off);
9176     return newGIVWHENOP(
9177         ref_array_or_hash(cond),
9178         block,
9179         OP_ENTERGIVEN, OP_LEAVEGIVEN,
9180         0);
9181 }
9182
9183 /*
9184 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
9185
9186 Constructs, checks, and returns an op tree expressing a C<when> block.
9187 C<cond> supplies the test expression, and C<block> supplies the block
9188 that will be executed if the test evaluates to true; they are consumed
9189 by this function and become part of the constructed op tree.  C<cond>
9190 will be interpreted DWIMically, often as a comparison against C<$_>,
9191 and may be null to generate a C<default> block.
9192
9193 =cut
9194 */
9195
9196 OP *
9197 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
9198 {
9199     const bool cond_llb = (!cond || looks_like_bool(cond));
9200     OP *cond_op;
9201
9202     PERL_ARGS_ASSERT_NEWWHENOP;
9203
9204     if (cond_llb)
9205         cond_op = cond;
9206     else {
9207         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
9208                 newDEFSVOP(),
9209                 scalar(ref_array_or_hash(cond)));
9210     }
9211     
9212     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
9213 }
9214
9215 /* must not conflict with SVf_UTF8 */
9216 #define CV_CKPROTO_CURSTASH     0x1
9217
9218 void
9219 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
9220                     const STRLEN len, const U32 flags)
9221 {
9222     SV *name = NULL, *msg;
9223     const char * cvp = SvROK(cv)
9224                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
9225                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
9226                            : ""
9227                         : CvPROTO(cv);
9228     STRLEN clen = CvPROTOLEN(cv), plen = len;
9229
9230     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
9231
9232     if (p == NULL && cvp == NULL)
9233         return;
9234
9235     if (!ckWARN_d(WARN_PROTOTYPE))
9236         return;
9237
9238     if (p && cvp) {
9239         p = S_strip_spaces(aTHX_ p, &plen);
9240         cvp = S_strip_spaces(aTHX_ cvp, &clen);
9241         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
9242             if (plen == clen && memEQ(cvp, p, plen))
9243                 return;
9244         } else {
9245             if (flags & SVf_UTF8) {
9246                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
9247                     return;
9248             }
9249             else {
9250                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
9251                     return;
9252             }
9253         }
9254     }
9255
9256     msg = sv_newmortal();
9257
9258     if (gv)
9259     {
9260         if (isGV(gv))
9261             gv_efullname3(name = sv_newmortal(), gv, NULL);
9262         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
9263             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
9264         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
9265             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
9266             sv_catpvs(name, "::");
9267             if (SvROK(gv)) {
9268                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
9269                 assert (CvNAMED(SvRV_const(gv)));
9270                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
9271             }
9272             else sv_catsv(name, (SV *)gv);
9273         }
9274         else name = (SV *)gv;
9275     }
9276     sv_setpvs(msg, "Prototype mismatch:");
9277     if (name)
9278         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
9279     if (cvp)
9280         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
9281             UTF8fARG(SvUTF8(cv),clen,cvp)
9282         );
9283     else
9284         sv_catpvs(msg, ": none");
9285     sv_catpvs(msg, " vs ");
9286     if (p)
9287         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
9288     else
9289         sv_catpvs(msg, "none");
9290     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
9291 }
9292
9293 static void const_sv_xsub(pTHX_ CV* cv);
9294 static void const_av_xsub(pTHX_ CV* cv);
9295
9296 /*
9297
9298 =head1 Optree Manipulation Functions
9299
9300 =for apidoc cv_const_sv
9301
9302 If C<cv> is a constant sub eligible for inlining, returns the constant
9303 value returned by the sub.  Otherwise, returns C<NULL>.
9304
9305 Constant subs can be created with C<newCONSTSUB> or as described in
9306 L<perlsub/"Constant Functions">.
9307
9308 =cut
9309 */
9310 SV *
9311 Perl_cv_const_sv(const CV *const cv)
9312 {
9313     SV *sv;
9314     if (!cv)
9315         return NULL;
9316     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
9317         return NULL;
9318     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
9319     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
9320     return sv;
9321 }
9322
9323 SV *
9324 Perl_cv_const_sv_or_av(const CV * const cv)
9325 {
9326     if (!cv)
9327         return NULL;
9328     if (SvROK(cv)) return SvRV((SV *)cv);
9329     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
9330     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
9331 }
9332
9333 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
9334  * Can be called in 2 ways:
9335  *
9336  * !allow_lex
9337  *      look for a single OP_CONST with attached value: return the value
9338  *
9339  * allow_lex && !CvCONST(cv);
9340  *
9341  *      examine the clone prototype, and if contains only a single
9342  *      OP_CONST, return the value; or if it contains a single PADSV ref-
9343  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
9344  *      a candidate for "constizing" at clone time, and return NULL.
9345  */
9346
9347 static SV *
9348 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
9349 {
9350     SV *sv = NULL;
9351     bool padsv = FALSE;
9352
9353     assert(o);
9354     assert(cv);
9355
9356     for (; o; o = o->op_next) {
9357         const OPCODE type = o->op_type;
9358
9359         if (type == OP_NEXTSTATE || type == OP_LINESEQ
9360              || type == OP_NULL
9361              || type == OP_PUSHMARK)
9362                 continue;
9363         if (type == OP_DBSTATE)
9364                 continue;
9365         if (type == OP_LEAVESUB)
9366             break;
9367         if (sv)
9368             return NULL;
9369         if (type == OP_CONST && cSVOPo->op_sv)
9370             sv = cSVOPo->op_sv;
9371         else if (type == OP_UNDEF && !o->op_private) {
9372             sv = newSV(0);
9373             SAVEFREESV(sv);
9374         }
9375         else if (allow_lex && type == OP_PADSV) {
9376                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
9377                 {
9378                     sv = &PL_sv_undef; /* an arbitrary non-null value */
9379                     padsv = TRUE;
9380                 }
9381                 else
9382                     return NULL;
9383         }
9384         else {
9385             return NULL;
9386         }
9387     }
9388     if (padsv) {
9389         CvCONST_on(cv);
9390         return NULL;
9391     }
9392     return sv;
9393 }
9394
9395 static void
9396 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
9397                         PADNAME * const name, SV ** const const_svp)
9398 {
9399     assert (cv);
9400     assert (o || name);
9401     assert (const_svp);
9402     if (!block) {
9403         if (CvFLAGS(PL_compcv)) {
9404             /* might have had built-in attrs applied */
9405             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
9406             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
9407              && ckWARN(WARN_MISC))
9408             {
9409                 /* protect against fatal warnings leaking compcv */
9410                 SAVEFREESV(PL_compcv);
9411                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
9412                 SvREFCNT_inc_simple_void_NN(PL_compcv);
9413             }
9414             CvFLAGS(cv) |=
9415                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
9416                   & ~(CVf_LVALUE * pureperl));
9417         }
9418         return;
9419     }
9420
9421     /* redundant check for speed: */
9422     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
9423         const line_t oldline = CopLINE(PL_curcop);
9424         SV *namesv = o
9425             ? cSVOPo->op_sv
9426             : sv_2mortal(newSVpvn_utf8(
9427                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
9428               ));
9429         if (PL_parser && PL_parser->copline != NOLINE)
9430             /* This ensures that warnings are reported at the first
9431                line of a redefinition, not the last.  */
9432             CopLINE_set(PL_curcop, PL_parser->copline);
9433         /* protect against fatal warnings leaking compcv */
9434         SAVEFREESV(PL_compcv);
9435         report_redefined_cv(namesv, cv, const_svp);
9436         SvREFCNT_inc_simple_void_NN(PL_compcv);
9437         CopLINE_set(PL_curcop, oldline);
9438     }
9439     SAVEFREESV(cv);
9440     return;
9441 }
9442
9443 CV *
9444 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
9445 {
9446     CV **spot;
9447     SV **svspot;
9448     const char *ps;
9449     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
9450     U32 ps_utf8 = 0;
9451     CV *cv = NULL;
9452     CV *compcv = PL_compcv;
9453     SV *const_sv;
9454     PADNAME *name;
9455     PADOFFSET pax = o->op_targ;
9456     CV *outcv = CvOUTSIDE(PL_compcv);
9457     CV *clonee = NULL;
9458     HEK *hek = NULL;
9459     bool reusable = FALSE;
9460     OP *start = NULL;
9461 #ifdef PERL_DEBUG_READONLY_OPS
9462     OPSLAB *slab = NULL;
9463 #endif
9464
9465     PERL_ARGS_ASSERT_NEWMYSUB;
9466
9467     PL_hints |= HINT_BLOCK_SCOPE;
9468
9469     /* Find the pad slot for storing the new sub.
9470        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
9471        need to look in CvOUTSIDE and find the pad belonging to the enclos-
9472        ing sub.  And then we need to dig deeper if this is a lexical from
9473        outside, as in:
9474            my sub foo; sub { sub foo { } }
9475      */
9476   redo:
9477     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
9478     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
9479         pax = PARENT_PAD_INDEX(name);
9480         outcv = CvOUTSIDE(outcv);
9481         assert(outcv);
9482         goto redo;
9483     }
9484     svspot =
9485         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
9486                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
9487     spot = (CV **)svspot;
9488
9489     if (!(PL_parser && PL_parser->error_count))
9490         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
9491
9492     if (proto) {
9493         assert(proto->op_type == OP_CONST);
9494         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
9495         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
9496     }
9497     else
9498         ps = NULL;
9499
9500     if (proto)
9501         SAVEFREEOP(proto);
9502     if (attrs)
9503         SAVEFREEOP(attrs);
9504
9505     if (PL_parser && PL_parser->error_count) {
9506         op_free(block);
9507         SvREFCNT_dec(PL_compcv);
9508         PL_compcv = 0;
9509         goto done;
9510     }
9511
9512     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
9513         cv = *spot;
9514         svspot = (SV **)(spot = &clonee);
9515     }
9516     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
9517         cv = *spot;
9518     else {
9519         assert (SvTYPE(*spot) == SVt_PVCV);
9520         if (CvNAMED(*spot))
9521             hek = CvNAME_HEK(*spot);
9522         else {
9523             dVAR;
9524             U32 hash;
9525             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
9526             CvNAME_HEK_set(*spot, hek =
9527                 share_hek(
9528                     PadnamePV(name)+1,
9529                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
9530                     hash
9531                 )
9532             );
9533             CvLEXICAL_on(*spot);
9534         }
9535         cv = PadnamePROTOCV(name);
9536         svspot = (SV **)(spot = &PadnamePROTOCV(name));
9537     }
9538
9539     if (block) {
9540         /* This makes sub {}; work as expected.  */
9541         if (block->op_type == OP_STUB) {
9542             const line_t l = PL_parser->copline;
9543             op_free(block);
9544             block = newSTATEOP(0, NULL, 0);
9545             PL_parser->copline = l;
9546         }
9547         block = CvLVALUE(compcv)
9548              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
9549                    ? newUNOP(OP_LEAVESUBLV, 0,
9550                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
9551                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
9552         start = LINKLIST(block);
9553         block->op_next = 0;
9554         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
9555             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
9556         else
9557             const_sv = NULL;
9558     }
9559     else
9560         const_sv = NULL;
9561
9562     if (cv) {
9563         const bool exists = CvROOT(cv) || CvXSUB(cv);
9564
9565         /* if the subroutine doesn't exist and wasn't pre-declared
9566          * with a prototype, assume it will be AUTOLOADed,
9567          * skipping the prototype check
9568          */
9569         if (exists || SvPOK(cv))
9570             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
9571                                  ps_utf8);
9572         /* already defined? */
9573         if (exists) {
9574             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
9575             if (block)
9576                 cv = NULL;
9577             else {
9578                 if (attrs)
9579                     goto attrs;
9580                 /* just a "sub foo;" when &foo is already defined */
9581                 SAVEFREESV(compcv);
9582                 goto done;
9583             }
9584         }
9585         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
9586             cv = NULL;
9587             reusable = TRUE;
9588         }
9589     }
9590
9591     if (const_sv) {
9592         SvREFCNT_inc_simple_void_NN(const_sv);
9593         SvFLAGS(const_sv) |= SVs_PADTMP;
9594         if (cv) {
9595             assert(!CvROOT(cv) && !CvCONST(cv));
9596             cv_forget_slab(cv);
9597         }
9598         else {
9599             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9600             CvFILE_set_from_cop(cv, PL_curcop);
9601             CvSTASH_set(cv, PL_curstash);
9602             *spot = cv;
9603         }
9604         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
9605         CvXSUBANY(cv).any_ptr = const_sv;
9606         CvXSUB(cv) = const_sv_xsub;
9607         CvCONST_on(cv);
9608         CvISXSUB_on(cv);
9609         PoisonPADLIST(cv);
9610         CvFLAGS(cv) |= CvMETHOD(compcv);
9611         op_free(block);
9612         SvREFCNT_dec(compcv);
9613         PL_compcv = NULL;
9614         goto setname;
9615     }
9616
9617     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
9618        determine whether this sub definition is in the same scope as its
9619        declaration.  If this sub definition is inside an inner named pack-
9620        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
9621        the package sub.  So check PadnameOUTER(name) too.
9622      */
9623     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
9624         assert(!CvWEAKOUTSIDE(compcv));
9625         SvREFCNT_dec(CvOUTSIDE(compcv));
9626         CvWEAKOUTSIDE_on(compcv);
9627     }
9628     /* XXX else do we have a circular reference? */
9629
9630     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
9631         /* transfer PL_compcv to cv */
9632         if (block) {
9633             cv_flags_t preserved_flags =
9634                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
9635             PADLIST *const temp_padl = CvPADLIST(cv);
9636             CV *const temp_cv = CvOUTSIDE(cv);
9637             const cv_flags_t other_flags =
9638                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
9639             OP * const cvstart = CvSTART(cv);
9640
9641             SvPOK_off(cv);
9642             CvFLAGS(cv) =
9643                 CvFLAGS(compcv) | preserved_flags;
9644             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
9645             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
9646             CvPADLIST_set(cv, CvPADLIST(compcv));
9647             CvOUTSIDE(compcv) = temp_cv;
9648             CvPADLIST_set(compcv, temp_padl);
9649             CvSTART(cv) = CvSTART(compcv);
9650             CvSTART(compcv) = cvstart;
9651             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
9652             CvFLAGS(compcv) |= other_flags;
9653
9654             if (CvFILE(cv) && CvDYNFILE(cv)) {
9655                 Safefree(CvFILE(cv));
9656             }
9657
9658             /* inner references to compcv must be fixed up ... */
9659             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
9660             if (PERLDB_INTER)/* Advice debugger on the new sub. */
9661                 ++PL_sub_generation;
9662         }
9663         else {
9664             /* Might have had built-in attributes applied -- propagate them. */
9665             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
9666         }
9667         /* ... before we throw it away */
9668         SvREFCNT_dec(compcv);
9669         PL_compcv = compcv = cv;
9670     }
9671     else {
9672         cv = compcv;
9673         *spot = cv;
9674     }
9675
9676   setname:
9677     CvLEXICAL_on(cv);
9678     if (!CvNAME_HEK(cv)) {
9679         if (hek) (void)share_hek_hek(hek);
9680         else {
9681             dVAR;
9682             U32 hash;
9683             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
9684             hek = share_hek(PadnamePV(name)+1,
9685                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
9686                       hash);
9687         }
9688         CvNAME_HEK_set(cv, hek);
9689     }
9690
9691     if (const_sv)
9692         goto clone;
9693
9694     CvFILE_set_from_cop(cv, PL_curcop);
9695     CvSTASH_set(cv, PL_curstash);
9696
9697     if (ps) {
9698         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
9699         if (ps_utf8)
9700             SvUTF8_on(MUTABLE_SV(cv));
9701     }
9702
9703     if (block) {
9704         /* If we assign an optree to a PVCV, then we've defined a
9705          * subroutine that the debugger could be able to set a breakpoint
9706          * in, so signal to pp_entereval that it should not throw away any
9707          * saved lines at scope exit.  */
9708
9709         PL_breakable_sub_gen++;
9710         CvROOT(cv) = block;
9711         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
9712            itself has a refcount. */
9713         CvSLABBED_off(cv);
9714         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
9715 #ifdef PERL_DEBUG_READONLY_OPS
9716         slab = (OPSLAB *)CvSTART(cv);
9717 #endif
9718         S_process_optree(aTHX_ cv, block, start);
9719     }
9720
9721   attrs:
9722     if (attrs) {
9723         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
9724         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
9725     }
9726
9727     if (block) {
9728         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
9729             SV * const tmpstr = sv_newmortal();
9730             GV * const db_postponed = gv_fetchpvs("DB::postponed",
9731                                                   GV_ADDMULTI, SVt_PVHV);
9732             HV *hv;
9733             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
9734                                           CopFILE(PL_curcop),
9735                                           (long)PL_subline,
9736                                           (long)CopLINE(PL_curcop));
9737             if (HvNAME_HEK(PL_curstash)) {
9738                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
9739                 sv_catpvs(tmpstr, "::");
9740             }
9741             else
9742                 sv_setpvs(tmpstr, "__ANON__::");
9743
9744             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
9745                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
9746             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
9747                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
9748             hv = GvHVn(db_postponed);
9749             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
9750                 CV * const pcv = GvCV(db_postponed);
9751                 if (pcv) {
9752                     dSP;
9753                     PUSHMARK(SP);
9754                     XPUSHs(tmpstr);
9755                     PUTBACK;
9756                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
9757                 }
9758             }
9759         }
9760     }
9761
9762   clone:
9763     if (clonee) {
9764         assert(CvDEPTH(outcv));
9765         spot = (CV **)
9766             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
9767         if (reusable)
9768             cv_clone_into(clonee, *spot);
9769         else *spot = cv_clone(clonee);
9770         SvREFCNT_dec_NN(clonee);
9771         cv = *spot;
9772     }
9773
9774     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
9775         PADOFFSET depth = CvDEPTH(outcv);
9776         while (--depth) {
9777             SV *oldcv;
9778             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
9779             oldcv = *svspot;
9780             *svspot = SvREFCNT_inc_simple_NN(cv);
9781             SvREFCNT_dec(oldcv);
9782         }
9783     }
9784
9785   done:
9786     if (PL_parser)
9787         PL_parser->copline = NOLINE;
9788     LEAVE_SCOPE(floor);
9789 #ifdef PERL_DEBUG_READONLY_OPS
9790     if (slab)
9791         Slab_to_ro(slab);
9792 #endif
9793     op_free(o);
9794     return cv;
9795 }
9796
9797 /*
9798 =for apidoc m|CV *|newATTRSUB_x|I32 floor|OP *o|OP *proto|OP *attrs|OP *block|bool o_is_gv
9799
9800 Construct a Perl subroutine, also performing some surrounding jobs.
9801
9802 This function is expected to be called in a Perl compilation context,
9803 and some aspects of the subroutine are taken from global variables
9804 associated with compilation.  In particular, C<PL_compcv> represents
9805 the subroutine that is currently being compiled.  It must be non-null
9806 when this function is called, and some aspects of the subroutine being
9807 constructed are taken from it.  The constructed subroutine may actually
9808 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
9809
9810 If C<block> is null then the subroutine will have no body, and for the
9811 time being it will be an error to call it.  This represents a forward
9812 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
9813 non-null then it provides the Perl code of the subroutine body, which
9814 will be executed when the subroutine is called.  This body includes
9815 any argument unwrapping code resulting from a subroutine signature or
9816 similar.  The pad use of the code must correspond to the pad attached
9817 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
9818 C<leavesublv> op; this function will add such an op.  C<block> is consumed
9819 by this function and will become part of the constructed subroutine.
9820
9821 C<proto> specifies the subroutine's prototype, unless one is supplied
9822 as an attribute (see below).  If C<proto> is null, then the subroutine
9823 will not have a prototype.  If C<proto> is non-null, it must point to a
9824 C<const> op whose value is a string, and the subroutine will have that
9825 string as its prototype.  If a prototype is supplied as an attribute, the
9826 attribute takes precedence over C<proto>, but in that case C<proto> should
9827 preferably be null.  In any case, C<proto> is consumed by this function.
9828
9829 C<attrs> supplies attributes to be applied the subroutine.  A handful of
9830 attributes take effect by built-in means, being applied to C<PL_compcv>
9831 immediately when seen.  Other attributes are collected up and attached
9832 to the subroutine by this route.  C<attrs> may be null to supply no
9833 attributes, or point to a C<const> op for a single attribute, or point
9834 to a C<list> op whose children apart from the C<pushmark> are C<const>
9835 ops for one or more attributes.  Each C<const> op must be a string,
9836 giving the attribute name optionally followed by parenthesised arguments,
9837 in the manner in which attributes appear in Perl source.  The attributes
9838 will be applied to the sub by this function.  C<attrs> is consumed by
9839 this function.
9840
9841 If C<o_is_gv> is false and C<o> is null, then the subroutine will
9842 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
9843 must point to a C<const> op, which will be consumed by this function,
9844 and its string value supplies a name for the subroutine.  The name may
9845 be qualified or unqualified, and if it is unqualified then a default
9846 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
9847 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
9848 by which the subroutine will be named.
9849
9850 If there is already a subroutine of the specified name, then the new
9851 sub will either replace the existing one in the glob or be merged with
9852 the existing one.  A warning may be generated about redefinition.
9853
9854 If the subroutine has one of a few special names, such as C<BEGIN> or
9855 C<END>, then it will be claimed by the appropriate queue for automatic
9856 running of phase-related subroutines.  In this case the relevant glob will
9857 be left not containing any subroutine, even if it did contain one before.
9858 In the case of C<BEGIN>, the subroutine will be executed and the reference
9859 to it disposed of before this function returns.
9860
9861 The function returns a pointer to the constructed subroutine.  If the sub
9862 is anonymous then ownership of one counted reference to the subroutine
9863 is transferred to the caller.  If the sub is named then the caller does
9864 not get ownership of a reference.  In most such cases, where the sub
9865 has a non-phase name, the sub will be alive at the point it is returned
9866 by virtue of being contained in the glob that names it.  A phase-named
9867 subroutine will usually be alive by virtue of the reference owned by the
9868 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
9869 been executed, will quite likely have been destroyed already by the
9870 time this function returns, making it erroneous for the caller to make
9871 any use of the returned pointer.  It is the caller's responsibility to
9872 ensure that it knows which of these situations applies.
9873
9874 =cut
9875 */
9876
9877 /* _x = extended */
9878 CV *
9879 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
9880                             OP *block, bool o_is_gv)
9881 {
9882     GV *gv;
9883     const char *ps;
9884     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
9885     U32 ps_utf8 = 0;
9886     CV *cv = NULL;     /* the previous CV with this name, if any */
9887     SV *const_sv;
9888     const bool ec = PL_parser && PL_parser->error_count;
9889     /* If the subroutine has no body, no attributes, and no builtin attributes
9890        then it's just a sub declaration, and we may be able to get away with
9891        storing with a placeholder scalar in the symbol table, rather than a
9892        full CV.  If anything is present then it will take a full CV to
9893        store it.  */
9894     const I32 gv_fetch_flags
9895         = ec ? GV_NOADD_NOINIT :
9896         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
9897         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
9898     STRLEN namlen = 0;
9899     const char * const name =
9900          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
9901     bool has_name;
9902     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
9903     bool evanescent = FALSE;
9904     OP *start = NULL;
9905 #ifdef PERL_DEBUG_READONLY_OPS
9906     OPSLAB *slab = NULL;
9907 #endif
9908
9909     if (o_is_gv) {
9910         gv = (GV*)o;
9911         o = NULL;
9912         has_name = TRUE;
9913     } else if (name) {
9914         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
9915            hek and CvSTASH pointer together can imply the GV.  If the name
9916            contains a package name, then GvSTASH(CvGV(cv)) may differ from
9917            CvSTASH, so forego the optimisation if we find any.
9918            Also, we may be called from load_module at run time, so
9919            PL_curstash (which sets CvSTASH) may not point to the stash the
9920            sub is stored in.  */
9921         /* XXX This optimization is currently disabled for packages other
9922                than main, since there was too much CPAN breakage.  */
9923         const I32 flags =
9924            ec ? GV_NOADD_NOINIT
9925               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
9926                || PL_curstash != PL_defstash
9927                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
9928                     ? gv_fetch_flags
9929                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
9930         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
9931         has_name = TRUE;
9932     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
9933         SV * const sv = sv_newmortal();
9934         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
9935                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
9936                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
9937         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
9938         has_name = TRUE;
9939     } else if (PL_curstash) {
9940         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
9941         has_name = FALSE;
9942     } else {
9943         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
9944         has_name = FALSE;
9945     }
9946
9947     if (!ec) {
9948         if (isGV(gv)) {
9949             move_proto_attr(&proto, &attrs, gv, 0);
9950         } else {
9951             assert(cSVOPo);
9952             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
9953         }
9954     }
9955
9956     if (proto) {
9957         assert(proto->op_type == OP_CONST);
9958         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
9959         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
9960     }
9961     else
9962         ps = NULL;
9963
9964     if (o)
9965         SAVEFREEOP(o);
9966     if (proto)
9967         SAVEFREEOP(proto);
9968     if (attrs)
9969         SAVEFREEOP(attrs);
9970
9971     if (ec) {
9972         op_free(block);
9973
9974         if (name)
9975             SvREFCNT_dec(PL_compcv);
9976         else
9977             cv = PL_compcv;
9978
9979         PL_compcv = 0;
9980         if (name && block) {
9981             const char *s = (char *) my_memrchr(name, ':', namlen);
9982             s = s ? s+1 : name;
9983             if (strEQ(s, "BEGIN")) {
9984                 if (PL_in_eval & EVAL_KEEPERR)
9985                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
9986                 else {
9987                     SV * const errsv = ERRSV;
9988                     /* force display of errors found but not reported */
9989                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
9990                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
9991                 }
9992             }
9993         }
9994         goto done;
9995     }
9996
9997     if (!block && SvTYPE(gv) != SVt_PVGV) {
9998         /* If we are not defining a new sub and the existing one is not a
9999            full GV + CV... */
10000         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
10001             /* We are applying attributes to an existing sub, so we need it
10002                upgraded if it is a constant.  */
10003             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
10004                 gv_init_pvn(gv, PL_curstash, name, namlen,
10005                             SVf_UTF8 * name_is_utf8);
10006         }
10007         else {                  /* Maybe prototype now, and had at maximum
10008                                    a prototype or const/sub ref before.  */
10009             if (SvTYPE(gv) > SVt_NULL) {
10010                 cv_ckproto_len_flags((const CV *)gv,
10011                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
10012                                     ps_len, ps_utf8);
10013             }
10014
10015             if (!SvROK(gv)) {
10016                 if (ps) {
10017                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
10018                     if (ps_utf8)
10019                         SvUTF8_on(MUTABLE_SV(gv));
10020                 }
10021                 else
10022                     sv_setiv(MUTABLE_SV(gv), -1);
10023             }
10024
10025             SvREFCNT_dec(PL_compcv);
10026             cv = PL_compcv = NULL;
10027             goto done;
10028         }
10029     }
10030
10031     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
10032         ? NULL
10033         : isGV(gv)
10034             ? GvCV(gv)
10035             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
10036                 ? (CV *)SvRV(gv)
10037                 : NULL;
10038
10039     if (block) {
10040         assert(PL_parser);
10041         /* This makes sub {}; work as expected.  */
10042         if (block->op_type == OP_STUB) {
10043             const line_t l = PL_parser->copline;
10044             op_free(block);
10045             block = newSTATEOP(0, NULL, 0);
10046             PL_parser->copline = l;
10047         }
10048         block = CvLVALUE(PL_compcv)
10049              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
10050                     && (!isGV(gv) || !GvASSUMECV(gv)))
10051                    ? newUNOP(OP_LEAVESUBLV, 0,
10052                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
10053                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
10054         start = LINKLIST(block);
10055         block->op_next = 0;
10056         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
10057             const_sv =
10058                 S_op_const_sv(aTHX_ start, PL_compcv,
10059                                         cBOOL(CvCLONE(PL_compcv)));
10060         else
10061             const_sv = NULL;
10062     }
10063     else
10064         const_sv = NULL;
10065
10066     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
10067         cv_ckproto_len_flags((const CV *)gv,
10068                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
10069                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
10070         if (SvROK(gv)) {
10071             /* All the other code for sub redefinition warnings expects the
10072                clobbered sub to be a CV.  Instead of making all those code
10073                paths more complex, just inline the RV version here.  */
10074             const line_t oldline = CopLINE(PL_curcop);
10075             assert(IN_PERL_COMPILETIME);
10076             if (PL_parser && PL_parser->copline != NOLINE)
10077                 /* This ensures that warnings are reported at the first
10078                    line of a redefinition, not the last.  */
10079                 CopLINE_set(PL_curcop, PL_parser->copline);
10080             /* protect against fatal warnings leaking compcv */
10081             SAVEFREESV(PL_compcv);
10082
10083             if (ckWARN(WARN_REDEFINE)
10084              || (  ckWARN_d(WARN_REDEFINE)
10085                 && (  !const_sv || SvRV(gv) == const_sv
10086                    || sv_cmp(SvRV(gv), const_sv)  ))) {
10087                 assert(cSVOPo);
10088                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
10089                           "Constant subroutine %" SVf " redefined",
10090                           SVfARG(cSVOPo->op_sv));
10091             }
10092
10093             SvREFCNT_inc_simple_void_NN(PL_compcv);
10094             CopLINE_set(PL_curcop, oldline);
10095             SvREFCNT_dec(SvRV(gv));
10096         }
10097     }
10098
10099     if (cv) {
10100         const bool exists = CvROOT(cv) || CvXSUB(cv);
10101
10102         /* if the subroutine doesn't exist and wasn't pre-declared
10103          * with a prototype, assume it will be AUTOLOADed,
10104          * skipping the prototype check
10105          */
10106         if (exists || SvPOK(cv))
10107             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
10108         /* already defined (or promised)? */
10109         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
10110             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
10111             if (block)
10112                 cv = NULL;
10113             else {
10114                 if (attrs)
10115                     goto attrs;
10116                 /* just a "sub foo;" when &foo is already defined */
10117                 SAVEFREESV(PL_compcv);
10118                 goto done;
10119             }
10120         }
10121     }
10122
10123     if (const_sv) {
10124         SvREFCNT_inc_simple_void_NN(const_sv);
10125         SvFLAGS(const_sv) |= SVs_PADTMP;
10126         if (cv) {
10127             assert(!CvROOT(cv) && !CvCONST(cv));
10128             cv_forget_slab(cv);
10129             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10130             CvXSUBANY(cv).any_ptr = const_sv;
10131             CvXSUB(cv) = const_sv_xsub;
10132             CvCONST_on(cv);
10133             CvISXSUB_on(cv);
10134             PoisonPADLIST(cv);
10135             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
10136         }
10137         else {
10138             if (isGV(gv) || CvMETHOD(PL_compcv)) {
10139                 if (name && isGV(gv))
10140                     GvCV_set(gv, NULL);
10141                 cv = newCONSTSUB_flags(
10142                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
10143                     const_sv
10144                 );
10145                 assert(cv);
10146                 assert(SvREFCNT((SV*)cv) != 0);
10147                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
10148             }
10149             else {
10150                 if (!SvROK(gv)) {
10151                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
10152                     prepare_SV_for_RV((SV *)gv);
10153                     SvOK_off((SV *)gv);
10154                     SvROK_on(gv);
10155                 }
10156                 SvRV_set(gv, const_sv);
10157             }
10158         }
10159         op_free(block);
10160         SvREFCNT_dec(PL_compcv);
10161         PL_compcv = NULL;
10162         goto done;
10163     }
10164
10165     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
10166     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
10167         cv = NULL;
10168
10169     if (cv) {                           /* must reuse cv if autoloaded */
10170         /* transfer PL_compcv to cv */
10171         if (block) {
10172             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
10173             PADLIST *const temp_av = CvPADLIST(cv);
10174             CV *const temp_cv = CvOUTSIDE(cv);
10175             const cv_flags_t other_flags =
10176                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10177             OP * const cvstart = CvSTART(cv);
10178
10179             if (isGV(gv)) {
10180                 CvGV_set(cv,gv);
10181                 assert(!CvCVGV_RC(cv));
10182                 assert(CvGV(cv) == gv);
10183             }
10184             else {
10185                 dVAR;
10186                 U32 hash;
10187                 PERL_HASH(hash, name, namlen);
10188                 CvNAME_HEK_set(cv,
10189                                share_hek(name,
10190                                          name_is_utf8
10191                                             ? -(SSize_t)namlen
10192                                             :  (SSize_t)namlen,
10193                                          hash));
10194             }
10195
10196             SvPOK_off(cv);
10197             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
10198                                              | CvNAMED(cv);
10199             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
10200             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
10201             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
10202             CvOUTSIDE(PL_compcv) = temp_cv;
10203             CvPADLIST_set(PL_compcv, temp_av);
10204             CvSTART(cv) = CvSTART(PL_compcv);
10205             CvSTART(PL_compcv) = cvstart;
10206             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10207             CvFLAGS(PL_compcv) |= other_flags;
10208
10209             if (CvFILE(cv) && CvDYNFILE(cv)) {
10210                 Safefree(CvFILE(cv));
10211             }
10212             CvFILE_set_from_cop(cv, PL_curcop);
10213             CvSTASH_set(cv, PL_curstash);
10214
10215             /* inner references to PL_compcv must be fixed up ... */
10216             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
10217             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10218                 ++PL_sub_generation;
10219         }
10220         else {
10221             /* Might have had built-in attributes applied -- propagate them. */
10222             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
10223         }
10224         /* ... before we throw it away */
10225         SvREFCNT_dec(PL_compcv);
10226         PL_compcv = cv;
10227     }
10228     else {
10229         cv = PL_compcv;
10230         if (name && isGV(gv)) {
10231             GvCV_set(gv, cv);
10232             GvCVGEN(gv) = 0;
10233             if (HvENAME_HEK(GvSTASH(gv)))
10234                 /* sub Foo::bar { (shift)+1 } */
10235                 gv_method_changed(gv);
10236         }
10237         else if (name) {
10238             if (!SvROK(gv)) {
10239                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
10240                 prepare_SV_for_RV((SV *)gv);
10241                 SvOK_off((SV *)gv);
10242                 SvROK_on(gv);
10243             }
10244             SvRV_set(gv, (SV *)cv);
10245             if (HvENAME_HEK(PL_curstash))
10246                 mro_method_changed_in(PL_curstash);
10247         }
10248     }
10249     assert(cv);
10250     assert(SvREFCNT((SV*)cv) != 0);
10251
10252     if (!CvHASGV(cv)) {
10253         if (isGV(gv))
10254             CvGV_set(cv, gv);
10255         else {
10256             dVAR;
10257             U32 hash;
10258             PERL_HASH(hash, name, namlen);
10259             CvNAME_HEK_set(cv, share_hek(name,
10260                                          name_is_utf8
10261                                             ? -(SSize_t)namlen
10262                                             :  (SSize_t)namlen,
10263                                          hash));
10264         }
10265         CvFILE_set_from_cop(cv, PL_curcop);
10266         CvSTASH_set(cv, PL_curstash);
10267     }
10268
10269     if (ps) {
10270         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
10271         if ( ps_utf8 )
10272             SvUTF8_on(MUTABLE_SV(cv));
10273     }
10274
10275     if (block) {
10276         /* If we assign an optree to a PVCV, then we've defined a
10277          * subroutine that the debugger could be able to set a breakpoint
10278          * in, so signal to pp_entereval that it should not throw away any
10279          * saved lines at scope exit.  */
10280
10281         PL_breakable_sub_gen++;
10282         CvROOT(cv) = block;
10283         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
10284            itself has a refcount. */
10285         CvSLABBED_off(cv);
10286         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
10287 #ifdef PERL_DEBUG_READONLY_OPS
10288         slab = (OPSLAB *)CvSTART(cv);
10289 #endif
10290         S_process_optree(aTHX_ cv, block, start);
10291     }
10292
10293   attrs:
10294     if (attrs) {
10295         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
10296         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
10297                         ? GvSTASH(CvGV(cv))
10298                         : PL_curstash;
10299         if (!name)
10300             SAVEFREESV(cv);
10301         apply_attrs(stash, MUTABLE_SV(cv), attrs);
10302         if (!name)
10303             SvREFCNT_inc_simple_void_NN(cv);
10304     }
10305
10306     if (block && has_name) {
10307         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
10308             SV * const tmpstr = cv_name(cv,NULL,0);
10309             GV * const db_postponed = gv_fetchpvs("DB::postponed",
10310                                                   GV_ADDMULTI, SVt_PVHV);
10311             HV *hv;
10312             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
10313                                           CopFILE(PL_curcop),
10314                                           (long)PL_subline,
10315                                           (long)CopLINE(PL_curcop));
10316             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
10317                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
10318             hv = GvHVn(db_postponed);
10319             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
10320                 CV * const pcv = GvCV(db_postponed);
10321                 if (pcv) {
10322                     dSP;
10323                     PUSHMARK(SP);
10324                     XPUSHs(tmpstr);
10325                     PUTBACK;
10326                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
10327                 }
10328             }
10329         }
10330
10331         if (name) {
10332             if (PL_parser && PL_parser->error_count)
10333                 clear_special_blocks(name, gv, cv);
10334             else
10335                 evanescent =
10336                     process_special_blocks(floor, name, gv, cv);
10337         }
10338     }
10339     assert(cv);
10340
10341   done:
10342     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
10343     if (PL_parser)
10344         PL_parser->copline = NOLINE;
10345     LEAVE_SCOPE(floor);
10346
10347     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
10348     if (!evanescent) {
10349 #ifdef PERL_DEBUG_READONLY_OPS
10350     if (slab)
10351         Slab_to_ro(slab);
10352 #endif
10353     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
10354         pad_add_weakref(cv);
10355     }
10356     return cv;
10357 }
10358
10359 STATIC void
10360 S_clear_special_blocks(pTHX_ const char *const fullname,
10361                        GV *const gv, CV *const cv) {
10362     const char *colon;
10363     const char *name;
10364
10365     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
10366
10367     colon = strrchr(fullname,':');
10368     name = colon ? colon + 1 : fullname;
10369
10370     if ((*name == 'B' && strEQ(name, "BEGIN"))
10371         || (*name == 'E' && strEQ(name, "END"))
10372         || (*name == 'U' && strEQ(name, "UNITCHECK"))
10373         || (*name == 'C' && strEQ(name, "CHECK"))
10374         || (*name == 'I' && strEQ(name, "INIT"))) {
10375         if (!isGV(gv)) {
10376             (void)CvGV(cv);
10377             assert(isGV(gv));
10378         }
10379         GvCV_set(gv, NULL);
10380         SvREFCNT_dec_NN(MUTABLE_SV(cv));
10381     }
10382 }
10383
10384 /* Returns true if the sub has been freed.  */
10385 STATIC bool
10386 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
10387                          GV *const gv,
10388                          CV *const cv)
10389 {
10390     const char *const colon = strrchr(fullname,':');
10391     const char *const name = colon ? colon + 1 : fullname;
10392
10393     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
10394
10395     if (*name == 'B') {
10396         if (strEQ(name, "BEGIN")) {
10397             const I32 oldscope = PL_scopestack_ix;
10398             dSP;
10399             (void)CvGV(cv);
10400             if (floor) LEAVE_SCOPE(floor);
10401             ENTER;
10402             PUSHSTACKi(PERLSI_REQUIRE);
10403             SAVECOPFILE(&PL_compiling);
10404             SAVECOPLINE(&PL_compiling);
10405             SAVEVPTR(PL_curcop);
10406
10407             DEBUG_x( dump_sub(gv) );
10408             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
10409             GvCV_set(gv,0);             /* cv has been hijacked */
10410             call_list(oldscope, PL_beginav);
10411
10412             POPSTACK;
10413             LEAVE;
10414             return !PL_savebegin;
10415         }
10416         else
10417             return FALSE;
10418     } else {
10419         if (*name == 'E') {
10420             if strEQ(name, "END") {
10421                 DEBUG_x( dump_sub(gv) );
10422                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
10423             } else
10424                 return FALSE;
10425         } else if (*name == 'U') {
10426             if (strEQ(name, "UNITCHECK")) {
10427                 /* It's never too late to run a unitcheck block */
10428                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
10429             }
10430             else
10431                 return FALSE;
10432         } else if (*name == 'C') {
10433             if (strEQ(name, "CHECK")) {
10434                 if (PL_main_start)
10435                     /* diag_listed_as: Too late to run %s block */
10436                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
10437                                    "Too late to run CHECK block");
10438                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
10439             }
10440             else
10441                 return FALSE;
10442         } else if (*name == 'I') {
10443             if (strEQ(name, "INIT")) {
10444                 if (PL_main_start)
10445                     /* diag_listed_as: Too late to run %s block */
10446                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
10447                                    "Too late to run INIT block");
10448                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
10449             }
10450             else
10451                 return FALSE;
10452         } else
10453             return FALSE;
10454         DEBUG_x( dump_sub(gv) );
10455         (void)CvGV(cv);
10456         GvCV_set(gv,0);         /* cv has been hijacked */
10457         return FALSE;
10458     }
10459 }
10460
10461 /*
10462 =for apidoc Am|CV *|newCONSTSUB|HV *stash|const char *name|SV *sv
10463
10464 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
10465 rather than of counted length, and no flags are set.  (This means that
10466 C<name> is always interpreted as Latin-1.)
10467
10468 =cut
10469 */
10470
10471 CV *
10472 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
10473 {
10474     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
10475 }
10476
10477 /*
10478 =for apidoc Am|CV *|newCONSTSUB_flags|HV *stash|const char *name|STRLEN len|U32 flags|SV *sv
10479
10480 Construct a constant subroutine, also performing some surrounding
10481 jobs.  A scalar constant-valued subroutine is eligible for inlining
10482 at compile-time, and in Perl code can be created by S<C<sub FOO () {
10483 123 }>>.  Other kinds of constant subroutine have other treatment.
10484
10485 The subroutine will have an empty prototype and will ignore any arguments
10486 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
10487 is null, the subroutine will yield an empty list.  If C<sv> points to a
10488 scalar, the subroutine will always yield that scalar.  If C<sv> points
10489 to an array, the subroutine will always yield a list of the elements of
10490 that array in list context, or the number of elements in the array in
10491 scalar context.  This function takes ownership of one counted reference
10492 to the scalar or array, and will arrange for the object to live as long
10493 as the subroutine does.  If C<sv> points to a scalar then the inlining
10494 assumes that the value of the scalar will never change, so the caller
10495 must ensure that the scalar is not subsequently written to.  If C<sv>
10496 points to an array then no such assumption is made, so it is ostensibly
10497 safe to mutate the array or its elements, but whether this is really
10498 supported has not been determined.
10499
10500 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
10501 Other aspects of the subroutine will be left in their default state.
10502 The caller is free to mutate the subroutine beyond its initial state
10503 after this function has returned.
10504
10505 If C<name> is null then the subroutine will be anonymous, with its
10506 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
10507 subroutine will be named accordingly, referenced by the appropriate glob.
10508 C<name> is a string of length C<len> bytes giving a sigilless symbol
10509 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
10510 otherwise.  The name may be either qualified or unqualified.  If the
10511 name is unqualified then it defaults to being in the stash specified by
10512 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
10513 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
10514 semantics.
10515
10516 C<flags> should not have bits set other than C<SVf_UTF8>.
10517
10518 If there is already a subroutine of the specified name, then the new sub
10519 will replace the existing one in the glob.  A warning may be generated
10520 about the redefinition.
10521
10522 If the subroutine has one of a few special names, such as C<BEGIN> or
10523 C<END>, then it will be claimed by the appropriate queue for automatic
10524 running of phase-related subroutines.  In this case the relevant glob will
10525 be left not containing any subroutine, even if it did contain one before.
10526 Execution of the subroutine will likely be a no-op, unless C<sv> was
10527 a tied array or the caller modified the subroutine in some interesting
10528 way before it was executed.  In the case of C<BEGIN>, the treatment is
10529 buggy: the sub will be executed when only half built, and may be deleted
10530 prematurely, possibly causing a crash.
10531
10532 The function returns a pointer to the constructed subroutine.  If the sub
10533 is anonymous then ownership of one counted reference to the subroutine
10534 is transferred to the caller.  If the sub is named then the caller does
10535 not get ownership of a reference.  In most such cases, where the sub
10536 has a non-phase name, the sub will be alive at the point it is returned
10537 by virtue of being contained in the glob that names it.  A phase-named
10538 subroutine will usually be alive by virtue of the reference owned by
10539 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
10540 destroyed already by the time this function returns, but currently bugs
10541 occur in that case before the caller gets control.  It is the caller's
10542 responsibility to ensure that it knows which of these situations applies.
10543
10544 =cut
10545 */
10546
10547 CV *
10548 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
10549                              U32 flags, SV *sv)
10550 {
10551     CV* cv;
10552     const char *const file = CopFILE(PL_curcop);
10553
10554     ENTER;
10555
10556     if (IN_PERL_RUNTIME) {
10557         /* at runtime, it's not safe to manipulate PL_curcop: it may be
10558          * an op shared between threads. Use a non-shared COP for our
10559          * dirty work */
10560          SAVEVPTR(PL_curcop);
10561          SAVECOMPILEWARNINGS();
10562          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
10563          PL_curcop = &PL_compiling;
10564     }
10565     SAVECOPLINE(PL_curcop);
10566     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
10567
10568     SAVEHINTS();
10569     PL_hints &= ~HINT_BLOCK_SCOPE;
10570
10571     if (stash) {
10572         SAVEGENERICSV(PL_curstash);
10573         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
10574     }
10575
10576     /* Protect sv against leakage caused by fatal warnings. */
10577     if (sv) SAVEFREESV(sv);
10578
10579     /* file becomes the CvFILE. For an XS, it's usually static storage,
10580        and so doesn't get free()d.  (It's expected to be from the C pre-
10581        processor __FILE__ directive). But we need a dynamically allocated one,
10582        and we need it to get freed.  */
10583     cv = newXS_len_flags(name, len,
10584                          sv && SvTYPE(sv) == SVt_PVAV
10585                              ? const_av_xsub
10586                              : const_sv_xsub,
10587                          file ? file : "", "",
10588                          &sv, XS_DYNAMIC_FILENAME | flags);
10589     assert(cv);
10590     assert(SvREFCNT((SV*)cv) != 0);
10591     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
10592     CvCONST_on(cv);
10593
10594     LEAVE;
10595
10596     return cv;
10597 }
10598
10599 /*
10600 =for apidoc U||newXS
10601
10602 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
10603 static storage, as it is used directly as CvFILE(), without a copy being made.
10604
10605 =cut
10606 */
10607
10608 CV *
10609 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
10610 {
10611     PERL_ARGS_ASSERT_NEWXS;
10612     return newXS_len_flags(
10613         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
10614     );
10615 }
10616
10617 CV *
10618 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
10619                  const char *const filename, const char *const proto,
10620                  U32 flags)
10621 {
10622     PERL_ARGS_ASSERT_NEWXS_FLAGS;
10623     return newXS_len_flags(
10624        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
10625     );
10626 }
10627
10628 CV *
10629 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
10630 {
10631     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
10632     return newXS_len_flags(
10633         name, strlen(name), subaddr, NULL, NULL, NULL, 0
10634     );
10635 }
10636
10637 /*
10638 =for apidoc m|CV *|newXS_len_flags|const char *name|STRLEN len|XSUBADDR_t subaddr|const char *const filename|const char *const proto|SV **const_svp|U32 flags
10639
10640 Construct an XS subroutine, also performing some surrounding jobs.
10641
10642 The subroutine will have the entry point C<subaddr>.  It will have
10643 the prototype specified by the nul-terminated string C<proto>, or
10644 no prototype if C<proto> is null.  The prototype string is copied;
10645 the caller can mutate the supplied string afterwards.  If C<filename>
10646 is non-null, it must be a nul-terminated filename, and the subroutine
10647 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
10648 point directly to the supplied string, which must be static.  If C<flags>
10649 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
10650 be taken instead.
10651
10652 Other aspects of the subroutine will be left in their default state.
10653 If anything else needs to be done to the subroutine for it to function
10654 correctly, it is the caller's responsibility to do that after this
10655 function has constructed it.  However, beware of the subroutine
10656 potentially being destroyed before this function returns, as described
10657 below.
10658
10659 If C<name> is null then the subroutine will be anonymous, with its
10660 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
10661 subroutine will be named accordingly, referenced by the appropriate glob.
10662 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
10663 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
10664 The name may be either qualified or unqualified, with the stash defaulting
10665 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
10666 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
10667 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
10668 the stash if necessary, with C<GV_ADDMULTI> semantics.
10669
10670 If there is already a subroutine of the specified name, then the new sub
10671 will replace the existing one in the glob.  A warning may be generated
10672 about the redefinition.  If the old subroutine was C<CvCONST> then the
10673 decision about whether to warn is influenced by an expectation about
10674 whether the new subroutine will become a constant of similar value.
10675 That expectation is determined by C<const_svp>.  (Note that the call to
10676 this function doesn't make the new subroutine C<CvCONST> in any case;
10677 that is left to the caller.)  If C<const_svp> is null then it indicates
10678 that the new subroutine will not become a constant.  If C<const_svp>
10679 is non-null then it indicates that the new subroutine will become a
10680 constant, and it points to an C<SV*> that provides the constant value
10681 that the subroutine will have.
10682
10683 If the subroutine has one of a few special names, such as C<BEGIN> or
10684 C<END>, then it will be claimed by the appropriate queue for automatic
10685 running of phase-related subroutines.  In this case the relevant glob will
10686 be left not containing any subroutine, even if it did contain one before.
10687 In the case of C<BEGIN>, the subroutine will be executed and the reference
10688 to it disposed of before this function returns, and also before its
10689 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
10690 constructed by this function to be ready for execution then the caller
10691 must prevent this happening by giving the subroutine a different name.
10692
10693 The function returns a pointer to the constructed subroutine.  If the sub
10694 is anonymous then ownership of one counted reference to the subroutine
10695 is transferred to the caller.  If the sub is named then the caller does
10696 not get ownership of a reference.  In most such cases, where the sub
10697 has a non-phase name, the sub will be alive at the point it is returned
10698 by virtue of being contained in the glob that names it.  A phase-named
10699 subroutine will usually be alive by virtue of the reference owned by the
10700 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
10701 been executed, will quite likely have been destroyed already by the
10702 time this function returns, making it erroneous for the caller to make
10703 any use of the returned pointer.  It is the caller's responsibility to
10704 ensure that it knows which of these situations applies.
10705
10706 =cut
10707 */
10708
10709 CV *
10710 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
10711                            XSUBADDR_t subaddr, const char *const filename,
10712                            const char *const proto, SV **const_svp,
10713                            U32 flags)
10714 {
10715     CV *cv;
10716     bool interleave = FALSE;
10717     bool evanescent = FALSE;
10718
10719     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
10720
10721     {
10722         GV * const gv = gv_fetchpvn(
10723                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
10724                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
10725                                 sizeof("__ANON__::__ANON__") - 1,
10726                             GV_ADDMULTI | flags, SVt_PVCV);
10727
10728         if ((cv = (name ? GvCV(gv) : NULL))) {
10729             if (GvCVGEN(gv)) {
10730                 /* just a cached method */
10731                 SvREFCNT_dec(cv);
10732                 cv = NULL;
10733             }
10734             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
10735                 /* already defined (or promised) */
10736                 /* Redundant check that allows us to avoid creating an SV
10737                    most of the time: */
10738                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
10739                     report_redefined_cv(newSVpvn_flags(
10740                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
10741                                         ),
10742                                         cv, const_svp);
10743                 }
10744                 interleave = TRUE;
10745                 ENTER;
10746                 SAVEFREESV(cv);
10747                 cv = NULL;
10748             }
10749         }
10750     
10751         if (cv)                         /* must reuse cv if autoloaded */
10752             cv_undef(cv);
10753         else {
10754             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10755             if (name) {
10756                 GvCV_set(gv,cv);
10757                 GvCVGEN(gv) = 0;
10758                 if (HvENAME_HEK(GvSTASH(gv)))
10759                     gv_method_changed(gv); /* newXS */
10760             }
10761         }
10762         assert(cv);
10763         assert(SvREFCNT((SV*)cv) != 0);
10764
10765         CvGV_set(cv, gv);
10766         if(filename) {
10767             /* XSUBs can't be perl lang/perl5db.pl debugged
10768             if (PERLDB_LINE_OR_SAVESRC)
10769                 (void)gv_fetchfile(filename); */
10770             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
10771             if (flags & XS_DYNAMIC_FILENAME) {
10772                 CvDYNFILE_on(cv);
10773                 CvFILE(cv) = savepv(filename);
10774             } else {
10775             /* NOTE: not copied, as it is expected to be an external constant string */
10776                 CvFILE(cv) = (char *)filename;
10777             }
10778         } else {
10779             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
10780             CvFILE(cv) = (char*)PL_xsubfilename;
10781         }
10782         CvISXSUB_on(cv);
10783         CvXSUB(cv) = subaddr;
10784 #ifndef PERL_IMPLICIT_CONTEXT
10785         CvHSCXT(cv) = &PL_stack_sp;
10786 #else
10787         PoisonPADLIST(cv);
10788 #endif
10789
10790         if (name)
10791             evanescent = process_special_blocks(0, name, gv, cv);
10792         else
10793             CvANON_on(cv);
10794     } /* <- not a conditional branch */
10795
10796     assert(cv);
10797     assert(evanescent || SvREFCNT((SV*)cv) != 0);
10798
10799     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
10800     if (interleave) LEAVE;
10801     assert(evanescent || SvREFCNT((SV*)cv) != 0);
10802     return cv;
10803 }
10804
10805 CV *
10806 Perl_newSTUB(pTHX_ GV *gv, bool fake)
10807 {
10808     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10809     GV *cvgv;
10810     PERL_ARGS_ASSERT_NEWSTUB;
10811     assert(!GvCVu(gv));
10812     GvCV_set(gv, cv);
10813     GvCVGEN(gv) = 0;
10814     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
10815         gv_method_changed(gv);
10816     if (SvFAKE(gv)) {
10817         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
10818         SvFAKE_off(cvgv);
10819     }
10820     else cvgv = gv;
10821     CvGV_set(cv, cvgv);
10822     CvFILE_set_from_cop(cv, PL_curcop);
10823     CvSTASH_set(cv, PL_curstash);
10824     GvMULTI_on(gv);
10825     return cv;
10826 }
10827
10828 void
10829 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
10830 {
10831     CV *cv;
10832     GV *gv;
10833     OP *root;
10834     OP *start;
10835
10836     if (PL_parser && PL_parser->error_count) {
10837         op_free(block);
10838         goto finish;
10839     }
10840
10841     gv = o
10842         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
10843         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
10844
10845     GvMULTI_on(gv);
10846     if ((cv = GvFORM(gv))) {
10847         if (ckWARN(WARN_REDEFINE)) {
10848             const line_t oldline = CopLINE(PL_curcop);
10849             if (PL_parser && PL_parser->copline != NOLINE)
10850                 CopLINE_set(PL_curcop, PL_parser->copline);
10851             if (o) {
10852                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
10853                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
10854             } else {
10855                 /* diag_listed_as: Format %s redefined */
10856                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
10857                             "Format STDOUT redefined");
10858             }
10859             CopLINE_set(PL_curcop, oldline);
10860         }
10861         SvREFCNT_dec(cv);
10862     }
10863     cv = PL_compcv;
10864     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
10865     CvGV_set(cv, gv);
10866     CvFILE_set_from_cop(cv, PL_curcop);
10867
10868
10869     root = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
10870     CvROOT(cv) = root;
10871     start = LINKLIST(root);
10872     root->op_next = 0;
10873     S_process_optree(aTHX_ cv, root, start);
10874     cv_forget_slab(cv);
10875
10876   finish:
10877     op_free(o);
10878     if (PL_parser)
10879         PL_parser->copline = NOLINE;
10880     LEAVE_SCOPE(floor);
10881     PL_compiling.cop_seq = 0;
10882 }
10883
10884 OP *
10885 Perl_newANONLIST(pTHX_ OP *o)
10886 {
10887     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
10888 }
10889
10890 OP *
10891 Perl_newANONHASH(pTHX_ OP *o)
10892 {
10893     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
10894 }
10895
10896 OP *
10897 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
10898 {
10899     return newANONATTRSUB(floor, proto, NULL, block);
10900 }
10901
10902 OP *
10903 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
10904 {
10905     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
10906     OP * anoncode = 
10907         newSVOP(OP_ANONCODE, 0,
10908                 cv);
10909     if (CvANONCONST(cv))
10910         anoncode = newUNOP(OP_ANONCONST, 0,
10911                            op_convert_list(OP_ENTERSUB,
10912                                            OPf_STACKED|OPf_WANT_SCALAR,
10913                                            anoncode));
10914     return newUNOP(OP_REFGEN, 0, anoncode);
10915 }
10916
10917 OP *
10918 Perl_oopsAV(pTHX_ OP *o)
10919 {
10920     dVAR;
10921
10922     PERL_ARGS_ASSERT_OOPSAV;
10923
10924     switch (o->op_type) {
10925     case OP_PADSV:
10926     case OP_PADHV:
10927         OpTYPE_set(o, OP_PADAV);
10928         return ref(o, OP_RV2AV);
10929
10930     case OP_RV2SV:
10931     case OP_RV2HV:
10932         OpTYPE_set(o, OP_RV2AV);
10933         ref(o, OP_RV2AV);
10934         break;
10935
10936     default:
10937         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
10938         break;
10939     }
10940     return o;
10941 }
10942
10943 OP *
10944 Perl_oopsHV(pTHX_ OP *o)
10945 {
10946     dVAR;
10947
10948     PERL_ARGS_ASSERT_OOPSHV;
10949
10950     switch (o->op_type) {
10951     case OP_PADSV:
10952     case OP_PADAV:
10953         OpTYPE_set(o, OP_PADHV);
10954         return ref(o, OP_RV2HV);
10955
10956     case OP_RV2SV:
10957     case OP_RV2AV:
10958         OpTYPE_set(o, OP_RV2HV);
10959         /* rv2hv steals the bottom bit for its own uses */
10960         o->op_private &= ~OPpARG1_MASK;
10961         ref(o, OP_RV2HV);
10962         break;
10963
10964     default:
10965         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
10966         break;
10967     }
10968     return o;
10969 }
10970
10971 OP *
10972 Perl_newAVREF(pTHX_ OP *o)
10973 {
10974     dVAR;
10975
10976     PERL_ARGS_ASSERT_NEWAVREF;
10977
10978     if (o->op_type == OP_PADANY) {
10979         OpTYPE_set(o, OP_PADAV);
10980         return o;
10981     }
10982     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
10983         Perl_croak(aTHX_ "Can't use an array as a reference");
10984     }
10985     return newUNOP(OP_RV2AV, 0, scalar(o));
10986 }
10987
10988 OP *
10989 Perl_newGVREF(pTHX_ I32 type, OP *o)
10990 {
10991     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
10992         return newUNOP(OP_NULL, 0, o);
10993     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
10994 }
10995
10996 OP *
10997 Perl_newHVREF(pTHX_ OP *o)
10998 {
10999     dVAR;
11000
11001     PERL_ARGS_ASSERT_NEWHVREF;
11002
11003     if (o->op_type == OP_PADANY) {
11004         OpTYPE_set(o, OP_PADHV);
11005         return o;
11006     }
11007     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
11008         Perl_croak(aTHX_ "Can't use a hash as a reference");
11009     }
11010     return newUNOP(OP_RV2HV, 0, scalar(o));
11011 }
11012
11013 OP *
11014 Perl_newCVREF(pTHX_ I32 flags, OP *o)
11015 {
11016     if (o->op_type == OP_PADANY) {
11017         dVAR;
11018         OpTYPE_set(o, OP_PADCV);
11019     }
11020     return newUNOP(OP_RV2CV, flags, scalar(o));
11021 }
11022
11023 OP *
11024 Perl_newSVREF(pTHX_ OP *o)
11025 {
11026     dVAR;
11027
11028     PERL_ARGS_ASSERT_NEWSVREF;
11029
11030     if (o->op_type == OP_PADANY) {
11031         OpTYPE_set(o, OP_PADSV);
11032         scalar(o);
11033         return o;
11034     }
11035     return newUNOP(OP_RV2SV, 0, scalar(o));
11036 }
11037
11038 /* Check routines. See the comments at the top of this file for details
11039  * on when these are called */
11040
11041 OP *
11042 Perl_ck_anoncode(pTHX_ OP *o)
11043 {
11044     PERL_ARGS_ASSERT_CK_ANONCODE;
11045
11046     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
11047     cSVOPo->op_sv = NULL;
11048     return o;
11049 }
11050
11051 static void
11052 S_io_hints(pTHX_ OP *o)
11053 {
11054 #if O_BINARY != 0 || O_TEXT != 0
11055     HV * const table =
11056         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
11057     if (table) {
11058         SV **svp = hv_fetchs(table, "open_IN", FALSE);
11059         if (svp && *svp) {
11060             STRLEN len = 0;
11061             const char *d = SvPV_const(*svp, len);
11062             const I32 mode = mode_from_discipline(d, len);
11063             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
11064 #  if O_BINARY != 0
11065             if (mode & O_BINARY)
11066                 o->op_private |= OPpOPEN_IN_RAW;
11067 #  endif
11068 #  if O_TEXT != 0
11069             if (mode & O_TEXT)
11070                 o->op_private |= OPpOPEN_IN_CRLF;
11071 #  endif
11072         }
11073
11074         svp = hv_fetchs(table, "open_OUT", FALSE);
11075         if (svp && *svp) {
11076             STRLEN len = 0;
11077             const char *d = SvPV_const(*svp, len);
11078             const I32 mode = mode_from_discipline(d, len);
11079             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
11080 #  if O_BINARY != 0
11081             if (mode & O_BINARY)
11082                 o->op_private |= OPpOPEN_OUT_RAW;
11083 #  endif
11084 #  if O_TEXT != 0
11085             if (mode & O_TEXT)
11086                 o->op_private |= OPpOPEN_OUT_CRLF;
11087 #  endif
11088         }
11089     }
11090 #else
11091     PERL_UNUSED_CONTEXT;
11092     PERL_UNUSED_ARG(o);
11093 #endif
11094 }
11095
11096 OP *
11097 Perl_ck_backtick(pTHX_ OP *o)
11098 {
11099     GV *gv;
11100     OP *newop = NULL;
11101     OP *sibl;
11102     PERL_ARGS_ASSERT_CK_BACKTICK;
11103     o = ck_fun(o);
11104     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
11105     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
11106      && (gv = gv_override("readpipe",8)))
11107     {
11108         /* detach rest of siblings from o and its first child */
11109         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
11110         newop = S_new_entersubop(aTHX_ gv, sibl);
11111     }
11112     else if (!(o->op_flags & OPf_KIDS))
11113         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
11114     if (newop) {
11115         op_free(o);
11116         return newop;
11117     }
11118     S_io_hints(aTHX_ o);
11119     return o;
11120 }
11121
11122 OP *
11123 Perl_ck_bitop(pTHX_ OP *o)
11124 {
11125     PERL_ARGS_ASSERT_CK_BITOP;
11126
11127     o->op_private = (U8)(PL_hints & HINT_INTEGER);
11128
11129     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
11130             && OP_IS_INFIX_BIT(o->op_type))
11131     {
11132         const OP * const left = cBINOPo->op_first;
11133         const OP * const right = OpSIBLING(left);
11134         if ((OP_IS_NUMCOMPARE(left->op_type) &&
11135                 (left->op_flags & OPf_PARENS) == 0) ||
11136             (OP_IS_NUMCOMPARE(right->op_type) &&
11137                 (right->op_flags & OPf_PARENS) == 0))
11138             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
11139                           "Possible precedence problem on bitwise %s operator",
11140                            o->op_type ==  OP_BIT_OR
11141                          ||o->op_type == OP_NBIT_OR  ? "|"
11142                         :  o->op_type ==  OP_BIT_AND
11143                          ||o->op_type == OP_NBIT_AND ? "&"
11144                         :  o->op_type ==  OP_BIT_XOR
11145                          ||o->op_type == OP_NBIT_XOR ? "^"
11146                         :  o->op_type == OP_SBIT_OR  ? "|."
11147                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
11148                            );
11149     }
11150     return o;
11151 }
11152
11153 PERL_STATIC_INLINE bool
11154 is_dollar_bracket(pTHX_ const OP * const o)
11155 {
11156     const OP *kid;
11157     PERL_UNUSED_CONTEXT;
11158     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
11159         && (kid = cUNOPx(o)->op_first)
11160         && kid->op_type == OP_GV
11161         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
11162 }
11163
11164 /* for lt, gt, le, ge, eq, ne and their i_ variants */
11165
11166 OP *
11167 Perl_ck_cmp(pTHX_ OP *o)
11168 {
11169     bool is_eq;
11170     bool neg;
11171     bool reverse;
11172     bool iv0;
11173     OP *indexop, *constop, *start;
11174     SV *sv;
11175     IV iv;
11176
11177     PERL_ARGS_ASSERT_CK_CMP;
11178
11179     is_eq = (   o->op_type == OP_EQ
11180              || o->op_type == OP_NE
11181              || o->op_type == OP_I_EQ
11182              || o->op_type == OP_I_NE);
11183
11184     if (!is_eq && ckWARN(WARN_SYNTAX)) {
11185         const OP *kid = cUNOPo->op_first;
11186         if (kid &&
11187             (
11188                 (   is_dollar_bracket(aTHX_ kid)
11189                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
11190                 )
11191              || (   kid->op_type == OP_CONST
11192                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
11193                 )
11194            )
11195         )
11196             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11197                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
11198     }
11199
11200     /* convert (index(...) == -1) and variations into
11201      *   (r)index/BOOL(,NEG)
11202      */
11203
11204     reverse = FALSE;
11205
11206     indexop = cUNOPo->op_first;
11207     constop = OpSIBLING(indexop);
11208     start = NULL;
11209     if (indexop->op_type == OP_CONST) {
11210         constop = indexop;
11211         indexop = OpSIBLING(constop);
11212         start = constop;
11213         reverse = TRUE;
11214     }
11215
11216     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
11217         return o;
11218
11219     /* ($lex = index(....)) == -1 */
11220     if (indexop->op_private & OPpTARGET_MY)
11221         return o;
11222
11223     if (constop->op_type != OP_CONST)
11224         return o;
11225
11226     sv = cSVOPx_sv(constop);
11227     if (!(sv && SvIOK_notUV(sv)))
11228         return o;
11229
11230     iv = SvIVX(sv);
11231     if (iv != -1 && iv != 0)
11232         return o;
11233     iv0 = (iv == 0);
11234
11235     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
11236         if (!(iv0 ^ reverse))
11237             return o;
11238         neg = iv0;
11239     }
11240     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
11241         if (iv0 ^ reverse)
11242             return o;
11243         neg = !iv0;
11244     }
11245     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
11246         if (!(iv0 ^ reverse))
11247             return o;
11248         neg = !iv0;
11249     }
11250     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
11251         if (iv0 ^ reverse)
11252             return o;
11253         neg = iv0;
11254     }
11255     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
11256         if (iv0)
11257             return o;
11258         neg = TRUE;
11259     }
11260     else {
11261         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
11262         if (iv0)
11263             return o;
11264         neg = FALSE;
11265     }
11266
11267     indexop->op_flags &= ~OPf_PARENS;
11268     indexop->op_flags |= (o->op_flags & OPf_PARENS);
11269     indexop->op_private |= OPpTRUEBOOL;
11270     if (neg)
11271         indexop->op_private |= OPpINDEX_BOOLNEG;
11272     /* cut out the index op and free the eq,const ops */
11273     (void)op_sibling_splice(o, start, 1, NULL);
11274     op_free(o);
11275
11276     return indexop;
11277 }
11278
11279
11280 OP *
11281 Perl_ck_concat(pTHX_ OP *o)
11282 {
11283     const OP * const kid = cUNOPo->op_first;
11284
11285     PERL_ARGS_ASSERT_CK_CONCAT;
11286     PERL_UNUSED_CONTEXT;
11287
11288     /* reuse the padtmp returned by the concat child */
11289     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
11290             !(kUNOP->op_first->op_flags & OPf_MOD))
11291     {
11292         o->op_flags |= OPf_STACKED;
11293         o->op_private |= OPpCONCAT_NESTED;
11294     }
11295     return o;
11296 }
11297
11298 OP *
11299 Perl_ck_spair(pTHX_ OP *o)
11300 {
11301     dVAR;
11302
11303     PERL_ARGS_ASSERT_CK_SPAIR;
11304
11305     if (o->op_flags & OPf_KIDS) {
11306         OP* newop;
11307         OP* kid;
11308         OP* kidkid;
11309         const OPCODE type = o->op_type;
11310         o = modkids(ck_fun(o), type);
11311         kid    = cUNOPo->op_first;
11312         kidkid = kUNOP->op_first;
11313         newop = OpSIBLING(kidkid);
11314         if (newop) {
11315             const OPCODE type = newop->op_type;
11316             if (OpHAS_SIBLING(newop))
11317                 return o;
11318             if (o->op_type == OP_REFGEN
11319              && (  type == OP_RV2CV
11320                 || (  !(newop->op_flags & OPf_PARENS)
11321                    && (  type == OP_RV2AV || type == OP_PADAV
11322                       || type == OP_RV2HV || type == OP_PADHV))))
11323                 NOOP; /* OK (allow srefgen for \@a and \%h) */
11324             else if (OP_GIMME(newop,0) != G_SCALAR)
11325                 return o;
11326         }
11327         /* excise first sibling */
11328         op_sibling_splice(kid, NULL, 1, NULL);
11329         op_free(kidkid);
11330     }
11331     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
11332      * and OP_CHOMP into OP_SCHOMP */
11333     o->op_ppaddr = PL_ppaddr[++o->op_type];
11334     return ck_fun(o);
11335 }
11336
11337 OP *
11338 Perl_ck_delete(pTHX_ OP *o)
11339 {
11340     PERL_ARGS_ASSERT_CK_DELETE;
11341
11342     o = ck_fun(o);
11343     o->op_private = 0;
11344     if (o->op_flags & OPf_KIDS) {
11345         OP * const kid = cUNOPo->op_first;
11346         switch (kid->op_type) {
11347         case OP_ASLICE:
11348             o->op_flags |= OPf_SPECIAL;
11349             /* FALLTHROUGH */
11350         case OP_HSLICE:
11351             o->op_private |= OPpSLICE;
11352             break;
11353         case OP_AELEM:
11354             o->op_flags |= OPf_SPECIAL;
11355             /* FALLTHROUGH */
11356         case OP_HELEM:
11357             break;
11358         case OP_KVASLICE:
11359             o->op_flags |= OPf_SPECIAL;
11360             /* FALLTHROUGH */
11361         case OP_KVHSLICE:
11362             o->op_private |= OPpKVSLICE;
11363             break;
11364         default:
11365             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
11366                              "element or slice");
11367         }
11368         if (kid->op_private & OPpLVAL_INTRO)
11369             o->op_private |= OPpLVAL_INTRO;
11370         op_null(kid);
11371     }
11372     return o;
11373 }
11374
11375 OP *
11376 Perl_ck_eof(pTHX_ OP *o)
11377 {
11378     PERL_ARGS_ASSERT_CK_EOF;
11379
11380     if (o->op_flags & OPf_KIDS) {
11381         OP *kid;
11382         if (cLISTOPo->op_first->op_type == OP_STUB) {
11383             OP * const newop
11384                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
11385             op_free(o);
11386             o = newop;
11387         }
11388         o = ck_fun(o);
11389         kid = cLISTOPo->op_first;
11390         if (kid->op_type == OP_RV2GV)
11391             kid->op_private |= OPpALLOW_FAKE;
11392     }
11393     return o;
11394 }
11395
11396
11397 OP *
11398 Perl_ck_eval(pTHX_ OP *o)
11399 {
11400     dVAR;
11401
11402     PERL_ARGS_ASSERT_CK_EVAL;
11403
11404     PL_hints |= HINT_BLOCK_SCOPE;
11405     if (o->op_flags & OPf_KIDS) {
11406         SVOP * const kid = (SVOP*)cUNOPo->op_first;
11407         assert(kid);
11408
11409         if (o->op_type == OP_ENTERTRY) {
11410             LOGOP *enter;
11411
11412             /* cut whole sibling chain free from o */
11413             op_sibling_splice(o, NULL, -1, NULL);
11414             op_free(o);
11415
11416             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
11417
11418             /* establish postfix order */
11419             enter->op_next = (OP*)enter;
11420
11421             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
11422             OpTYPE_set(o, OP_LEAVETRY);
11423             enter->op_other = o;
11424             return o;
11425         }
11426         else {
11427             scalar((OP*)kid);
11428             S_set_haseval(aTHX);
11429         }
11430     }
11431     else {
11432         const U8 priv = o->op_private;
11433         op_free(o);
11434         /* the newUNOP will recursively call ck_eval(), which will handle
11435          * all the stuff at the end of this function, like adding
11436          * OP_HINTSEVAL
11437          */
11438         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
11439     }
11440     o->op_targ = (PADOFFSET)PL_hints;
11441     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
11442     if ((PL_hints & HINT_LOCALIZE_HH) != 0
11443      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
11444         /* Store a copy of %^H that pp_entereval can pick up. */
11445         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
11446                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
11447         /* append hhop to only child  */
11448         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
11449
11450         o->op_private |= OPpEVAL_HAS_HH;
11451     }
11452     if (!(o->op_private & OPpEVAL_BYTES)
11453          && FEATURE_UNIEVAL_IS_ENABLED)
11454             o->op_private |= OPpEVAL_UNICODE;
11455     return o;
11456 }
11457
11458 OP *
11459 Perl_ck_exec(pTHX_ OP *o)
11460 {
11461     PERL_ARGS_ASSERT_CK_EXEC;
11462
11463     if (o->op_flags & OPf_STACKED) {
11464         OP *kid;
11465         o = ck_fun(o);
11466         kid = OpSIBLING(cUNOPo->op_first);
11467         if (kid->op_type == OP_RV2GV)
11468             op_null(kid);
11469     }
11470     else
11471         o = listkids(o);
11472     return o;
11473 }
11474
11475 OP *
11476 Perl_ck_exists(pTHX_ OP *o)
11477 {
11478     PERL_ARGS_ASSERT_CK_EXISTS;
11479
11480     o = ck_fun(o);
11481     if (o->op_flags & OPf_KIDS) {
11482         OP * const kid = cUNOPo->op_first;
11483         if (kid->op_type == OP_ENTERSUB) {
11484             (void) ref(kid, o->op_type);
11485             if (kid->op_type != OP_RV2CV
11486                         && !(PL_parser && PL_parser->error_count))
11487                 Perl_croak(aTHX_
11488                           "exists argument is not a subroutine name");
11489             o->op_private |= OPpEXISTS_SUB;
11490         }
11491         else if (kid->op_type == OP_AELEM)
11492             o->op_flags |= OPf_SPECIAL;
11493         else if (kid->op_type != OP_HELEM)
11494             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
11495                              "element or a subroutine");
11496         op_null(kid);
11497     }
11498     return o;
11499 }
11500
11501 OP *
11502 Perl_ck_rvconst(pTHX_ OP *o)
11503 {
11504     dVAR;
11505     SVOP * const kid = (SVOP*)cUNOPo->op_first;
11506
11507     PERL_ARGS_ASSERT_CK_RVCONST;
11508
11509     if (o->op_type == OP_RV2HV)
11510         /* rv2hv steals the bottom bit for its own uses */
11511         o->op_private &= ~OPpARG1_MASK;
11512
11513     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11514
11515     if (kid->op_type == OP_CONST) {
11516         int iscv;
11517         GV *gv;
11518         SV * const kidsv = kid->op_sv;
11519
11520         /* Is it a constant from cv_const_sv()? */
11521         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
11522             return o;
11523         }
11524         if (SvTYPE(kidsv) == SVt_PVAV) return o;
11525         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
11526             const char *badthing;
11527             switch (o->op_type) {
11528             case OP_RV2SV:
11529                 badthing = "a SCALAR";
11530                 break;
11531             case OP_RV2AV:
11532                 badthing = "an ARRAY";
11533                 break;
11534             case OP_RV2HV:
11535                 badthing = "a HASH";
11536                 break;
11537             default:
11538                 badthing = NULL;
11539                 break;
11540             }
11541             if (badthing)
11542                 Perl_croak(aTHX_
11543                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
11544                            SVfARG(kidsv), badthing);
11545         }
11546         /*
11547          * This is a little tricky.  We only want to add the symbol if we
11548          * didn't add it in the lexer.  Otherwise we get duplicate strict
11549          * warnings.  But if we didn't add it in the lexer, we must at
11550          * least pretend like we wanted to add it even if it existed before,
11551          * or we get possible typo warnings.  OPpCONST_ENTERED says
11552          * whether the lexer already added THIS instance of this symbol.
11553          */
11554         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
11555         gv = gv_fetchsv(kidsv,
11556                 o->op_type == OP_RV2CV
11557                         && o->op_private & OPpMAY_RETURN_CONSTANT
11558                     ? GV_NOEXPAND
11559                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
11560                 iscv
11561                     ? SVt_PVCV
11562                     : o->op_type == OP_RV2SV
11563                         ? SVt_PV
11564                         : o->op_type == OP_RV2AV
11565                             ? SVt_PVAV
11566                             : o->op_type == OP_RV2HV
11567                                 ? SVt_PVHV
11568                                 : SVt_PVGV);
11569         if (gv) {
11570             if (!isGV(gv)) {
11571                 assert(iscv);
11572                 assert(SvROK(gv));
11573                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
11574                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
11575                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
11576             }
11577             OpTYPE_set(kid, OP_GV);
11578             SvREFCNT_dec(kid->op_sv);
11579 #ifdef USE_ITHREADS
11580             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
11581             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
11582             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
11583             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
11584             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
11585 #else
11586             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
11587 #endif
11588             kid->op_private = 0;
11589             /* FAKE globs in the symbol table cause weird bugs (#77810) */
11590             SvFAKE_off(gv);
11591         }
11592     }
11593     return o;
11594 }
11595
11596 OP *
11597 Perl_ck_ftst(pTHX_ OP *o)
11598 {
11599     dVAR;
11600     const I32 type = o->op_type;
11601
11602     PERL_ARGS_ASSERT_CK_FTST;
11603
11604     if (o->op_flags & OPf_REF) {
11605         NOOP;
11606     }
11607     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
11608         SVOP * const kid = (SVOP*)cUNOPo->op_first;
11609         const OPCODE kidtype = kid->op_type;
11610
11611         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
11612          && !kid->op_folded) {
11613             OP * const newop = newGVOP(type, OPf_REF,
11614                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
11615             op_free(o);
11616             return newop;
11617         }
11618
11619         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
11620             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
11621             if (name) {
11622                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
11623                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
11624                             array_passed_to_stat, name);
11625             }
11626             else {
11627                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
11628                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
11629             }
11630        }
11631         scalar((OP *) kid);
11632         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
11633             o->op_private |= OPpFT_ACCESS;
11634         if (type != OP_STAT && type != OP_LSTAT
11635             && PL_check[kidtype] == Perl_ck_ftst
11636             && kidtype != OP_STAT && kidtype != OP_LSTAT
11637         ) {
11638             o->op_private |= OPpFT_STACKED;
11639             kid->op_private |= OPpFT_STACKING;
11640             if (kidtype == OP_FTTTY && (
11641                    !(kid->op_private & OPpFT_STACKED)
11642                 || kid->op_private & OPpFT_AFTER_t
11643                ))
11644                 o->op_private |= OPpFT_AFTER_t;
11645         }
11646     }
11647     else {
11648         op_free(o);
11649         if (type == OP_FTTTY)
11650             o = newGVOP(type, OPf_REF, PL_stdingv);
11651         else
11652             o = newUNOP(type, 0, newDEFSVOP());
11653     }
11654     return o;
11655 }
11656
11657 OP *
11658 Perl_ck_fun(pTHX_ OP *o)
11659 {
11660     const int type = o->op_type;
11661     I32 oa = PL_opargs[type] >> OASHIFT;
11662
11663     PERL_ARGS_ASSERT_CK_FUN;
11664
11665     if (o->op_flags & OPf_STACKED) {
11666         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
11667             oa &= ~OA_OPTIONAL;
11668         else
11669             return no_fh_allowed(o);
11670     }
11671
11672     if (o->op_flags & OPf_KIDS) {
11673         OP *prev_kid = NULL;
11674         OP *kid = cLISTOPo->op_first;
11675         I32 numargs = 0;
11676         bool seen_optional = FALSE;
11677
11678         if (kid->op_type == OP_PUSHMARK ||
11679             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
11680         {
11681             prev_kid = kid;
11682             kid = OpSIBLING(kid);
11683         }
11684         if (kid && kid->op_type == OP_COREARGS) {
11685             bool optional = FALSE;
11686             while (oa) {
11687                 numargs++;
11688                 if (oa & OA_OPTIONAL) optional = TRUE;
11689                 oa = oa >> 4;
11690             }
11691             if (optional) o->op_private |= numargs;
11692             return o;
11693         }
11694
11695         while (oa) {
11696             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
11697                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
11698                     kid = newDEFSVOP();
11699                     /* append kid to chain */
11700                     op_sibling_splice(o, prev_kid, 0, kid);
11701                 }
11702                 seen_optional = TRUE;
11703             }
11704             if (!kid) break;
11705
11706             numargs++;
11707             switch (oa & 7) {
11708             case OA_SCALAR:
11709                 /* list seen where single (scalar) arg expected? */
11710                 if (numargs == 1 && !(oa >> 4)
11711                     && kid->op_type == OP_LIST && type != OP_SCALAR)
11712                 {
11713                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
11714                 }
11715                 if (type != OP_DELETE) scalar(kid);
11716                 break;
11717             case OA_LIST:
11718                 if (oa < 16) {
11719                     kid = 0;
11720                     continue;
11721                 }
11722                 else
11723                     list(kid);
11724                 break;
11725             case OA_AVREF:
11726                 if ((type == OP_PUSH || type == OP_UNSHIFT)
11727                     && !OpHAS_SIBLING(kid))
11728                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
11729                                    "Useless use of %s with no values",
11730                                    PL_op_desc[type]);
11731
11732                 if (kid->op_type == OP_CONST
11733                       && (  !SvROK(cSVOPx_sv(kid)) 
11734                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
11735                         )
11736                     bad_type_pv(numargs, "array", o, kid);
11737                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
11738                          || kid->op_type == OP_RV2GV) {
11739                     bad_type_pv(1, "array", o, kid);
11740                 }
11741                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
11742                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
11743                                          PL_op_desc[type]), 0);
11744                 }
11745                 else {
11746                     op_lvalue(kid, type);
11747                 }
11748                 break;
11749             case OA_HVREF:
11750                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
11751                     bad_type_pv(numargs, "hash", o, kid);
11752                 op_lvalue(kid, type);
11753                 break;
11754             case OA_CVREF:
11755                 {
11756                     /* replace kid with newop in chain */
11757                     OP * const newop =
11758                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
11759                     newop->op_next = newop;
11760                     kid = newop;
11761                 }
11762                 break;
11763             case OA_FILEREF:
11764                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
11765                     if (kid->op_type == OP_CONST &&
11766                         (kid->op_private & OPpCONST_BARE))
11767                     {
11768                         OP * const newop = newGVOP(OP_GV, 0,
11769                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
11770                         /* replace kid with newop in chain */
11771                         op_sibling_splice(o, prev_kid, 1, newop);
11772                         op_free(kid);
11773                         kid = newop;
11774                     }
11775                     else if (kid->op_type == OP_READLINE) {
11776                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
11777                         bad_type_pv(numargs, "HANDLE", o, kid);
11778                     }
11779                     else {
11780                         I32 flags = OPf_SPECIAL;
11781                         I32 priv = 0;
11782                         PADOFFSET targ = 0;
11783
11784                         /* is this op a FH constructor? */
11785                         if (is_handle_constructor(o,numargs)) {
11786                             const char *name = NULL;
11787                             STRLEN len = 0;
11788                             U32 name_utf8 = 0;
11789                             bool want_dollar = TRUE;
11790
11791                             flags = 0;
11792                             /* Set a flag to tell rv2gv to vivify
11793                              * need to "prove" flag does not mean something
11794                              * else already - NI-S 1999/05/07
11795                              */
11796                             priv = OPpDEREF;
11797                             if (kid->op_type == OP_PADSV) {
11798                                 PADNAME * const pn
11799                                     = PAD_COMPNAME_SV(kid->op_targ);
11800                                 name = PadnamePV (pn);
11801                                 len  = PadnameLEN(pn);
11802                                 name_utf8 = PadnameUTF8(pn);
11803                             }
11804                             else if (kid->op_type == OP_RV2SV
11805                                      && kUNOP->op_first->op_type == OP_GV)
11806                             {
11807                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
11808                                 name = GvNAME(gv);
11809                                 len = GvNAMELEN(gv);
11810                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
11811                             }
11812                             else if (kid->op_type == OP_AELEM
11813                                      || kid->op_type == OP_HELEM)
11814                             {
11815                                  OP *firstop;
11816                                  OP *op = ((BINOP*)kid)->op_first;
11817                                  name = NULL;
11818                                  if (op) {
11819                                       SV *tmpstr = NULL;
11820                                       const char * const a =
11821                                            kid->op_type == OP_AELEM ?
11822                                            "[]" : "{}";
11823                                       if (((op->op_type == OP_RV2AV) ||
11824                                            (op->op_type == OP_RV2HV)) &&
11825                                           (firstop = ((UNOP*)op)->op_first) &&
11826                                           (firstop->op_type == OP_GV)) {
11827                                            /* packagevar $a[] or $h{} */
11828                                            GV * const gv = cGVOPx_gv(firstop);
11829                                            if (gv)
11830                                                 tmpstr =
11831                                                      Perl_newSVpvf(aTHX_
11832                                                                    "%s%c...%c",
11833                                                                    GvNAME(gv),
11834                                                                    a[0], a[1]);
11835                                       }
11836                                       else if (op->op_type == OP_PADAV
11837                                                || op->op_type == OP_PADHV) {
11838                                            /* lexicalvar $a[] or $h{} */
11839                                            const char * const padname =
11840                                                 PAD_COMPNAME_PV(op->op_targ);
11841                                            if (padname)
11842                                                 tmpstr =
11843                                                      Perl_newSVpvf(aTHX_
11844                                                                    "%s%c...%c",
11845                                                                    padname + 1,
11846                                                                    a[0], a[1]);
11847                                       }
11848                                       if (tmpstr) {
11849                                            name = SvPV_const(tmpstr, len);
11850                                            name_utf8 = SvUTF8(tmpstr);
11851                                            sv_2mortal(tmpstr);
11852                                       }
11853                                  }
11854                                  if (!name) {
11855                                       name = "__ANONIO__";
11856                                       len = 10;
11857                                       want_dollar = FALSE;
11858                                  }
11859                                  op_lvalue(kid, type);
11860                             }
11861                             if (name) {
11862                                 SV *namesv;
11863                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
11864                                 namesv = PAD_SVl(targ);
11865                                 if (want_dollar && *name != '$')
11866                                     sv_setpvs(namesv, "$");
11867                                 else
11868                                     SvPVCLEAR(namesv);
11869                                 sv_catpvn(namesv, name, len);
11870                                 if ( name_utf8 ) SvUTF8_on(namesv);
11871                             }
11872                         }
11873                         scalar(kid);
11874                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
11875                                     OP_RV2GV, flags);
11876                         kid->op_targ = targ;
11877                         kid->op_private |= priv;
11878                     }
11879                 }
11880                 scalar(kid);
11881                 break;
11882             case OA_SCALARREF:
11883                 if ((type == OP_UNDEF || type == OP_POS)
11884                     && numargs == 1 && !(oa >> 4)
11885                     && kid->op_type == OP_LIST)
11886                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
11887                 op_lvalue(scalar(kid), type);
11888                 break;
11889             }
11890             oa >>= 4;
11891             prev_kid = kid;
11892             kid = OpSIBLING(kid);
11893         }
11894         /* FIXME - should the numargs or-ing move after the too many
11895          * arguments check? */
11896         o->op_private |= numargs;
11897         if (kid)
11898             return too_many_arguments_pv(o,OP_DESC(o), 0);
11899         listkids(o);
11900     }
11901     else if (PL_opargs[type] & OA_DEFGV) {
11902         /* Ordering of these two is important to keep f_map.t passing.  */
11903         op_free(o);
11904         return newUNOP(type, 0, newDEFSVOP());
11905     }
11906
11907     if (oa) {
11908         while (oa & OA_OPTIONAL)
11909             oa >>= 4;
11910         if (oa && oa != OA_LIST)
11911             return too_few_arguments_pv(o,OP_DESC(o), 0);
11912     }
11913     return o;
11914 }
11915
11916 OP *
11917 Perl_ck_glob(pTHX_ OP *o)
11918 {
11919     GV *gv;
11920
11921     PERL_ARGS_ASSERT_CK_GLOB;
11922
11923     o = ck_fun(o);
11924     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
11925         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
11926
11927     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
11928     {
11929         /* convert
11930          *     glob
11931          *       \ null - const(wildcard)
11932          * into
11933          *     null
11934          *       \ enter
11935          *            \ list
11936          *                 \ mark - glob - rv2cv
11937          *                             |        \ gv(CORE::GLOBAL::glob)
11938          *                             |
11939          *                              \ null - const(wildcard)
11940          */
11941         o->op_flags |= OPf_SPECIAL;
11942         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
11943         o = S_new_entersubop(aTHX_ gv, o);
11944         o = newUNOP(OP_NULL, 0, o);
11945         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
11946         return o;
11947     }
11948     else o->op_flags &= ~OPf_SPECIAL;
11949 #if !defined(PERL_EXTERNAL_GLOB)
11950     if (!PL_globhook) {
11951         ENTER;
11952         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
11953                                newSVpvs("File::Glob"), NULL, NULL, NULL);
11954         LEAVE;
11955     }
11956 #endif /* !PERL_EXTERNAL_GLOB */
11957     gv = (GV *)newSV(0);
11958     gv_init(gv, 0, "", 0, 0);
11959     gv_IOadd(gv);
11960     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
11961     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
11962     scalarkids(o);
11963     return o;
11964 }
11965
11966 OP *
11967 Perl_ck_grep(pTHX_ OP *o)
11968 {
11969     LOGOP *gwop;
11970     OP *kid;
11971     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
11972
11973     PERL_ARGS_ASSERT_CK_GREP;
11974
11975     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
11976
11977     if (o->op_flags & OPf_STACKED) {
11978         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
11979         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
11980             return no_fh_allowed(o);
11981         o->op_flags &= ~OPf_STACKED;
11982     }
11983     kid = OpSIBLING(cLISTOPo->op_first);
11984     if (type == OP_MAPWHILE)
11985         list(kid);
11986     else
11987         scalar(kid);
11988     o = ck_fun(o);
11989     if (PL_parser && PL_parser->error_count)
11990         return o;
11991     kid = OpSIBLING(cLISTOPo->op_first);
11992     if (kid->op_type != OP_NULL)
11993         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
11994     kid = kUNOP->op_first;
11995
11996     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
11997     kid->op_next = (OP*)gwop;
11998     o->op_private = gwop->op_private = 0;
11999     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
12000
12001     kid = OpSIBLING(cLISTOPo->op_first);
12002     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
12003         op_lvalue(kid, OP_GREPSTART);
12004
12005     return (OP*)gwop;
12006 }
12007
12008 OP *
12009 Perl_ck_index(pTHX_ OP *o)
12010 {
12011     PERL_ARGS_ASSERT_CK_INDEX;
12012
12013     if (o->op_flags & OPf_KIDS) {
12014         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
12015         if (kid)
12016             kid = OpSIBLING(kid);                       /* get past "big" */
12017         if (kid && kid->op_type == OP_CONST) {
12018             const bool save_taint = TAINT_get;
12019             SV *sv = kSVOP->op_sv;
12020             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
12021                 && SvOK(sv) && !SvROK(sv))
12022             {
12023                 sv = newSV(0);
12024                 sv_copypv(sv, kSVOP->op_sv);
12025                 SvREFCNT_dec_NN(kSVOP->op_sv);
12026                 kSVOP->op_sv = sv;
12027             }
12028             if (SvOK(sv)) fbm_compile(sv, 0);
12029             TAINT_set(save_taint);
12030 #ifdef NO_TAINT_SUPPORT
12031             PERL_UNUSED_VAR(save_taint);
12032 #endif
12033         }
12034     }
12035     return ck_fun(o);
12036 }
12037
12038 OP *
12039 Perl_ck_lfun(pTHX_ OP *o)
12040 {
12041     const OPCODE type = o->op_type;
12042
12043     PERL_ARGS_ASSERT_CK_LFUN;
12044
12045     return modkids(ck_fun(o), type);
12046 }
12047
12048 OP *
12049 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
12050 {
12051     PERL_ARGS_ASSERT_CK_DEFINED;
12052
12053     if ((o->op_flags & OPf_KIDS)) {
12054         switch (cUNOPo->op_first->op_type) {
12055         case OP_RV2AV:
12056         case OP_PADAV:
12057             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
12058                              " (Maybe you should just omit the defined()?)");
12059             NOT_REACHED; /* NOTREACHED */
12060             break;
12061         case OP_RV2HV:
12062         case OP_PADHV:
12063             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
12064                              " (Maybe you should just omit the defined()?)");
12065             NOT_REACHED; /* NOTREACHED */
12066             break;
12067         default:
12068             /* no warning */
12069             break;
12070         }
12071     }
12072     return ck_rfun(o);
12073 }
12074
12075 OP *
12076 Perl_ck_readline(pTHX_ OP *o)
12077 {
12078     PERL_ARGS_ASSERT_CK_READLINE;
12079
12080     if (o->op_flags & OPf_KIDS) {
12081          OP *kid = cLISTOPo->op_first;
12082          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
12083     }
12084     else {
12085         OP * const newop
12086             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
12087         op_free(o);
12088         return newop;
12089     }
12090     return o;
12091 }
12092
12093 OP *
12094 Perl_ck_rfun(pTHX_ OP *o)
12095 {
12096     const OPCODE type = o->op_type;
12097
12098     PERL_ARGS_ASSERT_CK_RFUN;
12099
12100     return refkids(ck_fun(o), type);
12101 }
12102
12103 OP *
12104 Perl_ck_listiob(pTHX_ OP *o)
12105 {
12106     OP *kid;
12107
12108     PERL_ARGS_ASSERT_CK_LISTIOB;
12109
12110     kid = cLISTOPo->op_first;
12111     if (!kid) {
12112         o = force_list(o, 1);
12113         kid = cLISTOPo->op_first;
12114     }
12115     if (kid->op_type == OP_PUSHMARK)
12116         kid = OpSIBLING(kid);
12117     if (kid && o->op_flags & OPf_STACKED)
12118         kid = OpSIBLING(kid);
12119     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
12120         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
12121          && !kid->op_folded) {
12122             o->op_flags |= OPf_STACKED; /* make it a filehandle */
12123             scalar(kid);
12124             /* replace old const op with new OP_RV2GV parent */
12125             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
12126                                         OP_RV2GV, OPf_REF);
12127             kid = OpSIBLING(kid);
12128         }
12129     }
12130
12131     if (!kid)
12132         op_append_elem(o->op_type, o, newDEFSVOP());
12133
12134     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
12135     return listkids(o);
12136 }
12137
12138 OP *
12139 Perl_ck_smartmatch(pTHX_ OP *o)
12140 {
12141     dVAR;
12142     PERL_ARGS_ASSERT_CK_SMARTMATCH;
12143     if (0 == (o->op_flags & OPf_SPECIAL)) {
12144         OP *first  = cBINOPo->op_first;
12145         OP *second = OpSIBLING(first);
12146         
12147         /* Implicitly take a reference to an array or hash */
12148
12149         /* remove the original two siblings, then add back the
12150          * (possibly different) first and second sibs.
12151          */
12152         op_sibling_splice(o, NULL, 1, NULL);
12153         op_sibling_splice(o, NULL, 1, NULL);
12154         first  = ref_array_or_hash(first);
12155         second = ref_array_or_hash(second);
12156         op_sibling_splice(o, NULL, 0, second);
12157         op_sibling_splice(o, NULL, 0, first);
12158         
12159         /* Implicitly take a reference to a regular expression */
12160         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
12161             OpTYPE_set(first, OP_QR);
12162         }
12163         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
12164             OpTYPE_set(second, OP_QR);
12165         }
12166     }
12167     
12168     return o;
12169 }
12170
12171
12172 static OP *
12173 S_maybe_targlex(pTHX_ OP *o)
12174 {
12175     OP * const kid = cLISTOPo->op_first;
12176     /* has a disposable target? */
12177     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
12178         && !(kid->op_flags & OPf_STACKED)
12179         /* Cannot steal the second time! */
12180         && !(kid->op_private & OPpTARGET_MY)
12181         )
12182     {
12183         OP * const kkid = OpSIBLING(kid);
12184
12185         /* Can just relocate the target. */
12186         if (kkid && kkid->op_type == OP_PADSV
12187             && (!(kkid->op_private & OPpLVAL_INTRO)
12188                || kkid->op_private & OPpPAD_STATE))
12189         {
12190             kid->op_targ = kkid->op_targ;
12191             kkid->op_targ = 0;
12192             /* Now we do not need PADSV and SASSIGN.
12193              * Detach kid and free the rest. */
12194             op_sibling_splice(o, NULL, 1, NULL);
12195             op_free(o);
12196             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
12197             return kid;
12198         }
12199     }
12200     return o;
12201 }
12202
12203 OP *
12204 Perl_ck_sassign(pTHX_ OP *o)
12205 {
12206     dVAR;
12207     OP * const kid = cBINOPo->op_first;
12208
12209     PERL_ARGS_ASSERT_CK_SASSIGN;
12210
12211     if (OpHAS_SIBLING(kid)) {
12212         OP *kkid = OpSIBLING(kid);
12213         /* For state variable assignment with attributes, kkid is a list op
12214            whose op_last is a padsv. */
12215         if ((kkid->op_type == OP_PADSV ||
12216              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
12217               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
12218              )
12219             )
12220                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
12221                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
12222             return S_newONCEOP(aTHX_ o, kkid);
12223         }
12224     }
12225     return S_maybe_targlex(aTHX_ o);
12226 }
12227
12228
12229 OP *
12230 Perl_ck_match(pTHX_ OP *o)
12231 {
12232     PERL_UNUSED_CONTEXT;
12233     PERL_ARGS_ASSERT_CK_MATCH;
12234
12235     return o;
12236 }
12237
12238 OP *
12239 Perl_ck_method(pTHX_ OP *o)
12240 {
12241     SV *sv, *methsv, *rclass;
12242     const char* method;
12243     char* compatptr;
12244     int utf8;
12245     STRLEN len, nsplit = 0, i;
12246     OP* new_op;
12247     OP * const kid = cUNOPo->op_first;
12248
12249     PERL_ARGS_ASSERT_CK_METHOD;
12250     if (kid->op_type != OP_CONST) return o;
12251
12252     sv = kSVOP->op_sv;
12253
12254     /* replace ' with :: */
12255     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
12256                                         SvEND(sv) - SvPVX(sv) )))
12257     {
12258         *compatptr = ':';
12259         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
12260     }
12261
12262     method = SvPVX_const(sv);
12263     len = SvCUR(sv);
12264     utf8 = SvUTF8(sv) ? -1 : 1;
12265
12266     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
12267         nsplit = i+1;
12268         break;
12269     }
12270
12271     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
12272
12273     if (!nsplit) { /* $proto->method() */
12274         op_free(o);
12275         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
12276     }
12277
12278     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
12279         op_free(o);
12280         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
12281     }
12282
12283     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
12284     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
12285         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
12286         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
12287     } else {
12288         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
12289         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
12290     }
12291 #ifdef USE_ITHREADS
12292     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
12293 #else
12294     cMETHOPx(new_op)->op_rclass_sv = rclass;
12295 #endif
12296     op_free(o);
12297     return new_op;
12298 }
12299
12300 OP *
12301 Perl_ck_null(pTHX_ OP *o)
12302 {
12303     PERL_ARGS_ASSERT_CK_NULL;
12304     PERL_UNUSED_CONTEXT;
12305     return o;
12306 }
12307
12308 OP *
12309 Perl_ck_open(pTHX_ OP *o)
12310 {
12311     PERL_ARGS_ASSERT_CK_OPEN;
12312
12313     S_io_hints(aTHX_ o);
12314     {
12315          /* In case of three-arg dup open remove strictness
12316           * from the last arg if it is a bareword. */
12317          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
12318          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
12319          OP *oa;
12320          const char *mode;
12321
12322          if ((last->op_type == OP_CONST) &&             /* The bareword. */
12323              (last->op_private & OPpCONST_BARE) &&
12324              (last->op_private & OPpCONST_STRICT) &&
12325              (oa = OpSIBLING(first)) &&         /* The fh. */
12326              (oa = OpSIBLING(oa)) &&                    /* The mode. */
12327              (oa->op_type == OP_CONST) &&
12328              SvPOK(((SVOP*)oa)->op_sv) &&
12329              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
12330              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
12331              (last == OpSIBLING(oa)))                   /* The bareword. */
12332               last->op_private &= ~OPpCONST_STRICT;
12333     }
12334     return ck_fun(o);
12335 }
12336
12337 OP *
12338 Perl_ck_prototype(pTHX_ OP *o)
12339 {
12340     PERL_ARGS_ASSERT_CK_PROTOTYPE;
12341     if (!(o->op_flags & OPf_KIDS)) {
12342         op_free(o);
12343         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
12344     }
12345     return o;
12346 }
12347
12348 OP *
12349 Perl_ck_refassign(pTHX_ OP *o)
12350 {
12351     OP * const right = cLISTOPo->op_first;
12352     OP * const left = OpSIBLING(right);
12353     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
12354     bool stacked = 0;
12355
12356     PERL_ARGS_ASSERT_CK_REFASSIGN;
12357     assert (left);
12358     assert (left->op_type == OP_SREFGEN);
12359
12360     o->op_private = 0;
12361     /* we use OPpPAD_STATE in refassign to mean either of those things,
12362      * and the code assumes the two flags occupy the same bit position
12363      * in the various ops below */
12364     assert(OPpPAD_STATE == OPpOUR_INTRO);
12365
12366     switch (varop->op_type) {
12367     case OP_PADAV:
12368         o->op_private |= OPpLVREF_AV;
12369         goto settarg;
12370     case OP_PADHV:
12371         o->op_private |= OPpLVREF_HV;
12372         /* FALLTHROUGH */
12373     case OP_PADSV:
12374       settarg:
12375         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
12376         o->op_targ = varop->op_targ;
12377         varop->op_targ = 0;
12378         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
12379         break;
12380
12381     case OP_RV2AV:
12382         o->op_private |= OPpLVREF_AV;
12383         goto checkgv;
12384         NOT_REACHED; /* NOTREACHED */
12385     case OP_RV2HV:
12386         o->op_private |= OPpLVREF_HV;
12387         /* FALLTHROUGH */
12388     case OP_RV2SV:
12389       checkgv:
12390         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
12391         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
12392       detach_and_stack:
12393         /* Point varop to its GV kid, detached.  */
12394         varop = op_sibling_splice(varop, NULL, -1, NULL);
12395         stacked = TRUE;
12396         break;
12397     case OP_RV2CV: {
12398         OP * const kidparent =
12399             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
12400         OP * const kid = cUNOPx(kidparent)->op_first;
12401         o->op_private |= OPpLVREF_CV;
12402         if (kid->op_type == OP_GV) {
12403             varop = kidparent;
12404             goto detach_and_stack;
12405         }
12406         if (kid->op_type != OP_PADCV)   goto bad;
12407         o->op_targ = kid->op_targ;
12408         kid->op_targ = 0;
12409         break;
12410     }
12411     case OP_AELEM:
12412     case OP_HELEM:
12413         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
12414         o->op_private |= OPpLVREF_ELEM;
12415         op_null(varop);
12416         stacked = TRUE;
12417         /* Detach varop.  */
12418         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
12419         break;
12420     default:
12421       bad:
12422         /* diag_listed_as: Can't modify reference to %s in %s assignment */
12423         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
12424                                 "assignment",
12425                                  OP_DESC(varop)));
12426         return o;
12427     }
12428     if (!FEATURE_REFALIASING_IS_ENABLED)
12429         Perl_croak(aTHX_
12430                   "Experimental aliasing via reference not enabled");
12431     Perl_ck_warner_d(aTHX_
12432                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
12433                     "Aliasing via reference is experimental");
12434     if (stacked) {
12435         o->op_flags |= OPf_STACKED;
12436         op_sibling_splice(o, right, 1, varop);
12437     }
12438     else {
12439         o->op_flags &=~ OPf_STACKED;
12440         op_sibling_splice(o, right, 1, NULL);
12441     }
12442     op_free(left);
12443     return o;
12444 }
12445
12446 OP *
12447 Perl_ck_repeat(pTHX_ OP *o)
12448 {
12449     PERL_ARGS_ASSERT_CK_REPEAT;
12450
12451     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
12452         OP* kids;
12453         o->op_private |= OPpREPEAT_DOLIST;
12454         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
12455         kids = force_list(kids, 1); /* promote it to a list */
12456         op_sibling_splice(o, NULL, 0, kids); /* and add back */
12457     }
12458     else
12459         scalar(o);
12460     return o;
12461 }
12462
12463 OP *
12464 Perl_ck_require(pTHX_ OP *o)
12465 {
12466     GV* gv;
12467
12468     PERL_ARGS_ASSERT_CK_REQUIRE;
12469
12470     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
12471         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12472         U32 hash;
12473         char *s;
12474         STRLEN len;
12475         if (kid->op_type == OP_CONST) {
12476           SV * const sv = kid->op_sv;
12477           U32 const was_readonly = SvREADONLY(sv);
12478           if (kid->op_private & OPpCONST_BARE) {
12479             dVAR;
12480             const char *end;
12481             HEK *hek;
12482
12483             if (was_readonly) {
12484                     SvREADONLY_off(sv);
12485             }   
12486             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
12487
12488             s = SvPVX(sv);
12489             len = SvCUR(sv);
12490             end = s + len;
12491             /* treat ::foo::bar as foo::bar */
12492             if (len >= 2 && s[0] == ':' && s[1] == ':')
12493                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
12494             if (s == end)
12495                 DIE(aTHX_ "Bareword in require maps to empty filename");
12496
12497             for (; s < end; s++) {
12498                 if (*s == ':' && s[1] == ':') {
12499                     *s = '/';
12500                     Move(s+2, s+1, end - s - 1, char);
12501                     --end;
12502                 }
12503             }
12504             SvEND_set(sv, end);
12505             sv_catpvs(sv, ".pm");
12506             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
12507             hek = share_hek(SvPVX(sv),
12508                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
12509                             hash);
12510             sv_sethek(sv, hek);
12511             unshare_hek(hek);
12512             SvFLAGS(sv) |= was_readonly;
12513           }
12514           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
12515                 && !SvVOK(sv)) {
12516             s = SvPV(sv, len);
12517             if (SvREFCNT(sv) > 1) {
12518                 kid->op_sv = newSVpvn_share(
12519                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
12520                 SvREFCNT_dec_NN(sv);
12521             }
12522             else {
12523                 dVAR;
12524                 HEK *hek;
12525                 if (was_readonly) SvREADONLY_off(sv);
12526                 PERL_HASH(hash, s, len);
12527                 hek = share_hek(s,
12528                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
12529                                 hash);
12530                 sv_sethek(sv, hek);
12531                 unshare_hek(hek);
12532                 SvFLAGS(sv) |= was_readonly;
12533             }
12534           }
12535         }
12536     }
12537
12538     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
12539         /* handle override, if any */
12540      && (gv = gv_override("require", 7))) {
12541         OP *kid, *newop;
12542         if (o->op_flags & OPf_KIDS) {
12543             kid = cUNOPo->op_first;
12544             op_sibling_splice(o, NULL, -1, NULL);
12545         }
12546         else {
12547             kid = newDEFSVOP();
12548         }
12549         op_free(o);
12550         newop = S_new_entersubop(aTHX_ gv, kid);
12551         return newop;
12552     }
12553
12554     return ck_fun(o);
12555 }
12556
12557 OP *
12558 Perl_ck_return(pTHX_ OP *o)
12559 {
12560     OP *kid;
12561
12562     PERL_ARGS_ASSERT_CK_RETURN;
12563
12564     kid = OpSIBLING(cLISTOPo->op_first);
12565     if (PL_compcv && CvLVALUE(PL_compcv)) {
12566         for (; kid; kid = OpSIBLING(kid))
12567             op_lvalue(kid, OP_LEAVESUBLV);
12568     }
12569
12570     return o;
12571 }
12572
12573 OP *
12574 Perl_ck_select(pTHX_ OP *o)
12575 {
12576     dVAR;
12577     OP* kid;
12578
12579     PERL_ARGS_ASSERT_CK_SELECT;
12580
12581     if (o->op_flags & OPf_KIDS) {
12582         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
12583         if (kid && OpHAS_SIBLING(kid)) {
12584             OpTYPE_set(o, OP_SSELECT);
12585             o = ck_fun(o);
12586             return fold_constants(op_integerize(op_std_init(o)));
12587         }
12588     }
12589     o = ck_fun(o);
12590     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
12591     if (kid && kid->op_type == OP_RV2GV)
12592         kid->op_private &= ~HINT_STRICT_REFS;
12593     return o;
12594 }
12595
12596 OP *
12597 Perl_ck_shift(pTHX_ OP *o)
12598 {
12599     const I32 type = o->op_type;
12600
12601     PERL_ARGS_ASSERT_CK_SHIFT;
12602
12603     if (!(o->op_flags & OPf_KIDS)) {
12604         OP *argop;
12605
12606         if (!CvUNIQUE(PL_compcv)) {
12607             o->op_flags |= OPf_SPECIAL;
12608             return o;
12609         }
12610
12611         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
12612         op_free(o);
12613         return newUNOP(type, 0, scalar(argop));
12614     }
12615     return scalar(ck_fun(o));
12616 }
12617
12618 OP *
12619 Perl_ck_sort(pTHX_ OP *o)
12620 {
12621     OP *firstkid;
12622     OP *kid;
12623     HV * const hinthv =
12624         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
12625     U8 stacked;
12626
12627     PERL_ARGS_ASSERT_CK_SORT;
12628
12629     if (hinthv) {
12630             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
12631             if (svp) {
12632                 const I32 sorthints = (I32)SvIV(*svp);
12633                 if ((sorthints & HINT_SORT_STABLE) != 0)
12634                     o->op_private |= OPpSORT_STABLE;
12635                 if ((sorthints & HINT_SORT_UNSTABLE) != 0)
12636                     o->op_private |= OPpSORT_UNSTABLE;
12637             }
12638     }
12639
12640     if (o->op_flags & OPf_STACKED)
12641         simplify_sort(o);
12642     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
12643
12644     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
12645         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
12646
12647         /* if the first arg is a code block, process it and mark sort as
12648          * OPf_SPECIAL */
12649         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
12650             LINKLIST(kid);
12651             if (kid->op_type == OP_LEAVE)
12652                     op_null(kid);                       /* wipe out leave */
12653             /* Prevent execution from escaping out of the sort block. */
12654             kid->op_next = 0;
12655
12656             /* provide scalar context for comparison function/block */
12657             kid = scalar(firstkid);
12658             kid->op_next = kid;
12659             o->op_flags |= OPf_SPECIAL;
12660         }
12661         else if (kid->op_type == OP_CONST
12662               && kid->op_private & OPpCONST_BARE) {
12663             char tmpbuf[256];
12664             STRLEN len;
12665             PADOFFSET off;
12666             const char * const name = SvPV(kSVOP_sv, len);
12667             *tmpbuf = '&';
12668             assert (len < 256);
12669             Copy(name, tmpbuf+1, len, char);
12670             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
12671             if (off != NOT_IN_PAD) {
12672                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
12673                     SV * const fq =
12674                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
12675                     sv_catpvs(fq, "::");
12676                     sv_catsv(fq, kSVOP_sv);
12677                     SvREFCNT_dec_NN(kSVOP_sv);
12678                     kSVOP->op_sv = fq;
12679                 }
12680                 else {
12681                     OP * const padop = newOP(OP_PADCV, 0);
12682                     padop->op_targ = off;
12683                     /* replace the const op with the pad op */
12684                     op_sibling_splice(firstkid, NULL, 1, padop);
12685                     op_free(kid);
12686                 }
12687             }
12688         }
12689
12690         firstkid = OpSIBLING(firstkid);
12691     }
12692
12693     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
12694         /* provide list context for arguments */
12695         list(kid);
12696         if (stacked)
12697             op_lvalue(kid, OP_GREPSTART);
12698     }
12699
12700     return o;
12701 }
12702
12703 /* for sort { X } ..., where X is one of
12704  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
12705  * elide the second child of the sort (the one containing X),
12706  * and set these flags as appropriate
12707         OPpSORT_NUMERIC;
12708         OPpSORT_INTEGER;
12709         OPpSORT_DESCEND;
12710  * Also, check and warn on lexical $a, $b.
12711  */
12712
12713 STATIC void
12714 S_simplify_sort(pTHX_ OP *o)
12715 {
12716     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
12717     OP *k;
12718     int descending;
12719     GV *gv;
12720     const char *gvname;
12721     bool have_scopeop;
12722
12723     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
12724
12725     kid = kUNOP->op_first;                              /* get past null */
12726     if (!(have_scopeop = kid->op_type == OP_SCOPE)
12727      && kid->op_type != OP_LEAVE)
12728         return;
12729     kid = kLISTOP->op_last;                             /* get past scope */
12730     switch(kid->op_type) {
12731         case OP_NCMP:
12732         case OP_I_NCMP:
12733         case OP_SCMP:
12734             if (!have_scopeop) goto padkids;
12735             break;
12736         default:
12737             return;
12738     }
12739     k = kid;                                            /* remember this node*/
12740     if (kBINOP->op_first->op_type != OP_RV2SV
12741      || kBINOP->op_last ->op_type != OP_RV2SV)
12742     {
12743         /*
12744            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
12745            then used in a comparison.  This catches most, but not
12746            all cases.  For instance, it catches
12747                sort { my($a); $a <=> $b }
12748            but not
12749                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
12750            (although why you'd do that is anyone's guess).
12751         */
12752
12753        padkids:
12754         if (!ckWARN(WARN_SYNTAX)) return;
12755         kid = kBINOP->op_first;
12756         do {
12757             if (kid->op_type == OP_PADSV) {
12758                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
12759                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
12760                  && (  PadnamePV(name)[1] == 'a'
12761                     || PadnamePV(name)[1] == 'b'  ))
12762                     /* diag_listed_as: "my %s" used in sort comparison */
12763                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12764                                      "\"%s %s\" used in sort comparison",
12765                                       PadnameIsSTATE(name)
12766                                         ? "state"
12767                                         : "my",
12768                                       PadnamePV(name));
12769             }
12770         } while ((kid = OpSIBLING(kid)));
12771         return;
12772     }
12773     kid = kBINOP->op_first;                             /* get past cmp */
12774     if (kUNOP->op_first->op_type != OP_GV)
12775         return;
12776     kid = kUNOP->op_first;                              /* get past rv2sv */
12777     gv = kGVOP_gv;
12778     if (GvSTASH(gv) != PL_curstash)
12779         return;
12780     gvname = GvNAME(gv);
12781     if (*gvname == 'a' && gvname[1] == '\0')
12782         descending = 0;
12783     else if (*gvname == 'b' && gvname[1] == '\0')
12784         descending = 1;
12785     else
12786         return;
12787
12788     kid = k;                                            /* back to cmp */
12789     /* already checked above that it is rv2sv */
12790     kid = kBINOP->op_last;                              /* down to 2nd arg */
12791     if (kUNOP->op_first->op_type != OP_GV)
12792         return;
12793     kid = kUNOP->op_first;                              /* get past rv2sv */
12794     gv = kGVOP_gv;
12795     if (GvSTASH(gv) != PL_curstash)
12796         return;
12797     gvname = GvNAME(gv);
12798     if ( descending
12799          ? !(*gvname == 'a' && gvname[1] == '\0')
12800          : !(*gvname == 'b' && gvname[1] == '\0'))
12801         return;
12802     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
12803     if (descending)
12804         o->op_private |= OPpSORT_DESCEND;
12805     if (k->op_type == OP_NCMP)
12806         o->op_private |= OPpSORT_NUMERIC;
12807     if (k->op_type == OP_I_NCMP)
12808         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
12809     kid = OpSIBLING(cLISTOPo->op_first);
12810     /* cut out and delete old block (second sibling) */
12811     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
12812     op_free(kid);
12813 }
12814
12815 OP *
12816 Perl_ck_split(pTHX_ OP *o)
12817 {
12818     dVAR;
12819     OP *kid;
12820     OP *sibs;
12821
12822     PERL_ARGS_ASSERT_CK_SPLIT;
12823
12824     assert(o->op_type == OP_LIST);
12825
12826     if (o->op_flags & OPf_STACKED)
12827         return no_fh_allowed(o);
12828
12829     kid = cLISTOPo->op_first;
12830     /* delete leading NULL node, then add a CONST if no other nodes */
12831     assert(kid->op_type == OP_NULL);
12832     op_sibling_splice(o, NULL, 1,
12833         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
12834     op_free(kid);
12835     kid = cLISTOPo->op_first;
12836
12837     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
12838         /* remove match expression, and replace with new optree with
12839          * a match op at its head */
12840         op_sibling_splice(o, NULL, 1, NULL);
12841         /* pmruntime will handle split " " behavior with flag==2 */
12842         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
12843         op_sibling_splice(o, NULL, 0, kid);
12844     }
12845
12846     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
12847
12848     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
12849       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
12850                      "Use of /g modifier is meaningless in split");
12851     }
12852
12853     /* eliminate the split op, and move the match op (plus any children)
12854      * into its place, then convert the match op into a split op. i.e.
12855      *
12856      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
12857      *    |                        |                     |
12858      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
12859      *    |                        |                     |
12860      *    R                        X - Y                 X - Y
12861      *    |
12862      *    X - Y
12863      *
12864      * (R, if it exists, will be a regcomp op)
12865      */
12866
12867     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
12868     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
12869     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
12870     OpTYPE_set(kid, OP_SPLIT);
12871     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
12872     kid->op_private = o->op_private;
12873     op_free(o);
12874     o = kid;
12875     kid = sibs; /* kid is now the string arg of the split */
12876
12877     if (!kid) {
12878         kid = newDEFSVOP();
12879         op_append_elem(OP_SPLIT, o, kid);
12880     }
12881     scalar(kid);
12882
12883     kid = OpSIBLING(kid);
12884     if (!kid) {
12885         kid = newSVOP(OP_CONST, 0, newSViv(0));
12886         op_append_elem(OP_SPLIT, o, kid);
12887         o->op_private |= OPpSPLIT_IMPLIM;
12888     }
12889     scalar(kid);
12890
12891     if (OpHAS_SIBLING(kid))
12892         return too_many_arguments_pv(o,OP_DESC(o), 0);
12893
12894     return o;
12895 }
12896
12897 OP *
12898 Perl_ck_stringify(pTHX_ OP *o)
12899 {
12900     OP * const kid = OpSIBLING(cUNOPo->op_first);
12901     PERL_ARGS_ASSERT_CK_STRINGIFY;
12902     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
12903          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
12904          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
12905         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
12906     {
12907         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12908         op_free(o);
12909         return kid;
12910     }
12911     return ck_fun(o);
12912 }
12913         
12914 OP *
12915 Perl_ck_join(pTHX_ OP *o)
12916 {
12917     OP * const kid = OpSIBLING(cLISTOPo->op_first);
12918
12919     PERL_ARGS_ASSERT_CK_JOIN;
12920
12921     if (kid && kid->op_type == OP_MATCH) {
12922         if (ckWARN(WARN_SYNTAX)) {
12923             const REGEXP *re = PM_GETRE(kPMOP);
12924             const SV *msg = re
12925                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
12926                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
12927                     : newSVpvs_flags( "STRING", SVs_TEMP );
12928             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12929                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
12930                         SVfARG(msg), SVfARG(msg));
12931         }
12932     }
12933     if (kid
12934      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
12935         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
12936         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
12937            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
12938     {
12939         const OP * const bairn = OpSIBLING(kid); /* the list */
12940         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
12941          && OP_GIMME(bairn,0) == G_SCALAR)
12942         {
12943             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
12944                                      op_sibling_splice(o, kid, 1, NULL));
12945             op_free(o);
12946             return ret;
12947         }
12948     }
12949
12950     return ck_fun(o);
12951 }
12952
12953 /*
12954 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
12955
12956 Examines an op, which is expected to identify a subroutine at runtime,
12957 and attempts to determine at compile time which subroutine it identifies.
12958 This is normally used during Perl compilation to determine whether
12959 a prototype can be applied to a function call.  C<cvop> is the op
12960 being considered, normally an C<rv2cv> op.  A pointer to the identified
12961 subroutine is returned, if it could be determined statically, and a null
12962 pointer is returned if it was not possible to determine statically.
12963
12964 Currently, the subroutine can be identified statically if the RV that the
12965 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
12966 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
12967 suitable if the constant value must be an RV pointing to a CV.  Details of
12968 this process may change in future versions of Perl.  If the C<rv2cv> op
12969 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
12970 the subroutine statically: this flag is used to suppress compile-time
12971 magic on a subroutine call, forcing it to use default runtime behaviour.
12972
12973 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
12974 of a GV reference is modified.  If a GV was examined and its CV slot was
12975 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
12976 If the op is not optimised away, and the CV slot is later populated with
12977 a subroutine having a prototype, that flag eventually triggers the warning
12978 "called too early to check prototype".
12979
12980 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
12981 of returning a pointer to the subroutine it returns a pointer to the
12982 GV giving the most appropriate name for the subroutine in this context.
12983 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
12984 (C<CvANON>) subroutine that is referenced through a GV it will be the
12985 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
12986 A null pointer is returned as usual if there is no statically-determinable
12987 subroutine.
12988
12989 =cut
12990 */
12991
12992 /* shared by toke.c:yylex */
12993 CV *
12994 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
12995 {
12996     PADNAME *name = PAD_COMPNAME(off);
12997     CV *compcv = PL_compcv;
12998     while (PadnameOUTER(name)) {
12999         assert(PARENT_PAD_INDEX(name));
13000         compcv = CvOUTSIDE(compcv);
13001         name = PadlistNAMESARRAY(CvPADLIST(compcv))
13002                 [off = PARENT_PAD_INDEX(name)];
13003     }
13004     assert(!PadnameIsOUR(name));
13005     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
13006         return PadnamePROTOCV(name);
13007     }
13008     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
13009 }
13010
13011 CV *
13012 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
13013 {
13014     OP *rvop;
13015     CV *cv;
13016     GV *gv;
13017     PERL_ARGS_ASSERT_RV2CV_OP_CV;
13018     if (flags & ~RV2CVOPCV_FLAG_MASK)
13019         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
13020     if (cvop->op_type != OP_RV2CV)
13021         return NULL;
13022     if (cvop->op_private & OPpENTERSUB_AMPER)
13023         return NULL;
13024     if (!(cvop->op_flags & OPf_KIDS))
13025         return NULL;
13026     rvop = cUNOPx(cvop)->op_first;
13027     switch (rvop->op_type) {
13028         case OP_GV: {
13029             gv = cGVOPx_gv(rvop);
13030             if (!isGV(gv)) {
13031                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
13032                     cv = MUTABLE_CV(SvRV(gv));
13033                     gv = NULL;
13034                     break;
13035                 }
13036                 if (flags & RV2CVOPCV_RETURN_STUB)
13037                     return (CV *)gv;
13038                 else return NULL;
13039             }
13040             cv = GvCVu(gv);
13041             if (!cv) {
13042                 if (flags & RV2CVOPCV_MARK_EARLY)
13043                     rvop->op_private |= OPpEARLY_CV;
13044                 return NULL;
13045             }
13046         } break;
13047         case OP_CONST: {
13048             SV *rv = cSVOPx_sv(rvop);
13049             if (!SvROK(rv))
13050                 return NULL;
13051             cv = (CV*)SvRV(rv);
13052             gv = NULL;
13053         } break;
13054         case OP_PADCV: {
13055             cv = find_lexical_cv(rvop->op_targ);
13056             gv = NULL;
13057         } break;
13058         default: {
13059             return NULL;
13060         } NOT_REACHED; /* NOTREACHED */
13061     }
13062     if (SvTYPE((SV*)cv) != SVt_PVCV)
13063         return NULL;
13064     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
13065         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
13066             gv = CvGV(cv);
13067         return (CV*)gv;
13068     }
13069     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
13070         if (CvLEXICAL(cv) || CvNAMED(cv))
13071             return NULL;
13072         if (!CvANON(cv) || !gv)
13073             gv = CvGV(cv);
13074         return (CV*)gv;
13075
13076     } else {
13077         return cv;
13078     }
13079 }
13080
13081 /*
13082 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
13083
13084 Performs the default fixup of the arguments part of an C<entersub>
13085 op tree.  This consists of applying list context to each of the
13086 argument ops.  This is the standard treatment used on a call marked
13087 with C<&>, or a method call, or a call through a subroutine reference,
13088 or any other call where the callee can't be identified at compile time,
13089 or a call where the callee has no prototype.
13090
13091 =cut
13092 */
13093
13094 OP *
13095 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
13096 {
13097     OP *aop;
13098
13099     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
13100
13101     aop = cUNOPx(entersubop)->op_first;
13102     if (!OpHAS_SIBLING(aop))
13103         aop = cUNOPx(aop)->op_first;
13104     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
13105         /* skip the extra attributes->import() call implicitly added in
13106          * something like foo(my $x : bar)
13107          */
13108         if (   aop->op_type == OP_ENTERSUB
13109             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
13110         )
13111             continue;
13112         list(aop);
13113         op_lvalue(aop, OP_ENTERSUB);
13114     }
13115     return entersubop;
13116 }
13117
13118 /*
13119 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
13120
13121 Performs the fixup of the arguments part of an C<entersub> op tree
13122 based on a subroutine prototype.  This makes various modifications to
13123 the argument ops, from applying context up to inserting C<refgen> ops,
13124 and checking the number and syntactic types of arguments, as directed by
13125 the prototype.  This is the standard treatment used on a subroutine call,
13126 not marked with C<&>, where the callee can be identified at compile time
13127 and has a prototype.
13128
13129 C<protosv> supplies the subroutine prototype to be applied to the call.
13130 It may be a normal defined scalar, of which the string value will be used.
13131 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
13132 that has been cast to C<SV*>) which has a prototype.  The prototype
13133 supplied, in whichever form, does not need to match the actual callee
13134 referenced by the op tree.
13135
13136 If the argument ops disagree with the prototype, for example by having
13137 an unacceptable number of arguments, a valid op tree is returned anyway.
13138 The error is reflected in the parser state, normally resulting in a single
13139 exception at the top level of parsing which covers all the compilation
13140 errors that occurred.  In the error message, the callee is referred to
13141 by the name defined by the C<namegv> parameter.
13142
13143 =cut
13144 */
13145
13146 OP *
13147 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
13148 {
13149     STRLEN proto_len;
13150     const char *proto, *proto_end;
13151     OP *aop, *prev, *cvop, *parent;
13152     int optional = 0;
13153     I32 arg = 0;
13154     I32 contextclass = 0;
13155     const char *e = NULL;
13156     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
13157     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
13158         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
13159                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
13160     if (SvTYPE(protosv) == SVt_PVCV)
13161          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
13162     else proto = SvPV(protosv, proto_len);
13163     proto = S_strip_spaces(aTHX_ proto, &proto_len);
13164     proto_end = proto + proto_len;
13165     parent = entersubop;
13166     aop = cUNOPx(entersubop)->op_first;
13167     if (!OpHAS_SIBLING(aop)) {
13168         parent = aop;
13169         aop = cUNOPx(aop)->op_first;
13170     }
13171     prev = aop;
13172     aop = OpSIBLING(aop);
13173     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13174     while (aop != cvop) {
13175         OP* o3 = aop;
13176
13177         if (proto >= proto_end)
13178         {
13179             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
13180             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13181                                         SVfARG(namesv)), SvUTF8(namesv));
13182             return entersubop;
13183         }
13184
13185         switch (*proto) {
13186             case ';':
13187                 optional = 1;
13188                 proto++;
13189                 continue;
13190             case '_':
13191                 /* _ must be at the end */
13192                 if (proto[1] && !strchr(";@%", proto[1]))
13193                     goto oops;
13194                 /* FALLTHROUGH */
13195             case '$':
13196                 proto++;
13197                 arg++;
13198                 scalar(aop);
13199                 break;
13200             case '%':
13201             case '@':
13202                 list(aop);
13203                 arg++;
13204                 break;
13205             case '&':
13206                 proto++;
13207                 arg++;
13208                 if (    o3->op_type != OP_UNDEF
13209                     && (o3->op_type != OP_SREFGEN
13210                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
13211                                 != OP_ANONCODE
13212                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
13213                                 != OP_RV2CV)))
13214                     bad_type_gv(arg, namegv, o3,
13215                             arg == 1 ? "block or sub {}" : "sub {}");
13216                 break;
13217             case '*':
13218                 /* '*' allows any scalar type, including bareword */
13219                 proto++;
13220                 arg++;
13221                 if (o3->op_type == OP_RV2GV)
13222                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
13223                 else if (o3->op_type == OP_CONST)
13224                     o3->op_private &= ~OPpCONST_STRICT;
13225                 scalar(aop);
13226                 break;
13227             case '+':
13228                 proto++;
13229                 arg++;
13230                 if (o3->op_type == OP_RV2AV ||
13231                     o3->op_type == OP_PADAV ||
13232                     o3->op_type == OP_RV2HV ||
13233                     o3->op_type == OP_PADHV
13234                 ) {
13235                     goto wrapref;
13236                 }
13237                 scalar(aop);
13238                 break;
13239             case '[': case ']':
13240                 goto oops;
13241
13242             case '\\':
13243                 proto++;
13244                 arg++;
13245             again:
13246                 switch (*proto++) {
13247                     case '[':
13248                         if (contextclass++ == 0) {
13249                             e = (char *) memchr(proto, ']', proto_end - proto);
13250                             if (!e || e == proto)
13251                                 goto oops;
13252                         }
13253                         else
13254                             goto oops;
13255                         goto again;
13256
13257                     case ']':
13258                         if (contextclass) {
13259                             const char *p = proto;
13260                             const char *const end = proto;
13261                             contextclass = 0;
13262                             while (*--p != '[')
13263                                 /* \[$] accepts any scalar lvalue */
13264                                 if (*p == '$'
13265                                  && Perl_op_lvalue_flags(aTHX_
13266                                      scalar(o3),
13267                                      OP_READ, /* not entersub */
13268                                      OP_LVALUE_NO_CROAK
13269                                     )) goto wrapref;
13270                             bad_type_gv(arg, namegv, o3,
13271                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
13272                         } else
13273                             goto oops;
13274                         break;
13275                     case '*':
13276                         if (o3->op_type == OP_RV2GV)
13277                             goto wrapref;
13278                         if (!contextclass)
13279                             bad_type_gv(arg, namegv, o3, "symbol");
13280                         break;
13281                     case '&':
13282                         if (o3->op_type == OP_ENTERSUB
13283                          && !(o3->op_flags & OPf_STACKED))
13284                             goto wrapref;
13285                         if (!contextclass)
13286                             bad_type_gv(arg, namegv, o3, "subroutine");
13287                         break;
13288                     case '$':
13289                         if (o3->op_type == OP_RV2SV ||
13290                                 o3->op_type == OP_PADSV ||
13291                                 o3->op_type == OP_HELEM ||
13292                                 o3->op_type == OP_AELEM)
13293                             goto wrapref;
13294                         if (!contextclass) {
13295                             /* \$ accepts any scalar lvalue */
13296                             if (Perl_op_lvalue_flags(aTHX_
13297                                     scalar(o3),
13298                                     OP_READ,  /* not entersub */
13299                                     OP_LVALUE_NO_CROAK
13300                                )) goto wrapref;
13301                             bad_type_gv(arg, namegv, o3, "scalar");
13302                         }
13303                         break;
13304                     case '@':
13305                         if (o3->op_type == OP_RV2AV ||
13306                                 o3->op_type == OP_PADAV)
13307                         {
13308                             o3->op_flags &=~ OPf_PARENS;
13309                             goto wrapref;
13310                         }
13311                         if (!contextclass)
13312                             bad_type_gv(arg, namegv, o3, "array");
13313                         break;
13314                     case '%':
13315                         if (o3->op_type == OP_RV2HV ||
13316                                 o3->op_type == OP_PADHV)
13317                         {
13318                             o3->op_flags &=~ OPf_PARENS;
13319                             goto wrapref;
13320                         }
13321                         if (!contextclass)
13322                             bad_type_gv(arg, namegv, o3, "hash");
13323                         break;
13324                     wrapref:
13325                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
13326                                                 OP_REFGEN, 0);
13327                         if (contextclass && e) {
13328                             proto = e + 1;
13329                             contextclass = 0;
13330                         }
13331                         break;
13332                     default: goto oops;
13333                 }
13334                 if (contextclass)
13335                     goto again;
13336                 break;
13337             case ' ':
13338                 proto++;
13339                 continue;
13340             default:
13341             oops: {
13342                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
13343                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
13344                                   SVfARG(protosv));
13345             }
13346         }
13347
13348         op_lvalue(aop, OP_ENTERSUB);
13349         prev = aop;
13350         aop = OpSIBLING(aop);
13351     }
13352     if (aop == cvop && *proto == '_') {
13353         /* generate an access to $_ */
13354         op_sibling_splice(parent, prev, 0, newDEFSVOP());
13355     }
13356     if (!optional && proto_end > proto &&
13357         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
13358     {
13359         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
13360         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
13361                                     SVfARG(namesv)), SvUTF8(namesv));
13362     }
13363     return entersubop;
13364 }
13365
13366 /*
13367 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
13368
13369 Performs the fixup of the arguments part of an C<entersub> op tree either
13370 based on a subroutine prototype or using default list-context processing.
13371 This is the standard treatment used on a subroutine call, not marked
13372 with C<&>, where the callee can be identified at compile time.
13373
13374 C<protosv> supplies the subroutine prototype to be applied to the call,
13375 or indicates that there is no prototype.  It may be a normal scalar,
13376 in which case if it is defined then the string value will be used
13377 as a prototype, and if it is undefined then there is no prototype.
13378 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
13379 that has been cast to C<SV*>), of which the prototype will be used if it
13380 has one.  The prototype (or lack thereof) supplied, in whichever form,
13381 does not need to match the actual callee referenced by the op tree.
13382
13383 If the argument ops disagree with the prototype, for example by having
13384 an unacceptable number of arguments, a valid op tree is returned anyway.
13385 The error is reflected in the parser state, normally resulting in a single
13386 exception at the top level of parsing which covers all the compilation
13387 errors that occurred.  In the error message, the callee is referred to
13388 by the name defined by the C<namegv> parameter.
13389
13390 =cut
13391 */
13392
13393 OP *
13394 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
13395         GV *namegv, SV *protosv)
13396 {
13397     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
13398     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
13399         return ck_entersub_args_proto(entersubop, namegv, protosv);
13400     else
13401         return ck_entersub_args_list(entersubop);
13402 }
13403
13404 OP *
13405 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
13406 {
13407     IV cvflags = SvIVX(protosv);
13408     int opnum = cvflags & 0xffff;
13409     OP *aop = cUNOPx(entersubop)->op_first;
13410
13411     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
13412
13413     if (!opnum) {
13414         OP *cvop;
13415         if (!OpHAS_SIBLING(aop))
13416             aop = cUNOPx(aop)->op_first;
13417         aop = OpSIBLING(aop);
13418         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13419         if (aop != cvop) {
13420             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
13421             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13422                 SVfARG(namesv)), SvUTF8(namesv));
13423         }
13424         
13425         op_free(entersubop);
13426         switch(cvflags >> 16) {
13427         case 'F': return newSVOP(OP_CONST, 0,
13428                                         newSVpv(CopFILE(PL_curcop),0));
13429         case 'L': return newSVOP(
13430                            OP_CONST, 0,
13431                            Perl_newSVpvf(aTHX_
13432                              "%" IVdf, (IV)CopLINE(PL_curcop)
13433                            )
13434                          );
13435         case 'P': return newSVOP(OP_CONST, 0,
13436                                    (PL_curstash
13437                                      ? newSVhek(HvNAME_HEK(PL_curstash))
13438                                      : &PL_sv_undef
13439                                    )
13440                                 );
13441         }
13442         NOT_REACHED; /* NOTREACHED */
13443     }
13444     else {
13445         OP *prev, *cvop, *first, *parent;
13446         U32 flags = 0;
13447
13448         parent = entersubop;
13449         if (!OpHAS_SIBLING(aop)) {
13450             parent = aop;
13451             aop = cUNOPx(aop)->op_first;
13452         }
13453         
13454         first = prev = aop;
13455         aop = OpSIBLING(aop);
13456         /* find last sibling */
13457         for (cvop = aop;
13458              OpHAS_SIBLING(cvop);
13459              prev = cvop, cvop = OpSIBLING(cvop))
13460             ;
13461         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
13462             /* Usually, OPf_SPECIAL on an op with no args means that it had
13463              * parens, but these have their own meaning for that flag: */
13464             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
13465             && opnum != OP_DELETE && opnum != OP_EXISTS)
13466                 flags |= OPf_SPECIAL;
13467         /* excise cvop from end of sibling chain */
13468         op_sibling_splice(parent, prev, 1, NULL);
13469         op_free(cvop);
13470         if (aop == cvop) aop = NULL;
13471
13472         /* detach remaining siblings from the first sibling, then
13473          * dispose of original optree */
13474
13475         if (aop)
13476             op_sibling_splice(parent, first, -1, NULL);
13477         op_free(entersubop);
13478
13479         if (cvflags == (OP_ENTEREVAL | (1<<16)))
13480             flags |= OPpEVAL_BYTES <<8;
13481         
13482         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
13483         case OA_UNOP:
13484         case OA_BASEOP_OR_UNOP:
13485         case OA_FILESTATOP:
13486             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
13487         case OA_BASEOP:
13488             if (aop) {
13489                 SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
13490                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13491                     SVfARG(namesv)), SvUTF8(namesv));
13492                 op_free(aop);
13493             }
13494             return opnum == OP_RUNCV
13495                 ? newPVOP(OP_RUNCV,0,NULL)
13496                 : newOP(opnum,0);
13497         default:
13498             return op_convert_list(opnum,0,aop);
13499         }
13500     }
13501     NOT_REACHED; /* NOTREACHED */
13502     return entersubop;
13503 }
13504
13505 /*
13506 =for apidoc Am|void|cv_get_call_checker_flags|CV *cv|U32 gflags|Perl_call_checker *ckfun_p|SV **ckobj_p|U32 *ckflags_p
13507
13508 Retrieves the function that will be used to fix up a call to C<cv>.
13509 Specifically, the function is applied to an C<entersub> op tree for a
13510 subroutine call, not marked with C<&>, where the callee can be identified
13511 at compile time as C<cv>.
13512
13513 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
13514 for it is returned in C<*ckobj_p>, and control flags are returned in
13515 C<*ckflags_p>.  The function is intended to be called in this manner:
13516
13517  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
13518
13519 In this call, C<entersubop> is a pointer to the C<entersub> op,
13520 which may be replaced by the check function, and C<namegv> supplies
13521 the name that should be used by the check function to refer
13522 to the callee of the C<entersub> op if it needs to emit any diagnostics.
13523 It is permitted to apply the check function in non-standard situations,
13524 such as to a call to a different subroutine or to a method call.
13525
13526 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
13527 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
13528 instead, anything that can be used as the first argument to L</cv_name>.
13529 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
13530 check function requires C<namegv> to be a genuine GV.
13531
13532 By default, the check function is
13533 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
13534 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
13535 flag is clear.  This implements standard prototype processing.  It can
13536 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
13537
13538 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
13539 indicates that the caller only knows about the genuine GV version of
13540 C<namegv>, and accordingly the corresponding bit will always be set in
13541 C<*ckflags_p>, regardless of the check function's recorded requirements.
13542 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
13543 indicates the caller knows about the possibility of passing something
13544 other than a GV as C<namegv>, and accordingly the corresponding bit may
13545 be either set or clear in C<*ckflags_p>, indicating the check function's
13546 recorded requirements.
13547
13548 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
13549 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
13550 (for which see above).  All other bits should be clear.
13551
13552 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
13553
13554 The original form of L</cv_get_call_checker_flags>, which does not return
13555 checker flags.  When using a checker function returned by this function,
13556 it is only safe to call it with a genuine GV as its C<namegv> argument.
13557
13558 =cut
13559 */
13560
13561 void
13562 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
13563         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
13564 {
13565     MAGIC *callmg;
13566     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
13567     PERL_UNUSED_CONTEXT;
13568     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
13569     if (callmg) {
13570         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
13571         *ckobj_p = callmg->mg_obj;
13572         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
13573     } else {
13574         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
13575         *ckobj_p = (SV*)cv;
13576         *ckflags_p = gflags & MGf_REQUIRE_GV;
13577     }
13578 }
13579
13580 void
13581 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
13582 {
13583     U32 ckflags;
13584     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
13585     PERL_UNUSED_CONTEXT;
13586     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
13587         &ckflags);
13588 }
13589
13590 /*
13591 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 ckflags
13592
13593 Sets the function that will be used to fix up a call to C<cv>.
13594 Specifically, the function is applied to an C<entersub> op tree for a
13595 subroutine call, not marked with C<&>, where the callee can be identified
13596 at compile time as C<cv>.
13597
13598 The C-level function pointer is supplied in C<ckfun>, an SV argument for
13599 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
13600 The function should be defined like this:
13601
13602     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
13603
13604 It is intended to be called in this manner:
13605
13606     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
13607
13608 In this call, C<entersubop> is a pointer to the C<entersub> op,
13609 which may be replaced by the check function, and C<namegv> supplies
13610 the name that should be used by the check function to refer
13611 to the callee of the C<entersub> op if it needs to emit any diagnostics.
13612 It is permitted to apply the check function in non-standard situations,
13613 such as to a call to a different subroutine or to a method call.
13614
13615 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
13616 CV or other SV instead.  Whatever is passed can be used as the first
13617 argument to L</cv_name>.  You can force perl to pass a GV by including
13618 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
13619
13620 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
13621 bit currently has a defined meaning (for which see above).  All other
13622 bits should be clear.
13623
13624 The current setting for a particular CV can be retrieved by
13625 L</cv_get_call_checker_flags>.
13626
13627 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
13628
13629 The original form of L</cv_set_call_checker_flags>, which passes it the
13630 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
13631 of that flag setting is that the check function is guaranteed to get a
13632 genuine GV as its C<namegv> argument.
13633
13634 =cut
13635 */
13636
13637 void
13638 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
13639 {
13640     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
13641     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
13642 }
13643
13644 void
13645 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
13646                                      SV *ckobj, U32 ckflags)
13647 {
13648     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
13649     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
13650         if (SvMAGICAL((SV*)cv))
13651             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
13652     } else {
13653         MAGIC *callmg;
13654         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
13655         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
13656         assert(callmg);
13657         if (callmg->mg_flags & MGf_REFCOUNTED) {
13658             SvREFCNT_dec(callmg->mg_obj);
13659             callmg->mg_flags &= ~MGf_REFCOUNTED;
13660         }
13661         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
13662         callmg->mg_obj = ckobj;
13663         if (ckobj != (SV*)cv) {
13664             SvREFCNT_inc_simple_void_NN(ckobj);
13665             callmg->mg_flags |= MGf_REFCOUNTED;
13666         }
13667         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
13668                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
13669     }
13670 }
13671
13672 static void
13673 S_entersub_alloc_targ(pTHX_ OP * const o)
13674 {
13675     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
13676     o->op_private |= OPpENTERSUB_HASTARG;
13677 }
13678
13679 OP *
13680 Perl_ck_subr(pTHX_ OP *o)
13681 {
13682     OP *aop, *cvop;
13683     CV *cv;
13684     GV *namegv;
13685     SV **const_class = NULL;
13686
13687     PERL_ARGS_ASSERT_CK_SUBR;
13688
13689     aop = cUNOPx(o)->op_first;
13690     if (!OpHAS_SIBLING(aop))
13691         aop = cUNOPx(aop)->op_first;
13692     aop = OpSIBLING(aop);
13693     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13694     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
13695     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
13696
13697     o->op_private &= ~1;
13698     o->op_private |= (PL_hints & HINT_STRICT_REFS);
13699     if (PERLDB_SUB && PL_curstash != PL_debstash)
13700         o->op_private |= OPpENTERSUB_DB;
13701     switch (cvop->op_type) {
13702         case OP_RV2CV:
13703             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
13704             op_null(cvop);
13705             break;
13706         case OP_METHOD:
13707         case OP_METHOD_NAMED:
13708         case OP_METHOD_SUPER:
13709         case OP_METHOD_REDIR:
13710         case OP_METHOD_REDIR_SUPER:
13711             o->op_flags |= OPf_REF;
13712             if (aop->op_type == OP_CONST) {
13713                 aop->op_private &= ~OPpCONST_STRICT;
13714                 const_class = &cSVOPx(aop)->op_sv;
13715             }
13716             else if (aop->op_type == OP_LIST) {
13717                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
13718                 if (sib && sib->op_type == OP_CONST) {
13719                     sib->op_private &= ~OPpCONST_STRICT;
13720                     const_class = &cSVOPx(sib)->op_sv;
13721                 }
13722             }
13723             /* make class name a shared cow string to speedup method calls */
13724             /* constant string might be replaced with object, f.e. bigint */
13725             if (const_class && SvPOK(*const_class)) {
13726                 STRLEN len;
13727                 const char* str = SvPV(*const_class, len);
13728                 if (len) {
13729                     SV* const shared = newSVpvn_share(
13730                         str, SvUTF8(*const_class)
13731                                     ? -(SSize_t)len : (SSize_t)len,
13732                         0
13733                     );
13734                     if (SvREADONLY(*const_class))
13735                         SvREADONLY_on(shared);
13736                     SvREFCNT_dec(*const_class);
13737                     *const_class = shared;
13738                 }
13739             }
13740             break;
13741     }
13742
13743     if (!cv) {
13744         S_entersub_alloc_targ(aTHX_ o);
13745         return ck_entersub_args_list(o);
13746     } else {
13747         Perl_call_checker ckfun;
13748         SV *ckobj;
13749         U32 ckflags;
13750         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
13751         if (CvISXSUB(cv) || !CvROOT(cv))
13752             S_entersub_alloc_targ(aTHX_ o);
13753         if (!namegv) {
13754             /* The original call checker API guarantees that a GV will be
13755                be provided with the right name.  So, if the old API was
13756                used (or the REQUIRE_GV flag was passed), we have to reify
13757                the CV’s GV, unless this is an anonymous sub.  This is not
13758                ideal for lexical subs, as its stringification will include
13759                the package.  But it is the best we can do.  */
13760             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
13761                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
13762                     namegv = CvGV(cv);
13763             }
13764             else namegv = MUTABLE_GV(cv);
13765             /* After a syntax error in a lexical sub, the cv that
13766                rv2cv_op_cv returns may be a nameless stub. */
13767             if (!namegv) return ck_entersub_args_list(o);
13768
13769         }
13770         return ckfun(aTHX_ o, namegv, ckobj);
13771     }
13772 }
13773
13774 OP *
13775 Perl_ck_svconst(pTHX_ OP *o)
13776 {
13777     SV * const sv = cSVOPo->op_sv;
13778     PERL_ARGS_ASSERT_CK_SVCONST;
13779     PERL_UNUSED_CONTEXT;
13780 #ifdef PERL_COPY_ON_WRITE
13781     /* Since the read-only flag may be used to protect a string buffer, we
13782        cannot do copy-on-write with existing read-only scalars that are not
13783        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
13784        that constant, mark the constant as COWable here, if it is not
13785        already read-only. */
13786     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
13787         SvIsCOW_on(sv);
13788         CowREFCNT(sv) = 0;
13789 # ifdef PERL_DEBUG_READONLY_COW
13790         sv_buf_to_ro(sv);
13791 # endif
13792     }
13793 #endif
13794     SvREADONLY_on(sv);
13795     return o;
13796 }
13797
13798 OP *
13799 Perl_ck_trunc(pTHX_ OP *o)
13800 {
13801     PERL_ARGS_ASSERT_CK_TRUNC;
13802
13803     if (o->op_flags & OPf_KIDS) {
13804         SVOP *kid = (SVOP*)cUNOPo->op_first;
13805
13806         if (kid->op_type == OP_NULL)
13807             kid = (SVOP*)OpSIBLING(kid);
13808         if (kid && kid->op_type == OP_CONST &&
13809             (kid->op_private & OPpCONST_BARE) &&
13810             !kid->op_folded)
13811         {
13812             o->op_flags |= OPf_SPECIAL;
13813             kid->op_private &= ~OPpCONST_STRICT;
13814         }
13815     }
13816     return ck_fun(o);
13817 }
13818
13819 OP *
13820 Perl_ck_substr(pTHX_ OP *o)
13821 {
13822     PERL_ARGS_ASSERT_CK_SUBSTR;
13823
13824     o = ck_fun(o);
13825     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
13826         OP *kid = cLISTOPo->op_first;
13827
13828         if (kid->op_type == OP_NULL)
13829             kid = OpSIBLING(kid);
13830         if (kid)
13831             /* Historically, substr(delete $foo{bar},...) has been allowed
13832                with 4-arg substr.  Keep it working by applying entersub
13833                lvalue context.  */
13834             op_lvalue(kid, OP_ENTERSUB);
13835
13836     }
13837     return o;
13838 }
13839
13840 OP *
13841 Perl_ck_tell(pTHX_ OP *o)
13842 {
13843     PERL_ARGS_ASSERT_CK_TELL;
13844     o = ck_fun(o);
13845     if (o->op_flags & OPf_KIDS) {
13846      OP *kid = cLISTOPo->op_first;
13847      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
13848      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13849     }
13850     return o;
13851 }
13852
13853 OP *
13854 Perl_ck_each(pTHX_ OP *o)
13855 {
13856     dVAR;
13857     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
13858     const unsigned orig_type  = o->op_type;
13859
13860     PERL_ARGS_ASSERT_CK_EACH;
13861
13862     if (kid) {
13863         switch (kid->op_type) {
13864             case OP_PADHV:
13865             case OP_RV2HV:
13866                 break;
13867             case OP_PADAV:
13868             case OP_RV2AV:
13869                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
13870                             : orig_type == OP_KEYS ? OP_AKEYS
13871                             :                        OP_AVALUES);
13872                 break;
13873             case OP_CONST:
13874                 if (kid->op_private == OPpCONST_BARE
13875                  || !SvROK(cSVOPx_sv(kid))
13876                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
13877                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
13878                    )
13879                     goto bad;
13880                 /* FALLTHROUGH */
13881             default:
13882                 qerror(Perl_mess(aTHX_
13883                     "Experimental %s on scalar is now forbidden",
13884                      PL_op_desc[orig_type]));
13885                bad:
13886                 bad_type_pv(1, "hash or array", o, kid);
13887                 return o;
13888         }
13889     }
13890     return ck_fun(o);
13891 }
13892
13893 OP *
13894 Perl_ck_length(pTHX_ OP *o)
13895 {
13896     PERL_ARGS_ASSERT_CK_LENGTH;
13897
13898     o = ck_fun(o);
13899
13900     if (ckWARN(WARN_SYNTAX)) {
13901         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
13902
13903         if (kid) {
13904             SV *name = NULL;
13905             const bool hash = kid->op_type == OP_PADHV
13906                            || kid->op_type == OP_RV2HV;
13907             switch (kid->op_type) {
13908                 case OP_PADHV:
13909                 case OP_PADAV:
13910                 case OP_RV2HV:
13911                 case OP_RV2AV:
13912                     name = S_op_varname(aTHX_ kid);
13913                     break;
13914                 default:
13915                     return o;
13916             }
13917             if (name)
13918                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13919                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
13920                     ")\"?)",
13921                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
13922                 );
13923             else if (hash)
13924      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
13925                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13926                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
13927             else
13928      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
13929                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13930                     "length() used on @array (did you mean \"scalar(@array)\"?)");
13931         }
13932     }
13933
13934     return o;
13935 }
13936
13937
13938
13939 /* 
13940    ---------------------------------------------------------
13941  
13942    Common vars in list assignment
13943
13944    There now follows some enums and static functions for detecting
13945    common variables in list assignments. Here is a little essay I wrote
13946    for myself when trying to get my head around this. DAPM.
13947
13948    ----
13949
13950    First some random observations:
13951    
13952    * If a lexical var is an alias of something else, e.g.
13953        for my $x ($lex, $pkg, $a[0]) {...}
13954      then the act of aliasing will increase the reference count of the SV
13955    
13956    * If a package var is an alias of something else, it may still have a
13957      reference count of 1, depending on how the alias was created, e.g.
13958      in *a = *b, $a may have a refcount of 1 since the GP is shared
13959      with a single GvSV pointer to the SV. So If it's an alias of another
13960      package var, then RC may be 1; if it's an alias of another scalar, e.g.
13961      a lexical var or an array element, then it will have RC > 1.
13962    
13963    * There are many ways to create a package alias; ultimately, XS code
13964      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
13965      run-time tracing mechanisms are unlikely to be able to catch all cases.
13966    
13967    * When the LHS is all my declarations, the same vars can't appear directly
13968      on the RHS, but they can indirectly via closures, aliasing and lvalue
13969      subs. But those techniques all involve an increase in the lexical
13970      scalar's ref count.
13971    
13972    * When the LHS is all lexical vars (but not necessarily my declarations),
13973      it is possible for the same lexicals to appear directly on the RHS, and
13974      without an increased ref count, since the stack isn't refcounted.
13975      This case can be detected at compile time by scanning for common lex
13976      vars with PL_generation.
13977    
13978    * lvalue subs defeat common var detection, but they do at least
13979      return vars with a temporary ref count increment. Also, you can't
13980      tell at compile time whether a sub call is lvalue.
13981    
13982     
13983    So...
13984          
13985    A: There are a few circumstances where there definitely can't be any
13986      commonality:
13987    
13988        LHS empty:  () = (...);
13989        RHS empty:  (....) = ();
13990        RHS contains only constants or other 'can't possibly be shared'
13991            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
13992            i.e. they only contain ops not marked as dangerous, whose children
13993            are also not dangerous;
13994        LHS ditto;
13995        LHS contains a single scalar element: e.g. ($x) = (....); because
13996            after $x has been modified, it won't be used again on the RHS;
13997        RHS contains a single element with no aggregate on LHS: e.g.
13998            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
13999            won't be used again.
14000    
14001    B: If LHS are all 'my' lexical var declarations (or safe ops, which
14002      we can ignore):
14003    
14004        my ($a, $b, @c) = ...;
14005    
14006        Due to closure and goto tricks, these vars may already have content.
14007        For the same reason, an element on the RHS may be a lexical or package
14008        alias of one of the vars on the left, or share common elements, for
14009        example:
14010    
14011            my ($x,$y) = f(); # $x and $y on both sides
14012            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
14013    
14014        and
14015    
14016            my $ra = f();
14017            my @a = @$ra;  # elements of @a on both sides
14018            sub f { @a = 1..4; \@a }
14019    
14020    
14021        First, just consider scalar vars on LHS:
14022    
14023            RHS is safe only if (A), or in addition,
14024                * contains only lexical *scalar* vars, where neither side's
14025                  lexicals have been flagged as aliases 
14026    
14027            If RHS is not safe, then it's always legal to check LHS vars for
14028            RC==1, since the only RHS aliases will always be associated
14029            with an RC bump.
14030    
14031            Note that in particular, RHS is not safe if:
14032    
14033                * it contains package scalar vars; e.g.:
14034    
14035                    f();
14036                    my ($x, $y) = (2, $x_alias);
14037                    sub f { $x = 1; *x_alias = \$x; }
14038    
14039                * It contains other general elements, such as flattened or
14040                * spliced or single array or hash elements, e.g.
14041    
14042                    f();
14043                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc 
14044    
14045                    sub f {
14046                        ($x, $y) = (1,2);
14047                        use feature 'refaliasing';
14048                        \($a[0], $a[1]) = \($y,$x);
14049                    }
14050    
14051                  It doesn't matter if the array/hash is lexical or package.
14052    
14053                * it contains a function call that happens to be an lvalue
14054                  sub which returns one or more of the above, e.g.
14055    
14056                    f();
14057                    my ($x,$y) = f();
14058    
14059                    sub f : lvalue {
14060                        ($x, $y) = (1,2);
14061                        *x1 = \$x;
14062                        $y, $x1;
14063                    }
14064    
14065                    (so a sub call on the RHS should be treated the same
14066                    as having a package var on the RHS).
14067    
14068                * any other "dangerous" thing, such an op or built-in that
14069                  returns one of the above, e.g. pp_preinc
14070    
14071    
14072            If RHS is not safe, what we can do however is at compile time flag
14073            that the LHS are all my declarations, and at run time check whether
14074            all the LHS have RC == 1, and if so skip the full scan.
14075    
14076        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
14077    
14078            Here the issue is whether there can be elements of @a on the RHS
14079            which will get prematurely freed when @a is cleared prior to
14080            assignment. This is only a problem if the aliasing mechanism
14081            is one which doesn't increase the refcount - only if RC == 1
14082            will the RHS element be prematurely freed.
14083    
14084            Because the array/hash is being INTROed, it or its elements
14085            can't directly appear on the RHS:
14086    
14087                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
14088    
14089            but can indirectly, e.g.:
14090    
14091                my $r = f();
14092                my (@a) = @$r;
14093                sub f { @a = 1..3; \@a }
14094    
14095            So if the RHS isn't safe as defined by (A), we must always
14096            mortalise and bump the ref count of any remaining RHS elements
14097            when assigning to a non-empty LHS aggregate.
14098    
14099            Lexical scalars on the RHS aren't safe if they've been involved in
14100            aliasing, e.g.
14101    
14102                use feature 'refaliasing';
14103    
14104                f();
14105                \(my $lex) = \$pkg;
14106                my @a = ($lex,3); # equivalent to ($a[0],3)
14107    
14108                sub f {
14109                    @a = (1,2);
14110                    \$pkg = \$a[0];
14111                }
14112    
14113            Similarly with lexical arrays and hashes on the RHS:
14114    
14115                f();
14116                my @b;
14117                my @a = (@b);
14118    
14119                sub f {
14120                    @a = (1,2);
14121                    \$b[0] = \$a[1];
14122                    \$b[1] = \$a[0];
14123                }
14124    
14125    
14126    
14127    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
14128        my $a; ($a, my $b) = (....);
14129    
14130        The difference between (B) and (C) is that it is now physically
14131        possible for the LHS vars to appear on the RHS too, where they
14132        are not reference counted; but in this case, the compile-time
14133        PL_generation sweep will detect such common vars.
14134    
14135        So the rules for (C) differ from (B) in that if common vars are
14136        detected, the runtime "test RC==1" optimisation can no longer be used,
14137        and a full mark and sweep is required
14138    
14139    D: As (C), but in addition the LHS may contain package vars.
14140    
14141        Since package vars can be aliased without a corresponding refcount
14142        increase, all bets are off. It's only safe if (A). E.g.
14143    
14144            my ($x, $y) = (1,2);
14145    
14146            for $x_alias ($x) {
14147                ($x_alias, $y) = (3, $x); # whoops
14148            }
14149    
14150        Ditto for LHS aggregate package vars.
14151    
14152    E: Any other dangerous ops on LHS, e.g.
14153            (f(), $a[0], @$r) = (...);
14154    
14155        this is similar to (E) in that all bets are off. In addition, it's
14156        impossible to determine at compile time whether the LHS
14157        contains a scalar or an aggregate, e.g.
14158    
14159            sub f : lvalue { @a }
14160            (f()) = 1..3;
14161
14162 * ---------------------------------------------------------
14163 */
14164
14165
14166 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
14167  * that at least one of the things flagged was seen.
14168  */
14169
14170 enum {
14171     AAS_MY_SCALAR       = 0x001, /* my $scalar */
14172     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
14173     AAS_LEX_SCALAR      = 0x004, /* $lexical */
14174     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
14175     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
14176     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
14177     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
14178     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
14179                                          that's flagged OA_DANGEROUS */
14180     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
14181                                         not in any of the categories above */
14182     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
14183 };
14184
14185
14186
14187 /* helper function for S_aassign_scan().
14188  * check a PAD-related op for commonality and/or set its generation number.
14189  * Returns a boolean indicating whether its shared */
14190
14191 static bool
14192 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
14193 {
14194     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
14195         /* lexical used in aliasing */
14196         return TRUE;
14197
14198     if (rhs)
14199         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
14200     else
14201         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
14202
14203     return FALSE;
14204 }
14205
14206
14207 /*
14208   Helper function for OPpASSIGN_COMMON* detection in rpeep().
14209   It scans the left or right hand subtree of the aassign op, and returns a
14210   set of flags indicating what sorts of things it found there.
14211   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
14212   set PL_generation on lexical vars; if the latter, we see if
14213   PL_generation matches.
14214   'top' indicates whether we're recursing or at the top level.
14215   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
14216   This fn will increment it by the number seen. It's not intended to
14217   be an accurate count (especially as many ops can push a variable
14218   number of SVs onto the stack); rather it's used as to test whether there
14219   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
14220 */
14221
14222 static int
14223 S_aassign_scan(pTHX_ OP* o, bool rhs, bool top, int *scalars_p)
14224 {
14225     int flags = 0;
14226     bool kid_top = FALSE;
14227
14228     /* first, look for a solitary @_ on the RHS */
14229     if (   rhs
14230         && top
14231         && (o->op_flags & OPf_KIDS)
14232         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
14233     ) {
14234         OP *kid = cUNOPo->op_first;
14235         if (   (   kid->op_type == OP_PUSHMARK
14236                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
14237             && ((kid = OpSIBLING(kid)))
14238             && !OpHAS_SIBLING(kid)
14239             && kid->op_type == OP_RV2AV
14240             && !(kid->op_flags & OPf_REF)
14241             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
14242             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
14243             && ((kid = cUNOPx(kid)->op_first))
14244             && kid->op_type == OP_GV
14245             && cGVOPx_gv(kid) == PL_defgv
14246         )
14247             flags |= AAS_DEFAV;
14248     }
14249
14250     switch (o->op_type) {
14251     case OP_GVSV:
14252         (*scalars_p)++;
14253         return AAS_PKG_SCALAR;
14254
14255     case OP_PADAV:
14256     case OP_PADHV:
14257         (*scalars_p) += 2;
14258         /* if !top, could be e.g. @a[0,1] */
14259         if (top && (o->op_flags & OPf_REF))
14260             return (o->op_private & OPpLVAL_INTRO)
14261                 ? AAS_MY_AGG : AAS_LEX_AGG;
14262         return AAS_DANGEROUS;
14263
14264     case OP_PADSV:
14265         {
14266             int comm = S_aassign_padcheck(aTHX_ o, rhs)
14267                         ?  AAS_LEX_SCALAR_COMM : 0;
14268             (*scalars_p)++;
14269             return (o->op_private & OPpLVAL_INTRO)
14270                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
14271         }
14272
14273     case OP_RV2AV:
14274     case OP_RV2HV:
14275         (*scalars_p) += 2;
14276         if (cUNOPx(o)->op_first->op_type != OP_GV)
14277             return AAS_DANGEROUS; /* @{expr}, %{expr} */
14278         /* @pkg, %pkg */
14279         /* if !top, could be e.g. @a[0,1] */
14280         if (top && (o->op_flags & OPf_REF))
14281             return AAS_PKG_AGG;
14282         return AAS_DANGEROUS;
14283
14284     case OP_RV2SV:
14285         (*scalars_p)++;
14286         if (cUNOPx(o)->op_first->op_type != OP_GV) {
14287             (*scalars_p) += 2;
14288             return AAS_DANGEROUS; /* ${expr} */
14289         }
14290         return AAS_PKG_SCALAR; /* $pkg */
14291
14292     case OP_SPLIT:
14293         if (o->op_private & OPpSPLIT_ASSIGN) {
14294             /* the assign in @a = split() has been optimised away
14295              * and the @a attached directly to the split op
14296              * Treat the array as appearing on the RHS, i.e.
14297              *    ... = (@a = split)
14298              * is treated like
14299              *    ... = @a;
14300              */
14301
14302             if (o->op_flags & OPf_STACKED)
14303                 /* @{expr} = split() - the array expression is tacked
14304                  * on as an extra child to split - process kid */
14305                 return S_aassign_scan(aTHX_ cLISTOPo->op_last, rhs,
14306                                         top, scalars_p);
14307
14308             /* ... else array is directly attached to split op */
14309             (*scalars_p) += 2;
14310             if (PL_op->op_private & OPpSPLIT_LEX)
14311                 return (o->op_private & OPpLVAL_INTRO)
14312                     ? AAS_MY_AGG : AAS_LEX_AGG;
14313             else
14314                 return AAS_PKG_AGG;
14315         }
14316         (*scalars_p)++;
14317         /* other args of split can't be returned */
14318         return AAS_SAFE_SCALAR;
14319
14320     case OP_UNDEF:
14321         /* undef counts as a scalar on the RHS:
14322          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
14323          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
14324          */
14325         if (rhs)
14326             (*scalars_p)++;
14327         flags = AAS_SAFE_SCALAR;
14328         break;
14329
14330     case OP_PUSHMARK:
14331     case OP_STUB:
14332         /* these are all no-ops; they don't push a potentially common SV
14333          * onto the stack, so they are neither AAS_DANGEROUS nor
14334          * AAS_SAFE_SCALAR */
14335         return 0;
14336
14337     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
14338         break;
14339
14340     case OP_NULL:
14341     case OP_LIST:
14342         /* these do nothing but may have children; but their children
14343          * should also be treated as top-level */
14344         kid_top = top;
14345         break;
14346
14347     default:
14348         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
14349             (*scalars_p) += 2;
14350             flags = AAS_DANGEROUS;
14351             break;
14352         }
14353
14354         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
14355             && (o->op_private & OPpTARGET_MY))
14356         {
14357             (*scalars_p)++;
14358             return S_aassign_padcheck(aTHX_ o, rhs)
14359                 ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
14360         }
14361
14362         /* if its an unrecognised, non-dangerous op, assume that it
14363          * it the cause of at least one safe scalar */
14364         (*scalars_p)++;
14365         flags = AAS_SAFE_SCALAR;
14366         break;
14367     }
14368
14369     /* XXX this assumes that all other ops are "transparent" - i.e. that
14370      * they can return some of their children. While this true for e.g.
14371      * sort and grep, it's not true for e.g. map. We really need a
14372      * 'transparent' flag added to regen/opcodes
14373      */
14374     if (o->op_flags & OPf_KIDS) {
14375         OP *kid;
14376         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
14377             flags |= S_aassign_scan(aTHX_ kid, rhs, kid_top, scalars_p);
14378     }
14379     return flags;
14380 }
14381
14382
14383 /* Check for in place reverse and sort assignments like "@a = reverse @a"
14384    and modify the optree to make them work inplace */
14385
14386 STATIC void
14387 S_inplace_aassign(pTHX_ OP *o) {
14388
14389     OP *modop, *modop_pushmark;
14390     OP *oright;
14391     OP *oleft, *oleft_pushmark;
14392
14393     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
14394
14395     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
14396
14397     assert(cUNOPo->op_first->op_type == OP_NULL);
14398     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
14399     assert(modop_pushmark->op_type == OP_PUSHMARK);
14400     modop = OpSIBLING(modop_pushmark);
14401
14402     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
14403         return;
14404
14405     /* no other operation except sort/reverse */
14406     if (OpHAS_SIBLING(modop))
14407         return;
14408
14409     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
14410     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
14411
14412     if (modop->op_flags & OPf_STACKED) {
14413         /* skip sort subroutine/block */
14414         assert(oright->op_type == OP_NULL);
14415         oright = OpSIBLING(oright);
14416     }
14417
14418     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
14419     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
14420     assert(oleft_pushmark->op_type == OP_PUSHMARK);
14421     oleft = OpSIBLING(oleft_pushmark);
14422
14423     /* Check the lhs is an array */
14424     if (!oleft ||
14425         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
14426         || OpHAS_SIBLING(oleft)
14427         || (oleft->op_private & OPpLVAL_INTRO)
14428     )
14429         return;
14430
14431     /* Only one thing on the rhs */
14432     if (OpHAS_SIBLING(oright))
14433         return;
14434
14435     /* check the array is the same on both sides */
14436     if (oleft->op_type == OP_RV2AV) {
14437         if (oright->op_type != OP_RV2AV
14438             || !cUNOPx(oright)->op_first
14439             || cUNOPx(oright)->op_first->op_type != OP_GV
14440             || cUNOPx(oleft )->op_first->op_type != OP_GV
14441             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
14442                cGVOPx_gv(cUNOPx(oright)->op_first)
14443         )
14444             return;
14445     }
14446     else if (oright->op_type != OP_PADAV
14447         || oright->op_targ != oleft->op_targ
14448     )
14449         return;
14450
14451     /* This actually is an inplace assignment */
14452
14453     modop->op_private |= OPpSORT_INPLACE;
14454
14455     /* transfer MODishness etc from LHS arg to RHS arg */
14456     oright->op_flags = oleft->op_flags;
14457
14458     /* remove the aassign op and the lhs */
14459     op_null(o);
14460     op_null(oleft_pushmark);
14461     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
14462         op_null(cUNOPx(oleft)->op_first);
14463     op_null(oleft);
14464 }
14465
14466
14467
14468 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
14469  * that potentially represent a series of one or more aggregate derefs
14470  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
14471  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
14472  * additional ops left in too).
14473  *
14474  * The caller will have already verified that the first few ops in the
14475  * chain following 'start' indicate a multideref candidate, and will have
14476  * set 'orig_o' to the point further on in the chain where the first index
14477  * expression (if any) begins.  'orig_action' specifies what type of
14478  * beginning has already been determined by the ops between start..orig_o
14479  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
14480  *
14481  * 'hints' contains any hints flags that need adding (currently just
14482  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
14483  */
14484
14485 STATIC void
14486 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
14487 {
14488     dVAR;
14489     int pass;
14490     UNOP_AUX_item *arg_buf = NULL;
14491     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
14492     int index_skip         = -1;    /* don't output index arg on this action */
14493
14494     /* similar to regex compiling, do two passes; the first pass
14495      * determines whether the op chain is convertible and calculates the
14496      * buffer size; the second pass populates the buffer and makes any
14497      * changes necessary to ops (such as moving consts to the pad on
14498      * threaded builds).
14499      *
14500      * NB: for things like Coverity, note that both passes take the same
14501      * path through the logic tree (except for 'if (pass)' bits), since
14502      * both passes are following the same op_next chain; and in
14503      * particular, if it would return early on the second pass, it would
14504      * already have returned early on the first pass.
14505      */
14506     for (pass = 0; pass < 2; pass++) {
14507         OP *o                = orig_o;
14508         UV action            = orig_action;
14509         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
14510         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
14511         int action_count     = 0;     /* number of actions seen so far */
14512         int action_ix        = 0;     /* action_count % (actions per IV) */
14513         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
14514         bool is_last         = FALSE; /* no more derefs to follow */
14515         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
14516         UNOP_AUX_item *arg     = arg_buf;
14517         UNOP_AUX_item *action_ptr = arg_buf;
14518
14519         if (pass)
14520             action_ptr->uv = 0;
14521         arg++;
14522
14523         switch (action) {
14524         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
14525         case MDEREF_HV_gvhv_helem:
14526             next_is_hash = TRUE;
14527             /* FALLTHROUGH */
14528         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
14529         case MDEREF_AV_gvav_aelem:
14530             if (pass) {
14531 #ifdef USE_ITHREADS
14532                 arg->pad_offset = cPADOPx(start)->op_padix;
14533                 /* stop it being swiped when nulled */
14534                 cPADOPx(start)->op_padix = 0;
14535 #else
14536                 arg->sv = cSVOPx(start)->op_sv;
14537                 cSVOPx(start)->op_sv = NULL;
14538 #endif
14539             }
14540             arg++;
14541             break;
14542
14543         case MDEREF_HV_padhv_helem:
14544         case MDEREF_HV_padsv_vivify_rv2hv_helem:
14545             next_is_hash = TRUE;
14546             /* FALLTHROUGH */
14547         case MDEREF_AV_padav_aelem:
14548         case MDEREF_AV_padsv_vivify_rv2av_aelem:
14549             if (pass) {
14550                 arg->pad_offset = start->op_targ;
14551                 /* we skip setting op_targ = 0 for now, since the intact
14552                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
14553                 reset_start_targ = TRUE;
14554             }
14555             arg++;
14556             break;
14557
14558         case MDEREF_HV_pop_rv2hv_helem:
14559             next_is_hash = TRUE;
14560             /* FALLTHROUGH */
14561         case MDEREF_AV_pop_rv2av_aelem:
14562             break;
14563
14564         default:
14565             NOT_REACHED; /* NOTREACHED */
14566             return;
14567         }
14568
14569         while (!is_last) {
14570             /* look for another (rv2av/hv; get index;
14571              * aelem/helem/exists/delele) sequence */
14572
14573             OP *kid;
14574             bool is_deref;
14575             bool ok;
14576             UV index_type = MDEREF_INDEX_none;
14577
14578             if (action_count) {
14579                 /* if this is not the first lookup, consume the rv2av/hv  */
14580
14581                 /* for N levels of aggregate lookup, we normally expect
14582                  * that the first N-1 [ah]elem ops will be flagged as
14583                  * /DEREF (so they autovivifiy if necessary), and the last
14584                  * lookup op not to be.
14585                  * For other things (like @{$h{k1}{k2}}) extra scope or
14586                  * leave ops can appear, so abandon the effort in that
14587                  * case */
14588                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
14589                     return;
14590
14591                 /* rv2av or rv2hv sKR/1 */
14592
14593                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
14594                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
14595                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
14596                     return;
14597
14598                 /* at this point, we wouldn't expect any of these
14599                  * possible private flags:
14600                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
14601                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
14602                  */
14603                 ASSUME(!(o->op_private &
14604                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
14605
14606                 hints = (o->op_private & OPpHINT_STRICT_REFS);
14607
14608                 /* make sure the type of the previous /DEREF matches the
14609                  * type of the next lookup */
14610                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
14611                 top_op = o;
14612
14613                 action = next_is_hash
14614                             ? MDEREF_HV_vivify_rv2hv_helem
14615                             : MDEREF_AV_vivify_rv2av_aelem;
14616                 o = o->op_next;
14617             }
14618
14619             /* if this is the second pass, and we're at the depth where
14620              * previously we encountered a non-simple index expression,
14621              * stop processing the index at this point */
14622             if (action_count != index_skip) {
14623
14624                 /* look for one or more simple ops that return an array
14625                  * index or hash key */
14626
14627                 switch (o->op_type) {
14628                 case OP_PADSV:
14629                     /* it may be a lexical var index */
14630                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
14631                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
14632                     ASSUME(!(o->op_private &
14633                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
14634
14635                     if (   OP_GIMME(o,0) == G_SCALAR
14636                         && !(o->op_flags & (OPf_REF|OPf_MOD))
14637                         && o->op_private == 0)
14638                     {
14639                         if (pass)
14640                             arg->pad_offset = o->op_targ;
14641                         arg++;
14642                         index_type = MDEREF_INDEX_padsv;
14643                         o = o->op_next;
14644                     }
14645                     break;
14646
14647                 case OP_CONST:
14648                     if (next_is_hash) {
14649                         /* it's a constant hash index */
14650                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
14651                             /* "use constant foo => FOO; $h{+foo}" for
14652                              * some weird FOO, can leave you with constants
14653                              * that aren't simple strings. It's not worth
14654                              * the extra hassle for those edge cases */
14655                             break;
14656
14657                         if (pass) {
14658                             UNOP *rop = NULL;
14659                             OP * helem_op = o->op_next;
14660
14661                             ASSUME(   helem_op->op_type == OP_HELEM
14662                                    || helem_op->op_type == OP_NULL);
14663                             if (helem_op->op_type == OP_HELEM) {
14664                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
14665                                 if (   helem_op->op_private & OPpLVAL_INTRO
14666                                     || rop->op_type != OP_RV2HV
14667                                 )
14668                                     rop = NULL;
14669                             }
14670                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo);
14671
14672 #ifdef USE_ITHREADS
14673                             /* Relocate sv to the pad for thread safety */
14674                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
14675                             arg->pad_offset = o->op_targ;
14676                             o->op_targ = 0;
14677 #else
14678                             arg->sv = cSVOPx_sv(o);
14679 #endif
14680                         }
14681                     }
14682                     else {
14683                         /* it's a constant array index */
14684                         IV iv;
14685                         SV *ix_sv = cSVOPo->op_sv;
14686                         if (!SvIOK(ix_sv))
14687                             break;
14688                         iv = SvIV(ix_sv);
14689
14690                         if (   action_count == 0
14691                             && iv >= -128
14692                             && iv <= 127
14693                             && (   action == MDEREF_AV_padav_aelem
14694                                 || action == MDEREF_AV_gvav_aelem)
14695                         )
14696                             maybe_aelemfast = TRUE;
14697
14698                         if (pass) {
14699                             arg->iv = iv;
14700                             SvREFCNT_dec_NN(cSVOPo->op_sv);
14701                         }
14702                     }
14703                     if (pass)
14704                         /* we've taken ownership of the SV */
14705                         cSVOPo->op_sv = NULL;
14706                     arg++;
14707                     index_type = MDEREF_INDEX_const;
14708                     o = o->op_next;
14709                     break;
14710
14711                 case OP_GV:
14712                     /* it may be a package var index */
14713
14714                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
14715                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
14716                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
14717                         || o->op_private != 0
14718                     )
14719                         break;
14720
14721                     kid = o->op_next;
14722                     if (kid->op_type != OP_RV2SV)
14723                         break;
14724
14725                     ASSUME(!(kid->op_flags &
14726                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
14727                              |OPf_SPECIAL|OPf_PARENS)));
14728                     ASSUME(!(kid->op_private &
14729                                     ~(OPpARG1_MASK
14730                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
14731                                      |OPpDEREF|OPpLVAL_INTRO)));
14732                     if(   (kid->op_flags &~ OPf_PARENS)
14733                             != (OPf_WANT_SCALAR|OPf_KIDS)
14734                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
14735                     )
14736                         break;
14737
14738                     if (pass) {
14739 #ifdef USE_ITHREADS
14740                         arg->pad_offset = cPADOPx(o)->op_padix;
14741                         /* stop it being swiped when nulled */
14742                         cPADOPx(o)->op_padix = 0;
14743 #else
14744                         arg->sv = cSVOPx(o)->op_sv;
14745                         cSVOPo->op_sv = NULL;
14746 #endif
14747                     }
14748                     arg++;
14749                     index_type = MDEREF_INDEX_gvsv;
14750                     o = kid->op_next;
14751                     break;
14752
14753                 } /* switch */
14754             } /* action_count != index_skip */
14755
14756             action |= index_type;
14757
14758
14759             /* at this point we have either:
14760              *   * detected what looks like a simple index expression,
14761              *     and expect the next op to be an [ah]elem, or
14762              *     an nulled  [ah]elem followed by a delete or exists;
14763              *  * found a more complex expression, so something other
14764              *    than the above follows.
14765              */
14766
14767             /* possibly an optimised away [ah]elem (where op_next is
14768              * exists or delete) */
14769             if (o->op_type == OP_NULL)
14770                 o = o->op_next;
14771
14772             /* at this point we're looking for an OP_AELEM, OP_HELEM,
14773              * OP_EXISTS or OP_DELETE */
14774
14775             /* if a custom array/hash access checker is in scope,
14776              * abandon optimisation attempt */
14777             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
14778                && PL_check[o->op_type] != Perl_ck_null)
14779                 return;
14780             /* similarly for customised exists and delete */
14781             if (  (o->op_type == OP_EXISTS)
14782                && PL_check[o->op_type] != Perl_ck_exists)
14783                 return;
14784             if (  (o->op_type == OP_DELETE)
14785                && PL_check[o->op_type] != Perl_ck_delete)
14786                 return;
14787
14788             if (   o->op_type != OP_AELEM
14789                 || (o->op_private &
14790                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
14791                 )
14792                 maybe_aelemfast = FALSE;
14793
14794             /* look for aelem/helem/exists/delete. If it's not the last elem
14795              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
14796              * flags; if it's the last, then it mustn't have
14797              * OPpDEREF_AV/HV, but may have lots of other flags, like
14798              * OPpLVAL_INTRO etc
14799              */
14800
14801             if (   index_type == MDEREF_INDEX_none
14802                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
14803                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
14804             )
14805                 ok = FALSE;
14806             else {
14807                 /* we have aelem/helem/exists/delete with valid simple index */
14808
14809                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
14810                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
14811                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
14812
14813                 /* This doesn't make much sense but is legal:
14814                  *    @{ local $x[0][0] } = 1
14815                  * Since scope exit will undo the autovivification,
14816                  * don't bother in the first place. The OP_LEAVE
14817                  * assertion is in case there are other cases of both
14818                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
14819                  * exit that would undo the local - in which case this
14820                  * block of code would need rethinking.
14821                  */
14822                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
14823 #ifdef DEBUGGING
14824                     OP *n = o->op_next;
14825                     while (n && (  n->op_type == OP_NULL
14826                                 || n->op_type == OP_LIST))
14827                         n = n->op_next;
14828                     assert(n && n->op_type == OP_LEAVE);
14829 #endif
14830                     o->op_private &= ~OPpDEREF;
14831                     is_deref = FALSE;
14832                 }
14833
14834                 if (is_deref) {
14835                     ASSUME(!(o->op_flags &
14836                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
14837                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
14838
14839                     ok =    (o->op_flags &~ OPf_PARENS)
14840                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
14841                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
14842                 }
14843                 else if (o->op_type == OP_EXISTS) {
14844                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
14845                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
14846                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
14847                     ok =  !(o->op_private & ~OPpARG1_MASK);
14848                 }
14849                 else if (o->op_type == OP_DELETE) {
14850                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
14851                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
14852                     ASSUME(!(o->op_private &
14853                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
14854                     /* don't handle slices or 'local delete'; the latter
14855                      * is fairly rare, and has a complex runtime */
14856                     ok =  !(o->op_private & ~OPpARG1_MASK);
14857                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
14858                         /* skip handling run-tome error */
14859                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
14860                 }
14861                 else {
14862                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
14863                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
14864                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
14865                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
14866                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
14867                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
14868                 }
14869             }
14870
14871             if (ok) {
14872                 if (!first_elem_op)
14873                     first_elem_op = o;
14874                 top_op = o;
14875                 if (is_deref) {
14876                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
14877                     o = o->op_next;
14878                 }
14879                 else {
14880                     is_last = TRUE;
14881                     action |= MDEREF_FLAG_last;
14882                 }
14883             }
14884             else {
14885                 /* at this point we have something that started
14886                  * promisingly enough (with rv2av or whatever), but failed
14887                  * to find a simple index followed by an
14888                  * aelem/helem/exists/delete. If this is the first action,
14889                  * give up; but if we've already seen at least one
14890                  * aelem/helem, then keep them and add a new action with
14891                  * MDEREF_INDEX_none, which causes it to do the vivify
14892                  * from the end of the previous lookup, and do the deref,
14893                  * but stop at that point. So $a[0][expr] will do one
14894                  * av_fetch, vivify and deref, then continue executing at
14895                  * expr */
14896                 if (!action_count)
14897                     return;
14898                 is_last = TRUE;
14899                 index_skip = action_count;
14900                 action |= MDEREF_FLAG_last;
14901                 if (index_type != MDEREF_INDEX_none)
14902                     arg--;
14903             }
14904
14905             if (pass)
14906                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
14907             action_ix++;
14908             action_count++;
14909             /* if there's no space for the next action, create a new slot
14910              * for it *before* we start adding args for that action */
14911             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
14912                 action_ptr = arg;
14913                 if (pass)
14914                     arg->uv = 0;
14915                 arg++;
14916                 action_ix = 0;
14917             }
14918         } /* while !is_last */
14919
14920         /* success! */
14921
14922         if (pass) {
14923             OP *mderef;
14924             OP *p, *q;
14925
14926             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
14927             if (index_skip == -1) {
14928                 mderef->op_flags = o->op_flags
14929                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
14930                 if (o->op_type == OP_EXISTS)
14931                     mderef->op_private = OPpMULTIDEREF_EXISTS;
14932                 else if (o->op_type == OP_DELETE)
14933                     mderef->op_private = OPpMULTIDEREF_DELETE;
14934                 else
14935                     mderef->op_private = o->op_private
14936                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
14937             }
14938             /* accumulate strictness from every level (although I don't think
14939              * they can actually vary) */
14940             mderef->op_private |= hints;
14941
14942             /* integrate the new multideref op into the optree and the
14943              * op_next chain.
14944              *
14945              * In general an op like aelem or helem has two child
14946              * sub-trees: the aggregate expression (a_expr) and the
14947              * index expression (i_expr):
14948              *
14949              *     aelem
14950              *       |
14951              *     a_expr - i_expr
14952              *
14953              * The a_expr returns an AV or HV, while the i-expr returns an
14954              * index. In general a multideref replaces most or all of a
14955              * multi-level tree, e.g.
14956              *
14957              *     exists
14958              *       |
14959              *     ex-aelem
14960              *       |
14961              *     rv2av  - i_expr1
14962              *       |
14963              *     helem
14964              *       |
14965              *     rv2hv  - i_expr2
14966              *       |
14967              *     aelem
14968              *       |
14969              *     a_expr - i_expr3
14970              *
14971              * With multideref, all the i_exprs will be simple vars or
14972              * constants, except that i_expr1 may be arbitrary in the case
14973              * of MDEREF_INDEX_none.
14974              *
14975              * The bottom-most a_expr will be either:
14976              *   1) a simple var (so padXv or gv+rv2Xv);
14977              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
14978              *      so a simple var with an extra rv2Xv;
14979              *   3) or an arbitrary expression.
14980              *
14981              * 'start', the first op in the execution chain, will point to
14982              *   1),2): the padXv or gv op;
14983              *   3):    the rv2Xv which forms the last op in the a_expr
14984              *          execution chain, and the top-most op in the a_expr
14985              *          subtree.
14986              *
14987              * For all cases, the 'start' node is no longer required,
14988              * but we can't free it since one or more external nodes
14989              * may point to it. E.g. consider
14990              *     $h{foo} = $a ? $b : $c
14991              * Here, both the op_next and op_other branches of the
14992              * cond_expr point to the gv[*h] of the hash expression, so
14993              * we can't free the 'start' op.
14994              *
14995              * For expr->[...], we need to save the subtree containing the
14996              * expression; for the other cases, we just need to save the
14997              * start node.
14998              * So in all cases, we null the start op and keep it around by
14999              * making it the child of the multideref op; for the expr->
15000              * case, the expr will be a subtree of the start node.
15001              *
15002              * So in the simple 1,2 case the  optree above changes to
15003              *
15004              *     ex-exists
15005              *       |
15006              *     multideref
15007              *       |
15008              *     ex-gv (or ex-padxv)
15009              *
15010              *  with the op_next chain being
15011              *
15012              *  -> ex-gv -> multideref -> op-following-ex-exists ->
15013              *
15014              *  In the 3 case, we have
15015              *
15016              *     ex-exists
15017              *       |
15018              *     multideref
15019              *       |
15020              *     ex-rv2xv
15021              *       |
15022              *    rest-of-a_expr
15023              *      subtree
15024              *
15025              *  and
15026              *
15027              *  -> rest-of-a_expr subtree ->
15028              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
15029              *
15030              *
15031              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
15032              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
15033              * multideref attached as the child, e.g.
15034              *
15035              *     exists
15036              *       |
15037              *     ex-aelem
15038              *       |
15039              *     ex-rv2av  - i_expr1
15040              *       |
15041              *     multideref
15042              *       |
15043              *     ex-whatever
15044              *
15045              */
15046
15047             /* if we free this op, don't free the pad entry */
15048             if (reset_start_targ)
15049                 start->op_targ = 0;
15050
15051
15052             /* Cut the bit we need to save out of the tree and attach to
15053              * the multideref op, then free the rest of the tree */
15054
15055             /* find parent of node to be detached (for use by splice) */
15056             p = first_elem_op;
15057             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
15058                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
15059             {
15060                 /* there is an arbitrary expression preceding us, e.g.
15061                  * expr->[..]? so we need to save the 'expr' subtree */
15062                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
15063                     p = cUNOPx(p)->op_first;
15064                 ASSUME(   start->op_type == OP_RV2AV
15065                        || start->op_type == OP_RV2HV);
15066             }
15067             else {
15068                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
15069                  * above for exists/delete. */
15070                 while (   (p->op_flags & OPf_KIDS)
15071                        && cUNOPx(p)->op_first != start
15072                 )
15073                     p = cUNOPx(p)->op_first;
15074             }
15075             ASSUME(cUNOPx(p)->op_first == start);
15076
15077             /* detach from main tree, and re-attach under the multideref */
15078             op_sibling_splice(mderef, NULL, 0,
15079                     op_sibling_splice(p, NULL, 1, NULL));
15080             op_null(start);
15081
15082             start->op_next = mderef;
15083
15084             mderef->op_next = index_skip == -1 ? o->op_next : o;
15085
15086             /* excise and free the original tree, and replace with
15087              * the multideref op */
15088             p = op_sibling_splice(top_op, NULL, -1, mderef);
15089             while (p) {
15090                 q = OpSIBLING(p);
15091                 op_free(p);
15092                 p = q;
15093             }
15094             op_null(top_op);
15095         }
15096         else {
15097             Size_t size = arg - arg_buf;
15098
15099             if (maybe_aelemfast && action_count == 1)
15100                 return;
15101
15102             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
15103                                 sizeof(UNOP_AUX_item) * (size + 1));
15104             /* for dumping etc: store the length in a hidden first slot;
15105              * we set the op_aux pointer to the second slot */
15106             arg_buf->uv = size;
15107             arg_buf++;
15108         }
15109     } /* for (pass = ...) */
15110 }
15111
15112 /* See if the ops following o are such that o will always be executed in
15113  * boolean context: that is, the SV which o pushes onto the stack will
15114  * only ever be consumed by later ops via SvTRUE(sv) or similar.
15115  * If so, set a suitable private flag on o. Normally this will be
15116  * bool_flag; but see below why maybe_flag is needed too.
15117  *
15118  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
15119  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
15120  * already be taken, so you'll have to give that op two different flags.
15121  *
15122  * More explanation of 'maybe_flag' and 'safe_and' parameters.
15123  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
15124  * those underlying ops) short-circuit, which means that rather than
15125  * necessarily returning a truth value, they may return the LH argument,
15126  * which may not be boolean. For example in $x = (keys %h || -1), keys
15127  * should return a key count rather than a boolean, even though its
15128  * sort-of being used in boolean context.
15129  *
15130  * So we only consider such logical ops to provide boolean context to
15131  * their LH argument if they themselves are in void or boolean context.
15132  * However, sometimes the context isn't known until run-time. In this
15133  * case the op is marked with the maybe_flag flag it.
15134  *
15135  * Consider the following.
15136  *
15137  *     sub f { ....;  if (%h) { .... } }
15138  *
15139  * This is actually compiled as
15140  *
15141  *     sub f { ....;  %h && do { .... } }
15142  *
15143  * Here we won't know until runtime whether the final statement (and hence
15144  * the &&) is in void context and so is safe to return a boolean value.
15145  * So mark o with maybe_flag rather than the bool_flag.
15146  * Note that there is cost associated with determining context at runtime
15147  * (e.g. a call to block_gimme()), so it may not be worth setting (at
15148  * compile time) and testing (at runtime) maybe_flag if the scalar verses
15149  * boolean costs savings are marginal.
15150  *
15151  * However, we can do slightly better with && (compared to || and //):
15152  * this op only returns its LH argument when that argument is false. In
15153  * this case, as long as the op promises to return a false value which is
15154  * valid in both boolean and scalar contexts, we can mark an op consumed
15155  * by && with bool_flag rather than maybe_flag.
15156  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
15157  * than &PL_sv_no for a false result in boolean context, then it's safe. An
15158  * op which promises to handle this case is indicated by setting safe_and
15159  * to true.
15160  */
15161
15162 static void
15163 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
15164 {
15165     OP *lop;
15166     U8 flag = 0;
15167
15168     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
15169
15170     /* OPpTARGET_MY and boolean context probably don't mix well.
15171      * If someone finds a valid use case, maybe add an extra flag to this
15172      * function which indicates its safe to do so for this op? */
15173     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
15174              && (o->op_private & OPpTARGET_MY)));
15175
15176     lop = o->op_next;
15177
15178     while (lop) {
15179         switch (lop->op_type) {
15180         case OP_NULL:
15181         case OP_SCALAR:
15182             break;
15183
15184         /* these two consume the stack argument in the scalar case,
15185          * and treat it as a boolean in the non linenumber case */
15186         case OP_FLIP:
15187         case OP_FLOP:
15188             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
15189                 || (lop->op_private & OPpFLIP_LINENUM))
15190             {
15191                 lop = NULL;
15192                 break;
15193             }
15194             /* FALLTHROUGH */
15195         /* these never leave the original value on the stack */
15196         case OP_NOT:
15197         case OP_XOR:
15198         case OP_COND_EXPR:
15199         case OP_GREPWHILE:
15200             flag = bool_flag;
15201             lop = NULL;
15202             break;
15203
15204         /* OR DOR and AND evaluate their arg as a boolean, but then may
15205          * leave the original scalar value on the stack when following the
15206          * op_next route. If not in void context, we need to ensure
15207          * that whatever follows consumes the arg only in boolean context
15208          * too.
15209          */
15210         case OP_AND:
15211             if (safe_and) {
15212                 flag = bool_flag;
15213                 lop = NULL;
15214                 break;
15215             }
15216             /* FALLTHROUGH */
15217         case OP_OR:
15218         case OP_DOR:
15219             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
15220                 flag = bool_flag;
15221                 lop = NULL;
15222             }
15223             else if (!(lop->op_flags & OPf_WANT)) {
15224                 /* unknown context - decide at runtime */
15225                 flag = maybe_flag;
15226                 lop = NULL;
15227             }
15228             break;
15229
15230         default:
15231             lop = NULL;
15232             break;
15233         }
15234
15235         if (lop)
15236             lop = lop->op_next;
15237     }
15238
15239     o->op_private |= flag;
15240 }
15241
15242
15243
15244 /* mechanism for deferring recursion in rpeep() */
15245
15246 #define MAX_DEFERRED 4
15247
15248 #define DEFER(o) \
15249   STMT_START { \
15250     if (defer_ix == (MAX_DEFERRED-1)) { \
15251         OP **defer = defer_queue[defer_base]; \
15252         CALL_RPEEP(*defer); \
15253         S_prune_chain_head(defer); \
15254         defer_base = (defer_base + 1) % MAX_DEFERRED; \
15255         defer_ix--; \
15256     } \
15257     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
15258   } STMT_END
15259
15260 #define IS_AND_OP(o)   (o->op_type == OP_AND)
15261 #define IS_OR_OP(o)    (o->op_type == OP_OR)
15262
15263
15264 /* A peephole optimizer.  We visit the ops in the order they're to execute.
15265  * See the comments at the top of this file for more details about when
15266  * peep() is called */
15267
15268 void
15269 Perl_rpeep(pTHX_ OP *o)
15270 {
15271     dVAR;
15272     OP* oldop = NULL;
15273     OP* oldoldop = NULL;
15274     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
15275     int defer_base = 0;
15276     int defer_ix = -1;
15277
15278     if (!o || o->op_opt)
15279         return;
15280
15281     assert(o->op_type != OP_FREED);
15282
15283     ENTER;
15284     SAVEOP();
15285     SAVEVPTR(PL_curcop);
15286     for (;; o = o->op_next) {
15287         if (o && o->op_opt)
15288             o = NULL;
15289         if (!o) {
15290             while (defer_ix >= 0) {
15291                 OP **defer =
15292                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
15293                 CALL_RPEEP(*defer);
15294                 S_prune_chain_head(defer);
15295             }
15296             break;
15297         }
15298
15299       redo:
15300
15301         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
15302         assert(!oldoldop || oldoldop->op_next == oldop);
15303         assert(!oldop    || oldop->op_next    == o);
15304
15305         /* By default, this op has now been optimised. A couple of cases below
15306            clear this again.  */
15307         o->op_opt = 1;
15308         PL_op = o;
15309
15310         /* look for a series of 1 or more aggregate derefs, e.g.
15311          *   $a[1]{foo}[$i]{$k}
15312          * and replace with a single OP_MULTIDEREF op.
15313          * Each index must be either a const, or a simple variable,
15314          *
15315          * First, look for likely combinations of starting ops,
15316          * corresponding to (global and lexical variants of)
15317          *     $a[...]   $h{...}
15318          *     $r->[...] $r->{...}
15319          *     (preceding expression)->[...]
15320          *     (preceding expression)->{...}
15321          * and if so, call maybe_multideref() to do a full inspection
15322          * of the op chain and if appropriate, replace with an
15323          * OP_MULTIDEREF
15324          */
15325         {
15326             UV action;
15327             OP *o2 = o;
15328             U8 hints = 0;
15329
15330             switch (o2->op_type) {
15331             case OP_GV:
15332                 /* $pkg[..]   :   gv[*pkg]
15333                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
15334
15335                 /* Fail if there are new op flag combinations that we're
15336                  * not aware of, rather than:
15337                  *  * silently failing to optimise, or
15338                  *  * silently optimising the flag away.
15339                  * If this ASSUME starts failing, examine what new flag
15340                  * has been added to the op, and decide whether the
15341                  * optimisation should still occur with that flag, then
15342                  * update the code accordingly. This applies to all the
15343                  * other ASSUMEs in the block of code too.
15344                  */
15345                 ASSUME(!(o2->op_flags &
15346                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
15347                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
15348
15349                 o2 = o2->op_next;
15350
15351                 if (o2->op_type == OP_RV2AV) {
15352                     action = MDEREF_AV_gvav_aelem;
15353                     goto do_deref;
15354                 }
15355
15356                 if (o2->op_type == OP_RV2HV) {
15357                     action = MDEREF_HV_gvhv_helem;
15358                     goto do_deref;
15359                 }
15360
15361                 if (o2->op_type != OP_RV2SV)
15362                     break;
15363
15364                 /* at this point we've seen gv,rv2sv, so the only valid
15365                  * construct left is $pkg->[] or $pkg->{} */
15366
15367                 ASSUME(!(o2->op_flags & OPf_STACKED));
15368                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
15369                             != (OPf_WANT_SCALAR|OPf_MOD))
15370                     break;
15371
15372                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
15373                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
15374                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
15375                     break;
15376                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
15377                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
15378                     break;
15379
15380                 o2 = o2->op_next;
15381                 if (o2->op_type == OP_RV2AV) {
15382                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
15383                     goto do_deref;
15384                 }
15385                 if (o2->op_type == OP_RV2HV) {
15386                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
15387                     goto do_deref;
15388                 }
15389                 break;
15390
15391             case OP_PADSV:
15392                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
15393
15394                 ASSUME(!(o2->op_flags &
15395                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
15396                 if ((o2->op_flags &
15397                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
15398                      != (OPf_WANT_SCALAR|OPf_MOD))
15399                     break;
15400
15401                 ASSUME(!(o2->op_private &
15402                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
15403                 /* skip if state or intro, or not a deref */
15404                 if (      o2->op_private != OPpDEREF_AV
15405                        && o2->op_private != OPpDEREF_HV)
15406                     break;
15407
15408                 o2 = o2->op_next;
15409                 if (o2->op_type == OP_RV2AV) {
15410                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
15411                     goto do_deref;
15412                 }
15413                 if (o2->op_type == OP_RV2HV) {
15414                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
15415                     goto do_deref;
15416                 }
15417                 break;
15418
15419             case OP_PADAV:
15420             case OP_PADHV:
15421                 /*    $lex[..]:  padav[@lex:1,2] sR *
15422                  * or $lex{..}:  padhv[%lex:1,2] sR */
15423                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
15424                                             OPf_REF|OPf_SPECIAL)));
15425                 if ((o2->op_flags &
15426                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
15427                      != (OPf_WANT_SCALAR|OPf_REF))
15428                     break;
15429                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
15430                     break;
15431                 /* OPf_PARENS isn't currently used in this case;
15432                  * if that changes, let us know! */
15433                 ASSUME(!(o2->op_flags & OPf_PARENS));
15434
15435                 /* at this point, we wouldn't expect any of the remaining
15436                  * possible private flags:
15437                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
15438                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
15439                  *
15440                  * OPpSLICEWARNING shouldn't affect runtime
15441                  */
15442                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
15443
15444                 action = o2->op_type == OP_PADAV
15445                             ? MDEREF_AV_padav_aelem
15446                             : MDEREF_HV_padhv_helem;
15447                 o2 = o2->op_next;
15448                 S_maybe_multideref(aTHX_ o, o2, action, 0);
15449                 break;
15450
15451
15452             case OP_RV2AV:
15453             case OP_RV2HV:
15454                 action = o2->op_type == OP_RV2AV
15455                             ? MDEREF_AV_pop_rv2av_aelem
15456                             : MDEREF_HV_pop_rv2hv_helem;
15457                 /* FALLTHROUGH */
15458             do_deref:
15459                 /* (expr)->[...]:  rv2av sKR/1;
15460                  * (expr)->{...}:  rv2hv sKR/1; */
15461
15462                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
15463
15464                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15465                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
15466                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
15467                     break;
15468
15469                 /* at this point, we wouldn't expect any of these
15470                  * possible private flags:
15471                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
15472                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
15473                  */
15474                 ASSUME(!(o2->op_private &
15475                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
15476                      |OPpOUR_INTRO)));
15477                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
15478
15479                 o2 = o2->op_next;
15480
15481                 S_maybe_multideref(aTHX_ o, o2, action, hints);
15482                 break;
15483
15484             default:
15485                 break;
15486             }
15487         }
15488
15489
15490         switch (o->op_type) {
15491         case OP_DBSTATE:
15492             PL_curcop = ((COP*)o);              /* for warnings */
15493             break;
15494         case OP_NEXTSTATE:
15495             PL_curcop = ((COP*)o);              /* for warnings */
15496
15497             /* Optimise a "return ..." at the end of a sub to just be "...".
15498              * This saves 2 ops. Before:
15499              * 1  <;> nextstate(main 1 -e:1) v ->2
15500              * 4  <@> return K ->5
15501              * 2    <0> pushmark s ->3
15502              * -    <1> ex-rv2sv sK/1 ->4
15503              * 3      <#> gvsv[*cat] s ->4
15504              *
15505              * After:
15506              * -  <@> return K ->-
15507              * -    <0> pushmark s ->2
15508              * -    <1> ex-rv2sv sK/1 ->-
15509              * 2      <$> gvsv(*cat) s ->3
15510              */
15511             {
15512                 OP *next = o->op_next;
15513                 OP *sibling = OpSIBLING(o);
15514                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
15515                     && OP_TYPE_IS(sibling, OP_RETURN)
15516                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
15517                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
15518                        ||OP_TYPE_IS(sibling->op_next->op_next,
15519                                     OP_LEAVESUBLV))
15520                     && cUNOPx(sibling)->op_first == next
15521                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
15522                     && next->op_next
15523                 ) {
15524                     /* Look through the PUSHMARK's siblings for one that
15525                      * points to the RETURN */
15526                     OP *top = OpSIBLING(next);
15527                     while (top && top->op_next) {
15528                         if (top->op_next == sibling) {
15529                             top->op_next = sibling->op_next;
15530                             o->op_next = next->op_next;
15531                             break;
15532                         }
15533                         top = OpSIBLING(top);
15534                     }
15535                 }
15536             }
15537
15538             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
15539              *
15540              * This latter form is then suitable for conversion into padrange
15541              * later on. Convert:
15542              *
15543              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
15544              *
15545              * into:
15546              *
15547              *   nextstate1 ->     listop     -> nextstate3
15548              *                 /            \
15549              *         pushmark -> padop1 -> padop2
15550              */
15551             if (o->op_next && (
15552                     o->op_next->op_type == OP_PADSV
15553                  || o->op_next->op_type == OP_PADAV
15554                  || o->op_next->op_type == OP_PADHV
15555                 )
15556                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
15557                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
15558                 && o->op_next->op_next->op_next && (
15559                     o->op_next->op_next->op_next->op_type == OP_PADSV
15560                  || o->op_next->op_next->op_next->op_type == OP_PADAV
15561                  || o->op_next->op_next->op_next->op_type == OP_PADHV
15562                 )
15563                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
15564                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
15565                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
15566                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
15567             ) {
15568                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
15569
15570                 pad1 =    o->op_next;
15571                 ns2  = pad1->op_next;
15572                 pad2 =  ns2->op_next;
15573                 ns3  = pad2->op_next;
15574
15575                 /* we assume here that the op_next chain is the same as
15576                  * the op_sibling chain */
15577                 assert(OpSIBLING(o)    == pad1);
15578                 assert(OpSIBLING(pad1) == ns2);
15579                 assert(OpSIBLING(ns2)  == pad2);
15580                 assert(OpSIBLING(pad2) == ns3);
15581
15582                 /* excise and delete ns2 */
15583                 op_sibling_splice(NULL, pad1, 1, NULL);
15584                 op_free(ns2);
15585
15586                 /* excise pad1 and pad2 */
15587                 op_sibling_splice(NULL, o, 2, NULL);
15588
15589                 /* create new listop, with children consisting of:
15590                  * a new pushmark, pad1, pad2. */
15591                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
15592                 newop->op_flags |= OPf_PARENS;
15593                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
15594
15595                 /* insert newop between o and ns3 */
15596                 op_sibling_splice(NULL, o, 0, newop);
15597
15598                 /*fixup op_next chain */
15599                 newpm = cUNOPx(newop)->op_first; /* pushmark */
15600                 o    ->op_next = newpm;
15601                 newpm->op_next = pad1;
15602                 pad1 ->op_next = pad2;
15603                 pad2 ->op_next = newop; /* listop */
15604                 newop->op_next = ns3;
15605
15606                 /* Ensure pushmark has this flag if padops do */
15607                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
15608                     newpm->op_flags |= OPf_MOD;
15609                 }
15610
15611                 break;
15612             }
15613
15614             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
15615                to carry two labels. For now, take the easier option, and skip
15616                this optimisation if the first NEXTSTATE has a label.  */
15617             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
15618                 OP *nextop = o->op_next;
15619                 while (nextop && nextop->op_type == OP_NULL)
15620                     nextop = nextop->op_next;
15621
15622                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
15623                     op_null(o);
15624                     if (oldop)
15625                         oldop->op_next = nextop;
15626                     o = nextop;
15627                     /* Skip (old)oldop assignment since the current oldop's
15628                        op_next already points to the next op.  */
15629                     goto redo;
15630                 }
15631             }
15632             break;
15633
15634         case OP_CONCAT:
15635             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
15636                 if (o->op_next->op_private & OPpTARGET_MY) {
15637                     if (o->op_flags & OPf_STACKED) /* chained concats */
15638                         break; /* ignore_optimization */
15639                     else {
15640                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
15641                         o->op_targ = o->op_next->op_targ;
15642                         o->op_next->op_targ = 0;
15643                         o->op_private |= OPpTARGET_MY;
15644                     }
15645                 }
15646                 op_null(o->op_next);
15647             }
15648             break;
15649         case OP_STUB:
15650             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
15651                 break; /* Scalar stub must produce undef.  List stub is noop */
15652             }
15653             goto nothin;
15654         case OP_NULL:
15655             if (o->op_targ == OP_NEXTSTATE
15656                 || o->op_targ == OP_DBSTATE)
15657             {
15658                 PL_curcop = ((COP*)o);
15659             }
15660             /* XXX: We avoid setting op_seq here to prevent later calls
15661                to rpeep() from mistakenly concluding that optimisation
15662                has already occurred. This doesn't fix the real problem,
15663                though (See 20010220.007 (#5874)). AMS 20010719 */
15664             /* op_seq functionality is now replaced by op_opt */
15665             o->op_opt = 0;
15666             /* FALLTHROUGH */
15667         case OP_SCALAR:
15668         case OP_LINESEQ:
15669         case OP_SCOPE:
15670         nothin:
15671             if (oldop) {
15672                 oldop->op_next = o->op_next;
15673                 o->op_opt = 0;
15674                 continue;
15675             }
15676             break;
15677
15678         case OP_PUSHMARK:
15679
15680             /* Given
15681                  5 repeat/DOLIST
15682                  3   ex-list
15683                  1     pushmark
15684                  2     scalar or const
15685                  4   const[0]
15686                convert repeat into a stub with no kids.
15687              */
15688             if (o->op_next->op_type == OP_CONST
15689              || (  o->op_next->op_type == OP_PADSV
15690                 && !(o->op_next->op_private & OPpLVAL_INTRO))
15691              || (  o->op_next->op_type == OP_GV
15692                 && o->op_next->op_next->op_type == OP_RV2SV
15693                 && !(o->op_next->op_next->op_private
15694                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
15695             {
15696                 const OP *kid = o->op_next->op_next;
15697                 if (o->op_next->op_type == OP_GV)
15698                    kid = kid->op_next;
15699                 /* kid is now the ex-list.  */
15700                 if (kid->op_type == OP_NULL
15701                  && (kid = kid->op_next)->op_type == OP_CONST
15702                     /* kid is now the repeat count.  */
15703                  && kid->op_next->op_type == OP_REPEAT
15704                  && kid->op_next->op_private & OPpREPEAT_DOLIST
15705                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
15706                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
15707                  && oldop)
15708                 {
15709                     o = kid->op_next; /* repeat */
15710                     oldop->op_next = o;
15711                     op_free(cBINOPo->op_first);
15712                     op_free(cBINOPo->op_last );
15713                     o->op_flags &=~ OPf_KIDS;
15714                     /* stub is a baseop; repeat is a binop */
15715                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
15716                     OpTYPE_set(o, OP_STUB);
15717                     o->op_private = 0;
15718                     break;
15719                 }
15720             }
15721
15722             /* Convert a series of PAD ops for my vars plus support into a
15723              * single padrange op. Basically
15724              *
15725              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
15726              *
15727              * becomes, depending on circumstances, one of
15728              *
15729              *    padrange  ----------------------------------> (list) -> rest
15730              *    padrange  --------------------------------------------> rest
15731              *
15732              * where all the pad indexes are sequential and of the same type
15733              * (INTRO or not).
15734              * We convert the pushmark into a padrange op, then skip
15735              * any other pad ops, and possibly some trailing ops.
15736              * Note that we don't null() the skipped ops, to make it
15737              * easier for Deparse to undo this optimisation (and none of
15738              * the skipped ops are holding any resourses). It also makes
15739              * it easier for find_uninit_var(), as it can just ignore
15740              * padrange, and examine the original pad ops.
15741              */
15742         {
15743             OP *p;
15744             OP *followop = NULL; /* the op that will follow the padrange op */
15745             U8 count = 0;
15746             U8 intro = 0;
15747             PADOFFSET base = 0; /* init only to stop compiler whining */
15748             bool gvoid = 0;     /* init only to stop compiler whining */
15749             bool defav = 0;  /* seen (...) = @_ */
15750             bool reuse = 0;  /* reuse an existing padrange op */
15751
15752             /* look for a pushmark -> gv[_] -> rv2av */
15753
15754             {
15755                 OP *rv2av, *q;
15756                 p = o->op_next;
15757                 if (   p->op_type == OP_GV
15758                     && cGVOPx_gv(p) == PL_defgv
15759                     && (rv2av = p->op_next)
15760                     && rv2av->op_type == OP_RV2AV
15761                     && !(rv2av->op_flags & OPf_REF)
15762                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
15763                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
15764                 ) {
15765                     q = rv2av->op_next;
15766                     if (q->op_type == OP_NULL)
15767                         q = q->op_next;
15768                     if (q->op_type == OP_PUSHMARK) {
15769                         defav = 1;
15770                         p = q;
15771                     }
15772                 }
15773             }
15774             if (!defav) {
15775                 p = o;
15776             }
15777
15778             /* scan for PAD ops */
15779
15780             for (p = p->op_next; p; p = p->op_next) {
15781                 if (p->op_type == OP_NULL)
15782                     continue;
15783
15784                 if ((     p->op_type != OP_PADSV
15785                        && p->op_type != OP_PADAV
15786                        && p->op_type != OP_PADHV
15787                     )
15788                       /* any private flag other than INTRO? e.g. STATE */
15789                    || (p->op_private & ~OPpLVAL_INTRO)
15790                 )
15791                     break;
15792
15793                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
15794                  * instead */
15795                 if (   p->op_type == OP_PADAV
15796                     && p->op_next
15797                     && p->op_next->op_type == OP_CONST
15798                     && p->op_next->op_next
15799                     && p->op_next->op_next->op_type == OP_AELEM
15800                 )
15801                     break;
15802
15803                 /* for 1st padop, note what type it is and the range
15804                  * start; for the others, check that it's the same type
15805                  * and that the targs are contiguous */
15806                 if (count == 0) {
15807                     intro = (p->op_private & OPpLVAL_INTRO);
15808                     base = p->op_targ;
15809                     gvoid = OP_GIMME(p,0) == G_VOID;
15810                 }
15811                 else {
15812                     if ((p->op_private & OPpLVAL_INTRO) != intro)
15813                         break;
15814                     /* Note that you'd normally  expect targs to be
15815                      * contiguous in my($a,$b,$c), but that's not the case
15816                      * when external modules start doing things, e.g.
15817                      * Function::Parameters */
15818                     if (p->op_targ != base + count)
15819                         break;
15820                     assert(p->op_targ == base + count);
15821                     /* Either all the padops or none of the padops should
15822                        be in void context.  Since we only do the optimisa-
15823                        tion for av/hv when the aggregate itself is pushed
15824                        on to the stack (one item), there is no need to dis-
15825                        tinguish list from scalar context.  */
15826                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
15827                         break;
15828                 }
15829
15830                 /* for AV, HV, only when we're not flattening */
15831                 if (   p->op_type != OP_PADSV
15832                     && !gvoid
15833                     && !(p->op_flags & OPf_REF)
15834                 )
15835                     break;
15836
15837                 if (count >= OPpPADRANGE_COUNTMASK)
15838                     break;
15839
15840                 /* there's a biggest base we can fit into a
15841                  * SAVEt_CLEARPADRANGE in pp_padrange.
15842                  * (The sizeof() stuff will be constant-folded, and is
15843                  * intended to avoid getting "comparison is always false"
15844                  * compiler warnings. See the comments above
15845                  * MEM_WRAP_CHECK for more explanation on why we do this
15846                  * in a weird way to avoid compiler warnings.)
15847                  */
15848                 if (   intro
15849                     && (8*sizeof(base) >
15850                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
15851                         ? (Size_t)base
15852                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
15853                         ) >
15854                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
15855                 )
15856                     break;
15857
15858                 /* Success! We've got another valid pad op to optimise away */
15859                 count++;
15860                 followop = p->op_next;
15861             }
15862
15863             if (count < 1 || (count == 1 && !defav))
15864                 break;
15865
15866             /* pp_padrange in specifically compile-time void context
15867              * skips pushing a mark and lexicals; in all other contexts
15868              * (including unknown till runtime) it pushes a mark and the
15869              * lexicals. We must be very careful then, that the ops we
15870              * optimise away would have exactly the same effect as the
15871              * padrange.
15872              * In particular in void context, we can only optimise to
15873              * a padrange if we see the complete sequence
15874              *     pushmark, pad*v, ...., list
15875              * which has the net effect of leaving the markstack as it
15876              * was.  Not pushing onto the stack (whereas padsv does touch
15877              * the stack) makes no difference in void context.
15878              */
15879             assert(followop);
15880             if (gvoid) {
15881                 if (followop->op_type == OP_LIST
15882                         && OP_GIMME(followop,0) == G_VOID
15883                    )
15884                 {
15885                     followop = followop->op_next; /* skip OP_LIST */
15886
15887                     /* consolidate two successive my(...);'s */
15888
15889                     if (   oldoldop
15890                         && oldoldop->op_type == OP_PADRANGE
15891                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
15892                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
15893                         && !(oldoldop->op_flags & OPf_SPECIAL)
15894                     ) {
15895                         U8 old_count;
15896                         assert(oldoldop->op_next == oldop);
15897                         assert(   oldop->op_type == OP_NEXTSTATE
15898                                || oldop->op_type == OP_DBSTATE);
15899                         assert(oldop->op_next == o);
15900
15901                         old_count
15902                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
15903
15904                        /* Do not assume pad offsets for $c and $d are con-
15905                           tiguous in
15906                             my ($a,$b,$c);
15907                             my ($d,$e,$f);
15908                         */
15909                         if (  oldoldop->op_targ + old_count == base
15910                            && old_count < OPpPADRANGE_COUNTMASK - count) {
15911                             base = oldoldop->op_targ;
15912                             count += old_count;
15913                             reuse = 1;
15914                         }
15915                     }
15916
15917                     /* if there's any immediately following singleton
15918                      * my var's; then swallow them and the associated
15919                      * nextstates; i.e.
15920                      *    my ($a,$b); my $c; my $d;
15921                      * is treated as
15922                      *    my ($a,$b,$c,$d);
15923                      */
15924
15925                     while (    ((p = followop->op_next))
15926                             && (  p->op_type == OP_PADSV
15927                                || p->op_type == OP_PADAV
15928                                || p->op_type == OP_PADHV)
15929                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
15930                             && (p->op_private & OPpLVAL_INTRO) == intro
15931                             && !(p->op_private & ~OPpLVAL_INTRO)
15932                             && p->op_next
15933                             && (   p->op_next->op_type == OP_NEXTSTATE
15934                                 || p->op_next->op_type == OP_DBSTATE)
15935                             && count < OPpPADRANGE_COUNTMASK
15936                             && base + count == p->op_targ
15937                     ) {
15938                         count++;
15939                         followop = p->op_next;
15940                     }
15941                 }
15942                 else
15943                     break;
15944             }
15945
15946             if (reuse) {
15947                 assert(oldoldop->op_type == OP_PADRANGE);
15948                 oldoldop->op_next = followop;
15949                 oldoldop->op_private = (intro | count);
15950                 o = oldoldop;
15951                 oldop = NULL;
15952                 oldoldop = NULL;
15953             }
15954             else {
15955                 /* Convert the pushmark into a padrange.
15956                  * To make Deparse easier, we guarantee that a padrange was
15957                  * *always* formerly a pushmark */
15958                 assert(o->op_type == OP_PUSHMARK);
15959                 o->op_next = followop;
15960                 OpTYPE_set(o, OP_PADRANGE);
15961                 o->op_targ = base;
15962                 /* bit 7: INTRO; bit 6..0: count */
15963                 o->op_private = (intro | count);
15964                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
15965                               | gvoid * OPf_WANT_VOID
15966                               | (defav ? OPf_SPECIAL : 0));
15967             }
15968             break;
15969         }
15970
15971         case OP_RV2AV:
15972             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
15973                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
15974             break;
15975
15976         case OP_RV2HV:
15977         case OP_PADHV:
15978             /*'keys %h' in void or scalar context: skip the OP_KEYS
15979              * and perform the functionality directly in the RV2HV/PADHV
15980              * op
15981              */
15982             if (o->op_flags & OPf_REF) {
15983                 OP *k = o->op_next;
15984                 U8 want = (k->op_flags & OPf_WANT);
15985                 if (   k
15986                     && k->op_type == OP_KEYS
15987                     && (   want == OPf_WANT_VOID
15988                         || want == OPf_WANT_SCALAR)
15989                     && !(k->op_private & OPpMAYBE_LVSUB)
15990                     && !(k->op_flags & OPf_MOD)
15991                 ) {
15992                     o->op_next     = k->op_next;
15993                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
15994                     o->op_flags   |= want;
15995                     o->op_private |= (o->op_type == OP_PADHV ?
15996                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
15997                     /* for keys(%lex), hold onto the OP_KEYS's targ
15998                      * since padhv doesn't have its own targ to return
15999                      * an int with */
16000                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
16001                         op_null(k);
16002                 }
16003             }
16004
16005             /* see if %h is used in boolean context */
16006             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16007                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
16008
16009
16010             if (o->op_type != OP_PADHV)
16011                 break;
16012             /* FALLTHROUGH */
16013         case OP_PADAV:
16014             if (   o->op_type == OP_PADAV
16015                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
16016             )
16017                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16018             /* FALLTHROUGH */
16019         case OP_PADSV:
16020             /* Skip over state($x) in void context.  */
16021             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
16022              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
16023             {
16024                 oldop->op_next = o->op_next;
16025                 goto redo_nextstate;
16026             }
16027             if (o->op_type != OP_PADAV)
16028                 break;
16029             /* FALLTHROUGH */
16030         case OP_GV:
16031             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
16032                 OP* const pop = (o->op_type == OP_PADAV) ?
16033                             o->op_next : o->op_next->op_next;
16034                 IV i;
16035                 if (pop && pop->op_type == OP_CONST &&
16036                     ((PL_op = pop->op_next)) &&
16037                     pop->op_next->op_type == OP_AELEM &&
16038                     !(pop->op_next->op_private &
16039                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
16040                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
16041                 {
16042                     GV *gv;
16043                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
16044                         no_bareword_allowed(pop);
16045                     if (o->op_type == OP_GV)
16046                         op_null(o->op_next);
16047                     op_null(pop->op_next);
16048                     op_null(pop);
16049                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
16050                     o->op_next = pop->op_next->op_next;
16051                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
16052                     o->op_private = (U8)i;
16053                     if (o->op_type == OP_GV) {
16054                         gv = cGVOPo_gv;
16055                         GvAVn(gv);
16056                         o->op_type = OP_AELEMFAST;
16057                     }
16058                     else
16059                         o->op_type = OP_AELEMFAST_LEX;
16060                 }
16061                 if (o->op_type != OP_GV)
16062                     break;
16063             }
16064
16065             /* Remove $foo from the op_next chain in void context.  */
16066             if (oldop
16067              && (  o->op_next->op_type == OP_RV2SV
16068                 || o->op_next->op_type == OP_RV2AV
16069                 || o->op_next->op_type == OP_RV2HV  )
16070              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
16071              && !(o->op_next->op_private & OPpLVAL_INTRO))
16072             {
16073                 oldop->op_next = o->op_next->op_next;
16074                 /* Reprocess the previous op if it is a nextstate, to
16075                    allow double-nextstate optimisation.  */
16076               redo_nextstate:
16077                 if (oldop->op_type == OP_NEXTSTATE) {
16078                     oldop->op_opt = 0;
16079                     o = oldop;
16080                     oldop = oldoldop;
16081                     oldoldop = NULL;
16082                     goto redo;
16083                 }
16084                 o = oldop->op_next;
16085                 goto redo;
16086             }
16087             else if (o->op_next->op_type == OP_RV2SV) {
16088                 if (!(o->op_next->op_private & OPpDEREF)) {
16089                     op_null(o->op_next);
16090                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
16091                                                                | OPpOUR_INTRO);
16092                     o->op_next = o->op_next->op_next;
16093                     OpTYPE_set(o, OP_GVSV);
16094                 }
16095             }
16096             else if (o->op_next->op_type == OP_READLINE
16097                     && o->op_next->op_next->op_type == OP_CONCAT
16098                     && (o->op_next->op_next->op_flags & OPf_STACKED))
16099             {
16100                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
16101                 OpTYPE_set(o, OP_RCATLINE);
16102                 o->op_flags |= OPf_STACKED;
16103                 op_null(o->op_next->op_next);
16104                 op_null(o->op_next);
16105             }
16106
16107             break;
16108         
16109         case OP_NOT:
16110             break;
16111
16112         case OP_AND:
16113         case OP_OR:
16114         case OP_DOR:
16115             while (cLOGOP->op_other->op_type == OP_NULL)
16116                 cLOGOP->op_other = cLOGOP->op_other->op_next;
16117             while (o->op_next && (   o->op_type == o->op_next->op_type
16118                                   || o->op_next->op_type == OP_NULL))
16119                 o->op_next = o->op_next->op_next;
16120
16121             /* If we're an OR and our next is an AND in void context, we'll
16122                follow its op_other on short circuit, same for reverse.
16123                We can't do this with OP_DOR since if it's true, its return
16124                value is the underlying value which must be evaluated
16125                by the next op. */
16126             if (o->op_next &&
16127                 (
16128                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
16129                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
16130                 )
16131                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
16132             ) {
16133                 o->op_next = ((LOGOP*)o->op_next)->op_other;
16134             }
16135             DEFER(cLOGOP->op_other);
16136             o->op_opt = 1;
16137             break;
16138         
16139         case OP_GREPWHILE:
16140             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16141                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16142             /* FALLTHROUGH */
16143         case OP_COND_EXPR:
16144         case OP_MAPWHILE:
16145         case OP_ANDASSIGN:
16146         case OP_ORASSIGN:
16147         case OP_DORASSIGN:
16148         case OP_RANGE:
16149         case OP_ONCE:
16150         case OP_ARGDEFELEM:
16151             while (cLOGOP->op_other->op_type == OP_NULL)
16152                 cLOGOP->op_other = cLOGOP->op_other->op_next;
16153             DEFER(cLOGOP->op_other);
16154             break;
16155
16156         case OP_ENTERLOOP:
16157         case OP_ENTERITER:
16158             while (cLOOP->op_redoop->op_type == OP_NULL)
16159                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
16160             while (cLOOP->op_nextop->op_type == OP_NULL)
16161                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
16162             while (cLOOP->op_lastop->op_type == OP_NULL)
16163                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
16164             /* a while(1) loop doesn't have an op_next that escapes the
16165              * loop, so we have to explicitly follow the op_lastop to
16166              * process the rest of the code */
16167             DEFER(cLOOP->op_lastop);
16168             break;
16169
16170         case OP_ENTERTRY:
16171             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
16172             DEFER(cLOGOPo->op_other);
16173             break;
16174
16175         case OP_SUBST:
16176             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16177                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16178             assert(!(cPMOP->op_pmflags & PMf_ONCE));
16179             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
16180                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
16181                 cPMOP->op_pmstashstartu.op_pmreplstart
16182                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
16183             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
16184             break;
16185
16186         case OP_SORT: {
16187             OP *oright;
16188
16189             if (o->op_flags & OPf_SPECIAL) {
16190                 /* first arg is a code block */
16191                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
16192                 OP * kid          = cUNOPx(nullop)->op_first;
16193
16194                 assert(nullop->op_type == OP_NULL);
16195                 assert(kid->op_type == OP_SCOPE
16196                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
16197                 /* since OP_SORT doesn't have a handy op_other-style
16198                  * field that can point directly to the start of the code
16199                  * block, store it in the otherwise-unused op_next field
16200                  * of the top-level OP_NULL. This will be quicker at
16201                  * run-time, and it will also allow us to remove leading
16202                  * OP_NULLs by just messing with op_nexts without
16203                  * altering the basic op_first/op_sibling layout. */
16204                 kid = kLISTOP->op_first;
16205                 assert(
16206                       (kid->op_type == OP_NULL
16207                       && (  kid->op_targ == OP_NEXTSTATE
16208                          || kid->op_targ == OP_DBSTATE  ))
16209                     || kid->op_type == OP_STUB
16210                     || kid->op_type == OP_ENTER
16211                     || (PL_parser && PL_parser->error_count));
16212                 nullop->op_next = kid->op_next;
16213                 DEFER(nullop->op_next);
16214             }
16215
16216             /* check that RHS of sort is a single plain array */
16217             oright = cUNOPo->op_first;
16218             if (!oright || oright->op_type != OP_PUSHMARK)
16219                 break;
16220
16221             if (o->op_private & OPpSORT_INPLACE)
16222                 break;
16223
16224             /* reverse sort ... can be optimised.  */
16225             if (!OpHAS_SIBLING(cUNOPo)) {
16226                 /* Nothing follows us on the list. */
16227                 OP * const reverse = o->op_next;
16228
16229                 if (reverse->op_type == OP_REVERSE &&
16230                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
16231                     OP * const pushmark = cUNOPx(reverse)->op_first;
16232                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
16233                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
16234                         /* reverse -> pushmark -> sort */
16235                         o->op_private |= OPpSORT_REVERSE;
16236                         op_null(reverse);
16237                         pushmark->op_next = oright->op_next;
16238                         op_null(oright);
16239                     }
16240                 }
16241             }
16242
16243             break;
16244         }
16245
16246         case OP_REVERSE: {
16247             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
16248             OP *gvop = NULL;
16249             LISTOP *enter, *exlist;
16250
16251             if (o->op_private & OPpSORT_INPLACE)
16252                 break;
16253
16254             enter = (LISTOP *) o->op_next;
16255             if (!enter)
16256                 break;
16257             if (enter->op_type == OP_NULL) {
16258                 enter = (LISTOP *) enter->op_next;
16259                 if (!enter)
16260                     break;
16261             }
16262             /* for $a (...) will have OP_GV then OP_RV2GV here.
16263                for (...) just has an OP_GV.  */
16264             if (enter->op_type == OP_GV) {
16265                 gvop = (OP *) enter;
16266                 enter = (LISTOP *) enter->op_next;
16267                 if (!enter)
16268                     break;
16269                 if (enter->op_type == OP_RV2GV) {
16270                   enter = (LISTOP *) enter->op_next;
16271                   if (!enter)
16272                     break;
16273                 }
16274             }
16275
16276             if (enter->op_type != OP_ENTERITER)
16277                 break;
16278
16279             iter = enter->op_next;
16280             if (!iter || iter->op_type != OP_ITER)
16281                 break;
16282             
16283             expushmark = enter->op_first;
16284             if (!expushmark || expushmark->op_type != OP_NULL
16285                 || expushmark->op_targ != OP_PUSHMARK)
16286                 break;
16287
16288             exlist = (LISTOP *) OpSIBLING(expushmark);
16289             if (!exlist || exlist->op_type != OP_NULL
16290                 || exlist->op_targ != OP_LIST)
16291                 break;
16292
16293             if (exlist->op_last != o) {
16294                 /* Mmm. Was expecting to point back to this op.  */
16295                 break;
16296             }
16297             theirmark = exlist->op_first;
16298             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
16299                 break;
16300
16301             if (OpSIBLING(theirmark) != o) {
16302                 /* There's something between the mark and the reverse, eg
16303                    for (1, reverse (...))
16304                    so no go.  */
16305                 break;
16306             }
16307
16308             ourmark = ((LISTOP *)o)->op_first;
16309             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
16310                 break;
16311
16312             ourlast = ((LISTOP *)o)->op_last;
16313             if (!ourlast || ourlast->op_next != o)
16314                 break;
16315
16316             rv2av = OpSIBLING(ourmark);
16317             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
16318                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
16319                 /* We're just reversing a single array.  */
16320                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
16321                 enter->op_flags |= OPf_STACKED;
16322             }
16323
16324             /* We don't have control over who points to theirmark, so sacrifice
16325                ours.  */
16326             theirmark->op_next = ourmark->op_next;
16327             theirmark->op_flags = ourmark->op_flags;
16328             ourlast->op_next = gvop ? gvop : (OP *) enter;
16329             op_null(ourmark);
16330             op_null(o);
16331             enter->op_private |= OPpITER_REVERSED;
16332             iter->op_private |= OPpITER_REVERSED;
16333
16334             oldoldop = NULL;
16335             oldop    = ourlast;
16336             o        = oldop->op_next;
16337             goto redo;
16338             NOT_REACHED; /* NOTREACHED */
16339             break;
16340         }
16341
16342         case OP_QR:
16343         case OP_MATCH:
16344             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
16345                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
16346             }
16347             break;
16348
16349         case OP_RUNCV:
16350             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
16351              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
16352             {
16353                 SV *sv;
16354                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
16355                 else {
16356                     sv = newRV((SV *)PL_compcv);
16357                     sv_rvweaken(sv);
16358                     SvREADONLY_on(sv);
16359                 }
16360                 OpTYPE_set(o, OP_CONST);
16361                 o->op_flags |= OPf_SPECIAL;
16362                 cSVOPo->op_sv = sv;
16363             }
16364             break;
16365
16366         case OP_SASSIGN:
16367             if (OP_GIMME(o,0) == G_VOID
16368              || (  o->op_next->op_type == OP_LINESEQ
16369                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
16370                    || (  o->op_next->op_next->op_type == OP_RETURN
16371                       && !CvLVALUE(PL_compcv)))))
16372             {
16373                 OP *right = cBINOP->op_first;
16374                 if (right) {
16375                     /*   sassign
16376                     *      RIGHT
16377                     *      substr
16378                     *         pushmark
16379                     *         arg1
16380                     *         arg2
16381                     *         ...
16382                     * becomes
16383                     *
16384                     *  ex-sassign
16385                     *     substr
16386                     *        pushmark
16387                     *        RIGHT
16388                     *        arg1
16389                     *        arg2
16390                     *        ...
16391                     */
16392                     OP *left = OpSIBLING(right);
16393                     if (left->op_type == OP_SUBSTR
16394                          && (left->op_private & 7) < 4) {
16395                         op_null(o);
16396                         /* cut out right */
16397                         op_sibling_splice(o, NULL, 1, NULL);
16398                         /* and insert it as second child of OP_SUBSTR */
16399                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
16400                                     right);
16401                         left->op_private |= OPpSUBSTR_REPL_FIRST;
16402                         left->op_flags =
16403                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
16404                     }
16405                 }
16406             }
16407             break;
16408
16409         case OP_AASSIGN: {
16410             int l, r, lr, lscalars, rscalars;
16411
16412             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
16413                Note that we do this now rather than in newASSIGNOP(),
16414                since only by now are aliased lexicals flagged as such
16415
16416                See the essay "Common vars in list assignment" above for
16417                the full details of the rationale behind all the conditions
16418                below.
16419
16420                PL_generation sorcery:
16421                To detect whether there are common vars, the global var
16422                PL_generation is incremented for each assign op we scan.
16423                Then we run through all the lexical variables on the LHS,
16424                of the assignment, setting a spare slot in each of them to
16425                PL_generation.  Then we scan the RHS, and if any lexicals
16426                already have that value, we know we've got commonality.
16427                Also, if the generation number is already set to
16428                PERL_INT_MAX, then the variable is involved in aliasing, so
16429                we also have potential commonality in that case.
16430              */
16431
16432             PL_generation++;
16433             /* scan LHS */
16434             lscalars = 0;
16435             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, 1, &lscalars);
16436             /* scan RHS */
16437             rscalars = 0;
16438             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, 1, &rscalars);
16439             lr = (l|r);
16440
16441
16442             /* After looking for things which are *always* safe, this main
16443              * if/else chain selects primarily based on the type of the
16444              * LHS, gradually working its way down from the more dangerous
16445              * to the more restrictive and thus safer cases */
16446
16447             if (   !l                      /* () = ....; */
16448                 || !r                      /* .... = (); */
16449                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
16450                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
16451                 || (lscalars < 2)          /* ($x, undef) = ... */
16452             ) {
16453                 NOOP; /* always safe */
16454             }
16455             else if (l & AAS_DANGEROUS) {
16456                 /* always dangerous */
16457                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
16458                 o->op_private |= OPpASSIGN_COMMON_AGG;
16459             }
16460             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
16461                 /* package vars are always dangerous - too many
16462                  * aliasing possibilities */
16463                 if (l & AAS_PKG_SCALAR)
16464                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
16465                 if (l & AAS_PKG_AGG)
16466                     o->op_private |= OPpASSIGN_COMMON_AGG;
16467             }
16468             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
16469                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
16470             {
16471                 /* LHS contains only lexicals and safe ops */
16472
16473                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
16474                     o->op_private |= OPpASSIGN_COMMON_AGG;
16475
16476                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
16477                     if (lr & AAS_LEX_SCALAR_COMM)
16478                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
16479                     else if (   !(l & AAS_LEX_SCALAR)
16480                              && (r & AAS_DEFAV))
16481                     {
16482                         /* falsely mark
16483                          *    my (...) = @_
16484                          * as scalar-safe for performance reasons.
16485                          * (it will still have been marked _AGG if necessary */
16486                         NOOP;
16487                     }
16488                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
16489                         /* if there are only lexicals on the LHS and no
16490                          * common ones on the RHS, then we assume that the
16491                          * only way those lexicals could also get
16492                          * on the RHS is via some sort of dereffing or
16493                          * closure, e.g.
16494                          *    $r = \$lex;
16495                          *    ($lex, $x) = (1, $$r)
16496                          * and in this case we assume the var must have
16497                          *  a bumped ref count. So if its ref count is 1,
16498                          *  it must only be on the LHS.
16499                          */
16500                         o->op_private |= OPpASSIGN_COMMON_RC1;
16501                 }
16502             }
16503
16504             /* ... = ($x)
16505              * may have to handle aggregate on LHS, but we can't
16506              * have common scalars. */
16507             if (rscalars < 2)
16508                 o->op_private &=
16509                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
16510
16511             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16512                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
16513             break;
16514         }
16515
16516         case OP_REF:
16517             /* see if ref() is used in boolean context */
16518             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16519                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
16520             break;
16521
16522         case OP_LENGTH:
16523             /* see if the op is used in known boolean context,
16524              * but not if OA_TARGLEX optimisation is enabled */
16525             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
16526                 && !(o->op_private & OPpTARGET_MY)
16527             )
16528                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16529             break;
16530
16531         case OP_POS:
16532             /* see if the op is used in known boolean context */
16533             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16534                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16535             break;
16536
16537         case OP_CUSTOM: {
16538             Perl_cpeep_t cpeep = 
16539                 XopENTRYCUSTOM(o, xop_peep);
16540             if (cpeep)
16541                 cpeep(aTHX_ o, oldop);
16542             break;
16543         }
16544             
16545         }
16546         /* did we just null the current op? If so, re-process it to handle
16547          * eliding "empty" ops from the chain */
16548         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
16549             o->op_opt = 0;
16550             o = oldop;
16551         }
16552         else {
16553             oldoldop = oldop;
16554             oldop = o;
16555         }
16556     }
16557     LEAVE;
16558 }
16559
16560 void
16561 Perl_peep(pTHX_ OP *o)
16562 {
16563     CALL_RPEEP(o);
16564 }
16565
16566 /*
16567 =head1 Custom Operators
16568
16569 =for apidoc Ao||custom_op_xop
16570 Return the XOP structure for a given custom op.  This macro should be
16571 considered internal to C<OP_NAME> and the other access macros: use them instead.
16572 This macro does call a function.  Prior
16573 to 5.19.6, this was implemented as a
16574 function.
16575
16576 =cut
16577 */
16578
16579 XOPRETANY
16580 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
16581 {
16582     SV *keysv;
16583     HE *he = NULL;
16584     XOP *xop;
16585
16586     static const XOP xop_null = { 0, 0, 0, 0, 0 };
16587
16588     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
16589     assert(o->op_type == OP_CUSTOM);
16590
16591     /* This is wrong. It assumes a function pointer can be cast to IV,
16592      * which isn't guaranteed, but this is what the old custom OP code
16593      * did. In principle it should be safer to Copy the bytes of the
16594      * pointer into a PV: since the new interface is hidden behind
16595      * functions, this can be changed later if necessary.  */
16596     /* Change custom_op_xop if this ever happens */
16597     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
16598
16599     if (PL_custom_ops)
16600         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
16601
16602     /* assume noone will have just registered a desc */
16603     if (!he && PL_custom_op_names &&
16604         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
16605     ) {
16606         const char *pv;
16607         STRLEN l;
16608
16609         /* XXX does all this need to be shared mem? */
16610         Newxz(xop, 1, XOP);
16611         pv = SvPV(HeVAL(he), l);
16612         XopENTRY_set(xop, xop_name, savepvn(pv, l));
16613         if (PL_custom_op_descs &&
16614             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
16615         ) {
16616             pv = SvPV(HeVAL(he), l);
16617             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
16618         }
16619         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
16620     }
16621     else {
16622         if (!he)
16623             xop = (XOP *)&xop_null;
16624         else
16625             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
16626     }
16627     {
16628         XOPRETANY any;
16629         if(field == XOPe_xop_ptr) {
16630             any.xop_ptr = xop;
16631         } else {
16632             const U32 flags = XopFLAGS(xop);
16633             if(flags & field) {
16634                 switch(field) {
16635                 case XOPe_xop_name:
16636                     any.xop_name = xop->xop_name;
16637                     break;
16638                 case XOPe_xop_desc:
16639                     any.xop_desc = xop->xop_desc;
16640                     break;
16641                 case XOPe_xop_class:
16642                     any.xop_class = xop->xop_class;
16643                     break;
16644                 case XOPe_xop_peep:
16645                     any.xop_peep = xop->xop_peep;
16646                     break;
16647                 default:
16648                     NOT_REACHED; /* NOTREACHED */
16649                     break;
16650                 }
16651             } else {
16652                 switch(field) {
16653                 case XOPe_xop_name:
16654                     any.xop_name = XOPd_xop_name;
16655                     break;
16656                 case XOPe_xop_desc:
16657                     any.xop_desc = XOPd_xop_desc;
16658                     break;
16659                 case XOPe_xop_class:
16660                     any.xop_class = XOPd_xop_class;
16661                     break;
16662                 case XOPe_xop_peep:
16663                     any.xop_peep = XOPd_xop_peep;
16664                     break;
16665                 default:
16666                     NOT_REACHED; /* NOTREACHED */
16667                     break;
16668                 }
16669             }
16670         }
16671         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
16672          * op.c: In function 'Perl_custom_op_get_field':
16673          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
16674          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
16675          * expands to assert(0), which expands to ((0) ? (void)0 :
16676          * __assert(...)), and gcc doesn't know that __assert can never return. */
16677         return any;
16678     }
16679 }
16680
16681 /*
16682 =for apidoc Ao||custom_op_register
16683 Register a custom op.  See L<perlguts/"Custom Operators">.
16684
16685 =cut
16686 */
16687
16688 void
16689 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
16690 {
16691     SV *keysv;
16692
16693     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
16694
16695     /* see the comment in custom_op_xop */
16696     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
16697
16698     if (!PL_custom_ops)
16699         PL_custom_ops = newHV();
16700
16701     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
16702         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
16703 }
16704
16705 /*
16706
16707 =for apidoc core_prototype
16708
16709 This function assigns the prototype of the named core function to C<sv>, or
16710 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
16711 C<NULL> if the core function has no prototype.  C<code> is a code as returned
16712 by C<keyword()>.  It must not be equal to 0.
16713
16714 =cut
16715 */
16716
16717 SV *
16718 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
16719                           int * const opnum)
16720 {
16721     int i = 0, n = 0, seen_question = 0, defgv = 0;
16722     I32 oa;
16723 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
16724     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
16725     bool nullret = FALSE;
16726
16727     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
16728
16729     assert (code);
16730
16731     if (!sv) sv = sv_newmortal();
16732
16733 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
16734
16735     switch (code < 0 ? -code : code) {
16736     case KEY_and   : case KEY_chop: case KEY_chomp:
16737     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
16738     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
16739     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
16740     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
16741     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
16742     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
16743     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
16744     case KEY_x     : case KEY_xor    :
16745         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
16746     case KEY_glob:    retsetpvs("_;", OP_GLOB);
16747     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
16748     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
16749     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
16750     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
16751     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
16752         retsetpvs("", 0);
16753     case KEY_evalbytes:
16754         name = "entereval"; break;
16755     case KEY_readpipe:
16756         name = "backtick";
16757     }
16758
16759 #undef retsetpvs
16760
16761   findopnum:
16762     while (i < MAXO) {  /* The slow way. */
16763         if (strEQ(name, PL_op_name[i])
16764             || strEQ(name, PL_op_desc[i]))
16765         {
16766             if (nullret) { assert(opnum); *opnum = i; return NULL; }
16767             goto found;
16768         }
16769         i++;
16770     }
16771     return NULL;
16772   found:
16773     defgv = PL_opargs[i] & OA_DEFGV;
16774     oa = PL_opargs[i] >> OASHIFT;
16775     while (oa) {
16776         if (oa & OA_OPTIONAL && !seen_question && (
16777               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
16778         )) {
16779             seen_question = 1;
16780             str[n++] = ';';
16781         }
16782         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
16783             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
16784             /* But globs are already references (kinda) */
16785             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
16786         ) {
16787             str[n++] = '\\';
16788         }
16789         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
16790          && !scalar_mod_type(NULL, i)) {
16791             str[n++] = '[';
16792             str[n++] = '$';
16793             str[n++] = '@';
16794             str[n++] = '%';
16795             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
16796             str[n++] = '*';
16797             str[n++] = ']';
16798         }
16799         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
16800         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
16801             str[n-1] = '_'; defgv = 0;
16802         }
16803         oa = oa >> 4;
16804     }
16805     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
16806     str[n++] = '\0';
16807     sv_setpvn(sv, str, n - 1);
16808     if (opnum) *opnum = i;
16809     return sv;
16810 }
16811
16812 OP *
16813 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
16814                       const int opnum)
16815 {
16816     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
16817     OP *o;
16818
16819     PERL_ARGS_ASSERT_CORESUB_OP;
16820
16821     switch(opnum) {
16822     case 0:
16823         return op_append_elem(OP_LINESEQ,
16824                        argop,
16825                        newSLICEOP(0,
16826                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
16827                                   newOP(OP_CALLER,0)
16828                        )
16829                );
16830     case OP_EACH:
16831     case OP_KEYS:
16832     case OP_VALUES:
16833         o = newUNOP(OP_AVHVSWITCH,0,argop);
16834         o->op_private = opnum-OP_EACH;
16835         return o;
16836     case OP_SELECT: /* which represents OP_SSELECT as well */
16837         if (code)
16838             return newCONDOP(
16839                          0,
16840                          newBINOP(OP_GT, 0,
16841                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
16842                                   newSVOP(OP_CONST, 0, newSVuv(1))
16843                                  ),
16844                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
16845                                     OP_SSELECT),
16846                          coresub_op(coreargssv, 0, OP_SELECT)
16847                    );
16848         /* FALLTHROUGH */
16849     default:
16850         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
16851         case OA_BASEOP:
16852             return op_append_elem(
16853                         OP_LINESEQ, argop,
16854                         newOP(opnum,
16855                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
16856                                 ? OPpOFFBYONE << 8 : 0)
16857                    );
16858         case OA_BASEOP_OR_UNOP:
16859             if (opnum == OP_ENTEREVAL) {
16860                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
16861                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
16862             }
16863             else o = newUNOP(opnum,0,argop);
16864             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
16865             else {
16866           onearg:
16867               if (is_handle_constructor(o, 1))
16868                 argop->op_private |= OPpCOREARGS_DEREF1;
16869               if (scalar_mod_type(NULL, opnum))
16870                 argop->op_private |= OPpCOREARGS_SCALARMOD;
16871             }
16872             return o;
16873         default:
16874             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
16875             if (is_handle_constructor(o, 2))
16876                 argop->op_private |= OPpCOREARGS_DEREF2;
16877             if (opnum == OP_SUBSTR) {
16878                 o->op_private |= OPpMAYBE_LVSUB;
16879                 return o;
16880             }
16881             else goto onearg;
16882         }
16883     }
16884 }
16885
16886 void
16887 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
16888                                SV * const *new_const_svp)
16889 {
16890     const char *hvname;
16891     bool is_const = !!CvCONST(old_cv);
16892     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
16893
16894     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
16895
16896     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
16897         return;
16898         /* They are 2 constant subroutines generated from
16899            the same constant. This probably means that
16900            they are really the "same" proxy subroutine
16901            instantiated in 2 places. Most likely this is
16902            when a constant is exported twice.  Don't warn.
16903         */
16904     if (
16905         (ckWARN(WARN_REDEFINE)
16906          && !(
16907                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
16908              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
16909              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
16910                  strEQ(hvname, "autouse"))
16911              )
16912         )
16913      || (is_const
16914          && ckWARN_d(WARN_REDEFINE)
16915          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
16916         )
16917     )
16918         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
16919                           is_const
16920                             ? "Constant subroutine %" SVf " redefined"
16921                             : "Subroutine %" SVf " redefined",
16922                           SVfARG(name));
16923 }
16924
16925 /*
16926 =head1 Hook manipulation
16927
16928 These functions provide convenient and thread-safe means of manipulating
16929 hook variables.
16930
16931 =cut
16932 */
16933
16934 /*
16935 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
16936
16937 Puts a C function into the chain of check functions for a specified op
16938 type.  This is the preferred way to manipulate the L</PL_check> array.
16939 C<opcode> specifies which type of op is to be affected.  C<new_checker>
16940 is a pointer to the C function that is to be added to that opcode's
16941 check chain, and C<old_checker_p> points to the storage location where a
16942 pointer to the next function in the chain will be stored.  The value of
16943 C<new_checker> is written into the L</PL_check> array, while the value
16944 previously stored there is written to C<*old_checker_p>.
16945
16946 L</PL_check> is global to an entire process, and a module wishing to
16947 hook op checking may find itself invoked more than once per process,
16948 typically in different threads.  To handle that situation, this function
16949 is idempotent.  The location C<*old_checker_p> must initially (once
16950 per process) contain a null pointer.  A C variable of static duration
16951 (declared at file scope, typically also marked C<static> to give
16952 it internal linkage) will be implicitly initialised appropriately,
16953 if it does not have an explicit initialiser.  This function will only
16954 actually modify the check chain if it finds C<*old_checker_p> to be null.
16955 This function is also thread safe on the small scale.  It uses appropriate
16956 locking to avoid race conditions in accessing L</PL_check>.
16957
16958 When this function is called, the function referenced by C<new_checker>
16959 must be ready to be called, except for C<*old_checker_p> being unfilled.
16960 In a threading situation, C<new_checker> may be called immediately,
16961 even before this function has returned.  C<*old_checker_p> will always
16962 be appropriately set before C<new_checker> is called.  If C<new_checker>
16963 decides not to do anything special with an op that it is given (which
16964 is the usual case for most uses of op check hooking), it must chain the
16965 check function referenced by C<*old_checker_p>.
16966
16967 Taken all together, XS code to hook an op checker should typically look
16968 something like this:
16969
16970     static Perl_check_t nxck_frob;
16971     static OP *myck_frob(pTHX_ OP *op) {
16972         ...
16973         op = nxck_frob(aTHX_ op);
16974         ...
16975         return op;
16976     }
16977     BOOT:
16978         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
16979
16980 If you want to influence compilation of calls to a specific subroutine,
16981 then use L</cv_set_call_checker_flags> rather than hooking checking of
16982 all C<entersub> ops.
16983
16984 =cut
16985 */
16986
16987 void
16988 Perl_wrap_op_checker(pTHX_ Optype opcode,
16989     Perl_check_t new_checker, Perl_check_t *old_checker_p)
16990 {
16991     dVAR;
16992
16993     PERL_UNUSED_CONTEXT;
16994     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
16995     if (*old_checker_p) return;
16996     OP_CHECK_MUTEX_LOCK;
16997     if (!*old_checker_p) {
16998         *old_checker_p = PL_check[opcode];
16999         PL_check[opcode] = new_checker;
17000     }
17001     OP_CHECK_MUTEX_UNLOCK;
17002 }
17003
17004 #include "XSUB.h"
17005
17006 /* Efficient sub that returns a constant scalar value. */
17007 static void
17008 const_sv_xsub(pTHX_ CV* cv)
17009 {
17010     dXSARGS;
17011     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
17012     PERL_UNUSED_ARG(items);
17013     if (!sv) {
17014         XSRETURN(0);
17015     }
17016     EXTEND(sp, 1);
17017     ST(0) = sv;
17018     XSRETURN(1);
17019 }
17020
17021 static void
17022 const_av_xsub(pTHX_ CV* cv)
17023 {
17024     dXSARGS;
17025     AV * const av = MUTABLE_AV(XSANY.any_ptr);
17026     SP -= items;
17027     assert(av);
17028 #ifndef DEBUGGING
17029     if (!av) {
17030         XSRETURN(0);
17031     }
17032 #endif
17033     if (SvRMAGICAL(av))
17034         Perl_croak(aTHX_ "Magical list constants are not supported");
17035     if (GIMME_V != G_ARRAY) {
17036         EXTEND(SP, 1);
17037         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
17038         XSRETURN(1);
17039     }
17040     EXTEND(SP, AvFILLp(av)+1);
17041     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
17042     XSRETURN(AvFILLp(av)+1);
17043 }
17044
17045 /* Copy an existing cop->cop_warnings field.
17046  * If it's one of the standard addresses, just re-use the address.
17047  * This is the e implementation for the DUP_WARNINGS() macro
17048  */
17049
17050 STRLEN*
17051 Perl_dup_warnings(pTHX_ STRLEN* warnings)
17052 {
17053     Size_t size;
17054     STRLEN *new_warnings;
17055
17056     if (warnings == NULL || specialWARN(warnings))
17057         return warnings;
17058
17059     size = sizeof(*warnings) + *warnings;
17060
17061     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
17062     Copy(warnings, new_warnings, size, char);
17063     return new_warnings;
17064 }
17065
17066 /*
17067  * ex: set ts=8 sts=4 sw=4 et:
17068  */