This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Abigail volunteered to handle January's release of 5.25.9
[perl5.git] / op.c
1 #line 2 "op.c"
2 /*    op.c
3  *
4  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
5  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'You see: Mr. Drogo, he married poor Miss Primula Brandybuck.  She was
14  *  our Mr. Bilbo's first cousin on the mother's side (her mother being the
15  *  youngest of the Old Took's daughters); and Mr. Drogo was his second
16  *  cousin.  So Mr. Frodo is his first *and* second cousin, once removed
17  *  either way, as the saying is, if you follow me.'       --the Gaffer
18  *
19  *     [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
20  */
21
22 /* This file contains the functions that create, manipulate and optimize
23  * the OP structures that hold a compiled perl program.
24  *
25  * A Perl program is compiled into a tree of OPs. Each op contains
26  * structural pointers (eg to its siblings and the next op in the
27  * execution sequence), a pointer to the function that would execute the
28  * op, plus any data specific to that op. For example, an OP_CONST op
29  * points to the pp_const() function and to an SV containing the constant
30  * value. When pp_const() is executed, its job is to push that SV onto the
31  * stack.
32  *
33  * OPs are mainly created by the newFOO() functions, which are mainly
34  * called from the parser (in perly.y) as the code is parsed. For example
35  * the Perl code $a + $b * $c would cause the equivalent of the following
36  * to be called (oversimplifying a bit):
37  *
38  *  newBINOP(OP_ADD, flags,
39  *      newSVREF($a),
40  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
41  *  )
42  *
43  * Note that during the build of miniperl, a temporary copy of this file
44  * is made, called opmini.c.
45  */
46
47 /*
48 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
49
50     A bottom-up pass
51     A top-down pass
52     An execution-order pass
53
54 The bottom-up pass is represented by all the "newOP" routines and
55 the ck_ routines.  The bottom-upness is actually driven by yacc.
56 So at the point that a ck_ routine fires, we have no idea what the
57 context is, either upward in the syntax tree, or either forward or
58 backward in the execution order.  (The bottom-up parser builds that
59 part of the execution order it knows about, but if you follow the "next"
60 links around, you'll find it's actually a closed loop through the
61 top level node.)
62
63 Whenever the bottom-up parser gets to a node that supplies context to
64 its components, it invokes that portion of the top-down pass that applies
65 to that part of the subtree (and marks the top node as processed, so
66 if a node further up supplies context, it doesn't have to take the
67 plunge again).  As a particular subcase of this, as the new node is
68 built, it takes all the closed execution loops of its subcomponents
69 and links them into a new closed loop for the higher level node.  But
70 it's still not the real execution order.
71
72 The actual execution order is not known till we get a grammar reduction
73 to a top-level unit like a subroutine or file that will be called by
74 "name" rather than via a "next" pointer.  At that point, we can call
75 into peep() to do that code's portion of the 3rd pass.  It has to be
76 recursive, but it's recursive on basic blocks, not on tree nodes.
77 */
78
79 /* To implement user lexical pragmas, there needs to be a way at run time to
80    get the compile time state of %^H for that block.  Storing %^H in every
81    block (or even COP) would be very expensive, so a different approach is
82    taken.  The (running) state of %^H is serialised into a tree of HE-like
83    structs.  Stores into %^H are chained onto the current leaf as a struct
84    refcounted_he * with the key and the value.  Deletes from %^H are saved
85    with a value of PL_sv_placeholder.  The state of %^H at any point can be
86    turned back into a regular HV by walking back up the tree from that point's
87    leaf, ignoring any key you've already seen (placeholder or not), storing
88    the rest into the HV structure, then removing the placeholders. Hence
89    memory is only used to store the %^H deltas from the enclosing COP, rather
90    than the entire %^H on each COP.
91
92    To cause actions on %^H to write out the serialisation records, it has
93    magic type 'H'. This magic (itself) does nothing, but its presence causes
94    the values to gain magic type 'h', which has entries for set and clear.
95    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
96    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
97    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
98    it will be correctly restored when any inner compiling scope is exited.
99 */
100
101 #include "EXTERN.h"
102 #define PERL_IN_OP_C
103 #include "perl.h"
104 #include "keywords.h"
105 #include "feature.h"
106 #include "regcomp.h"
107
108 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
109 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
110 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
111
112 static const char array_passed_to_stat[] = "Array passed to stat will be coerced to a scalar";
113
114 /* Used to avoid recursion through the op tree in scalarvoid() and
115    op_free()
116 */
117
118 #define DEFERRED_OP_STEP 100
119 #define DEFER_OP(o) \
120   STMT_START { \
121     if (UNLIKELY(defer_ix == (defer_stack_alloc-1))) {    \
122         defer_stack_alloc += DEFERRED_OP_STEP; \
123         assert(defer_stack_alloc > 0); \
124         Renew(defer_stack, defer_stack_alloc, OP *); \
125     } \
126     defer_stack[++defer_ix] = o; \
127   } STMT_END
128
129 #define POP_DEFERRED_OP() (defer_ix >= 0 ? defer_stack[defer_ix--] : (OP *)NULL)
130
131 /* remove any leading "empty" ops from the op_next chain whose first
132  * node's address is stored in op_p. Store the updated address of the
133  * first node in op_p.
134  */
135
136 STATIC void
137 S_prune_chain_head(OP** op_p)
138 {
139     while (*op_p
140         && (   (*op_p)->op_type == OP_NULL
141             || (*op_p)->op_type == OP_SCOPE
142             || (*op_p)->op_type == OP_SCALAR
143             || (*op_p)->op_type == OP_LINESEQ)
144     )
145         *op_p = (*op_p)->op_next;
146 }
147
148
149 /* See the explanatory comments above struct opslab in op.h. */
150
151 #ifdef PERL_DEBUG_READONLY_OPS
152 #  define PERL_SLAB_SIZE 128
153 #  define PERL_MAX_SLAB_SIZE 4096
154 #  include <sys/mman.h>
155 #endif
156
157 #ifndef PERL_SLAB_SIZE
158 #  define PERL_SLAB_SIZE 64
159 #endif
160 #ifndef PERL_MAX_SLAB_SIZE
161 #  define PERL_MAX_SLAB_SIZE 2048
162 #endif
163
164 /* rounds up to nearest pointer */
165 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
166 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
167
168 static OPSLAB *
169 S_new_slab(pTHX_ size_t sz)
170 {
171 #ifdef PERL_DEBUG_READONLY_OPS
172     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
173                                    PROT_READ|PROT_WRITE,
174                                    MAP_ANON|MAP_PRIVATE, -1, 0);
175     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
176                           (unsigned long) sz, slab));
177     if (slab == MAP_FAILED) {
178         perror("mmap failed");
179         abort();
180     }
181     slab->opslab_size = (U16)sz;
182 #else
183     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
184 #endif
185 #ifndef WIN32
186     /* The context is unused in non-Windows */
187     PERL_UNUSED_CONTEXT;
188 #endif
189     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
190     return slab;
191 }
192
193 /* requires double parens and aTHX_ */
194 #define DEBUG_S_warn(args)                                             \
195     DEBUG_S(                                                            \
196         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
197     )
198
199 void *
200 Perl_Slab_Alloc(pTHX_ size_t sz)
201 {
202     OPSLAB *slab;
203     OPSLAB *slab2;
204     OPSLOT *slot;
205     OP *o;
206     size_t opsz, space;
207
208     /* We only allocate ops from the slab during subroutine compilation.
209        We find the slab via PL_compcv, hence that must be non-NULL. It could
210        also be pointing to a subroutine which is now fully set up (CvROOT()
211        pointing to the top of the optree for that sub), or a subroutine
212        which isn't using the slab allocator. If our sanity checks aren't met,
213        don't use a slab, but allocate the OP directly from the heap.  */
214     if (!PL_compcv || CvROOT(PL_compcv)
215      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
216     {
217         o = (OP*)PerlMemShared_calloc(1, sz);
218         goto gotit;
219     }
220
221     /* While the subroutine is under construction, the slabs are accessed via
222        CvSTART(), to avoid needing to expand PVCV by one pointer for something
223        unneeded at runtime. Once a subroutine is constructed, the slabs are
224        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
225        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
226        details.  */
227     if (!CvSTART(PL_compcv)) {
228         CvSTART(PL_compcv) =
229             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
230         CvSLABBED_on(PL_compcv);
231         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
232     }
233     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
234
235     opsz = SIZE_TO_PSIZE(sz);
236     sz = opsz + OPSLOT_HEADER_P;
237
238     /* The slabs maintain a free list of OPs. In particular, constant folding
239        will free up OPs, so it makes sense to re-use them where possible. A
240        freed up slot is used in preference to a new allocation.  */
241     if (slab->opslab_freed) {
242         OP **too = &slab->opslab_freed;
243         o = *too;
244         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", (void*)o, (void*)slab));
245         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
246             DEBUG_S_warn((aTHX_ "Alas! too small"));
247             o = *(too = &o->op_next);
248             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
249         }
250         if (o) {
251             *too = o->op_next;
252             Zero(o, opsz, I32 *);
253             o->op_slabbed = 1;
254             goto gotit;
255         }
256     }
257
258 #define INIT_OPSLOT \
259             slot->opslot_slab = slab;                   \
260             slot->opslot_next = slab2->opslab_first;    \
261             slab2->opslab_first = slot;                 \
262             o = &slot->opslot_op;                       \
263             o->op_slabbed = 1
264
265     /* The partially-filled slab is next in the chain. */
266     slab2 = slab->opslab_next ? slab->opslab_next : slab;
267     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
268         /* Remaining space is too small. */
269
270         /* If we can fit a BASEOP, add it to the free chain, so as not
271            to waste it. */
272         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
273             slot = &slab2->opslab_slots;
274             INIT_OPSLOT;
275             o->op_type = OP_FREED;
276             o->op_next = slab->opslab_freed;
277             slab->opslab_freed = o;
278         }
279
280         /* Create a new slab.  Make this one twice as big. */
281         slot = slab2->opslab_first;
282         while (slot->opslot_next) slot = slot->opslot_next;
283         slab2 = S_new_slab(aTHX_
284                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
285                                         ? PERL_MAX_SLAB_SIZE
286                                         : (DIFF(slab2, slot)+1)*2);
287         slab2->opslab_next = slab->opslab_next;
288         slab->opslab_next = slab2;
289     }
290     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
291
292     /* Create a new op slot */
293     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
294     assert(slot >= &slab2->opslab_slots);
295     if (DIFF(&slab2->opslab_slots, slot)
296          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
297         slot = &slab2->opslab_slots;
298     INIT_OPSLOT;
299     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", (void*)o, (void*)slab));
300
301   gotit:
302 #ifdef PERL_OP_PARENT
303     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
304     assert(!o->op_moresib);
305     assert(!o->op_sibparent);
306 #endif
307
308     return (void *)o;
309 }
310
311 #undef INIT_OPSLOT
312
313 #ifdef PERL_DEBUG_READONLY_OPS
314 void
315 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
316 {
317     PERL_ARGS_ASSERT_SLAB_TO_RO;
318
319     if (slab->opslab_readonly) return;
320     slab->opslab_readonly = 1;
321     for (; slab; slab = slab->opslab_next) {
322         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
323                               (unsigned long) slab->opslab_size, slab));*/
324         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
325             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
326                              (unsigned long)slab->opslab_size, errno);
327     }
328 }
329
330 void
331 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
332 {
333     OPSLAB *slab2;
334
335     PERL_ARGS_ASSERT_SLAB_TO_RW;
336
337     if (!slab->opslab_readonly) return;
338     slab2 = slab;
339     for (; slab2; slab2 = slab2->opslab_next) {
340         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
341                               (unsigned long) size, slab2));*/
342         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
343                      PROT_READ|PROT_WRITE)) {
344             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
345                              (unsigned long)slab2->opslab_size, errno);
346         }
347     }
348     slab->opslab_readonly = 0;
349 }
350
351 #else
352 #  define Slab_to_rw(op)    NOOP
353 #endif
354
355 /* This cannot possibly be right, but it was copied from the old slab
356    allocator, to which it was originally added, without explanation, in
357    commit 083fcd5. */
358 #ifdef NETWARE
359 #    define PerlMemShared PerlMem
360 #endif
361
362 void
363 Perl_Slab_Free(pTHX_ void *op)
364 {
365     OP * const o = (OP *)op;
366     OPSLAB *slab;
367
368     PERL_ARGS_ASSERT_SLAB_FREE;
369
370     if (!o->op_slabbed) {
371         if (!o->op_static)
372             PerlMemShared_free(op);
373         return;
374     }
375
376     slab = OpSLAB(o);
377     /* If this op is already freed, our refcount will get screwy. */
378     assert(o->op_type != OP_FREED);
379     o->op_type = OP_FREED;
380     o->op_next = slab->opslab_freed;
381     slab->opslab_freed = o;
382     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", (void*)o, (void*)slab));
383     OpslabREFCNT_dec_padok(slab);
384 }
385
386 void
387 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
388 {
389     const bool havepad = !!PL_comppad;
390     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
391     if (havepad) {
392         ENTER;
393         PAD_SAVE_SETNULLPAD();
394     }
395     opslab_free(slab);
396     if (havepad) LEAVE;
397 }
398
399 void
400 Perl_opslab_free(pTHX_ OPSLAB *slab)
401 {
402     OPSLAB *slab2;
403     PERL_ARGS_ASSERT_OPSLAB_FREE;
404     PERL_UNUSED_CONTEXT;
405     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
406     assert(slab->opslab_refcnt == 1);
407     do {
408         slab2 = slab->opslab_next;
409 #ifdef DEBUGGING
410         slab->opslab_refcnt = ~(size_t)0;
411 #endif
412 #ifdef PERL_DEBUG_READONLY_OPS
413         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
414                                                (void*)slab));
415         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
416             perror("munmap failed");
417             abort();
418         }
419 #else
420         PerlMemShared_free(slab);
421 #endif
422         slab = slab2;
423     } while (slab);
424 }
425
426 void
427 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
428 {
429     OPSLAB *slab2;
430     OPSLOT *slot;
431 #ifdef DEBUGGING
432     size_t savestack_count = 0;
433 #endif
434     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
435     slab2 = slab;
436     do {
437         for (slot = slab2->opslab_first;
438              slot->opslot_next;
439              slot = slot->opslot_next) {
440             if (slot->opslot_op.op_type != OP_FREED
441              && !(slot->opslot_op.op_savefree
442 #ifdef DEBUGGING
443                   && ++savestack_count
444 #endif
445                  )
446             ) {
447                 assert(slot->opslot_op.op_slabbed);
448                 op_free(&slot->opslot_op);
449                 if (slab->opslab_refcnt == 1) goto free;
450             }
451         }
452     } while ((slab2 = slab2->opslab_next));
453     /* > 1 because the CV still holds a reference count. */
454     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
455 #ifdef DEBUGGING
456         assert(savestack_count == slab->opslab_refcnt-1);
457 #endif
458         /* Remove the CV’s reference count. */
459         slab->opslab_refcnt--;
460         return;
461     }
462    free:
463     opslab_free(slab);
464 }
465
466 #ifdef PERL_DEBUG_READONLY_OPS
467 OP *
468 Perl_op_refcnt_inc(pTHX_ OP *o)
469 {
470     if(o) {
471         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
472         if (slab && slab->opslab_readonly) {
473             Slab_to_rw(slab);
474             ++o->op_targ;
475             Slab_to_ro(slab);
476         } else {
477             ++o->op_targ;
478         }
479     }
480     return o;
481
482 }
483
484 PADOFFSET
485 Perl_op_refcnt_dec(pTHX_ OP *o)
486 {
487     PADOFFSET result;
488     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
489
490     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
491
492     if (slab && slab->opslab_readonly) {
493         Slab_to_rw(slab);
494         result = --o->op_targ;
495         Slab_to_ro(slab);
496     } else {
497         result = --o->op_targ;
498     }
499     return result;
500 }
501 #endif
502 /*
503  * In the following definition, the ", (OP*)0" is just to make the compiler
504  * think the expression is of the right type: croak actually does a Siglongjmp.
505  */
506 #define CHECKOP(type,o) \
507     ((PL_op_mask && PL_op_mask[type])                           \
508      ? ( op_free((OP*)o),                                       \
509          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
510          (OP*)0 )                                               \
511      : PL_check[type](aTHX_ (OP*)o))
512
513 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
514
515 #define OpTYPE_set(o,type) \
516     STMT_START {                                \
517         o->op_type = (OPCODE)type;              \
518         o->op_ppaddr = PL_ppaddr[type];         \
519     } STMT_END
520
521 STATIC OP *
522 S_no_fh_allowed(pTHX_ OP *o)
523 {
524     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
525
526     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
527                  OP_DESC(o)));
528     return o;
529 }
530
531 STATIC OP *
532 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
533 {
534     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
535     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
536     return o;
537 }
538  
539 STATIC OP *
540 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
541 {
542     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
543
544     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
545     return o;
546 }
547
548 STATIC void
549 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
550 {
551     PERL_ARGS_ASSERT_BAD_TYPE_PV;
552
553     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
554                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
555 }
556
557 /* remove flags var, its unused in all callers, move to to right end since gv
558   and kid are always the same */
559 STATIC void
560 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
561 {
562     SV * const namesv = cv_name((CV *)gv, NULL, 0);
563     PERL_ARGS_ASSERT_BAD_TYPE_GV;
564  
565     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
566                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
567 }
568
569 STATIC void
570 S_no_bareword_allowed(pTHX_ OP *o)
571 {
572     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
573
574     qerror(Perl_mess(aTHX_
575                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
576                      SVfARG(cSVOPo_sv)));
577     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
578 }
579
580 /* "register" allocation */
581
582 PADOFFSET
583 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
584 {
585     PADOFFSET off;
586     const bool is_our = (PL_parser->in_my == KEY_our);
587
588     PERL_ARGS_ASSERT_ALLOCMY;
589
590     if (flags & ~SVf_UTF8)
591         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
592                    (UV)flags);
593
594     /* complain about "my $<special_var>" etc etc */
595     if (len &&
596         !(is_our ||
597           isALPHA(name[1]) ||
598           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
599           (name[1] == '_' && len > 2)))
600     {
601         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
602          && isASCII(name[1])
603          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
604             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
605                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
606                               PL_parser->in_my == KEY_state ? "state" : "my"));
607         } else {
608             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
609                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
610         }
611     }
612
613     /* allocate a spare slot and store the name in that slot */
614
615     off = pad_add_name_pvn(name, len,
616                        (is_our ? padadd_OUR :
617                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
618                     PL_parser->in_my_stash,
619                     (is_our
620                         /* $_ is always in main::, even with our */
621                         ? (PL_curstash && !memEQs(name,len,"$_")
622                             ? PL_curstash
623                             : PL_defstash)
624                         : NULL
625                     )
626     );
627     /* anon sub prototypes contains state vars should always be cloned,
628      * otherwise the state var would be shared between anon subs */
629
630     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
631         CvCLONE_on(PL_compcv);
632
633     return off;
634 }
635
636 /*
637 =head1 Optree Manipulation Functions
638
639 =for apidoc alloccopstash
640
641 Available only under threaded builds, this function allocates an entry in
642 C<PL_stashpad> for the stash passed to it.
643
644 =cut
645 */
646
647 #ifdef USE_ITHREADS
648 PADOFFSET
649 Perl_alloccopstash(pTHX_ HV *hv)
650 {
651     PADOFFSET off = 0, o = 1;
652     bool found_slot = FALSE;
653
654     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
655
656     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
657
658     for (; o < PL_stashpadmax; ++o) {
659         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
660         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
661             found_slot = TRUE, off = o;
662     }
663     if (!found_slot) {
664         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
665         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
666         off = PL_stashpadmax;
667         PL_stashpadmax += 10;
668     }
669
670     PL_stashpad[PL_stashpadix = off] = hv;
671     return off;
672 }
673 #endif
674
675 /* free the body of an op without examining its contents.
676  * Always use this rather than FreeOp directly */
677
678 static void
679 S_op_destroy(pTHX_ OP *o)
680 {
681     FreeOp(o);
682 }
683
684 /* Destructor */
685
686 /*
687 =for apidoc Am|void|op_free|OP *o
688
689 Free an op.  Only use this when an op is no longer linked to from any
690 optree.
691
692 =cut
693 */
694
695 void
696 Perl_op_free(pTHX_ OP *o)
697 {
698     dVAR;
699     OPCODE type;
700     SSize_t defer_ix = -1;
701     SSize_t defer_stack_alloc = 0;
702     OP **defer_stack = NULL;
703
704     do {
705
706         /* Though ops may be freed twice, freeing the op after its slab is a
707            big no-no. */
708         assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
709         /* During the forced freeing of ops after compilation failure, kidops
710            may be freed before their parents. */
711         if (!o || o->op_type == OP_FREED)
712             continue;
713
714         type = o->op_type;
715
716         /* an op should only ever acquire op_private flags that we know about.
717          * If this fails, you may need to fix something in regen/op_private.
718          * Don't bother testing if:
719          *   * the op_ppaddr doesn't match the op; someone may have
720          *     overridden the op and be doing strange things with it;
721          *   * we've errored, as op flags are often left in an
722          *     inconsistent state then. Note that an error when
723          *     compiling the main program leaves PL_parser NULL, so
724          *     we can't spot faults in the main code, only
725          *     evaled/required code */
726 #ifdef DEBUGGING
727         if (   o->op_ppaddr == PL_ppaddr[o->op_type]
728             && PL_parser
729             && !PL_parser->error_count)
730         {
731             assert(!(o->op_private & ~PL_op_private_valid[type]));
732         }
733 #endif
734
735         if (o->op_private & OPpREFCOUNTED) {
736             switch (type) {
737             case OP_LEAVESUB:
738             case OP_LEAVESUBLV:
739             case OP_LEAVEEVAL:
740             case OP_LEAVE:
741             case OP_SCOPE:
742             case OP_LEAVEWRITE:
743                 {
744                 PADOFFSET refcnt;
745                 OP_REFCNT_LOCK;
746                 refcnt = OpREFCNT_dec(o);
747                 OP_REFCNT_UNLOCK;
748                 if (refcnt) {
749                     /* Need to find and remove any pattern match ops from the list
750                        we maintain for reset().  */
751                     find_and_forget_pmops(o);
752                     continue;
753                 }
754                 }
755                 break;
756             default:
757                 break;
758             }
759         }
760
761         /* Call the op_free hook if it has been set. Do it now so that it's called
762          * at the right time for refcounted ops, but still before all of the kids
763          * are freed. */
764         CALL_OPFREEHOOK(o);
765
766         if (o->op_flags & OPf_KIDS) {
767             OP *kid, *nextkid;
768             for (kid = cUNOPo->op_first; kid; kid = nextkid) {
769                 nextkid = OpSIBLING(kid); /* Get before next freeing kid */
770                 if (!kid || kid->op_type == OP_FREED)
771                     /* During the forced freeing of ops after
772                        compilation failure, kidops may be freed before
773                        their parents. */
774                     continue;
775                 if (!(kid->op_flags & OPf_KIDS))
776                     /* If it has no kids, just free it now */
777                     op_free(kid);
778                 else
779                     DEFER_OP(kid);
780             }
781         }
782         if (type == OP_NULL)
783             type = (OPCODE)o->op_targ;
784
785         if (o->op_slabbed)
786             Slab_to_rw(OpSLAB(o));
787
788         /* COP* is not cleared by op_clear() so that we may track line
789          * numbers etc even after null() */
790         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
791             cop_free((COP*)o);
792         }
793
794         op_clear(o);
795         FreeOp(o);
796 #ifdef DEBUG_LEAKING_SCALARS
797         if (PL_op == o)
798             PL_op = NULL;
799 #endif
800     } while ( (o = POP_DEFERRED_OP()) );
801
802     Safefree(defer_stack);
803 }
804
805 /* S_op_clear_gv(): free a GV attached to an OP */
806
807 STATIC
808 #ifdef USE_ITHREADS
809 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
810 #else
811 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
812 #endif
813 {
814
815     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
816             || o->op_type == OP_MULTIDEREF)
817 #ifdef USE_ITHREADS
818                 && PL_curpad
819                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
820 #else
821                 ? (GV*)(*svp) : NULL;
822 #endif
823     /* It's possible during global destruction that the GV is freed
824        before the optree. Whilst the SvREFCNT_inc is happy to bump from
825        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
826        will trigger an assertion failure, because the entry to sv_clear
827        checks that the scalar is not already freed.  A check of for
828        !SvIS_FREED(gv) turns out to be invalid, because during global
829        destruction the reference count can be forced down to zero
830        (with SVf_BREAK set).  In which case raising to 1 and then
831        dropping to 0 triggers cleanup before it should happen.  I
832        *think* that this might actually be a general, systematic,
833        weakness of the whole idea of SVf_BREAK, in that code *is*
834        allowed to raise and lower references during global destruction,
835        so any *valid* code that happens to do this during global
836        destruction might well trigger premature cleanup.  */
837     bool still_valid = gv && SvREFCNT(gv);
838
839     if (still_valid)
840         SvREFCNT_inc_simple_void(gv);
841 #ifdef USE_ITHREADS
842     if (*ixp > 0) {
843         pad_swipe(*ixp, TRUE);
844         *ixp = 0;
845     }
846 #else
847     SvREFCNT_dec(*svp);
848     *svp = NULL;
849 #endif
850     if (still_valid) {
851         int try_downgrade = SvREFCNT(gv) == 2;
852         SvREFCNT_dec_NN(gv);
853         if (try_downgrade)
854             gv_try_downgrade(gv);
855     }
856 }
857
858
859 void
860 Perl_op_clear(pTHX_ OP *o)
861 {
862
863     dVAR;
864
865     PERL_ARGS_ASSERT_OP_CLEAR;
866
867     switch (o->op_type) {
868     case OP_NULL:       /* Was holding old type, if any. */
869         /* FALLTHROUGH */
870     case OP_ENTERTRY:
871     case OP_ENTEREVAL:  /* Was holding hints. */
872         o->op_targ = 0;
873         break;
874     default:
875         if (!(o->op_flags & OPf_REF)
876             || (PL_check[o->op_type] != Perl_ck_ftst))
877             break;
878         /* FALLTHROUGH */
879     case OP_GVSV:
880     case OP_GV:
881     case OP_AELEMFAST:
882 #ifdef USE_ITHREADS
883             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
884 #else
885             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
886 #endif
887         break;
888     case OP_METHOD_REDIR:
889     case OP_METHOD_REDIR_SUPER:
890 #ifdef USE_ITHREADS
891         if (cMETHOPx(o)->op_rclass_targ) {
892             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
893             cMETHOPx(o)->op_rclass_targ = 0;
894         }
895 #else
896         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
897         cMETHOPx(o)->op_rclass_sv = NULL;
898 #endif
899     case OP_METHOD_NAMED:
900     case OP_METHOD_SUPER:
901         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
902         cMETHOPx(o)->op_u.op_meth_sv = NULL;
903 #ifdef USE_ITHREADS
904         if (o->op_targ) {
905             pad_swipe(o->op_targ, 1);
906             o->op_targ = 0;
907         }
908 #endif
909         break;
910     case OP_CONST:
911     case OP_HINTSEVAL:
912         SvREFCNT_dec(cSVOPo->op_sv);
913         cSVOPo->op_sv = NULL;
914 #ifdef USE_ITHREADS
915         /** Bug #15654
916           Even if op_clear does a pad_free for the target of the op,
917           pad_free doesn't actually remove the sv that exists in the pad;
918           instead it lives on. This results in that it could be reused as 
919           a target later on when the pad was reallocated.
920         **/
921         if(o->op_targ) {
922           pad_swipe(o->op_targ,1);
923           o->op_targ = 0;
924         }
925 #endif
926         break;
927     case OP_DUMP:
928     case OP_GOTO:
929     case OP_NEXT:
930     case OP_LAST:
931     case OP_REDO:
932         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
933             break;
934         /* FALLTHROUGH */
935     case OP_TRANS:
936     case OP_TRANSR:
937         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
938             assert(o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
939 #ifdef USE_ITHREADS
940             if (cPADOPo->op_padix > 0) {
941                 pad_swipe(cPADOPo->op_padix, TRUE);
942                 cPADOPo->op_padix = 0;
943             }
944 #else
945             SvREFCNT_dec(cSVOPo->op_sv);
946             cSVOPo->op_sv = NULL;
947 #endif
948         }
949         else {
950             PerlMemShared_free(cPVOPo->op_pv);
951             cPVOPo->op_pv = NULL;
952         }
953         break;
954     case OP_SUBST:
955         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
956         goto clear_pmop;
957     case OP_PUSHRE:
958 #ifdef USE_ITHREADS
959         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
960             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
961         }
962 #else
963         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
964 #endif
965         /* FALLTHROUGH */
966     case OP_MATCH:
967     case OP_QR:
968     clear_pmop:
969         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
970             op_free(cPMOPo->op_code_list);
971         cPMOPo->op_code_list = NULL;
972         forget_pmop(cPMOPo);
973         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
974         /* we use the same protection as the "SAFE" version of the PM_ macros
975          * here since sv_clean_all might release some PMOPs
976          * after PL_regex_padav has been cleared
977          * and the clearing of PL_regex_padav needs to
978          * happen before sv_clean_all
979          */
980 #ifdef USE_ITHREADS
981         if(PL_regex_pad) {        /* We could be in destruction */
982             const IV offset = (cPMOPo)->op_pmoffset;
983             ReREFCNT_dec(PM_GETRE(cPMOPo));
984             PL_regex_pad[offset] = &PL_sv_undef;
985             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
986                            sizeof(offset));
987         }
988 #else
989         ReREFCNT_dec(PM_GETRE(cPMOPo));
990         PM_SETRE(cPMOPo, NULL);
991 #endif
992
993         break;
994
995     case OP_MULTIDEREF:
996         {
997             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
998             UV actions = items->uv;
999             bool last = 0;
1000             bool is_hash = FALSE;
1001
1002             while (!last) {
1003                 switch (actions & MDEREF_ACTION_MASK) {
1004
1005                 case MDEREF_reload:
1006                     actions = (++items)->uv;
1007                     continue;
1008
1009                 case MDEREF_HV_padhv_helem:
1010                     is_hash = TRUE;
1011                 case MDEREF_AV_padav_aelem:
1012                     pad_free((++items)->pad_offset);
1013                     goto do_elem;
1014
1015                 case MDEREF_HV_gvhv_helem:
1016                     is_hash = TRUE;
1017                 case MDEREF_AV_gvav_aelem:
1018 #ifdef USE_ITHREADS
1019                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1020 #else
1021                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1022 #endif
1023                     goto do_elem;
1024
1025                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1026                     is_hash = TRUE;
1027                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1028 #ifdef USE_ITHREADS
1029                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1030 #else
1031                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1032 #endif
1033                     goto do_vivify_rv2xv_elem;
1034
1035                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1036                     is_hash = TRUE;
1037                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1038                     pad_free((++items)->pad_offset);
1039                     goto do_vivify_rv2xv_elem;
1040
1041                 case MDEREF_HV_pop_rv2hv_helem:
1042                 case MDEREF_HV_vivify_rv2hv_helem:
1043                     is_hash = TRUE;
1044                 do_vivify_rv2xv_elem:
1045                 case MDEREF_AV_pop_rv2av_aelem:
1046                 case MDEREF_AV_vivify_rv2av_aelem:
1047                 do_elem:
1048                     switch (actions & MDEREF_INDEX_MASK) {
1049                     case MDEREF_INDEX_none:
1050                         last = 1;
1051                         break;
1052                     case MDEREF_INDEX_const:
1053                         if (is_hash) {
1054 #ifdef USE_ITHREADS
1055                             /* see RT #15654 */
1056                             pad_swipe((++items)->pad_offset, 1);
1057 #else
1058                             SvREFCNT_dec((++items)->sv);
1059 #endif
1060                         }
1061                         else
1062                             items++;
1063                         break;
1064                     case MDEREF_INDEX_padsv:
1065                         pad_free((++items)->pad_offset);
1066                         break;
1067                     case MDEREF_INDEX_gvsv:
1068 #ifdef USE_ITHREADS
1069                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1070 #else
1071                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1072 #endif
1073                         break;
1074                     }
1075
1076                     if (actions & MDEREF_FLAG_last)
1077                         last = 1;
1078                     is_hash = FALSE;
1079
1080                     break;
1081
1082                 default:
1083                     assert(0);
1084                     last = 1;
1085                     break;
1086
1087                 } /* switch */
1088
1089                 actions >>= MDEREF_SHIFT;
1090             } /* while */
1091
1092             /* start of malloc is at op_aux[-1], where the length is
1093              * stored */
1094             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1095         }
1096         break;
1097     }
1098
1099     if (o->op_targ > 0) {
1100         pad_free(o->op_targ);
1101         o->op_targ = 0;
1102     }
1103 }
1104
1105 STATIC void
1106 S_cop_free(pTHX_ COP* cop)
1107 {
1108     PERL_ARGS_ASSERT_COP_FREE;
1109
1110     CopFILE_free(cop);
1111     if (! specialWARN(cop->cop_warnings))
1112         PerlMemShared_free(cop->cop_warnings);
1113     cophh_free(CopHINTHASH_get(cop));
1114     if (PL_curcop == cop)
1115        PL_curcop = NULL;
1116 }
1117
1118 STATIC void
1119 S_forget_pmop(pTHX_ PMOP *const o
1120               )
1121 {
1122     HV * const pmstash = PmopSTASH(o);
1123
1124     PERL_ARGS_ASSERT_FORGET_PMOP;
1125
1126     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1127         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1128         if (mg) {
1129             PMOP **const array = (PMOP**) mg->mg_ptr;
1130             U32 count = mg->mg_len / sizeof(PMOP**);
1131             U32 i = count;
1132
1133             while (i--) {
1134                 if (array[i] == o) {
1135                     /* Found it. Move the entry at the end to overwrite it.  */
1136                     array[i] = array[--count];
1137                     mg->mg_len = count * sizeof(PMOP**);
1138                     /* Could realloc smaller at this point always, but probably
1139                        not worth it. Probably worth free()ing if we're the
1140                        last.  */
1141                     if(!count) {
1142                         Safefree(mg->mg_ptr);
1143                         mg->mg_ptr = NULL;
1144                     }
1145                     break;
1146                 }
1147             }
1148         }
1149     }
1150     if (PL_curpm == o) 
1151         PL_curpm = NULL;
1152 }
1153
1154 STATIC void
1155 S_find_and_forget_pmops(pTHX_ OP *o)
1156 {
1157     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1158
1159     if (o->op_flags & OPf_KIDS) {
1160         OP *kid = cUNOPo->op_first;
1161         while (kid) {
1162             switch (kid->op_type) {
1163             case OP_SUBST:
1164             case OP_PUSHRE:
1165             case OP_MATCH:
1166             case OP_QR:
1167                 forget_pmop((PMOP*)kid);
1168             }
1169             find_and_forget_pmops(kid);
1170             kid = OpSIBLING(kid);
1171         }
1172     }
1173 }
1174
1175 /*
1176 =for apidoc Am|void|op_null|OP *o
1177
1178 Neutralizes an op when it is no longer needed, but is still linked to from
1179 other ops.
1180
1181 =cut
1182 */
1183
1184 void
1185 Perl_op_null(pTHX_ OP *o)
1186 {
1187     dVAR;
1188
1189     PERL_ARGS_ASSERT_OP_NULL;
1190
1191     if (o->op_type == OP_NULL)
1192         return;
1193     op_clear(o);
1194     o->op_targ = o->op_type;
1195     OpTYPE_set(o, OP_NULL);
1196 }
1197
1198 void
1199 Perl_op_refcnt_lock(pTHX)
1200   PERL_TSA_ACQUIRE(PL_op_mutex)
1201 {
1202 #ifdef USE_ITHREADS
1203     dVAR;
1204 #endif
1205     PERL_UNUSED_CONTEXT;
1206     OP_REFCNT_LOCK;
1207 }
1208
1209 void
1210 Perl_op_refcnt_unlock(pTHX)
1211   PERL_TSA_RELEASE(PL_op_mutex)
1212 {
1213 #ifdef USE_ITHREADS
1214     dVAR;
1215 #endif
1216     PERL_UNUSED_CONTEXT;
1217     OP_REFCNT_UNLOCK;
1218 }
1219
1220
1221 /*
1222 =for apidoc op_sibling_splice
1223
1224 A general function for editing the structure of an existing chain of
1225 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1226 you to delete zero or more sequential nodes, replacing them with zero or
1227 more different nodes.  Performs the necessary op_first/op_last
1228 housekeeping on the parent node and op_sibling manipulation on the
1229 children.  The last deleted node will be marked as as the last node by
1230 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1231
1232 Note that op_next is not manipulated, and nodes are not freed; that is the
1233 responsibility of the caller.  It also won't create a new list op for an
1234 empty list etc; use higher-level functions like op_append_elem() for that.
1235
1236 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1237 the splicing doesn't affect the first or last op in the chain.
1238
1239 C<start> is the node preceding the first node to be spliced.  Node(s)
1240 following it will be deleted, and ops will be inserted after it.  If it is
1241 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1242 beginning.
1243
1244 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1245 If -1 or greater than or equal to the number of remaining kids, all
1246 remaining kids are deleted.
1247
1248 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1249 If C<NULL>, no nodes are inserted.
1250
1251 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1252 deleted.
1253
1254 For example:
1255
1256     action                    before      after         returns
1257     ------                    -----       -----         -------
1258
1259                               P           P
1260     splice(P, A, 2, X-Y-Z)    |           |             B-C
1261                               A-B-C-D     A-X-Y-Z-D
1262
1263                               P           P
1264     splice(P, NULL, 1, X-Y)   |           |             A
1265                               A-B-C-D     X-Y-B-C-D
1266
1267                               P           P
1268     splice(P, NULL, 3, NULL)  |           |             A-B-C
1269                               A-B-C-D     D
1270
1271                               P           P
1272     splice(P, B, 0, X-Y)      |           |             NULL
1273                               A-B-C-D     A-B-X-Y-C-D
1274
1275
1276 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1277 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1278
1279 =cut
1280 */
1281
1282 OP *
1283 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1284 {
1285     OP *first;
1286     OP *rest;
1287     OP *last_del = NULL;
1288     OP *last_ins = NULL;
1289
1290     if (start)
1291         first = OpSIBLING(start);
1292     else if (!parent)
1293         goto no_parent;
1294     else
1295         first = cLISTOPx(parent)->op_first;
1296
1297     assert(del_count >= -1);
1298
1299     if (del_count && first) {
1300         last_del = first;
1301         while (--del_count && OpHAS_SIBLING(last_del))
1302             last_del = OpSIBLING(last_del);
1303         rest = OpSIBLING(last_del);
1304         OpLASTSIB_set(last_del, NULL);
1305     }
1306     else
1307         rest = first;
1308
1309     if (insert) {
1310         last_ins = insert;
1311         while (OpHAS_SIBLING(last_ins))
1312             last_ins = OpSIBLING(last_ins);
1313         OpMAYBESIB_set(last_ins, rest, NULL);
1314     }
1315     else
1316         insert = rest;
1317
1318     if (start) {
1319         OpMAYBESIB_set(start, insert, NULL);
1320     }
1321     else {
1322         if (!parent)
1323             goto no_parent;
1324         cLISTOPx(parent)->op_first = insert;
1325         if (insert)
1326             parent->op_flags |= OPf_KIDS;
1327         else
1328             parent->op_flags &= ~OPf_KIDS;
1329     }
1330
1331     if (!rest) {
1332         /* update op_last etc */
1333         U32 type;
1334         OP *lastop;
1335
1336         if (!parent)
1337             goto no_parent;
1338
1339         /* ought to use OP_CLASS(parent) here, but that can't handle
1340          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1341          * either */
1342         type = parent->op_type;
1343         if (type == OP_CUSTOM) {
1344             dTHX;
1345             type = XopENTRYCUSTOM(parent, xop_class);
1346         }
1347         else {
1348             if (type == OP_NULL)
1349                 type = parent->op_targ;
1350             type = PL_opargs[type] & OA_CLASS_MASK;
1351         }
1352
1353         lastop = last_ins ? last_ins : start ? start : NULL;
1354         if (   type == OA_BINOP
1355             || type == OA_LISTOP
1356             || type == OA_PMOP
1357             || type == OA_LOOP
1358         )
1359             cLISTOPx(parent)->op_last = lastop;
1360
1361         if (lastop)
1362             OpLASTSIB_set(lastop, parent);
1363     }
1364     return last_del ? first : NULL;
1365
1366   no_parent:
1367     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1368 }
1369
1370
1371 #ifdef PERL_OP_PARENT
1372
1373 /*
1374 =for apidoc op_parent
1375
1376 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1377 This function is only available on perls built with C<-DPERL_OP_PARENT>.
1378
1379 =cut
1380 */
1381
1382 OP *
1383 Perl_op_parent(OP *o)
1384 {
1385     PERL_ARGS_ASSERT_OP_PARENT;
1386     while (OpHAS_SIBLING(o))
1387         o = OpSIBLING(o);
1388     return o->op_sibparent;
1389 }
1390
1391 #endif
1392
1393
1394 /* replace the sibling following start with a new UNOP, which becomes
1395  * the parent of the original sibling; e.g.
1396  *
1397  *  op_sibling_newUNOP(P, A, unop-args...)
1398  *
1399  *  P              P
1400  *  |      becomes |
1401  *  A-B-C          A-U-C
1402  *                   |
1403  *                   B
1404  *
1405  * where U is the new UNOP.
1406  *
1407  * parent and start args are the same as for op_sibling_splice();
1408  * type and flags args are as newUNOP().
1409  *
1410  * Returns the new UNOP.
1411  */
1412
1413 STATIC OP *
1414 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1415 {
1416     OP *kid, *newop;
1417
1418     kid = op_sibling_splice(parent, start, 1, NULL);
1419     newop = newUNOP(type, flags, kid);
1420     op_sibling_splice(parent, start, 0, newop);
1421     return newop;
1422 }
1423
1424
1425 /* lowest-level newLOGOP-style function - just allocates and populates
1426  * the struct. Higher-level stuff should be done by S_new_logop() /
1427  * newLOGOP(). This function exists mainly to avoid op_first assignment
1428  * being spread throughout this file.
1429  */
1430
1431 STATIC LOGOP *
1432 S_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1433 {
1434     dVAR;
1435     LOGOP *logop;
1436     OP *kid = first;
1437     NewOp(1101, logop, 1, LOGOP);
1438     OpTYPE_set(logop, type);
1439     logop->op_first = first;
1440     logop->op_other = other;
1441     logop->op_flags = OPf_KIDS;
1442     while (kid && OpHAS_SIBLING(kid))
1443         kid = OpSIBLING(kid);
1444     if (kid)
1445         OpLASTSIB_set(kid, (OP*)logop);
1446     return logop;
1447 }
1448
1449
1450 /* Contextualizers */
1451
1452 /*
1453 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1454
1455 Applies a syntactic context to an op tree representing an expression.
1456 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1457 or C<G_VOID> to specify the context to apply.  The modified op tree
1458 is returned.
1459
1460 =cut
1461 */
1462
1463 OP *
1464 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1465 {
1466     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1467     switch (context) {
1468         case G_SCALAR: return scalar(o);
1469         case G_ARRAY:  return list(o);
1470         case G_VOID:   return scalarvoid(o);
1471         default:
1472             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1473                        (long) context);
1474     }
1475 }
1476
1477 /*
1478
1479 =for apidoc Am|OP*|op_linklist|OP *o
1480 This function is the implementation of the L</LINKLIST> macro.  It should
1481 not be called directly.
1482
1483 =cut
1484 */
1485
1486 OP *
1487 Perl_op_linklist(pTHX_ OP *o)
1488 {
1489     OP *first;
1490
1491     PERL_ARGS_ASSERT_OP_LINKLIST;
1492
1493     if (o->op_next)
1494         return o->op_next;
1495
1496     /* establish postfix order */
1497     first = cUNOPo->op_first;
1498     if (first) {
1499         OP *kid;
1500         o->op_next = LINKLIST(first);
1501         kid = first;
1502         for (;;) {
1503             OP *sibl = OpSIBLING(kid);
1504             if (sibl) {
1505                 kid->op_next = LINKLIST(sibl);
1506                 kid = sibl;
1507             } else {
1508                 kid->op_next = o;
1509                 break;
1510             }
1511         }
1512     }
1513     else
1514         o->op_next = o;
1515
1516     return o->op_next;
1517 }
1518
1519 static OP *
1520 S_scalarkids(pTHX_ OP *o)
1521 {
1522     if (o && o->op_flags & OPf_KIDS) {
1523         OP *kid;
1524         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1525             scalar(kid);
1526     }
1527     return o;
1528 }
1529
1530 STATIC OP *
1531 S_scalarboolean(pTHX_ OP *o)
1532 {
1533     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1534
1535     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1536          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1537         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1538          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1539          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1540         if (ckWARN(WARN_SYNTAX)) {
1541             const line_t oldline = CopLINE(PL_curcop);
1542
1543             if (PL_parser && PL_parser->copline != NOLINE) {
1544                 /* This ensures that warnings are reported at the first line
1545                    of the conditional, not the last.  */
1546                 CopLINE_set(PL_curcop, PL_parser->copline);
1547             }
1548             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1549             CopLINE_set(PL_curcop, oldline);
1550         }
1551     }
1552     return scalar(o);
1553 }
1554
1555 static SV *
1556 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1557 {
1558     assert(o);
1559     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1560            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1561     {
1562         const char funny  = o->op_type == OP_PADAV
1563                          || o->op_type == OP_RV2AV ? '@' : '%';
1564         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1565             GV *gv;
1566             if (cUNOPo->op_first->op_type != OP_GV
1567              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1568                 return NULL;
1569             return varname(gv, funny, 0, NULL, 0, subscript_type);
1570         }
1571         return
1572             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1573     }
1574 }
1575
1576 static SV *
1577 S_op_varname(pTHX_ const OP *o)
1578 {
1579     return S_op_varname_subscript(aTHX_ o, 1);
1580 }
1581
1582 static void
1583 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1584 { /* or not so pretty :-) */
1585     if (o->op_type == OP_CONST) {
1586         *retsv = cSVOPo_sv;
1587         if (SvPOK(*retsv)) {
1588             SV *sv = *retsv;
1589             *retsv = sv_newmortal();
1590             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1591                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1592         }
1593         else if (!SvOK(*retsv))
1594             *retpv = "undef";
1595     }
1596     else *retpv = "...";
1597 }
1598
1599 static void
1600 S_scalar_slice_warning(pTHX_ const OP *o)
1601 {
1602     OP *kid;
1603     const char lbrack =
1604         o->op_type == OP_HSLICE ? '{' : '[';
1605     const char rbrack =
1606         o->op_type == OP_HSLICE ? '}' : ']';
1607     SV *name;
1608     SV *keysv = NULL; /* just to silence compiler warnings */
1609     const char *key = NULL;
1610
1611     if (!(o->op_private & OPpSLICEWARNING))
1612         return;
1613     if (PL_parser && PL_parser->error_count)
1614         /* This warning can be nonsensical when there is a syntax error. */
1615         return;
1616
1617     kid = cLISTOPo->op_first;
1618     kid = OpSIBLING(kid); /* get past pushmark */
1619     /* weed out false positives: any ops that can return lists */
1620     switch (kid->op_type) {
1621     case OP_BACKTICK:
1622     case OP_GLOB:
1623     case OP_READLINE:
1624     case OP_MATCH:
1625     case OP_RV2AV:
1626     case OP_EACH:
1627     case OP_VALUES:
1628     case OP_KEYS:
1629     case OP_SPLIT:
1630     case OP_LIST:
1631     case OP_SORT:
1632     case OP_REVERSE:
1633     case OP_ENTERSUB:
1634     case OP_CALLER:
1635     case OP_LSTAT:
1636     case OP_STAT:
1637     case OP_READDIR:
1638     case OP_SYSTEM:
1639     case OP_TMS:
1640     case OP_LOCALTIME:
1641     case OP_GMTIME:
1642     case OP_ENTEREVAL:
1643         return;
1644     }
1645
1646     /* Don't warn if we have a nulled list either. */
1647     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1648         return;
1649
1650     assert(OpSIBLING(kid));
1651     name = S_op_varname(aTHX_ OpSIBLING(kid));
1652     if (!name) /* XS module fiddling with the op tree */
1653         return;
1654     S_op_pretty(aTHX_ kid, &keysv, &key);
1655     assert(SvPOK(name));
1656     sv_chop(name,SvPVX(name)+1);
1657     if (key)
1658        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1659         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1660                    "Scalar value @%"SVf"%c%s%c better written as $%"SVf
1661                    "%c%s%c",
1662                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1663                     lbrack, key, rbrack);
1664     else
1665        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1666         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1667                    "Scalar value @%"SVf"%c%"SVf"%c better written as $%"
1668                     SVf"%c%"SVf"%c",
1669                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1670                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1671 }
1672
1673 OP *
1674 Perl_scalar(pTHX_ OP *o)
1675 {
1676     OP *kid;
1677
1678     /* assumes no premature commitment */
1679     if (!o || (PL_parser && PL_parser->error_count)
1680          || (o->op_flags & OPf_WANT)
1681          || o->op_type == OP_RETURN)
1682     {
1683         return o;
1684     }
1685
1686     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1687
1688     switch (o->op_type) {
1689     case OP_REPEAT:
1690         scalar(cBINOPo->op_first);
1691         if (o->op_private & OPpREPEAT_DOLIST) {
1692             kid = cLISTOPx(cUNOPo->op_first)->op_first;
1693             assert(kid->op_type == OP_PUSHMARK);
1694             if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1695                 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1696                 o->op_private &=~ OPpREPEAT_DOLIST;
1697             }
1698         }
1699         break;
1700     case OP_OR:
1701     case OP_AND:
1702     case OP_COND_EXPR:
1703         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
1704             scalar(kid);
1705         break;
1706         /* FALLTHROUGH */
1707     case OP_SPLIT:
1708     case OP_MATCH:
1709     case OP_QR:
1710     case OP_SUBST:
1711     case OP_NULL:
1712     default:
1713         if (o->op_flags & OPf_KIDS) {
1714             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
1715                 scalar(kid);
1716         }
1717         break;
1718     case OP_LEAVE:
1719     case OP_LEAVETRY:
1720         kid = cLISTOPo->op_first;
1721         scalar(kid);
1722         kid = OpSIBLING(kid);
1723     do_kids:
1724         while (kid) {
1725             OP *sib = OpSIBLING(kid);
1726             if (sib && kid->op_type != OP_LEAVEWHEN
1727              && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
1728                 || (  sib->op_targ != OP_NEXTSTATE
1729                    && sib->op_targ != OP_DBSTATE  )))
1730                 scalarvoid(kid);
1731             else
1732                 scalar(kid);
1733             kid = sib;
1734         }
1735         PL_curcop = &PL_compiling;
1736         break;
1737     case OP_SCOPE:
1738     case OP_LINESEQ:
1739     case OP_LIST:
1740         kid = cLISTOPo->op_first;
1741         goto do_kids;
1742     case OP_SORT:
1743         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1744         break;
1745     case OP_KVHSLICE:
1746     case OP_KVASLICE:
1747     {
1748         /* Warn about scalar context */
1749         const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1750         const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1751         SV *name;
1752         SV *keysv;
1753         const char *key = NULL;
1754
1755         /* This warning can be nonsensical when there is a syntax error. */
1756         if (PL_parser && PL_parser->error_count)
1757             break;
1758
1759         if (!ckWARN(WARN_SYNTAX)) break;
1760
1761         kid = cLISTOPo->op_first;
1762         kid = OpSIBLING(kid); /* get past pushmark */
1763         assert(OpSIBLING(kid));
1764         name = S_op_varname(aTHX_ OpSIBLING(kid));
1765         if (!name) /* XS module fiddling with the op tree */
1766             break;
1767         S_op_pretty(aTHX_ kid, &keysv, &key);
1768         assert(SvPOK(name));
1769         sv_chop(name,SvPVX(name)+1);
1770         if (key)
1771   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1772             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1773                        "%%%"SVf"%c%s%c in scalar context better written "
1774                        "as $%"SVf"%c%s%c",
1775                         SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1776                         lbrack, key, rbrack);
1777         else
1778   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1779             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1780                        "%%%"SVf"%c%"SVf"%c in scalar context better "
1781                        "written as $%"SVf"%c%"SVf"%c",
1782                         SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1783                         SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1784     }
1785     }
1786     return o;
1787 }
1788
1789 OP *
1790 Perl_scalarvoid(pTHX_ OP *arg)
1791 {
1792     dVAR;
1793     OP *kid;
1794     SV* sv;
1795     U8 want;
1796     SSize_t defer_stack_alloc = 0;
1797     SSize_t defer_ix = -1;
1798     OP **defer_stack = NULL;
1799     OP *o = arg;
1800
1801     PERL_ARGS_ASSERT_SCALARVOID;
1802
1803     do {
1804         SV *useless_sv = NULL;
1805         const char* useless = NULL;
1806
1807         if (o->op_type == OP_NEXTSTATE
1808             || o->op_type == OP_DBSTATE
1809             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1810                                           || o->op_targ == OP_DBSTATE)))
1811             PL_curcop = (COP*)o;                /* for warning below */
1812
1813         /* assumes no premature commitment */
1814         want = o->op_flags & OPf_WANT;
1815         if ((want && want != OPf_WANT_SCALAR)
1816             || (PL_parser && PL_parser->error_count)
1817             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1818         {
1819             continue;
1820         }
1821
1822         if ((o->op_private & OPpTARGET_MY)
1823             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1824         {
1825             /* newASSIGNOP has already applied scalar context, which we
1826                leave, as if this op is inside SASSIGN.  */
1827             continue;
1828         }
1829
1830         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1831
1832         switch (o->op_type) {
1833         default:
1834             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1835                 break;
1836             /* FALLTHROUGH */
1837         case OP_REPEAT:
1838             if (o->op_flags & OPf_STACKED)
1839                 break;
1840             if (o->op_type == OP_REPEAT)
1841                 scalar(cBINOPo->op_first);
1842             goto func_ops;
1843         case OP_SUBSTR:
1844             if (o->op_private == 4)
1845                 break;
1846             /* FALLTHROUGH */
1847         case OP_WANTARRAY:
1848         case OP_GV:
1849         case OP_SMARTMATCH:
1850         case OP_AV2ARYLEN:
1851         case OP_REF:
1852         case OP_REFGEN:
1853         case OP_SREFGEN:
1854         case OP_DEFINED:
1855         case OP_HEX:
1856         case OP_OCT:
1857         case OP_LENGTH:
1858         case OP_VEC:
1859         case OP_INDEX:
1860         case OP_RINDEX:
1861         case OP_SPRINTF:
1862         case OP_KVASLICE:
1863         case OP_KVHSLICE:
1864         case OP_UNPACK:
1865         case OP_PACK:
1866         case OP_JOIN:
1867         case OP_LSLICE:
1868         case OP_ANONLIST:
1869         case OP_ANONHASH:
1870         case OP_SORT:
1871         case OP_REVERSE:
1872         case OP_RANGE:
1873         case OP_FLIP:
1874         case OP_FLOP:
1875         case OP_CALLER:
1876         case OP_FILENO:
1877         case OP_EOF:
1878         case OP_TELL:
1879         case OP_GETSOCKNAME:
1880         case OP_GETPEERNAME:
1881         case OP_READLINK:
1882         case OP_TELLDIR:
1883         case OP_GETPPID:
1884         case OP_GETPGRP:
1885         case OP_GETPRIORITY:
1886         case OP_TIME:
1887         case OP_TMS:
1888         case OP_LOCALTIME:
1889         case OP_GMTIME:
1890         case OP_GHBYNAME:
1891         case OP_GHBYADDR:
1892         case OP_GHOSTENT:
1893         case OP_GNBYNAME:
1894         case OP_GNBYADDR:
1895         case OP_GNETENT:
1896         case OP_GPBYNAME:
1897         case OP_GPBYNUMBER:
1898         case OP_GPROTOENT:
1899         case OP_GSBYNAME:
1900         case OP_GSBYPORT:
1901         case OP_GSERVENT:
1902         case OP_GPWNAM:
1903         case OP_GPWUID:
1904         case OP_GGRNAM:
1905         case OP_GGRGID:
1906         case OP_GETLOGIN:
1907         case OP_PROTOTYPE:
1908         case OP_RUNCV:
1909         func_ops:
1910             useless = OP_DESC(o);
1911             break;
1912
1913         case OP_GVSV:
1914         case OP_PADSV:
1915         case OP_PADAV:
1916         case OP_PADHV:
1917         case OP_PADANY:
1918         case OP_AELEM:
1919         case OP_AELEMFAST:
1920         case OP_AELEMFAST_LEX:
1921         case OP_ASLICE:
1922         case OP_HELEM:
1923         case OP_HSLICE:
1924             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1925                 /* Otherwise it's "Useless use of grep iterator" */
1926                 useless = OP_DESC(o);
1927             break;
1928
1929         case OP_SPLIT:
1930             kid = cLISTOPo->op_first;
1931             if (kid && kid->op_type == OP_PUSHRE
1932                 && !kid->op_targ
1933                 && !(o->op_flags & OPf_STACKED)
1934 #ifdef USE_ITHREADS
1935                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
1936 #else
1937                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
1938 #endif
1939                 )
1940                 useless = OP_DESC(o);
1941             break;
1942
1943         case OP_NOT:
1944             kid = cUNOPo->op_first;
1945             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1946                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1947                 goto func_ops;
1948             }
1949             useless = "negative pattern binding (!~)";
1950             break;
1951
1952         case OP_SUBST:
1953             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1954                 useless = "non-destructive substitution (s///r)";
1955             break;
1956
1957         case OP_TRANSR:
1958             useless = "non-destructive transliteration (tr///r)";
1959             break;
1960
1961         case OP_RV2GV:
1962         case OP_RV2SV:
1963         case OP_RV2AV:
1964         case OP_RV2HV:
1965             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1966                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
1967                 useless = "a variable";
1968             break;
1969
1970         case OP_CONST:
1971             sv = cSVOPo_sv;
1972             if (cSVOPo->op_private & OPpCONST_STRICT)
1973                 no_bareword_allowed(o);
1974             else {
1975                 if (ckWARN(WARN_VOID)) {
1976                     NV nv;
1977                     /* don't warn on optimised away booleans, eg
1978                      * use constant Foo, 5; Foo || print; */
1979                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1980                         useless = NULL;
1981                     /* the constants 0 and 1 are permitted as they are
1982                        conventionally used as dummies in constructs like
1983                        1 while some_condition_with_side_effects;  */
1984                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
1985                         useless = NULL;
1986                     else if (SvPOK(sv)) {
1987                         SV * const dsv = newSVpvs("");
1988                         useless_sv
1989                             = Perl_newSVpvf(aTHX_
1990                                             "a constant (%s)",
1991                                             pv_pretty(dsv, SvPVX_const(sv),
1992                                                       SvCUR(sv), 32, NULL, NULL,
1993                                                       PERL_PV_PRETTY_DUMP
1994                                                       | PERL_PV_ESCAPE_NOCLEAR
1995                                                       | PERL_PV_ESCAPE_UNI_DETECT));
1996                         SvREFCNT_dec_NN(dsv);
1997                     }
1998                     else if (SvOK(sv)) {
1999                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%"SVf")", SVfARG(sv));
2000                     }
2001                     else
2002                         useless = "a constant (undef)";
2003                 }
2004             }
2005             op_null(o);         /* don't execute or even remember it */
2006             break;
2007
2008         case OP_POSTINC:
2009             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2010             break;
2011
2012         case OP_POSTDEC:
2013             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2014             break;
2015
2016         case OP_I_POSTINC:
2017             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2018             break;
2019
2020         case OP_I_POSTDEC:
2021             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2022             break;
2023
2024         case OP_SASSIGN: {
2025             OP *rv2gv;
2026             UNOP *refgen, *rv2cv;
2027             LISTOP *exlist;
2028
2029             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2030                 break;
2031
2032             rv2gv = ((BINOP *)o)->op_last;
2033             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2034                 break;
2035
2036             refgen = (UNOP *)((BINOP *)o)->op_first;
2037
2038             if (!refgen || (refgen->op_type != OP_REFGEN
2039                             && refgen->op_type != OP_SREFGEN))
2040                 break;
2041
2042             exlist = (LISTOP *)refgen->op_first;
2043             if (!exlist || exlist->op_type != OP_NULL
2044                 || exlist->op_targ != OP_LIST)
2045                 break;
2046
2047             if (exlist->op_first->op_type != OP_PUSHMARK
2048                 && exlist->op_first != exlist->op_last)
2049                 break;
2050
2051             rv2cv = (UNOP*)exlist->op_last;
2052
2053             if (rv2cv->op_type != OP_RV2CV)
2054                 break;
2055
2056             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2057             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2058             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2059
2060             o->op_private |= OPpASSIGN_CV_TO_GV;
2061             rv2gv->op_private |= OPpDONT_INIT_GV;
2062             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2063
2064             break;
2065         }
2066
2067         case OP_AASSIGN: {
2068             inplace_aassign(o);
2069             break;
2070         }
2071
2072         case OP_OR:
2073         case OP_AND:
2074             kid = cLOGOPo->op_first;
2075             if (kid->op_type == OP_NOT
2076                 && (kid->op_flags & OPf_KIDS)) {
2077                 if (o->op_type == OP_AND) {
2078                     OpTYPE_set(o, OP_OR);
2079                 } else {
2080                     OpTYPE_set(o, OP_AND);
2081                 }
2082                 op_null(kid);
2083             }
2084             /* FALLTHROUGH */
2085
2086         case OP_DOR:
2087         case OP_COND_EXPR:
2088         case OP_ENTERGIVEN:
2089         case OP_ENTERWHEN:
2090             for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2091                 if (!(kid->op_flags & OPf_KIDS))
2092                     scalarvoid(kid);
2093                 else
2094                     DEFER_OP(kid);
2095         break;
2096
2097         case OP_NULL:
2098             if (o->op_flags & OPf_STACKED)
2099                 break;
2100             /* FALLTHROUGH */
2101         case OP_NEXTSTATE:
2102         case OP_DBSTATE:
2103         case OP_ENTERTRY:
2104         case OP_ENTER:
2105             if (!(o->op_flags & OPf_KIDS))
2106                 break;
2107             /* FALLTHROUGH */
2108         case OP_SCOPE:
2109         case OP_LEAVE:
2110         case OP_LEAVETRY:
2111         case OP_LEAVELOOP:
2112         case OP_LINESEQ:
2113         case OP_LEAVEGIVEN:
2114         case OP_LEAVEWHEN:
2115         kids:
2116             for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2117                 if (!(kid->op_flags & OPf_KIDS))
2118                     scalarvoid(kid);
2119                 else
2120                     DEFER_OP(kid);
2121             break;
2122         case OP_LIST:
2123             /* If the first kid after pushmark is something that the padrange
2124                optimisation would reject, then null the list and the pushmark.
2125             */
2126             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2127                 && (  !(kid = OpSIBLING(kid))
2128                       || (  kid->op_type != OP_PADSV
2129                             && kid->op_type != OP_PADAV
2130                             && kid->op_type != OP_PADHV)
2131                       || kid->op_private & ~OPpLVAL_INTRO
2132                       || !(kid = OpSIBLING(kid))
2133                       || (  kid->op_type != OP_PADSV
2134                             && kid->op_type != OP_PADAV
2135                             && kid->op_type != OP_PADHV)
2136                       || kid->op_private & ~OPpLVAL_INTRO)
2137             ) {
2138                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2139                 op_null(o); /* NULL the list */
2140             }
2141             goto kids;
2142         case OP_ENTEREVAL:
2143             scalarkids(o);
2144             break;
2145         case OP_SCALAR:
2146             scalar(o);
2147             break;
2148         }
2149
2150         if (useless_sv) {
2151             /* mortalise it, in case warnings are fatal.  */
2152             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2153                            "Useless use of %"SVf" in void context",
2154                            SVfARG(sv_2mortal(useless_sv)));
2155         }
2156         else if (useless) {
2157             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2158                            "Useless use of %s in void context",
2159                            useless);
2160         }
2161     } while ( (o = POP_DEFERRED_OP()) );
2162
2163     Safefree(defer_stack);
2164
2165     return arg;
2166 }
2167
2168 static OP *
2169 S_listkids(pTHX_ OP *o)
2170 {
2171     if (o && o->op_flags & OPf_KIDS) {
2172         OP *kid;
2173         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2174             list(kid);
2175     }
2176     return o;
2177 }
2178
2179 OP *
2180 Perl_list(pTHX_ OP *o)
2181 {
2182     OP *kid;
2183
2184     /* assumes no premature commitment */
2185     if (!o || (o->op_flags & OPf_WANT)
2186          || (PL_parser && PL_parser->error_count)
2187          || o->op_type == OP_RETURN)
2188     {
2189         return o;
2190     }
2191
2192     if ((o->op_private & OPpTARGET_MY)
2193         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2194     {
2195         return o;                               /* As if inside SASSIGN */
2196     }
2197
2198     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2199
2200     switch (o->op_type) {
2201     case OP_FLOP:
2202         list(cBINOPo->op_first);
2203         break;
2204     case OP_REPEAT:
2205         if (o->op_private & OPpREPEAT_DOLIST
2206          && !(o->op_flags & OPf_STACKED))
2207         {
2208             list(cBINOPo->op_first);
2209             kid = cBINOPo->op_last;
2210             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2211              && SvIVX(kSVOP_sv) == 1)
2212             {
2213                 op_null(o); /* repeat */
2214                 op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2215                 /* const (rhs): */
2216                 op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2217             }
2218         }
2219         break;
2220     case OP_OR:
2221     case OP_AND:
2222     case OP_COND_EXPR:
2223         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2224             list(kid);
2225         break;
2226     default:
2227     case OP_MATCH:
2228     case OP_QR:
2229     case OP_SUBST:
2230     case OP_NULL:
2231         if (!(o->op_flags & OPf_KIDS))
2232             break;
2233         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2234             list(cBINOPo->op_first);
2235             return gen_constant_list(o);
2236         }
2237         listkids(o);
2238         break;
2239     case OP_LIST:
2240         listkids(o);
2241         if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2242             op_null(cUNOPo->op_first); /* NULL the pushmark */
2243             op_null(o); /* NULL the list */
2244         }
2245         break;
2246     case OP_LEAVE:
2247     case OP_LEAVETRY:
2248         kid = cLISTOPo->op_first;
2249         list(kid);
2250         kid = OpSIBLING(kid);
2251     do_kids:
2252         while (kid) {
2253             OP *sib = OpSIBLING(kid);
2254             if (sib && kid->op_type != OP_LEAVEWHEN)
2255                 scalarvoid(kid);
2256             else
2257                 list(kid);
2258             kid = sib;
2259         }
2260         PL_curcop = &PL_compiling;
2261         break;
2262     case OP_SCOPE:
2263     case OP_LINESEQ:
2264         kid = cLISTOPo->op_first;
2265         goto do_kids;
2266     }
2267     return o;
2268 }
2269
2270 static OP *
2271 S_scalarseq(pTHX_ OP *o)
2272 {
2273     if (o) {
2274         const OPCODE type = o->op_type;
2275
2276         if (type == OP_LINESEQ || type == OP_SCOPE ||
2277             type == OP_LEAVE || type == OP_LEAVETRY)
2278         {
2279             OP *kid, *sib;
2280             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2281                 if ((sib = OpSIBLING(kid))
2282                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2283                     || (  sib->op_targ != OP_NEXTSTATE
2284                        && sib->op_targ != OP_DBSTATE  )))
2285                 {
2286                     scalarvoid(kid);
2287                 }
2288             }
2289             PL_curcop = &PL_compiling;
2290         }
2291         o->op_flags &= ~OPf_PARENS;
2292         if (PL_hints & HINT_BLOCK_SCOPE)
2293             o->op_flags |= OPf_PARENS;
2294     }
2295     else
2296         o = newOP(OP_STUB, 0);
2297     return o;
2298 }
2299
2300 STATIC OP *
2301 S_modkids(pTHX_ OP *o, I32 type)
2302 {
2303     if (o && o->op_flags & OPf_KIDS) {
2304         OP *kid;
2305         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2306             op_lvalue(kid, type);
2307     }
2308     return o;
2309 }
2310
2311
2312 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2313  * const fields. Also, convert CONST keys to HEK-in-SVs.
2314  * rop is the op that retrieves the hash;
2315  * key_op is the first key
2316  */
2317
2318 STATIC void
2319 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op)
2320 {
2321     PADNAME *lexname;
2322     GV **fields;
2323     bool check_fields;
2324
2325     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2326     if (rop) {
2327         if (rop->op_first->op_type == OP_PADSV)
2328             /* @$hash{qw(keys here)} */
2329             rop = (UNOP*)rop->op_first;
2330         else {
2331             /* @{$hash}{qw(keys here)} */
2332             if (rop->op_first->op_type == OP_SCOPE
2333                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2334                 {
2335                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2336                 }
2337             else
2338                 rop = NULL;
2339         }
2340     }
2341
2342     lexname = NULL; /* just to silence compiler warnings */
2343     fields  = NULL; /* just to silence compiler warnings */
2344
2345     check_fields =
2346             rop
2347          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2348              SvPAD_TYPED(lexname))
2349          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2350          && isGV(*fields) && GvHV(*fields);
2351
2352     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2353         SV **svp, *sv;
2354         if (key_op->op_type != OP_CONST)
2355             continue;
2356         svp = cSVOPx_svp(key_op);
2357
2358         /* make sure it's not a bareword under strict subs */
2359         if (key_op->op_private & OPpCONST_BARE &&
2360             key_op->op_private & OPpCONST_STRICT)
2361         {
2362             no_bareword_allowed((OP*)key_op);
2363         }
2364
2365         /* Make the CONST have a shared SV */
2366         if (   !SvIsCOW_shared_hash(sv = *svp)
2367             && SvTYPE(sv) < SVt_PVMG
2368             && SvOK(sv)
2369             && !SvROK(sv))
2370         {
2371             SSize_t keylen;
2372             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2373             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2374             SvREFCNT_dec_NN(sv);
2375             *svp = nsv;
2376         }
2377
2378         if (   check_fields
2379             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2380         {
2381             Perl_croak(aTHX_ "No such class field \"%"SVf"\" "
2382                         "in variable %"PNf" of type %"HEKf,
2383                         SVfARG(*svp), PNfARG(lexname),
2384                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2385         }
2386     }
2387 }
2388
2389
2390 /*
2391 =for apidoc finalize_optree
2392
2393 This function finalizes the optree.  Should be called directly after
2394 the complete optree is built.  It does some additional
2395 checking which can't be done in the normal C<ck_>xxx functions and makes
2396 the tree thread-safe.
2397
2398 =cut
2399 */
2400 void
2401 Perl_finalize_optree(pTHX_ OP* o)
2402 {
2403     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
2404
2405     ENTER;
2406     SAVEVPTR(PL_curcop);
2407
2408     finalize_op(o);
2409
2410     LEAVE;
2411 }
2412
2413 #ifdef USE_ITHREADS
2414 /* Relocate sv to the pad for thread safety.
2415  * Despite being a "constant", the SV is written to,
2416  * for reference counts, sv_upgrade() etc. */
2417 PERL_STATIC_INLINE void
2418 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
2419 {
2420     PADOFFSET ix;
2421     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
2422     if (!*svp) return;
2423     ix = pad_alloc(OP_CONST, SVf_READONLY);
2424     SvREFCNT_dec(PAD_SVl(ix));
2425     PAD_SETSV(ix, *svp);
2426     /* XXX I don't know how this isn't readonly already. */
2427     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
2428     *svp = NULL;
2429     *targp = ix;
2430 }
2431 #endif
2432
2433
2434 STATIC void
2435 S_finalize_op(pTHX_ OP* o)
2436 {
2437     PERL_ARGS_ASSERT_FINALIZE_OP;
2438
2439
2440     switch (o->op_type) {
2441     case OP_NEXTSTATE:
2442     case OP_DBSTATE:
2443         PL_curcop = ((COP*)o);          /* for warnings */
2444         break;
2445     case OP_EXEC:
2446         if (OpHAS_SIBLING(o)) {
2447             OP *sib = OpSIBLING(o);
2448             if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
2449                 && ckWARN(WARN_EXEC)
2450                 && OpHAS_SIBLING(sib))
2451             {
2452                     const OPCODE type = OpSIBLING(sib)->op_type;
2453                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
2454                         const line_t oldline = CopLINE(PL_curcop);
2455                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
2456                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2457                             "Statement unlikely to be reached");
2458                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2459                             "\t(Maybe you meant system() when you said exec()?)\n");
2460                         CopLINE_set(PL_curcop, oldline);
2461                     }
2462             }
2463         }
2464         break;
2465
2466     case OP_GV:
2467         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
2468             GV * const gv = cGVOPo_gv;
2469             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
2470                 /* XXX could check prototype here instead of just carping */
2471                 SV * const sv = sv_newmortal();
2472                 gv_efullname3(sv, gv, NULL);
2473                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
2474                     "%"SVf"() called too early to check prototype",
2475                     SVfARG(sv));
2476             }
2477         }
2478         break;
2479
2480     case OP_CONST:
2481         if (cSVOPo->op_private & OPpCONST_STRICT)
2482             no_bareword_allowed(o);
2483         /* FALLTHROUGH */
2484 #ifdef USE_ITHREADS
2485     case OP_HINTSEVAL:
2486         op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
2487 #endif
2488         break;
2489
2490 #ifdef USE_ITHREADS
2491     /* Relocate all the METHOP's SVs to the pad for thread safety. */
2492     case OP_METHOD_NAMED:
2493     case OP_METHOD_SUPER:
2494     case OP_METHOD_REDIR:
2495     case OP_METHOD_REDIR_SUPER:
2496         op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
2497         break;
2498 #endif
2499
2500     case OP_HELEM: {
2501         UNOP *rop;
2502         SVOP *key_op;
2503         OP *kid;
2504
2505         if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
2506             break;
2507
2508         rop = (UNOP*)((BINOP*)o)->op_first;
2509
2510         goto check_keys;
2511
2512     case OP_HSLICE:
2513         S_scalar_slice_warning(aTHX_ o);
2514         /* FALLTHROUGH */
2515
2516     case OP_KVHSLICE:
2517         kid = OpSIBLING(cLISTOPo->op_first);
2518         if (/* I bet there's always a pushmark... */
2519             OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
2520             && OP_TYPE_ISNT_NN(kid, OP_CONST))
2521         {
2522             break;
2523         }
2524
2525         key_op = (SVOP*)(kid->op_type == OP_CONST
2526                                 ? kid
2527                                 : OpSIBLING(kLISTOP->op_first));
2528
2529         rop = (UNOP*)((LISTOP*)o)->op_last;
2530
2531       check_keys:       
2532         if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
2533             rop = NULL;
2534         S_check_hash_fields_and_hekify(aTHX_ rop, key_op);
2535         break;
2536     }
2537     case OP_ASLICE:
2538         S_scalar_slice_warning(aTHX_ o);
2539         break;
2540
2541     case OP_SUBST: {
2542         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
2543             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
2544         break;
2545     }
2546     default:
2547         break;
2548     }
2549
2550     if (o->op_flags & OPf_KIDS) {
2551         OP *kid;
2552
2553 #ifdef DEBUGGING
2554         /* check that op_last points to the last sibling, and that
2555          * the last op_sibling/op_sibparent field points back to the
2556          * parent, and that the only ops with KIDS are those which are
2557          * entitled to them */
2558         U32 type = o->op_type;
2559         U32 family;
2560         bool has_last;
2561
2562         if (type == OP_NULL) {
2563             type = o->op_targ;
2564             /* ck_glob creates a null UNOP with ex-type GLOB
2565              * (which is a list op. So pretend it wasn't a listop */
2566             if (type == OP_GLOB)
2567                 type = OP_NULL;
2568         }
2569         family = PL_opargs[type] & OA_CLASS_MASK;
2570
2571         has_last = (   family == OA_BINOP
2572                     || family == OA_LISTOP
2573                     || family == OA_PMOP
2574                     || family == OA_LOOP
2575                    );
2576         assert(  has_last /* has op_first and op_last, or ...
2577               ... has (or may have) op_first: */
2578               || family == OA_UNOP
2579               || family == OA_UNOP_AUX
2580               || family == OA_LOGOP
2581               || family == OA_BASEOP_OR_UNOP
2582               || family == OA_FILESTATOP
2583               || family == OA_LOOPEXOP
2584               || family == OA_METHOP
2585               /* I don't know why SASSIGN is tagged as OA_BASEOP - DAPM */
2586               || type == OP_SASSIGN
2587               || type == OP_CUSTOM
2588               || type == OP_NULL /* new_logop does this */
2589               );
2590
2591         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2592 #  ifdef PERL_OP_PARENT
2593             if (!OpHAS_SIBLING(kid)) {
2594                 if (has_last)
2595                     assert(kid == cLISTOPo->op_last);
2596                 assert(kid->op_sibparent == o);
2597             }
2598 #  else
2599             if (has_last && !OpHAS_SIBLING(kid))
2600                 assert(kid == cLISTOPo->op_last);
2601 #  endif
2602         }
2603 #endif
2604
2605         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
2606             finalize_op(kid);
2607     }
2608 }
2609
2610 /*
2611 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
2612
2613 Propagate lvalue ("modifiable") context to an op and its children.
2614 C<type> represents the context type, roughly based on the type of op that
2615 would do the modifying, although C<local()> is represented by C<OP_NULL>,
2616 because it has no op type of its own (it is signalled by a flag on
2617 the lvalue op).
2618
2619 This function detects things that can't be modified, such as C<$x+1>, and
2620 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
2621 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
2622
2623 It also flags things that need to behave specially in an lvalue context,
2624 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
2625
2626 =cut
2627 */
2628
2629 static void
2630 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
2631 {
2632     CV *cv = PL_compcv;
2633     PadnameLVALUE_on(pn);
2634     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
2635         cv = CvOUTSIDE(cv);
2636         /* RT #127786: cv can be NULL due to an eval within the DB package
2637          * called from an anon sub - anon subs don't have CvOUTSIDE() set
2638          * unless they contain an eval, but calling eval within DB
2639          * pretends the eval was done in the caller's scope.
2640          */
2641         if (!cv)
2642             break;
2643         assert(CvPADLIST(cv));
2644         pn =
2645            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
2646         assert(PadnameLEN(pn));
2647         PadnameLVALUE_on(pn);
2648     }
2649 }
2650
2651 static bool
2652 S_vivifies(const OPCODE type)
2653 {
2654     switch(type) {
2655     case OP_RV2AV:     case   OP_ASLICE:
2656     case OP_RV2HV:     case OP_KVASLICE:
2657     case OP_RV2SV:     case   OP_HSLICE:
2658     case OP_AELEMFAST: case OP_KVHSLICE:
2659     case OP_HELEM:
2660     case OP_AELEM:
2661         return 1;
2662     }
2663     return 0;
2664 }
2665
2666 static void
2667 S_lvref(pTHX_ OP *o, I32 type)
2668 {
2669     dVAR;
2670     OP *kid;
2671     switch (o->op_type) {
2672     case OP_COND_EXPR:
2673         for (kid = OpSIBLING(cUNOPo->op_first); kid;
2674              kid = OpSIBLING(kid))
2675             S_lvref(aTHX_ kid, type);
2676         /* FALLTHROUGH */
2677     case OP_PUSHMARK:
2678         return;
2679     case OP_RV2AV:
2680         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2681         o->op_flags |= OPf_STACKED;
2682         if (o->op_flags & OPf_PARENS) {
2683             if (o->op_private & OPpLVAL_INTRO) {
2684                  yyerror(Perl_form(aTHX_ "Can't modify reference to "
2685                       "localized parenthesized array in list assignment"));
2686                 return;
2687             }
2688           slurpy:
2689             OpTYPE_set(o, OP_LVAVREF);
2690             o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
2691             o->op_flags |= OPf_MOD|OPf_REF;
2692             return;
2693         }
2694         o->op_private |= OPpLVREF_AV;
2695         goto checkgv;
2696     case OP_RV2CV:
2697         kid = cUNOPo->op_first;
2698         if (kid->op_type == OP_NULL)
2699             kid = cUNOPx(OpSIBLING(kUNOP->op_first))
2700                 ->op_first;
2701         o->op_private = OPpLVREF_CV;
2702         if (kid->op_type == OP_GV)
2703             o->op_flags |= OPf_STACKED;
2704         else if (kid->op_type == OP_PADCV) {
2705             o->op_targ = kid->op_targ;
2706             kid->op_targ = 0;
2707             op_free(cUNOPo->op_first);
2708             cUNOPo->op_first = NULL;
2709             o->op_flags &=~ OPf_KIDS;
2710         }
2711         else goto badref;
2712         break;
2713     case OP_RV2HV:
2714         if (o->op_flags & OPf_PARENS) {
2715           parenhash:
2716             yyerror(Perl_form(aTHX_ "Can't modify reference to "
2717                                  "parenthesized hash in list assignment"));
2718                 return;
2719         }
2720         o->op_private |= OPpLVREF_HV;
2721         /* FALLTHROUGH */
2722     case OP_RV2SV:
2723       checkgv:
2724         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2725         o->op_flags |= OPf_STACKED;
2726         break;
2727     case OP_PADHV:
2728         if (o->op_flags & OPf_PARENS) goto parenhash;
2729         o->op_private |= OPpLVREF_HV;
2730         /* FALLTHROUGH */
2731     case OP_PADSV:
2732         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2733         break;
2734     case OP_PADAV:
2735         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2736         if (o->op_flags & OPf_PARENS) goto slurpy;
2737         o->op_private |= OPpLVREF_AV;
2738         break;
2739     case OP_AELEM:
2740     case OP_HELEM:
2741         o->op_private |= OPpLVREF_ELEM;
2742         o->op_flags   |= OPf_STACKED;
2743         break;
2744     case OP_ASLICE:
2745     case OP_HSLICE:
2746         OpTYPE_set(o, OP_LVREFSLICE);
2747         o->op_private &= OPpLVAL_INTRO;
2748         return;
2749     case OP_NULL:
2750         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2751             goto badref;
2752         else if (!(o->op_flags & OPf_KIDS))
2753             return;
2754         if (o->op_targ != OP_LIST) {
2755             S_lvref(aTHX_ cBINOPo->op_first, type);
2756             return;
2757         }
2758         /* FALLTHROUGH */
2759     case OP_LIST:
2760         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid)) {
2761             assert((kid->op_flags & OPf_WANT) != OPf_WANT_VOID);
2762             S_lvref(aTHX_ kid, type);
2763         }
2764         return;
2765     case OP_STUB:
2766         if (o->op_flags & OPf_PARENS)
2767             return;
2768         /* FALLTHROUGH */
2769     default:
2770       badref:
2771         /* diag_listed_as: Can't modify reference to %s in %s assignment */
2772         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
2773                      o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
2774                       ? "do block"
2775                       : OP_DESC(o),
2776                      PL_op_desc[type]));
2777     }
2778     OpTYPE_set(o, OP_LVREF);
2779     o->op_private &=
2780         OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
2781     if (type == OP_ENTERLOOP)
2782         o->op_private |= OPpLVREF_ITER;
2783 }
2784
2785 PERL_STATIC_INLINE bool
2786 S_potential_mod_type(I32 type)
2787 {
2788     /* Types that only potentially result in modification.  */
2789     return type == OP_GREPSTART || type == OP_ENTERSUB
2790         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
2791 }
2792
2793 OP *
2794 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
2795 {
2796     dVAR;
2797     OP *kid;
2798     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
2799     int localize = -1;
2800
2801     if (!o || (PL_parser && PL_parser->error_count))
2802         return o;
2803
2804     if ((o->op_private & OPpTARGET_MY)
2805         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2806     {
2807         return o;
2808     }
2809
2810     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
2811
2812     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
2813
2814     switch (o->op_type) {
2815     case OP_UNDEF:
2816         PL_modcount++;
2817         return o;
2818     case OP_STUB:
2819         if ((o->op_flags & OPf_PARENS))
2820             break;
2821         goto nomod;
2822     case OP_ENTERSUB:
2823         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
2824             !(o->op_flags & OPf_STACKED)) {
2825             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
2826             assert(cUNOPo->op_first->op_type == OP_NULL);
2827             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
2828             break;
2829         }
2830         else {                          /* lvalue subroutine call */
2831             o->op_private |= OPpLVAL_INTRO;
2832             PL_modcount = RETURN_UNLIMITED_NUMBER;
2833             if (S_potential_mod_type(type)) {
2834                 o->op_private |= OPpENTERSUB_INARGS;
2835                 break;
2836             }
2837             else {                      /* Compile-time error message: */
2838                 OP *kid = cUNOPo->op_first;
2839                 CV *cv;
2840                 GV *gv;
2841                 SV *namesv;
2842
2843                 if (kid->op_type != OP_PUSHMARK) {
2844                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
2845                         Perl_croak(aTHX_
2846                                 "panic: unexpected lvalue entersub "
2847                                 "args: type/targ %ld:%"UVuf,
2848                                 (long)kid->op_type, (UV)kid->op_targ);
2849                     kid = kLISTOP->op_first;
2850                 }
2851                 while (OpHAS_SIBLING(kid))
2852                     kid = OpSIBLING(kid);
2853                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2854                     break;      /* Postpone until runtime */
2855                 }
2856
2857                 kid = kUNOP->op_first;
2858                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2859                     kid = kUNOP->op_first;
2860                 if (kid->op_type == OP_NULL)
2861                     Perl_croak(aTHX_
2862                                "Unexpected constant lvalue entersub "
2863                                "entry via type/targ %ld:%"UVuf,
2864                                (long)kid->op_type, (UV)kid->op_targ);
2865                 if (kid->op_type != OP_GV) {
2866                     break;
2867                 }
2868
2869                 gv = kGVOP_gv;
2870                 cv = isGV(gv)
2871                     ? GvCV(gv)
2872                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
2873                         ? MUTABLE_CV(SvRV(gv))
2874                         : NULL;
2875                 if (!cv)
2876                     break;
2877                 if (CvLVALUE(cv))
2878                     break;
2879                 if (flags & OP_LVALUE_NO_CROAK)
2880                     return NULL;
2881
2882                 namesv = cv_name(cv, NULL, 0);
2883                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
2884                                      "subroutine call of &%"SVf" in %s",
2885                                      SVfARG(namesv), PL_op_desc[type]),
2886                            SvUTF8(namesv));
2887                 return o;
2888             }
2889         }
2890         /* FALLTHROUGH */
2891     default:
2892       nomod:
2893         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2894         /* grep, foreach, subcalls, refgen */
2895         if (S_potential_mod_type(type))
2896             break;
2897         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2898                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2899                       ? "do block"
2900                       : OP_DESC(o)),
2901                      type ? PL_op_desc[type] : "local"));
2902         return o;
2903
2904     case OP_PREINC:
2905     case OP_PREDEC:
2906     case OP_POW:
2907     case OP_MULTIPLY:
2908     case OP_DIVIDE:
2909     case OP_MODULO:
2910     case OP_ADD:
2911     case OP_SUBTRACT:
2912     case OP_CONCAT:
2913     case OP_LEFT_SHIFT:
2914     case OP_RIGHT_SHIFT:
2915     case OP_BIT_AND:
2916     case OP_BIT_XOR:
2917     case OP_BIT_OR:
2918     case OP_I_MULTIPLY:
2919     case OP_I_DIVIDE:
2920     case OP_I_MODULO:
2921     case OP_I_ADD:
2922     case OP_I_SUBTRACT:
2923         if (!(o->op_flags & OPf_STACKED))
2924             goto nomod;
2925         PL_modcount++;
2926         break;
2927
2928     case OP_REPEAT:
2929         if (o->op_flags & OPf_STACKED) {
2930             PL_modcount++;
2931             break;
2932         }
2933         if (!(o->op_private & OPpREPEAT_DOLIST))
2934             goto nomod;
2935         else {
2936             const I32 mods = PL_modcount;
2937             modkids(cBINOPo->op_first, type);
2938             if (type != OP_AASSIGN)
2939                 goto nomod;
2940             kid = cBINOPo->op_last;
2941             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
2942                 const IV iv = SvIV(kSVOP_sv);
2943                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
2944                     PL_modcount =
2945                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
2946             }
2947             else
2948                 PL_modcount = RETURN_UNLIMITED_NUMBER;
2949         }
2950         break;
2951
2952     case OP_COND_EXPR:
2953         localize = 1;
2954         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2955             op_lvalue(kid, type);
2956         break;
2957
2958     case OP_RV2AV:
2959     case OP_RV2HV:
2960         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2961            PL_modcount = RETURN_UNLIMITED_NUMBER;
2962             return o;           /* Treat \(@foo) like ordinary list. */
2963         }
2964         /* FALLTHROUGH */
2965     case OP_RV2GV:
2966         if (scalar_mod_type(o, type))
2967             goto nomod;
2968         ref(cUNOPo->op_first, o->op_type);
2969         /* FALLTHROUGH */
2970     case OP_ASLICE:
2971     case OP_HSLICE:
2972         localize = 1;
2973         /* FALLTHROUGH */
2974     case OP_AASSIGN:
2975         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
2976         if (type == OP_LEAVESUBLV && (
2977                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
2978              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2979            ))
2980             o->op_private |= OPpMAYBE_LVSUB;
2981         /* FALLTHROUGH */
2982     case OP_NEXTSTATE:
2983     case OP_DBSTATE:
2984        PL_modcount = RETURN_UNLIMITED_NUMBER;
2985         break;
2986     case OP_KVHSLICE:
2987     case OP_KVASLICE:
2988     case OP_AKEYS:
2989         if (type == OP_LEAVESUBLV)
2990             o->op_private |= OPpMAYBE_LVSUB;
2991         goto nomod;
2992     case OP_AVHVSWITCH:
2993         if (type == OP_LEAVESUBLV
2994          && (o->op_private & 3) + OP_EACH == OP_KEYS)
2995             o->op_private |= OPpMAYBE_LVSUB;
2996         goto nomod;
2997     case OP_AV2ARYLEN:
2998         PL_hints |= HINT_BLOCK_SCOPE;
2999         if (type == OP_LEAVESUBLV)
3000             o->op_private |= OPpMAYBE_LVSUB;
3001         PL_modcount++;
3002         break;
3003     case OP_RV2SV:
3004         ref(cUNOPo->op_first, o->op_type);
3005         localize = 1;
3006         /* FALLTHROUGH */
3007     case OP_GV:
3008         PL_hints |= HINT_BLOCK_SCOPE;
3009         /* FALLTHROUGH */
3010     case OP_SASSIGN:
3011     case OP_ANDASSIGN:
3012     case OP_ORASSIGN:
3013     case OP_DORASSIGN:
3014         PL_modcount++;
3015         break;
3016
3017     case OP_AELEMFAST:
3018     case OP_AELEMFAST_LEX:
3019         localize = -1;
3020         PL_modcount++;
3021         break;
3022
3023     case OP_PADAV:
3024     case OP_PADHV:
3025        PL_modcount = RETURN_UNLIMITED_NUMBER;
3026         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
3027             return o;           /* Treat \(@foo) like ordinary list. */
3028         if (scalar_mod_type(o, type))
3029             goto nomod;
3030         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
3031           && type == OP_LEAVESUBLV)
3032             o->op_private |= OPpMAYBE_LVSUB;
3033         /* FALLTHROUGH */
3034     case OP_PADSV:
3035         PL_modcount++;
3036         if (!type) /* local() */
3037             Perl_croak(aTHX_ "Can't localize lexical variable %"PNf,
3038                               PNfARG(PAD_COMPNAME(o->op_targ)));
3039         if (!(o->op_private & OPpLVAL_INTRO)
3040          || (  type != OP_SASSIGN && type != OP_AASSIGN
3041             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
3042             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
3043         break;
3044
3045     case OP_PUSHMARK:
3046         localize = 0;
3047         break;
3048
3049     case OP_KEYS:
3050         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
3051             goto nomod;
3052         goto lvalue_func;
3053     case OP_SUBSTR:
3054         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
3055             goto nomod;
3056         /* FALLTHROUGH */
3057     case OP_POS:
3058     case OP_VEC:
3059       lvalue_func:
3060         if (type == OP_LEAVESUBLV)
3061             o->op_private |= OPpMAYBE_LVSUB;
3062         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
3063             /* substr and vec */
3064             /* If this op is in merely potential (non-fatal) modifiable
3065                context, then apply OP_ENTERSUB context to
3066                the kid op (to avoid croaking).  Other-
3067                wise pass this op’s own type so the correct op is mentioned
3068                in error messages.  */
3069             op_lvalue(OpSIBLING(cBINOPo->op_first),
3070                       S_potential_mod_type(type)
3071                         ? (I32)OP_ENTERSUB
3072                         : o->op_type);
3073         }
3074         break;
3075
3076     case OP_AELEM:
3077     case OP_HELEM:
3078         ref(cBINOPo->op_first, o->op_type);
3079         if (type == OP_ENTERSUB &&
3080              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
3081             o->op_private |= OPpLVAL_DEFER;
3082         if (type == OP_LEAVESUBLV)
3083             o->op_private |= OPpMAYBE_LVSUB;
3084         localize = 1;
3085         PL_modcount++;
3086         break;
3087
3088     case OP_LEAVE:
3089     case OP_LEAVELOOP:
3090         o->op_private |= OPpLVALUE;
3091         /* FALLTHROUGH */
3092     case OP_SCOPE:
3093     case OP_ENTER:
3094     case OP_LINESEQ:
3095         localize = 0;
3096         if (o->op_flags & OPf_KIDS)
3097             op_lvalue(cLISTOPo->op_last, type);
3098         break;
3099
3100     case OP_NULL:
3101         localize = 0;
3102         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
3103             goto nomod;
3104         else if (!(o->op_flags & OPf_KIDS))
3105             break;
3106         if (o->op_targ != OP_LIST) {
3107             op_lvalue(cBINOPo->op_first, type);
3108             break;
3109         }
3110         /* FALLTHROUGH */
3111     case OP_LIST:
3112         localize = 0;
3113         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3114             /* elements might be in void context because the list is
3115                in scalar context or because they are attribute sub calls */
3116             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
3117                 op_lvalue(kid, type);
3118         break;
3119
3120     case OP_COREARGS:
3121         return o;
3122
3123     case OP_AND:
3124     case OP_OR:
3125         if (type == OP_LEAVESUBLV
3126          || !S_vivifies(cLOGOPo->op_first->op_type))
3127             op_lvalue(cLOGOPo->op_first, type);
3128         if (type == OP_LEAVESUBLV
3129          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
3130             op_lvalue(OpSIBLING(cLOGOPo->op_first), type);
3131         goto nomod;
3132
3133     case OP_SREFGEN:
3134         if (type != OP_AASSIGN && type != OP_SASSIGN
3135          && type != OP_ENTERLOOP)
3136             goto nomod;
3137         /* Don’t bother applying lvalue context to the ex-list.  */
3138         kid = cUNOPx(cUNOPo->op_first)->op_first;
3139         assert (!OpHAS_SIBLING(kid));
3140         goto kid_2lvref;
3141     case OP_REFGEN:
3142         if (type != OP_AASSIGN) goto nomod;
3143         kid = cUNOPo->op_first;
3144       kid_2lvref:
3145         {
3146             const U8 ec = PL_parser ? PL_parser->error_count : 0;
3147             S_lvref(aTHX_ kid, type);
3148             if (!PL_parser || PL_parser->error_count == ec) {
3149                 if (!FEATURE_REFALIASING_IS_ENABLED)
3150                     Perl_croak(aTHX_
3151                        "Experimental aliasing via reference not enabled");
3152                 Perl_ck_warner_d(aTHX_
3153                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
3154                                 "Aliasing via reference is experimental");
3155             }
3156         }
3157         if (o->op_type == OP_REFGEN)
3158             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
3159         op_null(o);
3160         return o;
3161
3162     case OP_SPLIT:
3163         kid = cLISTOPo->op_first;
3164         if (kid && kid->op_type == OP_PUSHRE &&
3165                 (  kid->op_targ
3166                 || o->op_flags & OPf_STACKED
3167 #ifdef USE_ITHREADS
3168                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
3169 #else
3170                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
3171 #endif
3172         )) {
3173             /* This is actually @array = split.  */
3174             PL_modcount = RETURN_UNLIMITED_NUMBER;
3175             break;
3176         }
3177         goto nomod;
3178
3179     case OP_SCALAR:
3180         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
3181         goto nomod;
3182     }
3183
3184     /* [20011101.069] File test operators interpret OPf_REF to mean that
3185        their argument is a filehandle; thus \stat(".") should not set
3186        it. AMS 20011102 */
3187     if (type == OP_REFGEN &&
3188         PL_check[o->op_type] == Perl_ck_ftst)
3189         return o;
3190
3191     if (type != OP_LEAVESUBLV)
3192         o->op_flags |= OPf_MOD;
3193
3194     if (type == OP_AASSIGN || type == OP_SASSIGN)
3195         o->op_flags |= OPf_SPECIAL|OPf_REF;
3196     else if (!type) { /* local() */
3197         switch (localize) {
3198         case 1:
3199             o->op_private |= OPpLVAL_INTRO;
3200             o->op_flags &= ~OPf_SPECIAL;
3201             PL_hints |= HINT_BLOCK_SCOPE;
3202             break;
3203         case 0:
3204             break;
3205         case -1:
3206             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
3207                            "Useless localization of %s", OP_DESC(o));
3208         }
3209     }
3210     else if (type != OP_GREPSTART && type != OP_ENTERSUB
3211              && type != OP_LEAVESUBLV)
3212         o->op_flags |= OPf_REF;
3213     return o;
3214 }
3215
3216 STATIC bool
3217 S_scalar_mod_type(const OP *o, I32 type)
3218 {
3219     switch (type) {
3220     case OP_POS:
3221     case OP_SASSIGN:
3222         if (o && o->op_type == OP_RV2GV)
3223             return FALSE;
3224         /* FALLTHROUGH */
3225     case OP_PREINC:
3226     case OP_PREDEC:
3227     case OP_POSTINC:
3228     case OP_POSTDEC:
3229     case OP_I_PREINC:
3230     case OP_I_PREDEC:
3231     case OP_I_POSTINC:
3232     case OP_I_POSTDEC:
3233     case OP_POW:
3234     case OP_MULTIPLY:
3235     case OP_DIVIDE:
3236     case OP_MODULO:
3237     case OP_REPEAT:
3238     case OP_ADD:
3239     case OP_SUBTRACT:
3240     case OP_I_MULTIPLY:
3241     case OP_I_DIVIDE:
3242     case OP_I_MODULO:
3243     case OP_I_ADD:
3244     case OP_I_SUBTRACT:
3245     case OP_LEFT_SHIFT:
3246     case OP_RIGHT_SHIFT:
3247     case OP_BIT_AND:
3248     case OP_BIT_XOR:
3249     case OP_BIT_OR:
3250     case OP_NBIT_AND:
3251     case OP_NBIT_XOR:
3252     case OP_NBIT_OR:
3253     case OP_SBIT_AND:
3254     case OP_SBIT_XOR:
3255     case OP_SBIT_OR:
3256     case OP_CONCAT:
3257     case OP_SUBST:
3258     case OP_TRANS:
3259     case OP_TRANSR:
3260     case OP_READ:
3261     case OP_SYSREAD:
3262     case OP_RECV:
3263     case OP_ANDASSIGN:
3264     case OP_ORASSIGN:
3265     case OP_DORASSIGN:
3266     case OP_VEC:
3267     case OP_SUBSTR:
3268         return TRUE;
3269     default:
3270         return FALSE;
3271     }
3272 }
3273
3274 STATIC bool
3275 S_is_handle_constructor(const OP *o, I32 numargs)
3276 {
3277     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
3278
3279     switch (o->op_type) {
3280     case OP_PIPE_OP:
3281     case OP_SOCKPAIR:
3282         if (numargs == 2)
3283             return TRUE;
3284         /* FALLTHROUGH */
3285     case OP_SYSOPEN:
3286     case OP_OPEN:
3287     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
3288     case OP_SOCKET:
3289     case OP_OPEN_DIR:
3290     case OP_ACCEPT:
3291         if (numargs == 1)
3292             return TRUE;
3293         /* FALLTHROUGH */
3294     default:
3295         return FALSE;
3296     }
3297 }
3298
3299 static OP *
3300 S_refkids(pTHX_ OP *o, I32 type)
3301 {
3302     if (o && o->op_flags & OPf_KIDS) {
3303         OP *kid;
3304         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3305             ref(kid, type);
3306     }
3307     return o;
3308 }
3309
3310 OP *
3311 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
3312 {
3313     dVAR;
3314     OP *kid;
3315
3316     PERL_ARGS_ASSERT_DOREF;
3317
3318     if (PL_parser && PL_parser->error_count)
3319         return o;
3320
3321     switch (o->op_type) {
3322     case OP_ENTERSUB:
3323         if ((type == OP_EXISTS || type == OP_DEFINED) &&
3324             !(o->op_flags & OPf_STACKED)) {
3325             OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
3326             assert(cUNOPo->op_first->op_type == OP_NULL);
3327             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
3328             o->op_flags |= OPf_SPECIAL;
3329         }
3330         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
3331             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3332                               : type == OP_RV2HV ? OPpDEREF_HV
3333                               : OPpDEREF_SV);
3334             o->op_flags |= OPf_MOD;
3335         }
3336
3337         break;
3338
3339     case OP_COND_EXPR:
3340         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
3341             doref(kid, type, set_op_ref);
3342         break;
3343     case OP_RV2SV:
3344         if (type == OP_DEFINED)
3345             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3346         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3347         /* FALLTHROUGH */
3348     case OP_PADSV:
3349         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3350             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3351                               : type == OP_RV2HV ? OPpDEREF_HV
3352                               : OPpDEREF_SV);
3353             o->op_flags |= OPf_MOD;
3354         }
3355         break;
3356
3357     case OP_RV2AV:
3358     case OP_RV2HV:
3359         if (set_op_ref)
3360             o->op_flags |= OPf_REF;
3361         /* FALLTHROUGH */
3362     case OP_RV2GV:
3363         if (type == OP_DEFINED)
3364             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3365         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3366         break;
3367
3368     case OP_PADAV:
3369     case OP_PADHV:
3370         if (set_op_ref)
3371             o->op_flags |= OPf_REF;
3372         break;
3373
3374     case OP_SCALAR:
3375     case OP_NULL:
3376         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
3377             break;
3378         doref(cBINOPo->op_first, type, set_op_ref);
3379         break;
3380     case OP_AELEM:
3381     case OP_HELEM:
3382         doref(cBINOPo->op_first, o->op_type, set_op_ref);
3383         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3384             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3385                               : type == OP_RV2HV ? OPpDEREF_HV
3386                               : OPpDEREF_SV);
3387             o->op_flags |= OPf_MOD;
3388         }
3389         break;
3390
3391     case OP_SCOPE:
3392     case OP_LEAVE:
3393         set_op_ref = FALSE;
3394         /* FALLTHROUGH */
3395     case OP_ENTER:
3396     case OP_LIST:
3397         if (!(o->op_flags & OPf_KIDS))
3398             break;
3399         doref(cLISTOPo->op_last, type, set_op_ref);
3400         break;
3401     default:
3402         break;
3403     }
3404     return scalar(o);
3405
3406 }
3407
3408 STATIC OP *
3409 S_dup_attrlist(pTHX_ OP *o)
3410 {
3411     OP *rop;
3412
3413     PERL_ARGS_ASSERT_DUP_ATTRLIST;
3414
3415     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
3416      * where the first kid is OP_PUSHMARK and the remaining ones
3417      * are OP_CONST.  We need to push the OP_CONST values.
3418      */
3419     if (o->op_type == OP_CONST)
3420         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
3421     else {
3422         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
3423         rop = NULL;
3424         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
3425             if (o->op_type == OP_CONST)
3426                 rop = op_append_elem(OP_LIST, rop,
3427                                   newSVOP(OP_CONST, o->op_flags,
3428                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
3429         }
3430     }
3431     return rop;
3432 }
3433
3434 STATIC void
3435 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
3436 {
3437     PERL_ARGS_ASSERT_APPLY_ATTRS;
3438     {
3439         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
3440
3441         /* fake up C<use attributes $pkg,$rv,@attrs> */
3442
3443 #define ATTRSMODULE "attributes"
3444 #define ATTRSMODULE_PM "attributes.pm"
3445
3446         Perl_load_module(
3447           aTHX_ PERL_LOADMOD_IMPORT_OPS,
3448           newSVpvs(ATTRSMODULE),
3449           NULL,
3450           op_prepend_elem(OP_LIST,
3451                           newSVOP(OP_CONST, 0, stashsv),
3452                           op_prepend_elem(OP_LIST,
3453                                           newSVOP(OP_CONST, 0,
3454                                                   newRV(target)),
3455                                           dup_attrlist(attrs))));
3456     }
3457 }
3458
3459 STATIC void
3460 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
3461 {
3462     OP *pack, *imop, *arg;
3463     SV *meth, *stashsv, **svp;
3464
3465     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
3466
3467     if (!attrs)
3468         return;
3469
3470     assert(target->op_type == OP_PADSV ||
3471            target->op_type == OP_PADHV ||
3472            target->op_type == OP_PADAV);
3473
3474     /* Ensure that attributes.pm is loaded. */
3475     /* Don't force the C<use> if we don't need it. */
3476     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
3477     if (svp && *svp != &PL_sv_undef)
3478         NOOP;   /* already in %INC */
3479     else
3480         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
3481                                newSVpvs(ATTRSMODULE), NULL);
3482
3483     /* Need package name for method call. */
3484     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
3485
3486     /* Build up the real arg-list. */
3487     stashsv = newSVhek(HvNAME_HEK(stash));
3488
3489     arg = newOP(OP_PADSV, 0);
3490     arg->op_targ = target->op_targ;
3491     arg = op_prepend_elem(OP_LIST,
3492                        newSVOP(OP_CONST, 0, stashsv),
3493                        op_prepend_elem(OP_LIST,
3494                                     newUNOP(OP_REFGEN, 0,
3495                                             arg),
3496                                     dup_attrlist(attrs)));
3497
3498     /* Fake up a method call to import */
3499     meth = newSVpvs_share("import");
3500     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
3501                    op_append_elem(OP_LIST,
3502                                op_prepend_elem(OP_LIST, pack, arg),
3503                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
3504
3505     /* Combine the ops. */
3506     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
3507 }
3508
3509 /*
3510 =notfor apidoc apply_attrs_string
3511
3512 Attempts to apply a list of attributes specified by the C<attrstr> and
3513 C<len> arguments to the subroutine identified by the C<cv> argument which
3514 is expected to be associated with the package identified by the C<stashpv>
3515 argument (see L<attributes>).  It gets this wrong, though, in that it
3516 does not correctly identify the boundaries of the individual attribute
3517 specifications within C<attrstr>.  This is not really intended for the
3518 public API, but has to be listed here for systems such as AIX which
3519 need an explicit export list for symbols.  (It's called from XS code
3520 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
3521 to respect attribute syntax properly would be welcome.
3522
3523 =cut
3524 */
3525
3526 void
3527 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
3528                         const char *attrstr, STRLEN len)
3529 {
3530     OP *attrs = NULL;
3531
3532     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
3533
3534     if (!len) {
3535         len = strlen(attrstr);
3536     }
3537
3538     while (len) {
3539         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
3540         if (len) {
3541             const char * const sstr = attrstr;
3542             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
3543             attrs = op_append_elem(OP_LIST, attrs,
3544                                 newSVOP(OP_CONST, 0,
3545                                         newSVpvn(sstr, attrstr-sstr)));
3546         }
3547     }
3548
3549     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3550                      newSVpvs(ATTRSMODULE),
3551                      NULL, op_prepend_elem(OP_LIST,
3552                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
3553                                   op_prepend_elem(OP_LIST,
3554                                                newSVOP(OP_CONST, 0,
3555                                                        newRV(MUTABLE_SV(cv))),
3556                                                attrs)));
3557 }
3558
3559 STATIC void
3560 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name)
3561 {
3562     OP *new_proto = NULL;
3563     STRLEN pvlen;
3564     char *pv;
3565     OP *o;
3566
3567     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
3568
3569     if (!*attrs)
3570         return;
3571
3572     o = *attrs;
3573     if (o->op_type == OP_CONST) {
3574         pv = SvPV(cSVOPo_sv, pvlen);
3575         if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3576             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3577             SV ** const tmpo = cSVOPx_svp(o);
3578             SvREFCNT_dec(cSVOPo_sv);
3579             *tmpo = tmpsv;
3580             new_proto = o;
3581             *attrs = NULL;
3582         }
3583     } else if (o->op_type == OP_LIST) {
3584         OP * lasto;
3585         assert(o->op_flags & OPf_KIDS);
3586         lasto = cLISTOPo->op_first;
3587         assert(lasto->op_type == OP_PUSHMARK);
3588         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
3589             if (o->op_type == OP_CONST) {
3590                 pv = SvPV(cSVOPo_sv, pvlen);
3591                 if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3592                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3593                     SV ** const tmpo = cSVOPx_svp(o);
3594                     SvREFCNT_dec(cSVOPo_sv);
3595                     *tmpo = tmpsv;
3596                     if (new_proto && ckWARN(WARN_MISC)) {
3597                         STRLEN new_len;
3598                         const char * newp = SvPV(cSVOPo_sv, new_len);
3599                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3600                             "Attribute prototype(%"UTF8f") discards earlier prototype attribute in same sub",
3601                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3602                         op_free(new_proto);
3603                     }
3604                     else if (new_proto)
3605                         op_free(new_proto);
3606                     new_proto = o;
3607                     /* excise new_proto from the list */
3608                     op_sibling_splice(*attrs, lasto, 1, NULL);
3609                     o = lasto;
3610                     continue;
3611                 }
3612             }
3613             lasto = o;
3614         }
3615         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3616            would get pulled in with no real need */
3617         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3618             op_free(*attrs);
3619             *attrs = NULL;
3620         }
3621     }
3622
3623     if (new_proto) {
3624         SV *svname;
3625         if (isGV(name)) {
3626             svname = sv_newmortal();
3627             gv_efullname3(svname, name, NULL);
3628         }
3629         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3630             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3631         else
3632             svname = (SV *)name;
3633         if (ckWARN(WARN_ILLEGALPROTO))
3634             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE);
3635         if (*proto && ckWARN(WARN_PROTOTYPE)) {
3636             STRLEN old_len, new_len;
3637             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3638             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3639
3640             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3641                 "Prototype '%"UTF8f"' overridden by attribute 'prototype(%"UTF8f")'"
3642                 " in %"SVf,
3643                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3644                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3645                 SVfARG(svname));
3646         }
3647         if (*proto)
3648             op_free(*proto);
3649         *proto = new_proto;
3650     }
3651 }
3652
3653 static void
3654 S_cant_declare(pTHX_ OP *o)
3655 {
3656     if (o->op_type == OP_NULL
3657      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
3658         o = cUNOPo->op_first;
3659     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
3660                              o->op_type == OP_NULL
3661                                && o->op_flags & OPf_SPECIAL
3662                                  ? "do block"
3663                                  : OP_DESC(o),
3664                              PL_parser->in_my == KEY_our   ? "our"   :
3665                              PL_parser->in_my == KEY_state ? "state" :
3666                                                              "my"));
3667 }
3668
3669 STATIC OP *
3670 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
3671 {
3672     I32 type;
3673     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
3674
3675     PERL_ARGS_ASSERT_MY_KID;
3676
3677     if (!o || (PL_parser && PL_parser->error_count))
3678         return o;
3679
3680     type = o->op_type;
3681
3682     if (type == OP_LIST) {
3683         OP *kid;
3684         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3685             my_kid(kid, attrs, imopsp);
3686         return o;
3687     } else if (type == OP_UNDEF || type == OP_STUB) {
3688         return o;
3689     } else if (type == OP_RV2SV ||      /* "our" declaration */
3690                type == OP_RV2AV ||
3691                type == OP_RV2HV) {
3692         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
3693             S_cant_declare(aTHX_ o);
3694         } else if (attrs) {
3695             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
3696             assert(PL_parser);
3697             PL_parser->in_my = FALSE;
3698             PL_parser->in_my_stash = NULL;
3699             apply_attrs(GvSTASH(gv),
3700                         (type == OP_RV2SV ? GvSV(gv) :
3701                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
3702                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
3703                         attrs);
3704         }
3705         o->op_private |= OPpOUR_INTRO;
3706         return o;
3707     }
3708     else if (type != OP_PADSV &&
3709              type != OP_PADAV &&
3710              type != OP_PADHV &&
3711              type != OP_PUSHMARK)
3712     {
3713         S_cant_declare(aTHX_ o);
3714         return o;
3715     }
3716     else if (attrs && type != OP_PUSHMARK) {
3717         HV *stash;
3718
3719         assert(PL_parser);
3720         PL_parser->in_my = FALSE;
3721         PL_parser->in_my_stash = NULL;
3722
3723         /* check for C<my Dog $spot> when deciding package */
3724         stash = PAD_COMPNAME_TYPE(o->op_targ);
3725         if (!stash)
3726             stash = PL_curstash;
3727         apply_attrs_my(stash, o, attrs, imopsp);
3728     }
3729     o->op_flags |= OPf_MOD;
3730     o->op_private |= OPpLVAL_INTRO;
3731     if (stately)
3732         o->op_private |= OPpPAD_STATE;
3733     return o;
3734 }
3735
3736 OP *
3737 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
3738 {
3739     OP *rops;
3740     int maybe_scalar = 0;
3741
3742     PERL_ARGS_ASSERT_MY_ATTRS;
3743
3744 /* [perl #17376]: this appears to be premature, and results in code such as
3745    C< our(%x); > executing in list mode rather than void mode */
3746 #if 0
3747     if (o->op_flags & OPf_PARENS)
3748         list(o);
3749     else
3750         maybe_scalar = 1;
3751 #else
3752     maybe_scalar = 1;
3753 #endif
3754     if (attrs)
3755         SAVEFREEOP(attrs);
3756     rops = NULL;
3757     o = my_kid(o, attrs, &rops);
3758     if (rops) {
3759         if (maybe_scalar && o->op_type == OP_PADSV) {
3760             o = scalar(op_append_list(OP_LIST, rops, o));
3761             o->op_private |= OPpLVAL_INTRO;
3762         }
3763         else {
3764             /* The listop in rops might have a pushmark at the beginning,
3765                which will mess up list assignment. */
3766             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
3767             if (rops->op_type == OP_LIST && 
3768                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
3769             {
3770                 OP * const pushmark = lrops->op_first;
3771                 /* excise pushmark */
3772                 op_sibling_splice(rops, NULL, 1, NULL);
3773                 op_free(pushmark);
3774             }
3775             o = op_append_list(OP_LIST, o, rops);
3776         }
3777     }
3778     PL_parser->in_my = FALSE;
3779     PL_parser->in_my_stash = NULL;
3780     return o;
3781 }
3782
3783 OP *
3784 Perl_sawparens(pTHX_ OP *o)
3785 {
3786     PERL_UNUSED_CONTEXT;
3787     if (o)
3788         o->op_flags |= OPf_PARENS;
3789     return o;
3790 }
3791
3792 OP *
3793 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
3794 {
3795     OP *o;
3796     bool ismatchop = 0;
3797     const OPCODE ltype = left->op_type;
3798     const OPCODE rtype = right->op_type;
3799
3800     PERL_ARGS_ASSERT_BIND_MATCH;
3801
3802     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
3803           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
3804     {
3805       const char * const desc
3806           = PL_op_desc[(
3807                           rtype == OP_SUBST || rtype == OP_TRANS
3808                        || rtype == OP_TRANSR
3809                        )
3810                        ? (int)rtype : OP_MATCH];
3811       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
3812       SV * const name =
3813         S_op_varname(aTHX_ left);
3814       if (name)
3815         Perl_warner(aTHX_ packWARN(WARN_MISC),
3816              "Applying %s to %"SVf" will act on scalar(%"SVf")",
3817              desc, SVfARG(name), SVfARG(name));
3818       else {
3819         const char * const sample = (isary
3820              ? "@array" : "%hash");
3821         Perl_warner(aTHX_ packWARN(WARN_MISC),
3822              "Applying %s to %s will act on scalar(%s)",
3823              desc, sample, sample);
3824       }
3825     }
3826
3827     if (rtype == OP_CONST &&
3828         cSVOPx(right)->op_private & OPpCONST_BARE &&
3829         cSVOPx(right)->op_private & OPpCONST_STRICT)
3830     {
3831         no_bareword_allowed(right);
3832     }
3833
3834     /* !~ doesn't make sense with /r, so error on it for now */
3835     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
3836         type == OP_NOT)
3837         /* diag_listed_as: Using !~ with %s doesn't make sense */
3838         yyerror("Using !~ with s///r doesn't make sense");
3839     if (rtype == OP_TRANSR && type == OP_NOT)
3840         /* diag_listed_as: Using !~ with %s doesn't make sense */
3841         yyerror("Using !~ with tr///r doesn't make sense");
3842
3843     ismatchop = (rtype == OP_MATCH ||
3844                  rtype == OP_SUBST ||
3845                  rtype == OP_TRANS || rtype == OP_TRANSR)
3846              && !(right->op_flags & OPf_SPECIAL);
3847     if (ismatchop && right->op_private & OPpTARGET_MY) {
3848         right->op_targ = 0;
3849         right->op_private &= ~OPpTARGET_MY;
3850     }
3851     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
3852         if (left->op_type == OP_PADSV
3853          && !(left->op_private & OPpLVAL_INTRO))
3854         {
3855             right->op_targ = left->op_targ;
3856             op_free(left);
3857             o = right;
3858         }
3859         else {
3860             right->op_flags |= OPf_STACKED;
3861             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
3862             ! (rtype == OP_TRANS &&
3863                right->op_private & OPpTRANS_IDENTICAL) &&
3864             ! (rtype == OP_SUBST &&
3865                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
3866                 left = op_lvalue(left, rtype);
3867             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
3868                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
3869             else
3870                 o = op_prepend_elem(rtype, scalar(left), right);
3871         }
3872         if (type == OP_NOT)
3873             return newUNOP(OP_NOT, 0, scalar(o));
3874         return o;
3875     }
3876     else
3877         return bind_match(type, left,
3878                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
3879 }
3880
3881 OP *
3882 Perl_invert(pTHX_ OP *o)
3883 {
3884     if (!o)
3885         return NULL;
3886     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
3887 }
3888
3889 /*
3890 =for apidoc Amx|OP *|op_scope|OP *o
3891
3892 Wraps up an op tree with some additional ops so that at runtime a dynamic
3893 scope will be created.  The original ops run in the new dynamic scope,
3894 and then, provided that they exit normally, the scope will be unwound.
3895 The additional ops used to create and unwind the dynamic scope will
3896 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
3897 instead if the ops are simple enough to not need the full dynamic scope
3898 structure.
3899
3900 =cut
3901 */
3902
3903 OP *
3904 Perl_op_scope(pTHX_ OP *o)
3905 {
3906     dVAR;
3907     if (o) {
3908         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
3909             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
3910             OpTYPE_set(o, OP_LEAVE);
3911         }
3912         else if (o->op_type == OP_LINESEQ) {
3913             OP *kid;
3914             OpTYPE_set(o, OP_SCOPE);
3915             kid = ((LISTOP*)o)->op_first;
3916             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3917                 op_null(kid);
3918
3919                 /* The following deals with things like 'do {1 for 1}' */
3920                 kid = OpSIBLING(kid);
3921                 if (kid &&
3922                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
3923                     op_null(kid);
3924             }
3925         }
3926         else
3927             o = newLISTOP(OP_SCOPE, 0, o, NULL);
3928     }
3929     return o;
3930 }
3931
3932 OP *
3933 Perl_op_unscope(pTHX_ OP *o)
3934 {
3935     if (o && o->op_type == OP_LINESEQ) {
3936         OP *kid = cLISTOPo->op_first;
3937         for(; kid; kid = OpSIBLING(kid))
3938             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
3939                 op_null(kid);
3940     }
3941     return o;
3942 }
3943
3944 /*
3945 =for apidoc Am|int|block_start|int full
3946
3947 Handles compile-time scope entry.
3948 Arranges for hints to be restored on block
3949 exit and also handles pad sequence numbers to make lexical variables scope
3950 right.  Returns a savestack index for use with C<block_end>.
3951
3952 =cut
3953 */
3954
3955 int
3956 Perl_block_start(pTHX_ int full)
3957 {
3958     const int retval = PL_savestack_ix;
3959
3960     PL_compiling.cop_seq = PL_cop_seqmax;
3961     COP_SEQMAX_INC;
3962     pad_block_start(full);
3963     SAVEHINTS();
3964     PL_hints &= ~HINT_BLOCK_SCOPE;
3965     SAVECOMPILEWARNINGS();
3966     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
3967     SAVEI32(PL_compiling.cop_seq);
3968     PL_compiling.cop_seq = 0;
3969
3970     CALL_BLOCK_HOOKS(bhk_start, full);
3971
3972     return retval;
3973 }
3974
3975 /*
3976 =for apidoc Am|OP *|block_end|I32 floor|OP *seq
3977
3978 Handles compile-time scope exit.  C<floor>
3979 is the savestack index returned by
3980 C<block_start>, and C<seq> is the body of the block.  Returns the block,
3981 possibly modified.
3982
3983 =cut
3984 */
3985
3986 OP*
3987 Perl_block_end(pTHX_ I32 floor, OP *seq)
3988 {
3989     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
3990     OP* retval = scalarseq(seq);
3991     OP *o;
3992
3993     /* XXX Is the null PL_parser check necessary here? */
3994     assert(PL_parser); /* Let’s find out under debugging builds.  */
3995     if (PL_parser && PL_parser->parsed_sub) {
3996         o = newSTATEOP(0, NULL, NULL);
3997         op_null(o);
3998         retval = op_append_elem(OP_LINESEQ, retval, o);
3999     }
4000
4001     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
4002
4003     LEAVE_SCOPE(floor);
4004     if (needblockscope)
4005         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
4006     o = pad_leavemy();
4007
4008     if (o) {
4009         /* pad_leavemy has created a sequence of introcv ops for all my
4010            subs declared in the block.  We have to replicate that list with
4011            clonecv ops, to deal with this situation:
4012
4013                sub {
4014                    my sub s1;
4015                    my sub s2;
4016                    sub s1 { state sub foo { \&s2 } }
4017                }->()
4018
4019            Originally, I was going to have introcv clone the CV and turn
4020            off the stale flag.  Since &s1 is declared before &s2, the
4021            introcv op for &s1 is executed (on sub entry) before the one for
4022            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
4023            cloned, since it is a state sub) closes over &s2 and expects
4024            to see it in its outer CV’s pad.  If the introcv op clones &s1,
4025            then &s2 is still marked stale.  Since &s1 is not active, and
4026            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
4027            ble will not stay shared’ warning.  Because it is the same stub
4028            that will be used when the introcv op for &s2 is executed, clos-
4029            ing over it is safe.  Hence, we have to turn off the stale flag
4030            on all lexical subs in the block before we clone any of them.
4031            Hence, having introcv clone the sub cannot work.  So we create a
4032            list of ops like this:
4033
4034                lineseq
4035                   |
4036                   +-- introcv
4037                   |
4038                   +-- introcv
4039                   |
4040                   +-- introcv
4041                   |
4042                   .
4043                   .
4044                   .
4045                   |
4046                   +-- clonecv
4047                   |
4048                   +-- clonecv
4049                   |
4050                   +-- clonecv
4051                   |
4052                   .
4053                   .
4054                   .
4055          */
4056         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
4057         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
4058         for (;; kid = OpSIBLING(kid)) {
4059             OP *newkid = newOP(OP_CLONECV, 0);
4060             newkid->op_targ = kid->op_targ;
4061             o = op_append_elem(OP_LINESEQ, o, newkid);
4062             if (kid == last) break;
4063         }
4064         retval = op_prepend_elem(OP_LINESEQ, o, retval);
4065     }
4066
4067     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
4068
4069     return retval;
4070 }
4071
4072 /*
4073 =head1 Compile-time scope hooks
4074
4075 =for apidoc Aox||blockhook_register
4076
4077 Register a set of hooks to be called when the Perl lexical scope changes
4078 at compile time.  See L<perlguts/"Compile-time scope hooks">.
4079
4080 =cut
4081 */
4082
4083 void
4084 Perl_blockhook_register(pTHX_ BHK *hk)
4085 {
4086     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
4087
4088     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
4089 }
4090
4091 void
4092 Perl_newPROG(pTHX_ OP *o)
4093 {
4094     PERL_ARGS_ASSERT_NEWPROG;
4095
4096     if (PL_in_eval) {
4097         PERL_CONTEXT *cx;
4098         I32 i;
4099         if (PL_eval_root)
4100                 return;
4101         PL_eval_root = newUNOP(OP_LEAVEEVAL,
4102                                ((PL_in_eval & EVAL_KEEPERR)
4103                                 ? OPf_SPECIAL : 0), o);
4104
4105         cx = CX_CUR();
4106         assert(CxTYPE(cx) == CXt_EVAL);
4107
4108         if ((cx->blk_gimme & G_WANT) == G_VOID)
4109             scalarvoid(PL_eval_root);
4110         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
4111             list(PL_eval_root);
4112         else
4113             scalar(PL_eval_root);
4114
4115         PL_eval_start = op_linklist(PL_eval_root);
4116         PL_eval_root->op_private |= OPpREFCOUNTED;
4117         OpREFCNT_set(PL_eval_root, 1);
4118         PL_eval_root->op_next = 0;
4119         i = PL_savestack_ix;
4120         SAVEFREEOP(o);
4121         ENTER;
4122         CALL_PEEP(PL_eval_start);
4123         finalize_optree(PL_eval_root);
4124         S_prune_chain_head(&PL_eval_start);
4125         LEAVE;
4126         PL_savestack_ix = i;
4127     }
4128     else {
4129         if (o->op_type == OP_STUB) {
4130             /* This block is entered if nothing is compiled for the main
4131                program. This will be the case for an genuinely empty main
4132                program, or one which only has BEGIN blocks etc, so already
4133                run and freed.
4134
4135                Historically (5.000) the guard above was !o. However, commit
4136                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
4137                c71fccf11fde0068, changed perly.y so that newPROG() is now
4138                called with the output of block_end(), which returns a new
4139                OP_STUB for the case of an empty optree. ByteLoader (and
4140                maybe other things) also take this path, because they set up
4141                PL_main_start and PL_main_root directly, without generating an
4142                optree.
4143
4144                If the parsing the main program aborts (due to parse errors,
4145                or due to BEGIN or similar calling exit), then newPROG()
4146                isn't even called, and hence this code path and its cleanups
4147                are skipped. This shouldn't make a make a difference:
4148                * a non-zero return from perl_parse is a failure, and
4149                  perl_destruct() should be called immediately.
4150                * however, if exit(0) is called during the parse, then
4151                  perl_parse() returns 0, and perl_run() is called. As
4152                  PL_main_start will be NULL, perl_run() will return
4153                  promptly, and the exit code will remain 0.
4154             */
4155
4156             PL_comppad_name = 0;
4157             PL_compcv = 0;
4158             S_op_destroy(aTHX_ o);
4159             return;
4160         }
4161         PL_main_root = op_scope(sawparens(scalarvoid(o)));
4162         PL_curcop = &PL_compiling;
4163         PL_main_start = LINKLIST(PL_main_root);
4164         PL_main_root->op_private |= OPpREFCOUNTED;
4165         OpREFCNT_set(PL_main_root, 1);
4166         PL_main_root->op_next = 0;
4167         CALL_PEEP(PL_main_start);
4168         finalize_optree(PL_main_root);
4169         S_prune_chain_head(&PL_main_start);
4170         cv_forget_slab(PL_compcv);
4171         PL_compcv = 0;
4172
4173         /* Register with debugger */
4174         if (PERLDB_INTER) {
4175             CV * const cv = get_cvs("DB::postponed", 0);
4176             if (cv) {
4177                 dSP;
4178                 PUSHMARK(SP);
4179                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4180                 PUTBACK;
4181                 call_sv(MUTABLE_SV(cv), G_DISCARD);
4182             }
4183         }
4184     }
4185 }
4186
4187 OP *
4188 Perl_localize(pTHX_ OP *o, I32 lex)
4189 {
4190     PERL_ARGS_ASSERT_LOCALIZE;
4191
4192     if (o->op_flags & OPf_PARENS)
4193 /* [perl #17376]: this appears to be premature, and results in code such as
4194    C< our(%x); > executing in list mode rather than void mode */
4195 #if 0
4196         list(o);
4197 #else
4198         NOOP;
4199 #endif
4200     else {
4201         if ( PL_parser->bufptr > PL_parser->oldbufptr
4202             && PL_parser->bufptr[-1] == ','
4203             && ckWARN(WARN_PARENTHESIS))
4204         {
4205             char *s = PL_parser->bufptr;
4206             bool sigil = FALSE;
4207
4208             /* some heuristics to detect a potential error */
4209             while (*s && (strchr(", \t\n", *s)))
4210                 s++;
4211
4212             while (1) {
4213                 if (*s && (strchr("@$%", *s) || (!lex && *s == '*'))
4214                        && *++s
4215                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
4216                     s++;
4217                     sigil = TRUE;
4218                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
4219                         s++;
4220                     while (*s && (strchr(", \t\n", *s)))
4221                         s++;
4222                 }
4223                 else
4224                     break;
4225             }
4226             if (sigil && (*s == ';' || *s == '=')) {
4227                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
4228                                 "Parentheses missing around \"%s\" list",
4229                                 lex
4230                                     ? (PL_parser->in_my == KEY_our
4231                                         ? "our"
4232                                         : PL_parser->in_my == KEY_state
4233                                             ? "state"
4234                                             : "my")
4235                                     : "local");
4236             }
4237         }
4238     }
4239     if (lex)
4240         o = my(o);
4241     else
4242         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
4243     PL_parser->in_my = FALSE;
4244     PL_parser->in_my_stash = NULL;
4245     return o;
4246 }
4247
4248 OP *
4249 Perl_jmaybe(pTHX_ OP *o)
4250 {
4251     PERL_ARGS_ASSERT_JMAYBE;
4252
4253     if (o->op_type == OP_LIST) {
4254         OP * const o2
4255             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
4256         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
4257     }
4258     return o;
4259 }
4260
4261 PERL_STATIC_INLINE OP *
4262 S_op_std_init(pTHX_ OP *o)
4263 {
4264     I32 type = o->op_type;
4265
4266     PERL_ARGS_ASSERT_OP_STD_INIT;
4267
4268     if (PL_opargs[type] & OA_RETSCALAR)
4269         scalar(o);
4270     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
4271         o->op_targ = pad_alloc(type, SVs_PADTMP);
4272
4273     return o;
4274 }
4275
4276 PERL_STATIC_INLINE OP *
4277 S_op_integerize(pTHX_ OP *o)
4278 {
4279     I32 type = o->op_type;
4280
4281     PERL_ARGS_ASSERT_OP_INTEGERIZE;
4282
4283     /* integerize op. */
4284     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
4285     {
4286         dVAR;
4287         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
4288     }
4289
4290     if (type == OP_NEGATE)
4291         /* XXX might want a ck_negate() for this */
4292         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
4293
4294     return o;
4295 }
4296
4297 static OP *
4298 S_fold_constants(pTHX_ OP *o)
4299 {
4300     dVAR;
4301     OP * VOL curop;
4302     OP *newop;
4303     VOL I32 type = o->op_type;
4304     bool is_stringify;
4305     SV * VOL sv = NULL;
4306     int ret = 0;
4307     OP *old_next;
4308     SV * const oldwarnhook = PL_warnhook;
4309     SV * const olddiehook  = PL_diehook;
4310     COP not_compiling;
4311     U8 oldwarn = PL_dowarn;
4312     I32 old_cxix;
4313     dJMPENV;
4314
4315     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
4316
4317     if (!(PL_opargs[type] & OA_FOLDCONST))
4318         goto nope;
4319
4320     switch (type) {
4321     case OP_UCFIRST:
4322     case OP_LCFIRST:
4323     case OP_UC:
4324     case OP_LC:
4325     case OP_FC:
4326 #ifdef USE_LOCALE_CTYPE
4327         if (IN_LC_COMPILETIME(LC_CTYPE))
4328             goto nope;
4329 #endif
4330         break;
4331     case OP_SLT:
4332     case OP_SGT:
4333     case OP_SLE:
4334     case OP_SGE:
4335     case OP_SCMP:
4336 #ifdef USE_LOCALE_COLLATE
4337         if (IN_LC_COMPILETIME(LC_COLLATE))
4338             goto nope;
4339 #endif
4340         break;
4341     case OP_SPRINTF:
4342         /* XXX what about the numeric ops? */
4343 #ifdef USE_LOCALE_NUMERIC
4344         if (IN_LC_COMPILETIME(LC_NUMERIC))
4345             goto nope;
4346 #endif
4347         break;
4348     case OP_PACK:
4349         if (!OpHAS_SIBLING(cLISTOPo->op_first)
4350           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
4351             goto nope;
4352         {
4353             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
4354             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
4355             {
4356                 const char *s = SvPVX_const(sv);
4357                 while (s < SvEND(sv)) {
4358                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
4359                     s++;
4360                 }
4361             }
4362         }
4363         break;
4364     case OP_REPEAT:
4365         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
4366         break;
4367     case OP_SREFGEN:
4368         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
4369          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
4370             goto nope;
4371     }
4372
4373     if (PL_parser && PL_parser->error_count)
4374         goto nope;              /* Don't try to run w/ errors */
4375
4376     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
4377         switch (curop->op_type) {
4378         case OP_CONST:
4379             if (   (curop->op_private & OPpCONST_BARE)
4380                 && (curop->op_private & OPpCONST_STRICT)) {
4381                 no_bareword_allowed(curop);
4382                 goto nope;
4383             }
4384             /* FALLTHROUGH */
4385         case OP_LIST:
4386         case OP_SCALAR:
4387         case OP_NULL:
4388         case OP_PUSHMARK:
4389             /* Foldable; move to next op in list */
4390             break;
4391
4392         default:
4393             /* No other op types are considered foldable */
4394             goto nope;
4395         }
4396     }
4397
4398     curop = LINKLIST(o);
4399     old_next = o->op_next;
4400     o->op_next = 0;
4401     PL_op = curop;
4402
4403     old_cxix = cxstack_ix;
4404     create_eval_scope(NULL, G_FAKINGEVAL);
4405
4406     /* Verify that we don't need to save it:  */
4407     assert(PL_curcop == &PL_compiling);
4408     StructCopy(&PL_compiling, &not_compiling, COP);
4409     PL_curcop = &not_compiling;
4410     /* The above ensures that we run with all the correct hints of the
4411        currently compiling COP, but that IN_PERL_RUNTIME is true. */
4412     assert(IN_PERL_RUNTIME);
4413     PL_warnhook = PERL_WARNHOOK_FATAL;
4414     PL_diehook  = NULL;
4415     JMPENV_PUSH(ret);
4416
4417     /* Effective $^W=1.  */
4418     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
4419         PL_dowarn |= G_WARN_ON;
4420
4421     switch (ret) {
4422     case 0:
4423         CALLRUNOPS(aTHX);
4424         sv = *(PL_stack_sp--);
4425         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
4426             pad_swipe(o->op_targ,  FALSE);
4427         }
4428         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
4429             SvREFCNT_inc_simple_void(sv);
4430             SvTEMP_off(sv);
4431         }
4432         else { assert(SvIMMORTAL(sv)); }
4433         break;
4434     case 3:
4435         /* Something tried to die.  Abandon constant folding.  */
4436         /* Pretend the error never happened.  */
4437         CLEAR_ERRSV();
4438         o->op_next = old_next;
4439         break;
4440     default:
4441         JMPENV_POP;
4442         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
4443         PL_warnhook = oldwarnhook;
4444         PL_diehook  = olddiehook;
4445         /* XXX note that this croak may fail as we've already blown away
4446          * the stack - eg any nested evals */
4447         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
4448     }
4449     JMPENV_POP;
4450     PL_dowarn   = oldwarn;
4451     PL_warnhook = oldwarnhook;
4452     PL_diehook  = olddiehook;
4453     PL_curcop = &PL_compiling;
4454
4455     /* if we croaked, depending on how we croaked the eval scope
4456      * may or may not have already been popped */
4457     if (cxstack_ix > old_cxix) {
4458         assert(cxstack_ix == old_cxix + 1);
4459         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
4460         delete_eval_scope();
4461     }
4462     if (ret)
4463         goto nope;
4464
4465     /* OP_STRINGIFY and constant folding are used to implement qq.
4466        Here the constant folding is an implementation detail that we
4467        want to hide.  If the stringify op is itself already marked
4468        folded, however, then it is actually a folded join.  */
4469     is_stringify = type == OP_STRINGIFY && !o->op_folded;
4470     op_free(o);
4471     assert(sv);
4472     if (is_stringify)
4473         SvPADTMP_off(sv);
4474     else if (!SvIMMORTAL(sv)) {
4475         SvPADTMP_on(sv);
4476         SvREADONLY_on(sv);
4477     }
4478     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
4479     if (!is_stringify) newop->op_folded = 1;
4480     return newop;
4481
4482  nope:
4483     return o;
4484 }
4485
4486 static OP *
4487 S_gen_constant_list(pTHX_ OP *o)
4488 {
4489     dVAR;
4490     OP *curop;
4491     const SSize_t oldtmps_floor = PL_tmps_floor;
4492     SV **svp;
4493     AV *av;
4494
4495     list(o);
4496     if (PL_parser && PL_parser->error_count)
4497         return o;               /* Don't attempt to run with errors */
4498
4499     curop = LINKLIST(o);
4500     o->op_next = 0;
4501     CALL_PEEP(curop);
4502     S_prune_chain_head(&curop);
4503     PL_op = curop;
4504     Perl_pp_pushmark(aTHX);
4505     CALLRUNOPS(aTHX);
4506     PL_op = curop;
4507     assert (!(curop->op_flags & OPf_SPECIAL));
4508     assert(curop->op_type == OP_RANGE);
4509     Perl_pp_anonlist(aTHX);
4510     PL_tmps_floor = oldtmps_floor;
4511
4512     OpTYPE_set(o, OP_RV2AV);
4513     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
4514     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
4515     o->op_opt = 0;              /* needs to be revisited in rpeep() */
4516     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
4517
4518     /* replace subtree with an OP_CONST */
4519     curop = ((UNOP*)o)->op_first;
4520     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
4521     op_free(curop);
4522
4523     if (AvFILLp(av) != -1)
4524         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
4525         {
4526             SvPADTMP_on(*svp);
4527             SvREADONLY_on(*svp);
4528         }
4529     LINKLIST(o);
4530     return list(o);
4531 }
4532
4533 /*
4534 =head1 Optree Manipulation Functions
4535 */
4536
4537 /* List constructors */
4538
4539 /*
4540 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
4541
4542 Append an item to the list of ops contained directly within a list-type
4543 op, returning the lengthened list.  C<first> is the list-type op,
4544 and C<last> is the op to append to the list.  C<optype> specifies the
4545 intended opcode for the list.  If C<first> is not already a list of the
4546 right type, it will be upgraded into one.  If either C<first> or C<last>
4547 is null, the other is returned unchanged.
4548
4549 =cut
4550 */
4551
4552 OP *
4553 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
4554 {
4555     if (!first)
4556         return last;
4557
4558     if (!last)
4559         return first;
4560
4561     if (first->op_type != (unsigned)type
4562         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
4563     {
4564         return newLISTOP(type, 0, first, last);
4565     }
4566
4567     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
4568     first->op_flags |= OPf_KIDS;
4569     return first;
4570 }
4571
4572 /*
4573 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
4574
4575 Concatenate the lists of ops contained directly within two list-type ops,
4576 returning the combined list.  C<first> and C<last> are the list-type ops
4577 to concatenate.  C<optype> specifies the intended opcode for the list.
4578 If either C<first> or C<last> is not already a list of the right type,
4579 it will be upgraded into one.  If either C<first> or C<last> is null,
4580 the other is returned unchanged.
4581
4582 =cut
4583 */
4584
4585 OP *
4586 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
4587 {
4588     if (!first)
4589         return last;
4590
4591     if (!last)
4592         return first;
4593
4594     if (first->op_type != (unsigned)type)
4595         return op_prepend_elem(type, first, last);
4596
4597     if (last->op_type != (unsigned)type)
4598         return op_append_elem(type, first, last);
4599
4600     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
4601     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
4602     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
4603     first->op_flags |= (last->op_flags & OPf_KIDS);
4604
4605     S_op_destroy(aTHX_ last);
4606
4607     return first;
4608 }
4609
4610 /*
4611 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
4612
4613 Prepend an item to the list of ops contained directly within a list-type
4614 op, returning the lengthened list.  C<first> is the op to prepend to the
4615 list, and C<last> is the list-type op.  C<optype> specifies the intended
4616 opcode for the list.  If C<last> is not already a list of the right type,
4617 it will be upgraded into one.  If either C<first> or C<last> is null,
4618 the other is returned unchanged.
4619
4620 =cut
4621 */
4622
4623 OP *
4624 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
4625 {
4626     if (!first)
4627         return last;
4628
4629     if (!last)
4630         return first;
4631
4632     if (last->op_type == (unsigned)type) {
4633         if (type == OP_LIST) {  /* already a PUSHMARK there */
4634             /* insert 'first' after pushmark */
4635             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
4636             if (!(first->op_flags & OPf_PARENS))
4637                 last->op_flags &= ~OPf_PARENS;
4638         }
4639         else
4640             op_sibling_splice(last, NULL, 0, first);
4641         last->op_flags |= OPf_KIDS;
4642         return last;
4643     }
4644
4645     return newLISTOP(type, 0, first, last);
4646 }
4647
4648 /*
4649 =for apidoc Am|OP *|op_convert_list|I32 type|I32 flags|OP *o
4650
4651 Converts C<o> into a list op if it is not one already, and then converts it
4652 into the specified C<type>, calling its check function, allocating a target if
4653 it needs one, and folding constants.
4654
4655 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
4656 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
4657 C<op_convert_list> to make it the right type.
4658
4659 =cut
4660 */
4661
4662 OP *
4663 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
4664 {
4665     dVAR;
4666     if (type < 0) type = -type, flags |= OPf_SPECIAL;
4667     if (!o || o->op_type != OP_LIST)
4668         o = force_list(o, 0);
4669     else
4670     {
4671         o->op_flags &= ~OPf_WANT;
4672         o->op_private &= ~OPpLVAL_INTRO;
4673     }
4674
4675     if (!(PL_opargs[type] & OA_MARK))
4676         op_null(cLISTOPo->op_first);
4677     else {
4678         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
4679         if (kid2 && kid2->op_type == OP_COREARGS) {
4680             op_null(cLISTOPo->op_first);
4681             kid2->op_private |= OPpCOREARGS_PUSHMARK;
4682         }
4683     }
4684
4685     OpTYPE_set(o, type);
4686     o->op_flags |= flags;
4687     if (flags & OPf_FOLDED)
4688         o->op_folded = 1;
4689
4690     o = CHECKOP(type, o);
4691     if (o->op_type != (unsigned)type)
4692         return o;
4693
4694     return fold_constants(op_integerize(op_std_init(o)));
4695 }
4696
4697 /* Constructors */
4698
4699
4700 /*
4701 =head1 Optree construction
4702
4703 =for apidoc Am|OP *|newNULLLIST
4704
4705 Constructs, checks, and returns a new C<stub> op, which represents an
4706 empty list expression.
4707
4708 =cut
4709 */
4710
4711 OP *
4712 Perl_newNULLLIST(pTHX)
4713 {
4714     return newOP(OP_STUB, 0);
4715 }
4716
4717 /* promote o and any siblings to be a list if its not already; i.e.
4718  *
4719  *  o - A - B
4720  *
4721  * becomes
4722  *
4723  *  list
4724  *    |
4725  *  pushmark - o - A - B
4726  *
4727  * If nullit it true, the list op is nulled.
4728  */
4729
4730 static OP *
4731 S_force_list(pTHX_ OP *o, bool nullit)
4732 {
4733     if (!o || o->op_type != OP_LIST) {
4734         OP *rest = NULL;
4735         if (o) {
4736             /* manually detach any siblings then add them back later */
4737             rest = OpSIBLING(o);
4738             OpLASTSIB_set(o, NULL);
4739         }
4740         o = newLISTOP(OP_LIST, 0, o, NULL);
4741         if (rest)
4742             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
4743     }
4744     if (nullit)
4745         op_null(o);
4746     return o;
4747 }
4748
4749 /*
4750 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
4751
4752 Constructs, checks, and returns an op of any list type.  C<type> is
4753 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
4754 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
4755 supply up to two ops to be direct children of the list op; they are
4756 consumed by this function and become part of the constructed op tree.
4757
4758 For most list operators, the check function expects all the kid ops to be
4759 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
4760 appropriate.  What you want to do in that case is create an op of type
4761 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
4762 See L</op_convert_list> for more information.
4763
4764
4765 =cut
4766 */
4767
4768 OP *
4769 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4770 {
4771     dVAR;
4772     LISTOP *listop;
4773
4774     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
4775         || type == OP_CUSTOM);
4776
4777     NewOp(1101, listop, 1, LISTOP);
4778
4779     OpTYPE_set(listop, type);
4780     if (first || last)
4781         flags |= OPf_KIDS;
4782     listop->op_flags = (U8)flags;
4783
4784     if (!last && first)
4785         last = first;
4786     else if (!first && last)
4787         first = last;
4788     else if (first)
4789         OpMORESIB_set(first, last);
4790     listop->op_first = first;
4791     listop->op_last = last;
4792     if (type == OP_LIST) {
4793         OP* const pushop = newOP(OP_PUSHMARK, 0);
4794         OpMORESIB_set(pushop, first);
4795         listop->op_first = pushop;
4796         listop->op_flags |= OPf_KIDS;
4797         if (!last)
4798             listop->op_last = pushop;
4799     }
4800     if (listop->op_last)
4801         OpLASTSIB_set(listop->op_last, (OP*)listop);
4802
4803     return CHECKOP(type, listop);
4804 }
4805
4806 /*
4807 =for apidoc Am|OP *|newOP|I32 type|I32 flags
4808
4809 Constructs, checks, and returns an op of any base type (any type that
4810 has no extra fields).  C<type> is the opcode.  C<flags> gives the
4811 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
4812 of C<op_private>.
4813
4814 =cut
4815 */
4816
4817 OP *
4818 Perl_newOP(pTHX_ I32 type, I32 flags)
4819 {
4820     dVAR;
4821     OP *o;
4822
4823     if (type == -OP_ENTEREVAL) {
4824         type = OP_ENTEREVAL;
4825         flags |= OPpEVAL_BYTES<<8;
4826     }
4827
4828     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
4829         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4830         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4831         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
4832
4833     NewOp(1101, o, 1, OP);
4834     OpTYPE_set(o, type);
4835     o->op_flags = (U8)flags;
4836
4837     o->op_next = o;
4838     o->op_private = (U8)(0 | (flags >> 8));
4839     if (PL_opargs[type] & OA_RETSCALAR)
4840         scalar(o);
4841     if (PL_opargs[type] & OA_TARGET)
4842         o->op_targ = pad_alloc(type, SVs_PADTMP);
4843     return CHECKOP(type, o);
4844 }
4845
4846 /*
4847 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
4848
4849 Constructs, checks, and returns an op of any unary type.  C<type> is
4850 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
4851 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
4852 bits, the eight bits of C<op_private>, except that the bit with value 1
4853 is automatically set.  C<first> supplies an optional op to be the direct
4854 child of the unary op; it is consumed by this function and become part
4855 of the constructed op tree.
4856
4857 =cut
4858 */
4859
4860 OP *
4861 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
4862 {
4863     dVAR;
4864     UNOP *unop;
4865
4866     if (type == -OP_ENTEREVAL) {
4867         type = OP_ENTEREVAL;
4868         flags |= OPpEVAL_BYTES<<8;
4869     }
4870
4871     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
4872         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4873         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4874         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
4875         || type == OP_SASSIGN
4876         || type == OP_ENTERTRY
4877         || type == OP_CUSTOM
4878         || type == OP_NULL );
4879
4880     if (!first)
4881         first = newOP(OP_STUB, 0);
4882     if (PL_opargs[type] & OA_MARK)
4883         first = force_list(first, 1);
4884
4885     NewOp(1101, unop, 1, UNOP);
4886     OpTYPE_set(unop, type);
4887     unop->op_first = first;
4888     unop->op_flags = (U8)(flags | OPf_KIDS);
4889     unop->op_private = (U8)(1 | (flags >> 8));
4890
4891     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
4892         OpLASTSIB_set(first, (OP*)unop);
4893
4894     unop = (UNOP*) CHECKOP(type, unop);
4895     if (unop->op_next)
4896         return (OP*)unop;
4897
4898     return fold_constants(op_integerize(op_std_init((OP *) unop)));
4899 }
4900
4901 /*
4902 =for apidoc newUNOP_AUX
4903
4904 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
4905 initialised to C<aux>
4906
4907 =cut
4908 */
4909
4910 OP *
4911 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
4912 {
4913     dVAR;
4914     UNOP_AUX *unop;
4915
4916     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
4917         || type == OP_CUSTOM);
4918
4919     NewOp(1101, unop, 1, UNOP_AUX);
4920     unop->op_type = (OPCODE)type;
4921     unop->op_ppaddr = PL_ppaddr[type];
4922     unop->op_first = first;
4923     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
4924     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
4925     unop->op_aux = aux;
4926
4927     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
4928         OpLASTSIB_set(first, (OP*)unop);
4929
4930     unop = (UNOP_AUX*) CHECKOP(type, unop);
4931
4932     return op_std_init((OP *) unop);
4933 }
4934
4935 /*
4936 =for apidoc Am|OP *|newMETHOP|I32 type|I32 flags|OP *first
4937
4938 Constructs, checks, and returns an op of method type with a method name
4939 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
4940 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
4941 and, shifted up eight bits, the eight bits of C<op_private>, except that
4942 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
4943 op which evaluates method name; it is consumed by this function and
4944 become part of the constructed op tree.
4945 Supported optypes: C<OP_METHOD>.
4946
4947 =cut
4948 */
4949
4950 static OP*
4951 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
4952     dVAR;
4953     METHOP *methop;
4954
4955     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
4956         || type == OP_CUSTOM);
4957
4958     NewOp(1101, methop, 1, METHOP);
4959     if (dynamic_meth) {
4960         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
4961         methop->op_flags = (U8)(flags | OPf_KIDS);
4962         methop->op_u.op_first = dynamic_meth;
4963         methop->op_private = (U8)(1 | (flags >> 8));
4964
4965         if (!OpHAS_SIBLING(dynamic_meth))
4966             OpLASTSIB_set(dynamic_meth, (OP*)methop);
4967     }
4968     else {
4969         assert(const_meth);
4970         methop->op_flags = (U8)(flags & ~OPf_KIDS);
4971         methop->op_u.op_meth_sv = const_meth;
4972         methop->op_private = (U8)(0 | (flags >> 8));
4973         methop->op_next = (OP*)methop;
4974     }
4975
4976 #ifdef USE_ITHREADS
4977     methop->op_rclass_targ = 0;
4978 #else
4979     methop->op_rclass_sv = NULL;
4980 #endif
4981
4982     OpTYPE_set(methop, type);
4983     return CHECKOP(type, methop);
4984 }
4985
4986 OP *
4987 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
4988     PERL_ARGS_ASSERT_NEWMETHOP;
4989     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
4990 }
4991
4992 /*
4993 =for apidoc Am|OP *|newMETHOP_named|I32 type|I32 flags|SV *const_meth
4994
4995 Constructs, checks, and returns an op of method type with a constant
4996 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
4997 C<op_flags>, and, shifted up eight bits, the eight bits of
4998 C<op_private>.  C<const_meth> supplies a constant method name;
4999 it must be a shared COW string.
5000 Supported optypes: C<OP_METHOD_NAMED>.
5001
5002 =cut
5003 */
5004
5005 OP *
5006 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
5007     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
5008     return newMETHOP_internal(type, flags, NULL, const_meth);
5009 }
5010
5011 /*
5012 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
5013
5014 Constructs, checks, and returns an op of any binary type.  C<type>
5015 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
5016 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
5017 the eight bits of C<op_private>, except that the bit with value 1 or
5018 2 is automatically set as required.  C<first> and C<last> supply up to
5019 two ops to be the direct children of the binary op; they are consumed
5020 by this function and become part of the constructed op tree.
5021
5022 =cut
5023 */
5024
5025 OP *
5026 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
5027 {
5028     dVAR;
5029     BINOP *binop;
5030
5031     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
5032         || type == OP_SASSIGN || type == OP_NULL || type == OP_CUSTOM);
5033
5034     NewOp(1101, binop, 1, BINOP);
5035
5036     if (!first)
5037         first = newOP(OP_NULL, 0);
5038
5039     OpTYPE_set(binop, type);
5040     binop->op_first = first;
5041     binop->op_flags = (U8)(flags | OPf_KIDS);
5042     if (!last) {
5043         last = first;
5044         binop->op_private = (U8)(1 | (flags >> 8));
5045     }
5046     else {
5047         binop->op_private = (U8)(2 | (flags >> 8));
5048         OpMORESIB_set(first, last);
5049     }
5050
5051     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
5052         OpLASTSIB_set(last, (OP*)binop);
5053
5054     binop->op_last = OpSIBLING(binop->op_first);
5055     if (binop->op_last)
5056         OpLASTSIB_set(binop->op_last, (OP*)binop);
5057
5058     binop = (BINOP*)CHECKOP(type, binop);
5059     if (binop->op_next || binop->op_type != (OPCODE)type)
5060         return (OP*)binop;
5061
5062     return fold_constants(op_integerize(op_std_init((OP *)binop)));
5063 }
5064
5065 static int uvcompare(const void *a, const void *b)
5066     __attribute__nonnull__(1)
5067     __attribute__nonnull__(2)
5068     __attribute__pure__;
5069 static int uvcompare(const void *a, const void *b)
5070 {
5071     if (*((const UV *)a) < (*(const UV *)b))
5072         return -1;
5073     if (*((const UV *)a) > (*(const UV *)b))
5074         return 1;
5075     if (*((const UV *)a+1) < (*(const UV *)b+1))
5076         return -1;
5077     if (*((const UV *)a+1) > (*(const UV *)b+1))
5078         return 1;
5079     return 0;
5080 }
5081
5082 static OP *
5083 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
5084 {
5085     SV * const tstr = ((SVOP*)expr)->op_sv;
5086     SV * const rstr =
5087                               ((SVOP*)repl)->op_sv;
5088     STRLEN tlen;
5089     STRLEN rlen;
5090     const U8 *t = (U8*)SvPV_const(tstr, tlen);
5091     const U8 *r = (U8*)SvPV_const(rstr, rlen);
5092     I32 i;
5093     I32 j;
5094     I32 grows = 0;
5095     short *tbl;
5096
5097     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
5098     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
5099     I32 del              = o->op_private & OPpTRANS_DELETE;
5100     SV* swash;
5101
5102     PERL_ARGS_ASSERT_PMTRANS;
5103
5104     PL_hints |= HINT_BLOCK_SCOPE;
5105
5106     if (SvUTF8(tstr))
5107         o->op_private |= OPpTRANS_FROM_UTF;
5108
5109     if (SvUTF8(rstr))
5110         o->op_private |= OPpTRANS_TO_UTF;
5111
5112     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
5113         SV* const listsv = newSVpvs("# comment\n");
5114         SV* transv = NULL;
5115         const U8* tend = t + tlen;
5116         const U8* rend = r + rlen;
5117         STRLEN ulen;
5118         UV tfirst = 1;
5119         UV tlast = 0;
5120         IV tdiff;
5121         STRLEN tcount = 0;
5122         UV rfirst = 1;
5123         UV rlast = 0;
5124         IV rdiff;
5125         STRLEN rcount = 0;
5126         IV diff;
5127         I32 none = 0;
5128         U32 max = 0;
5129         I32 bits;
5130         I32 havefinal = 0;
5131         U32 final = 0;
5132         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
5133         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
5134         U8* tsave = NULL;
5135         U8* rsave = NULL;
5136         const U32 flags = UTF8_ALLOW_DEFAULT;
5137
5138         if (!from_utf) {
5139             STRLEN len = tlen;
5140             t = tsave = bytes_to_utf8(t, &len);
5141             tend = t + len;
5142         }
5143         if (!to_utf && rlen) {
5144             STRLEN len = rlen;
5145             r = rsave = bytes_to_utf8(r, &len);
5146             rend = r + len;
5147         }
5148
5149 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
5150  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
5151  * odd.  */
5152
5153         if (complement) {
5154             U8 tmpbuf[UTF8_MAXBYTES+1];
5155             UV *cp;
5156             UV nextmin = 0;
5157             Newx(cp, 2*tlen, UV);
5158             i = 0;
5159             transv = newSVpvs("");
5160             while (t < tend) {
5161                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5162                 t += ulen;
5163                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
5164                     t++;
5165                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5166                     t += ulen;
5167                 }
5168                 else {
5169                  cp[2*i+1] = cp[2*i];
5170                 }
5171                 i++;
5172             }
5173             qsort(cp, i, 2*sizeof(UV), uvcompare);
5174             for (j = 0; j < i; j++) {
5175                 UV  val = cp[2*j];
5176                 diff = val - nextmin;
5177                 if (diff > 0) {
5178                     t = uvchr_to_utf8(tmpbuf,nextmin);
5179                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5180                     if (diff > 1) {
5181                         U8  range_mark = ILLEGAL_UTF8_BYTE;
5182                         t = uvchr_to_utf8(tmpbuf, val - 1);
5183                         sv_catpvn(transv, (char *)&range_mark, 1);
5184                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5185                     }
5186                 }
5187                 val = cp[2*j+1];
5188                 if (val >= nextmin)
5189                     nextmin = val + 1;
5190             }
5191             t = uvchr_to_utf8(tmpbuf,nextmin);
5192             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5193             {
5194                 U8 range_mark = ILLEGAL_UTF8_BYTE;
5195                 sv_catpvn(transv, (char *)&range_mark, 1);
5196             }
5197             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
5198             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5199             t = (const U8*)SvPVX_const(transv);
5200             tlen = SvCUR(transv);
5201             tend = t + tlen;
5202             Safefree(cp);
5203         }
5204         else if (!rlen && !del) {
5205             r = t; rlen = tlen; rend = tend;
5206         }
5207         if (!squash) {
5208                 if ((!rlen && !del) || t == r ||
5209                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
5210                 {
5211                     o->op_private |= OPpTRANS_IDENTICAL;
5212                 }
5213         }
5214
5215         while (t < tend || tfirst <= tlast) {
5216             /* see if we need more "t" chars */
5217             if (tfirst > tlast) {
5218                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5219                 t += ulen;
5220                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
5221                     t++;
5222                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5223                     t += ulen;
5224                 }
5225                 else
5226                     tlast = tfirst;
5227             }
5228
5229             /* now see if we need more "r" chars */
5230             if (rfirst > rlast) {
5231                 if (r < rend) {
5232                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5233                     r += ulen;
5234                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
5235                         r++;
5236                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5237                         r += ulen;
5238                     }
5239                     else
5240                         rlast = rfirst;
5241                 }
5242                 else {
5243                     if (!havefinal++)
5244                         final = rlast;
5245                     rfirst = rlast = 0xffffffff;
5246                 }
5247             }
5248
5249             /* now see which range will peter out first, if either. */
5250             tdiff = tlast - tfirst;
5251             rdiff = rlast - rfirst;
5252             tcount += tdiff + 1;
5253             rcount += rdiff + 1;
5254
5255             if (tdiff <= rdiff)
5256                 diff = tdiff;
5257             else
5258                 diff = rdiff;
5259
5260             if (rfirst == 0xffffffff) {
5261                 diff = tdiff;   /* oops, pretend rdiff is infinite */
5262                 if (diff > 0)
5263                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
5264                                    (long)tfirst, (long)tlast);
5265                 else
5266                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
5267             }
5268             else {
5269                 if (diff > 0)
5270                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
5271                                    (long)tfirst, (long)(tfirst + diff),
5272                                    (long)rfirst);
5273                 else
5274                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
5275                                    (long)tfirst, (long)rfirst);
5276
5277                 if (rfirst + diff > max)
5278                     max = rfirst + diff;
5279                 if (!grows)
5280                     grows = (tfirst < rfirst &&
5281                              UVCHR_SKIP(tfirst) < UVCHR_SKIP(rfirst + diff));
5282                 rfirst += diff + 1;
5283             }
5284             tfirst += diff + 1;
5285         }
5286
5287         none = ++max;
5288         if (del)
5289             del = ++max;
5290
5291         if (max > 0xffff)
5292             bits = 32;
5293         else if (max > 0xff)
5294             bits = 16;
5295         else
5296             bits = 8;
5297
5298         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
5299 #ifdef USE_ITHREADS
5300         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
5301         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
5302         PAD_SETSV(cPADOPo->op_padix, swash);
5303         SvPADTMP_on(swash);
5304         SvREADONLY_on(swash);
5305 #else
5306         cSVOPo->op_sv = swash;
5307 #endif
5308         SvREFCNT_dec(listsv);
5309         SvREFCNT_dec(transv);
5310
5311         if (!del && havefinal && rlen)
5312             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
5313                            newSVuv((UV)final), 0);
5314
5315         Safefree(tsave);
5316         Safefree(rsave);
5317
5318         tlen = tcount;
5319         rlen = rcount;
5320         if (r < rend)
5321             rlen++;
5322         else if (rlast == 0xffffffff)
5323             rlen = 0;
5324
5325         goto warnins;
5326     }
5327
5328     tbl = (short*)PerlMemShared_calloc(
5329         (o->op_private & OPpTRANS_COMPLEMENT) &&
5330             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
5331         sizeof(short));
5332     cPVOPo->op_pv = (char*)tbl;
5333     if (complement) {
5334         for (i = 0; i < (I32)tlen; i++)
5335             tbl[t[i]] = -1;
5336         for (i = 0, j = 0; i < 256; i++) {
5337             if (!tbl[i]) {
5338                 if (j >= (I32)rlen) {
5339                     if (del)
5340                         tbl[i] = -2;
5341                     else if (rlen)
5342                         tbl[i] = r[j-1];
5343                     else
5344                         tbl[i] = (short)i;
5345                 }
5346                 else {
5347                     if (i < 128 && r[j] >= 128)
5348                         grows = 1;
5349                     tbl[i] = r[j++];
5350                 }
5351             }
5352         }
5353         if (!del) {
5354             if (!rlen) {
5355                 j = rlen;
5356                 if (!squash)
5357                     o->op_private |= OPpTRANS_IDENTICAL;
5358             }
5359             else if (j >= (I32)rlen)
5360                 j = rlen - 1;
5361             else {
5362                 tbl = 
5363                     (short *)
5364                     PerlMemShared_realloc(tbl,
5365                                           (0x101+rlen-j) * sizeof(short));
5366                 cPVOPo->op_pv = (char*)tbl;
5367             }
5368             tbl[0x100] = (short)(rlen - j);
5369             for (i=0; i < (I32)rlen - j; i++)
5370                 tbl[0x101+i] = r[j+i];
5371         }
5372     }
5373     else {
5374         if (!rlen && !del) {
5375             r = t; rlen = tlen;
5376             if (!squash)
5377                 o->op_private |= OPpTRANS_IDENTICAL;
5378         }
5379         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
5380             o->op_private |= OPpTRANS_IDENTICAL;
5381         }
5382         for (i = 0; i < 256; i++)
5383             tbl[i] = -1;
5384         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
5385             if (j >= (I32)rlen) {
5386                 if (del) {
5387                     if (tbl[t[i]] == -1)
5388                         tbl[t[i]] = -2;
5389                     continue;
5390                 }
5391                 --j;
5392             }
5393             if (tbl[t[i]] == -1) {
5394                 if (t[i] < 128 && r[j] >= 128)
5395                     grows = 1;
5396                 tbl[t[i]] = r[j];
5397             }
5398         }
5399     }
5400
5401   warnins:
5402     if(del && rlen == tlen) {
5403         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
5404     } else if(rlen > tlen && !complement) {
5405         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
5406     }
5407
5408     if (grows)
5409         o->op_private |= OPpTRANS_GROWS;
5410     op_free(expr);
5411     op_free(repl);
5412
5413     return o;
5414 }
5415
5416 /*
5417 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
5418
5419 Constructs, checks, and returns an op of any pattern matching type.
5420 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
5421 and, shifted up eight bits, the eight bits of C<op_private>.
5422
5423 =cut
5424 */
5425
5426 OP *
5427 Perl_newPMOP(pTHX_ I32 type, I32 flags)
5428 {
5429     dVAR;
5430     PMOP *pmop;
5431
5432     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
5433         || type == OP_CUSTOM);
5434
5435     NewOp(1101, pmop, 1, PMOP);
5436     OpTYPE_set(pmop, type);
5437     pmop->op_flags = (U8)flags;
5438     pmop->op_private = (U8)(0 | (flags >> 8));
5439     if (PL_opargs[type] & OA_RETSCALAR)
5440         scalar((OP *)pmop);
5441
5442     if (PL_hints & HINT_RE_TAINT)
5443         pmop->op_pmflags |= PMf_RETAINT;
5444 #ifdef USE_LOCALE_CTYPE
5445     if (IN_LC_COMPILETIME(LC_CTYPE)) {
5446         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
5447     }
5448     else
5449 #endif
5450          if (IN_UNI_8_BIT) {
5451         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
5452     }
5453     if (PL_hints & HINT_RE_FLAGS) {
5454         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5455          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
5456         );
5457         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
5458         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5459          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
5460         );
5461         if (reflags && SvOK(reflags)) {
5462             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
5463         }
5464     }
5465
5466
5467 #ifdef USE_ITHREADS
5468     assert(SvPOK(PL_regex_pad[0]));
5469     if (SvCUR(PL_regex_pad[0])) {
5470         /* Pop off the "packed" IV from the end.  */
5471         SV *const repointer_list = PL_regex_pad[0];
5472         const char *p = SvEND(repointer_list) - sizeof(IV);
5473         const IV offset = *((IV*)p);
5474
5475         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
5476
5477         SvEND_set(repointer_list, p);
5478
5479         pmop->op_pmoffset = offset;
5480         /* This slot should be free, so assert this:  */
5481         assert(PL_regex_pad[offset] == &PL_sv_undef);
5482     } else {
5483         SV * const repointer = &PL_sv_undef;
5484         av_push(PL_regex_padav, repointer);
5485         pmop->op_pmoffset = av_tindex(PL_regex_padav);
5486         PL_regex_pad = AvARRAY(PL_regex_padav);
5487     }
5488 #endif
5489
5490     return CHECKOP(type, pmop);
5491 }
5492
5493 static void
5494 S_set_haseval(pTHX)
5495 {
5496     PADOFFSET i = 1;
5497     PL_cv_has_eval = 1;
5498     /* Any pad names in scope are potentially lvalues.  */
5499     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
5500         PADNAME *pn = PAD_COMPNAME_SV(i);
5501         if (!pn || !PadnameLEN(pn))
5502             continue;
5503         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
5504             S_mark_padname_lvalue(aTHX_ pn);
5505     }
5506 }
5507
5508 /* Given some sort of match op o, and an expression expr containing a
5509  * pattern, either compile expr into a regex and attach it to o (if it's
5510  * constant), or convert expr into a runtime regcomp op sequence (if it's
5511  * not)
5512  *
5513  * isreg indicates that the pattern is part of a regex construct, eg
5514  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
5515  * split "pattern", which aren't. In the former case, expr will be a list
5516  * if the pattern contains more than one term (eg /a$b/).
5517  *
5518  * When the pattern has been compiled within a new anon CV (for
5519  * qr/(?{...})/ ), then floor indicates the savestack level just before
5520  * the new sub was created
5521  */
5522
5523 OP *
5524 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, bool isreg, I32 floor)
5525 {
5526     PMOP *pm;
5527     LOGOP *rcop;
5528     I32 repl_has_vars = 0;
5529     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
5530     bool is_compiletime;
5531     bool has_code;
5532
5533     PERL_ARGS_ASSERT_PMRUNTIME;
5534
5535     if (is_trans) {
5536         return pmtrans(o, expr, repl);
5537     }
5538
5539     /* find whether we have any runtime or code elements;
5540      * at the same time, temporarily set the op_next of each DO block;
5541      * then when we LINKLIST, this will cause the DO blocks to be excluded
5542      * from the op_next chain (and from having LINKLIST recursively
5543      * applied to them). We fix up the DOs specially later */
5544
5545     is_compiletime = 1;
5546     has_code = 0;
5547     if (expr->op_type == OP_LIST) {
5548         OP *o;
5549         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5550             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5551                 has_code = 1;
5552                 assert(!o->op_next);
5553                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
5554                     assert(PL_parser && PL_parser->error_count);
5555                     /* This can happen with qr/ (?{(^{})/.  Just fake up
5556                        the op we were expecting to see, to avoid crashing
5557                        elsewhere.  */
5558                     op_sibling_splice(expr, o, 0,
5559                                       newSVOP(OP_CONST, 0, &PL_sv_no));
5560                 }
5561                 o->op_next = OpSIBLING(o);
5562             }
5563             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
5564                 is_compiletime = 0;
5565         }
5566     }
5567     else if (expr->op_type != OP_CONST)
5568         is_compiletime = 0;
5569
5570     LINKLIST(expr);
5571
5572     /* fix up DO blocks; treat each one as a separate little sub;
5573      * also, mark any arrays as LIST/REF */
5574
5575     if (expr->op_type == OP_LIST) {
5576         OP *o;
5577         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5578
5579             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
5580                 assert( !(o->op_flags  & OPf_WANT));
5581                 /* push the array rather than its contents. The regex
5582                  * engine will retrieve and join the elements later */
5583                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
5584                 continue;
5585             }
5586
5587             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
5588                 continue;
5589             o->op_next = NULL; /* undo temporary hack from above */
5590             scalar(o);
5591             LINKLIST(o);
5592             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
5593                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
5594                 /* skip ENTER */
5595                 assert(leaveop->op_first->op_type == OP_ENTER);
5596                 assert(OpHAS_SIBLING(leaveop->op_first));
5597                 o->op_next = OpSIBLING(leaveop->op_first);
5598                 /* skip leave */
5599                 assert(leaveop->op_flags & OPf_KIDS);
5600                 assert(leaveop->op_last->op_next == (OP*)leaveop);
5601                 leaveop->op_next = NULL; /* stop on last op */
5602                 op_null((OP*)leaveop);
5603             }
5604             else {
5605                 /* skip SCOPE */
5606                 OP *scope = cLISTOPo->op_first;
5607                 assert(scope->op_type == OP_SCOPE);
5608                 assert(scope->op_flags & OPf_KIDS);
5609                 scope->op_next = NULL; /* stop on last op */
5610                 op_null(scope);
5611             }
5612             /* have to peep the DOs individually as we've removed it from
5613              * the op_next chain */
5614             CALL_PEEP(o);
5615             S_prune_chain_head(&(o->op_next));
5616             if (is_compiletime)
5617                 /* runtime finalizes as part of finalizing whole tree */
5618                 finalize_optree(o);
5619         }
5620     }
5621     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
5622         assert( !(expr->op_flags  & OPf_WANT));
5623         /* push the array rather than its contents. The regex
5624          * engine will retrieve and join the elements later */
5625         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
5626     }
5627
5628     PL_hints |= HINT_BLOCK_SCOPE;
5629     pm = (PMOP*)o;
5630     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
5631
5632     if (is_compiletime) {
5633         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
5634         regexp_engine const *eng = current_re_engine();
5635
5636         if (o->op_flags & OPf_SPECIAL)
5637             rx_flags |= RXf_SPLIT;
5638
5639         if (!has_code || !eng->op_comp) {
5640             /* compile-time simple constant pattern */
5641
5642             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
5643                 /* whoops! we guessed that a qr// had a code block, but we
5644                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
5645                  * that isn't required now. Note that we have to be pretty
5646                  * confident that nothing used that CV's pad while the
5647                  * regex was parsed, except maybe op targets for \Q etc.
5648                  * If there were any op targets, though, they should have
5649                  * been stolen by constant folding.
5650                  */
5651 #ifdef DEBUGGING
5652                 SSize_t i = 0;
5653                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
5654                 while (++i <= AvFILLp(PL_comppad)) {
5655                     assert(!PL_curpad[i]);
5656                 }
5657 #endif
5658                 /* But we know that one op is using this CV's slab. */
5659                 cv_forget_slab(PL_compcv);
5660                 LEAVE_SCOPE(floor);
5661                 pm->op_pmflags &= ~PMf_HAS_CV;
5662             }
5663
5664             PM_SETRE(pm,
5665                 eng->op_comp
5666                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5667                                         rx_flags, pm->op_pmflags)
5668                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5669                                         rx_flags, pm->op_pmflags)
5670             );
5671             op_free(expr);
5672         }
5673         else {
5674             /* compile-time pattern that includes literal code blocks */
5675             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5676                         rx_flags,
5677                         (pm->op_pmflags |
5678                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
5679                     );
5680             PM_SETRE(pm, re);
5681             if (pm->op_pmflags & PMf_HAS_CV) {
5682                 CV *cv;
5683                 /* this QR op (and the anon sub we embed it in) is never
5684                  * actually executed. It's just a placeholder where we can
5685                  * squirrel away expr in op_code_list without the peephole
5686                  * optimiser etc processing it for a second time */
5687                 OP *qr = newPMOP(OP_QR, 0);
5688                 ((PMOP*)qr)->op_code_list = expr;
5689
5690                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
5691                 SvREFCNT_inc_simple_void(PL_compcv);
5692                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
5693                 ReANY(re)->qr_anoncv = cv;
5694
5695                 /* attach the anon CV to the pad so that
5696                  * pad_fixup_inner_anons() can find it */
5697                 (void)pad_add_anon(cv, o->op_type);
5698                 SvREFCNT_inc_simple_void(cv);
5699             }
5700             else {
5701                 pm->op_code_list = expr;
5702             }
5703         }
5704     }
5705     else {
5706         /* runtime pattern: build chain of regcomp etc ops */
5707         bool reglist;
5708         PADOFFSET cv_targ = 0;
5709
5710         reglist = isreg && expr->op_type == OP_LIST;
5711         if (reglist)
5712             op_null(expr);
5713
5714         if (has_code) {
5715             pm->op_code_list = expr;
5716             /* don't free op_code_list; its ops are embedded elsewhere too */
5717             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
5718         }
5719
5720         if (o->op_flags & OPf_SPECIAL)
5721             pm->op_pmflags |= PMf_SPLIT;
5722
5723         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
5724          * to allow its op_next to be pointed past the regcomp and
5725          * preceding stacking ops;
5726          * OP_REGCRESET is there to reset taint before executing the
5727          * stacking ops */
5728         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
5729             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
5730
5731         if (pm->op_pmflags & PMf_HAS_CV) {
5732             /* we have a runtime qr with literal code. This means
5733              * that the qr// has been wrapped in a new CV, which
5734              * means that runtime consts, vars etc will have been compiled
5735              * against a new pad. So... we need to execute those ops
5736              * within the environment of the new CV. So wrap them in a call
5737              * to a new anon sub. i.e. for
5738              *
5739              *     qr/a$b(?{...})/,
5740              *
5741              * we build an anon sub that looks like
5742              *
5743              *     sub { "a", $b, '(?{...})' }
5744              *
5745              * and call it, passing the returned list to regcomp.
5746              * Or to put it another way, the list of ops that get executed
5747              * are:
5748              *
5749              *     normal              PMf_HAS_CV
5750              *     ------              -------------------
5751              *                         pushmark (for regcomp)
5752              *                         pushmark (for entersub)
5753              *                         anoncode
5754              *                         srefgen
5755              *                         entersub
5756              *     regcreset                  regcreset
5757              *     pushmark                   pushmark
5758              *     const("a")                 const("a")
5759              *     gvsv(b)                    gvsv(b)
5760              *     const("(?{...})")          const("(?{...})")
5761              *                                leavesub
5762              *     regcomp             regcomp
5763              */
5764
5765             SvREFCNT_inc_simple_void(PL_compcv);
5766             CvLVALUE_on(PL_compcv);
5767             /* these lines are just an unrolled newANONATTRSUB */
5768             expr = newSVOP(OP_ANONCODE, 0,
5769                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
5770             cv_targ = expr->op_targ;
5771             expr = newUNOP(OP_REFGEN, 0, expr);
5772
5773             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
5774         }
5775
5776         rcop = S_alloc_LOGOP(aTHX_ OP_REGCOMP, scalar(expr), o);
5777         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
5778                            | (reglist ? OPf_STACKED : 0);
5779         rcop->op_targ = cv_targ;
5780
5781         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
5782         if (PL_hints & HINT_RE_EVAL)
5783             S_set_haseval(aTHX);
5784
5785         /* establish postfix order */
5786         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
5787             LINKLIST(expr);
5788             rcop->op_next = expr;
5789             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
5790         }
5791         else {
5792             rcop->op_next = LINKLIST(expr);
5793             expr->op_next = (OP*)rcop;
5794         }
5795
5796         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
5797     }
5798
5799     if (repl) {
5800         OP *curop = repl;
5801         bool konst;
5802         /* If we are looking at s//.../e with a single statement, get past
5803            the implicit do{}. */
5804         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
5805              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
5806              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
5807          {
5808             OP *sib;
5809             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
5810             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
5811              && !OpHAS_SIBLING(sib))
5812                 curop = sib;
5813         }
5814         if (curop->op_type == OP_CONST)
5815             konst = TRUE;
5816         else if (( (curop->op_type == OP_RV2SV ||
5817                     curop->op_type == OP_RV2AV ||
5818                     curop->op_type == OP_RV2HV ||
5819                     curop->op_type == OP_RV2GV)
5820                    && cUNOPx(curop)->op_first
5821                    && cUNOPx(curop)->op_first->op_type == OP_GV )
5822                 || curop->op_type == OP_PADSV
5823                 || curop->op_type == OP_PADAV
5824                 || curop->op_type == OP_PADHV
5825                 || curop->op_type == OP_PADANY) {
5826             repl_has_vars = 1;
5827             konst = TRUE;
5828         }
5829         else konst = FALSE;
5830         if (konst
5831             && !(repl_has_vars
5832                  && (!PM_GETRE(pm)
5833                      || !RX_PRELEN(PM_GETRE(pm))
5834                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
5835         {
5836             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
5837             op_prepend_elem(o->op_type, scalar(repl), o);
5838         }
5839         else {
5840             rcop = S_alloc_LOGOP(aTHX_ OP_SUBSTCONT, scalar(repl), o);
5841             rcop->op_private = 1;
5842
5843             /* establish postfix order */
5844             rcop->op_next = LINKLIST(repl);
5845             repl->op_next = (OP*)rcop;
5846
5847             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
5848             assert(!(pm->op_pmflags & PMf_ONCE));
5849             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
5850             rcop->op_next = 0;
5851         }
5852     }
5853
5854     return (OP*)pm;
5855 }
5856
5857 /*
5858 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
5859
5860 Constructs, checks, and returns an op of any type that involves an
5861 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
5862 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
5863 takes ownership of one reference to it.
5864
5865 =cut
5866 */
5867
5868 OP *
5869 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
5870 {
5871     dVAR;
5872     SVOP *svop;
5873
5874     PERL_ARGS_ASSERT_NEWSVOP;
5875
5876     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5877         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5878         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5879         || type == OP_CUSTOM);
5880
5881     NewOp(1101, svop, 1, SVOP);
5882     OpTYPE_set(svop, type);
5883     svop->op_sv = sv;
5884     svop->op_next = (OP*)svop;
5885     svop->op_flags = (U8)flags;
5886     svop->op_private = (U8)(0 | (flags >> 8));
5887     if (PL_opargs[type] & OA_RETSCALAR)
5888         scalar((OP*)svop);
5889     if (PL_opargs[type] & OA_TARGET)
5890         svop->op_targ = pad_alloc(type, SVs_PADTMP);
5891     return CHECKOP(type, svop);
5892 }
5893
5894 /*
5895 =for apidoc Am|OP *|newDEFSVOP|
5896
5897 Constructs and returns an op to access C<$_>.
5898
5899 =cut
5900 */
5901
5902 OP *
5903 Perl_newDEFSVOP(pTHX)
5904 {
5905         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
5906 }
5907
5908 #ifdef USE_ITHREADS
5909
5910 /*
5911 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
5912
5913 Constructs, checks, and returns an op of any type that involves a
5914 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
5915 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
5916 is populated with C<sv>; this function takes ownership of one reference
5917 to it.
5918
5919 This function only exists if Perl has been compiled to use ithreads.
5920
5921 =cut
5922 */
5923
5924 OP *
5925 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
5926 {
5927     dVAR;
5928     PADOP *padop;
5929
5930     PERL_ARGS_ASSERT_NEWPADOP;
5931
5932     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5933         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5934         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5935         || type == OP_CUSTOM);
5936
5937     NewOp(1101, padop, 1, PADOP);
5938     OpTYPE_set(padop, type);
5939     padop->op_padix =
5940         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
5941     SvREFCNT_dec(PAD_SVl(padop->op_padix));
5942     PAD_SETSV(padop->op_padix, sv);
5943     assert(sv);
5944     padop->op_next = (OP*)padop;
5945     padop->op_flags = (U8)flags;
5946     if (PL_opargs[type] & OA_RETSCALAR)
5947         scalar((OP*)padop);
5948     if (PL_opargs[type] & OA_TARGET)
5949         padop->op_targ = pad_alloc(type, SVs_PADTMP);
5950     return CHECKOP(type, padop);
5951 }
5952
5953 #endif /* USE_ITHREADS */
5954
5955 /*
5956 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
5957
5958 Constructs, checks, and returns an op of any type that involves an
5959 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
5960 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
5961 reference; calling this function does not transfer ownership of any
5962 reference to it.
5963
5964 =cut
5965 */
5966
5967 OP *
5968 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
5969 {
5970     PERL_ARGS_ASSERT_NEWGVOP;
5971
5972 #ifdef USE_ITHREADS
5973     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5974 #else
5975     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5976 #endif
5977 }
5978
5979 /*
5980 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
5981
5982 Constructs, checks, and returns an op of any type that involves an
5983 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
5984 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer, which
5985 must have been allocated using C<PerlMemShared_malloc>; the memory will
5986 be freed when the op is destroyed.
5987
5988 =cut
5989 */
5990
5991 OP *
5992 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
5993 {
5994     dVAR;
5995     const bool utf8 = cBOOL(flags & SVf_UTF8);
5996     PVOP *pvop;
5997
5998     flags &= ~SVf_UTF8;
5999
6000     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
6001         || type == OP_RUNCV || type == OP_CUSTOM
6002         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6003
6004     NewOp(1101, pvop, 1, PVOP);
6005     OpTYPE_set(pvop, type);
6006     pvop->op_pv = pv;
6007     pvop->op_next = (OP*)pvop;
6008     pvop->op_flags = (U8)flags;
6009     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
6010     if (PL_opargs[type] & OA_RETSCALAR)
6011         scalar((OP*)pvop);
6012     if (PL_opargs[type] & OA_TARGET)
6013         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
6014     return CHECKOP(type, pvop);
6015 }
6016
6017 void
6018 Perl_package(pTHX_ OP *o)
6019 {
6020     SV *const sv = cSVOPo->op_sv;
6021
6022     PERL_ARGS_ASSERT_PACKAGE;
6023
6024     SAVEGENERICSV(PL_curstash);
6025     save_item(PL_curstname);
6026
6027     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
6028
6029     sv_setsv(PL_curstname, sv);
6030
6031     PL_hints |= HINT_BLOCK_SCOPE;
6032     PL_parser->copline = NOLINE;
6033
6034     op_free(o);
6035 }
6036
6037 void
6038 Perl_package_version( pTHX_ OP *v )
6039 {
6040     U32 savehints = PL_hints;
6041     PERL_ARGS_ASSERT_PACKAGE_VERSION;
6042     PL_hints &= ~HINT_STRICT_VARS;
6043     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
6044     PL_hints = savehints;
6045     op_free(v);
6046 }
6047
6048 void
6049 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
6050 {
6051     OP *pack;
6052     OP *imop;
6053     OP *veop;
6054     SV *use_version = NULL;
6055
6056     PERL_ARGS_ASSERT_UTILIZE;
6057
6058     if (idop->op_type != OP_CONST)
6059         Perl_croak(aTHX_ "Module name must be constant");
6060
6061     veop = NULL;
6062
6063     if (version) {
6064         SV * const vesv = ((SVOP*)version)->op_sv;
6065
6066         if (!arg && !SvNIOKp(vesv)) {
6067             arg = version;
6068         }
6069         else {
6070             OP *pack;
6071             SV *meth;
6072
6073             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
6074                 Perl_croak(aTHX_ "Version number must be a constant number");
6075
6076             /* Make copy of idop so we don't free it twice */
6077             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6078
6079             /* Fake up a method call to VERSION */
6080             meth = newSVpvs_share("VERSION");
6081             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6082                             op_append_elem(OP_LIST,
6083                                         op_prepend_elem(OP_LIST, pack, version),
6084                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
6085         }
6086     }
6087
6088     /* Fake up an import/unimport */
6089     if (arg && arg->op_type == OP_STUB) {
6090         imop = arg;             /* no import on explicit () */
6091     }
6092     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
6093         imop = NULL;            /* use 5.0; */
6094         if (aver)
6095             use_version = ((SVOP*)idop)->op_sv;
6096         else
6097             idop->op_private |= OPpCONST_NOVER;
6098     }
6099     else {
6100         SV *meth;
6101
6102         /* Make copy of idop so we don't free it twice */
6103         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6104
6105         /* Fake up a method call to import/unimport */
6106         meth = aver
6107             ? newSVpvs_share("import") : newSVpvs_share("unimport");
6108         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6109                        op_append_elem(OP_LIST,
6110                                    op_prepend_elem(OP_LIST, pack, arg),
6111                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
6112                        ));
6113     }
6114
6115     /* Fake up the BEGIN {}, which does its thing immediately. */
6116     newATTRSUB(floor,
6117         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
6118         NULL,
6119         NULL,
6120         op_append_elem(OP_LINESEQ,
6121             op_append_elem(OP_LINESEQ,
6122                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
6123                 newSTATEOP(0, NULL, veop)),
6124             newSTATEOP(0, NULL, imop) ));
6125
6126     if (use_version) {
6127         /* Enable the
6128          * feature bundle that corresponds to the required version. */
6129         use_version = sv_2mortal(new_version(use_version));
6130         S_enable_feature_bundle(aTHX_ use_version);
6131
6132         /* If a version >= 5.11.0 is requested, strictures are on by default! */
6133         if (vcmp(use_version,
6134                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
6135             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6136                 PL_hints |= HINT_STRICT_REFS;
6137             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6138                 PL_hints |= HINT_STRICT_SUBS;
6139             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6140                 PL_hints |= HINT_STRICT_VARS;
6141         }
6142         /* otherwise they are off */
6143         else {
6144             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6145                 PL_hints &= ~HINT_STRICT_REFS;
6146             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6147                 PL_hints &= ~HINT_STRICT_SUBS;
6148             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6149                 PL_hints &= ~HINT_STRICT_VARS;
6150         }
6151     }
6152
6153     /* The "did you use incorrect case?" warning used to be here.
6154      * The problem is that on case-insensitive filesystems one
6155      * might get false positives for "use" (and "require"):
6156      * "use Strict" or "require CARP" will work.  This causes
6157      * portability problems for the script: in case-strict
6158      * filesystems the script will stop working.
6159      *
6160      * The "incorrect case" warning checked whether "use Foo"
6161      * imported "Foo" to your namespace, but that is wrong, too:
6162      * there is no requirement nor promise in the language that
6163      * a Foo.pm should or would contain anything in package "Foo".
6164      *
6165      * There is very little Configure-wise that can be done, either:
6166      * the case-sensitivity of the build filesystem of Perl does not
6167      * help in guessing the case-sensitivity of the runtime environment.
6168      */
6169
6170     PL_hints |= HINT_BLOCK_SCOPE;
6171     PL_parser->copline = NOLINE;
6172     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
6173 }
6174
6175 /*
6176 =head1 Embedding Functions
6177
6178 =for apidoc load_module
6179
6180 Loads the module whose name is pointed to by the string part of name.
6181 Note that the actual module name, not its filename, should be given.
6182 Eg, "Foo::Bar" instead of "Foo/Bar.pm".  flags can be any of
6183 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
6184 (or 0 for no flags).  ver, if specified
6185 and not NULL, provides version semantics
6186 similar to C<use Foo::Bar VERSION>.  The optional trailing SV*
6187 arguments can be used to specify arguments to the module's C<import()>
6188 method, similar to C<use Foo::Bar VERSION LIST>.  They must be
6189 terminated with a final C<NULL> pointer.  Note that this list can only
6190 be omitted when the C<PERL_LOADMOD_NOIMPORT> flag has been used.
6191 Otherwise at least a single C<NULL> pointer to designate the default
6192 import list is required.
6193
6194 The reference count for each specified C<SV*> parameter is decremented.
6195
6196 =cut */
6197
6198 void
6199 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
6200 {
6201     va_list args;
6202
6203     PERL_ARGS_ASSERT_LOAD_MODULE;
6204
6205     va_start(args, ver);
6206     vload_module(flags, name, ver, &args);
6207     va_end(args);
6208 }
6209
6210 #ifdef PERL_IMPLICIT_CONTEXT
6211 void
6212 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
6213 {
6214     dTHX;
6215     va_list args;
6216     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
6217     va_start(args, ver);
6218     vload_module(flags, name, ver, &args);
6219     va_end(args);
6220 }
6221 #endif
6222
6223 void
6224 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
6225 {
6226     OP *veop, *imop;
6227     OP * const modname = newSVOP(OP_CONST, 0, name);
6228
6229     PERL_ARGS_ASSERT_VLOAD_MODULE;
6230
6231     modname->op_private |= OPpCONST_BARE;
6232     if (ver) {
6233         veop = newSVOP(OP_CONST, 0, ver);
6234     }
6235     else
6236         veop = NULL;
6237     if (flags & PERL_LOADMOD_NOIMPORT) {
6238         imop = sawparens(newNULLLIST());
6239     }
6240     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
6241         imop = va_arg(*args, OP*);
6242     }
6243     else {
6244         SV *sv;
6245         imop = NULL;
6246         sv = va_arg(*args, SV*);
6247         while (sv) {
6248             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
6249             sv = va_arg(*args, SV*);
6250         }
6251     }
6252
6253     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
6254      * that it has a PL_parser to play with while doing that, and also
6255      * that it doesn't mess with any existing parser, by creating a tmp
6256      * new parser with lex_start(). This won't actually be used for much,
6257      * since pp_require() will create another parser for the real work.
6258      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
6259
6260     ENTER;
6261     SAVEVPTR(PL_curcop);
6262     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
6263     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
6264             veop, modname, imop);
6265     LEAVE;
6266 }
6267
6268 PERL_STATIC_INLINE OP *
6269 S_new_entersubop(pTHX_ GV *gv, OP *arg)
6270 {
6271     return newUNOP(OP_ENTERSUB, OPf_STACKED,
6272                    newLISTOP(OP_LIST, 0, arg,
6273                              newUNOP(OP_RV2CV, 0,
6274                                      newGVOP(OP_GV, 0, gv))));
6275 }
6276
6277 OP *
6278 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
6279 {
6280     OP *doop;
6281     GV *gv;
6282
6283     PERL_ARGS_ASSERT_DOFILE;
6284
6285     if (!force_builtin && (gv = gv_override("do", 2))) {
6286         doop = S_new_entersubop(aTHX_ gv, term);
6287     }
6288     else {
6289         doop = newUNOP(OP_DOFILE, 0, scalar(term));
6290     }
6291     return doop;
6292 }
6293
6294 /*
6295 =head1 Optree construction
6296
6297 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
6298
6299 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
6300 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
6301 be set automatically, and, shifted up eight bits, the eight bits of
6302 C<op_private>, except that the bit with value 1 or 2 is automatically
6303 set as required.  C<listval> and C<subscript> supply the parameters of
6304 the slice; they are consumed by this function and become part of the
6305 constructed op tree.
6306
6307 =cut
6308 */
6309
6310 OP *
6311 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
6312 {
6313     return newBINOP(OP_LSLICE, flags,
6314             list(force_list(subscript, 1)),
6315             list(force_list(listval,   1)) );
6316 }
6317
6318 #define ASSIGN_LIST   1
6319 #define ASSIGN_REF    2
6320
6321 STATIC I32
6322 S_assignment_type(pTHX_ const OP *o)
6323 {
6324     unsigned type;
6325     U8 flags;
6326     U8 ret;
6327
6328     if (!o)
6329         return TRUE;
6330
6331     if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
6332         o = cUNOPo->op_first;
6333
6334     flags = o->op_flags;
6335     type = o->op_type;
6336     if (type == OP_COND_EXPR) {
6337         OP * const sib = OpSIBLING(cLOGOPo->op_first);
6338         const I32 t = assignment_type(sib);
6339         const I32 f = assignment_type(OpSIBLING(sib));
6340
6341         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
6342             return ASSIGN_LIST;
6343         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
6344             yyerror("Assignment to both a list and a scalar");
6345         return FALSE;
6346     }
6347
6348     if (type == OP_SREFGEN)
6349     {
6350         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
6351         type = kid->op_type;
6352         flags |= kid->op_flags;
6353         if (!(flags & OPf_PARENS)
6354           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
6355               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
6356             return ASSIGN_REF;
6357         ret = ASSIGN_REF;
6358     }
6359     else ret = 0;
6360
6361     if (type == OP_LIST &&
6362         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
6363         o->op_private & OPpLVAL_INTRO)
6364         return ret;
6365
6366     if (type == OP_LIST || flags & OPf_PARENS ||
6367         type == OP_RV2AV || type == OP_RV2HV ||
6368         type == OP_ASLICE || type == OP_HSLICE ||
6369         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
6370         return TRUE;
6371
6372     if (type == OP_PADAV || type == OP_PADHV)
6373         return TRUE;
6374
6375     if (type == OP_RV2SV)
6376         return ret;
6377
6378     return ret;
6379 }
6380
6381
6382 /*
6383 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
6384
6385 Constructs, checks, and returns an assignment op.  C<left> and C<right>
6386 supply the parameters of the assignment; they are consumed by this
6387 function and become part of the constructed op tree.
6388
6389 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
6390 a suitable conditional optree is constructed.  If C<optype> is the opcode
6391 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
6392 performs the binary operation and assigns the result to the left argument.
6393 Either way, if C<optype> is non-zero then C<flags> has no effect.
6394
6395 If C<optype> is zero, then a plain scalar or list assignment is
6396 constructed.  Which type of assignment it is is automatically determined.
6397 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6398 will be set automatically, and, shifted up eight bits, the eight bits
6399 of C<op_private>, except that the bit with value 1 or 2 is automatically
6400 set as required.
6401
6402 =cut
6403 */
6404
6405 OP *
6406 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
6407 {
6408     OP *o;
6409     I32 assign_type;
6410
6411     if (optype) {
6412         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
6413             return newLOGOP(optype, 0,
6414                 op_lvalue(scalar(left), optype),
6415                 newUNOP(OP_SASSIGN, 0, scalar(right)));
6416         }
6417         else {
6418             return newBINOP(optype, OPf_STACKED,
6419                 op_lvalue(scalar(left), optype), scalar(right));
6420         }
6421     }
6422
6423     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
6424         static const char no_list_state[] = "Initialization of state variables"
6425             " in list context currently forbidden";
6426         OP *curop;
6427
6428         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
6429             left->op_private &= ~ OPpSLICEWARNING;
6430
6431         PL_modcount = 0;
6432         left = op_lvalue(left, OP_AASSIGN);
6433         curop = list(force_list(left, 1));
6434         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
6435         o->op_private = (U8)(0 | (flags >> 8));
6436
6437         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
6438         {
6439             OP* lop = ((LISTOP*)left)->op_first;
6440             while (lop) {
6441                 if ((lop->op_type == OP_PADSV ||
6442                      lop->op_type == OP_PADAV ||
6443                      lop->op_type == OP_PADHV ||
6444                      lop->op_type == OP_PADANY)
6445                   && (lop->op_private & OPpPAD_STATE)
6446                 )
6447                     yyerror(no_list_state);
6448                 lop = OpSIBLING(lop);
6449             }
6450         }
6451         else if (  (left->op_private & OPpLVAL_INTRO)
6452                 && (left->op_private & OPpPAD_STATE)
6453                 && (   left->op_type == OP_PADSV
6454                     || left->op_type == OP_PADAV
6455                     || left->op_type == OP_PADHV
6456                     || left->op_type == OP_PADANY)
6457         ) {
6458                 /* All single variable list context state assignments, hence
6459                    state ($a) = ...
6460                    (state $a) = ...
6461                    state @a = ...
6462                    state (@a) = ...
6463                    (state @a) = ...
6464                    state %a = ...
6465                    state (%a) = ...
6466                    (state %a) = ...
6467                 */
6468                 yyerror(no_list_state);
6469         }
6470
6471         if (right && right->op_type == OP_SPLIT
6472          && !(right->op_flags & OPf_STACKED)) {
6473             OP* tmpop = ((LISTOP*)right)->op_first;
6474             PMOP * const pm = (PMOP*)tmpop;
6475             assert (tmpop && (tmpop->op_type == OP_PUSHRE));
6476             if (
6477 #ifdef USE_ITHREADS
6478                     !pm->op_pmreplrootu.op_pmtargetoff
6479 #else
6480                     !pm->op_pmreplrootu.op_pmtargetgv
6481 #endif
6482                  && !pm->op_targ
6483                 ) {
6484                     if (!(left->op_private & OPpLVAL_INTRO) &&
6485                         ( (left->op_type == OP_RV2AV &&
6486                           (tmpop=((UNOP*)left)->op_first)->op_type==OP_GV)
6487                         || left->op_type == OP_PADAV )
6488                         ) {
6489                         if (tmpop != (OP *)pm) {
6490 #ifdef USE_ITHREADS
6491                           pm->op_pmreplrootu.op_pmtargetoff
6492                             = cPADOPx(tmpop)->op_padix;
6493                           cPADOPx(tmpop)->op_padix = 0; /* steal it */
6494 #else
6495                           pm->op_pmreplrootu.op_pmtargetgv
6496                             = MUTABLE_GV(cSVOPx(tmpop)->op_sv);
6497                           cSVOPx(tmpop)->op_sv = NULL;  /* steal it */
6498 #endif
6499                           right->op_private |=
6500                             left->op_private & OPpOUR_INTRO;
6501                         }
6502                         else {
6503                             pm->op_targ = left->op_targ;
6504                             left->op_targ = 0; /* filch it */
6505                         }
6506                       detach_split:
6507                         tmpop = cUNOPo->op_first;       /* to list (nulled) */
6508                         tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
6509                         /* detach rest of siblings from o subtree,
6510                          * and free subtree */
6511                         op_sibling_splice(cUNOPo->op_first, tmpop, -1, NULL);
6512                         op_free(o);                     /* blow off assign */
6513                         right->op_flags &= ~OPf_WANT;
6514                                 /* "I don't know and I don't care." */
6515                         return right;
6516                     }
6517                     else if (left->op_type == OP_RV2AV
6518                           || left->op_type == OP_PADAV)
6519                     {
6520                         /* Detach the array.  */
6521 #ifdef DEBUGGING
6522                         OP * const ary =
6523 #endif
6524                         op_sibling_splice(cBINOPo->op_last,
6525                                           cUNOPx(cBINOPo->op_last)
6526                                                 ->op_first, 1, NULL);
6527                         assert(ary == left);
6528                         /* Attach it to the split.  */
6529                         op_sibling_splice(right, cLISTOPx(right)->op_last,
6530                                           0, left);
6531                         right->op_flags |= OPf_STACKED;
6532                         /* Detach split and expunge aassign as above.  */
6533                         goto detach_split;
6534                     }
6535                     else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
6536                             ((LISTOP*)right)->op_last->op_type == OP_CONST)
6537                     {
6538                         SV ** const svp =
6539                             &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
6540                         SV * const sv = *svp;
6541                         if (SvIOK(sv) && SvIVX(sv) == 0)
6542                         {
6543                           if (right->op_private & OPpSPLIT_IMPLIM) {
6544                             /* our own SV, created in ck_split */
6545                             SvREADONLY_off(sv);
6546                             sv_setiv(sv, PL_modcount+1);
6547                           }
6548                           else {
6549                             /* SV may belong to someone else */
6550                             SvREFCNT_dec(sv);
6551                             *svp = newSViv(PL_modcount+1);
6552                           }
6553                         }
6554                     }
6555             }
6556         }
6557         return o;
6558     }
6559     if (assign_type == ASSIGN_REF)
6560         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
6561     if (!right)
6562         right = newOP(OP_UNDEF, 0);
6563     if (right->op_type == OP_READLINE) {
6564         right->op_flags |= OPf_STACKED;
6565         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
6566                 scalar(right));
6567     }
6568     else {
6569         o = newBINOP(OP_SASSIGN, flags,
6570             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
6571     }
6572     return o;
6573 }
6574
6575 /*
6576 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
6577
6578 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
6579 but will be a C<dbstate> op if debugging is enabled for currently-compiled
6580 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
6581 If C<label> is non-null, it supplies the name of a label to attach to
6582 the state op; this function takes ownership of the memory pointed at by
6583 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
6584 for the state op.
6585
6586 If C<o> is null, the state op is returned.  Otherwise the state op is
6587 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
6588 is consumed by this function and becomes part of the returned op tree.
6589
6590 =cut
6591 */
6592
6593 OP *
6594 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
6595 {
6596     dVAR;
6597     const U32 seq = intro_my();
6598     const U32 utf8 = flags & SVf_UTF8;
6599     COP *cop;
6600
6601     PL_parser->parsed_sub = 0;
6602
6603     flags &= ~SVf_UTF8;
6604
6605     NewOp(1101, cop, 1, COP);
6606     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
6607         OpTYPE_set(cop, OP_DBSTATE);
6608     }
6609     else {
6610         OpTYPE_set(cop, OP_NEXTSTATE);
6611     }
6612     cop->op_flags = (U8)flags;
6613     CopHINTS_set(cop, PL_hints);
6614 #ifdef VMS
6615     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
6616 #endif
6617     cop->op_next = (OP*)cop;
6618
6619     cop->cop_seq = seq;
6620     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
6621     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
6622     if (label) {
6623         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
6624
6625         PL_hints |= HINT_BLOCK_SCOPE;
6626         /* It seems that we need to defer freeing this pointer, as other parts
6627            of the grammar end up wanting to copy it after this op has been
6628            created. */
6629         SAVEFREEPV(label);
6630     }
6631
6632     if (PL_parser->preambling != NOLINE) {
6633         CopLINE_set(cop, PL_parser->preambling);
6634         PL_parser->copline = NOLINE;
6635     }
6636     else if (PL_parser->copline == NOLINE)
6637         CopLINE_set(cop, CopLINE(PL_curcop));
6638     else {
6639         CopLINE_set(cop, PL_parser->copline);
6640         PL_parser->copline = NOLINE;
6641     }
6642 #ifdef USE_ITHREADS
6643     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
6644 #else
6645     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
6646 #endif
6647     CopSTASH_set(cop, PL_curstash);
6648
6649     if (cop->op_type == OP_DBSTATE) {
6650         /* this line can have a breakpoint - store the cop in IV */
6651         AV *av = CopFILEAVx(PL_curcop);
6652         if (av) {
6653             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
6654             if (svp && *svp != &PL_sv_undef ) {
6655                 (void)SvIOK_on(*svp);
6656                 SvIV_set(*svp, PTR2IV(cop));
6657             }
6658         }
6659     }
6660
6661     if (flags & OPf_SPECIAL)
6662         op_null((OP*)cop);
6663     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
6664 }
6665
6666 /*
6667 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
6668
6669 Constructs, checks, and returns a logical (flow control) op.  C<type>
6670 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6671 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6672 the eight bits of C<op_private>, except that the bit with value 1 is
6673 automatically set.  C<first> supplies the expression controlling the
6674 flow, and C<other> supplies the side (alternate) chain of ops; they are
6675 consumed by this function and become part of the constructed op tree.
6676
6677 =cut
6678 */
6679
6680 OP *
6681 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
6682 {
6683     PERL_ARGS_ASSERT_NEWLOGOP;
6684
6685     return new_logop(type, flags, &first, &other);
6686 }
6687
6688 STATIC OP *
6689 S_search_const(pTHX_ OP *o)
6690 {
6691     PERL_ARGS_ASSERT_SEARCH_CONST;
6692
6693     switch (o->op_type) {
6694         case OP_CONST:
6695             return o;
6696         case OP_NULL:
6697             if (o->op_flags & OPf_KIDS)
6698                 return search_const(cUNOPo->op_first);
6699             break;
6700         case OP_LEAVE:
6701         case OP_SCOPE:
6702         case OP_LINESEQ:
6703         {
6704             OP *kid;
6705             if (!(o->op_flags & OPf_KIDS))
6706                 return NULL;
6707             kid = cLISTOPo->op_first;
6708             do {
6709                 switch (kid->op_type) {
6710                     case OP_ENTER:
6711                     case OP_NULL:
6712                     case OP_NEXTSTATE:
6713                         kid = OpSIBLING(kid);
6714                         break;
6715                     default:
6716                         if (kid != cLISTOPo->op_last)
6717                             return NULL;
6718                         goto last;
6719                 }
6720             } while (kid);
6721             if (!kid)
6722                 kid = cLISTOPo->op_last;
6723           last:
6724             return search_const(kid);
6725         }
6726     }
6727
6728     return NULL;
6729 }
6730
6731 STATIC OP *
6732 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
6733 {
6734     dVAR;
6735     LOGOP *logop;
6736     OP *o;
6737     OP *first;
6738     OP *other;
6739     OP *cstop = NULL;
6740     int prepend_not = 0;
6741
6742     PERL_ARGS_ASSERT_NEW_LOGOP;
6743
6744     first = *firstp;
6745     other = *otherp;
6746
6747     /* [perl #59802]: Warn about things like "return $a or $b", which
6748        is parsed as "(return $a) or $b" rather than "return ($a or
6749        $b)".  NB: This also applies to xor, which is why we do it
6750        here.
6751      */
6752     switch (first->op_type) {
6753     case OP_NEXT:
6754     case OP_LAST:
6755     case OP_REDO:
6756         /* XXX: Perhaps we should emit a stronger warning for these.
6757            Even with the high-precedence operator they don't seem to do
6758            anything sensible.
6759
6760            But until we do, fall through here.
6761          */
6762     case OP_RETURN:
6763     case OP_EXIT:
6764     case OP_DIE:
6765     case OP_GOTO:
6766         /* XXX: Currently we allow people to "shoot themselves in the
6767            foot" by explicitly writing "(return $a) or $b".
6768
6769            Warn unless we are looking at the result from folding or if
6770            the programmer explicitly grouped the operators like this.
6771            The former can occur with e.g.
6772
6773                 use constant FEATURE => ( $] >= ... );
6774                 sub { not FEATURE and return or do_stuff(); }
6775          */
6776         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
6777             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
6778                            "Possible precedence issue with control flow operator");
6779         /* XXX: Should we optimze this to "return $a;" (i.e. remove
6780            the "or $b" part)?
6781         */
6782         break;
6783     }
6784
6785     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
6786         return newBINOP(type, flags, scalar(first), scalar(other));
6787
6788     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
6789         || type == OP_CUSTOM);
6790
6791     scalarboolean(first);
6792
6793     /* search for a constant op that could let us fold the test */
6794     if ((cstop = search_const(first))) {
6795         if (cstop->op_private & OPpCONST_STRICT)
6796             no_bareword_allowed(cstop);
6797         else if ((cstop->op_private & OPpCONST_BARE))
6798                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
6799         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
6800             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
6801             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
6802             /* Elide the (constant) lhs, since it can't affect the outcome */
6803             *firstp = NULL;
6804             if (other->op_type == OP_CONST)
6805                 other->op_private |= OPpCONST_SHORTCIRCUIT;
6806             op_free(first);
6807             if (other->op_type == OP_LEAVE)
6808                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
6809             else if (other->op_type == OP_MATCH
6810                   || other->op_type == OP_SUBST
6811                   || other->op_type == OP_TRANSR
6812                   || other->op_type == OP_TRANS)
6813                 /* Mark the op as being unbindable with =~ */
6814                 other->op_flags |= OPf_SPECIAL;
6815
6816             other->op_folded = 1;
6817             return other;
6818         }
6819         else {
6820             /* Elide the rhs, since the outcome is entirely determined by
6821              * the (constant) lhs */
6822
6823             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
6824             const OP *o2 = other;
6825             if ( ! (o2->op_type == OP_LIST
6826                     && (( o2 = cUNOPx(o2)->op_first))
6827                     && o2->op_type == OP_PUSHMARK
6828                     && (( o2 = OpSIBLING(o2))) )
6829             )
6830                 o2 = other;
6831             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
6832                         || o2->op_type == OP_PADHV)
6833                 && o2->op_private & OPpLVAL_INTRO
6834                 && !(o2->op_private & OPpPAD_STATE))
6835             {
6836                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
6837                                  "Deprecated use of my() in false conditional");
6838             }
6839
6840             *otherp = NULL;
6841             if (cstop->op_type == OP_CONST)
6842                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
6843             op_free(other);
6844             return first;
6845         }
6846     }
6847     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
6848         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
6849     {
6850         const OP * const k1 = ((UNOP*)first)->op_first;
6851         const OP * const k2 = OpSIBLING(k1);
6852         OPCODE warnop = 0;
6853         switch (first->op_type)
6854         {
6855         case OP_NULL:
6856             if (k2 && k2->op_type == OP_READLINE
6857                   && (k2->op_flags & OPf_STACKED)
6858                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6859             {
6860                 warnop = k2->op_type;
6861             }
6862             break;
6863
6864         case OP_SASSIGN:
6865             if (k1->op_type == OP_READDIR
6866                   || k1->op_type == OP_GLOB
6867                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6868                  || k1->op_type == OP_EACH
6869                  || k1->op_type == OP_AEACH)
6870             {
6871                 warnop = ((k1->op_type == OP_NULL)
6872                           ? (OPCODE)k1->op_targ : k1->op_type);
6873             }
6874             break;
6875         }
6876         if (warnop) {
6877             const line_t oldline = CopLINE(PL_curcop);
6878             /* This ensures that warnings are reported at the first line
6879                of the construction, not the last.  */
6880             CopLINE_set(PL_curcop, PL_parser->copline);
6881             Perl_warner(aTHX_ packWARN(WARN_MISC),
6882                  "Value of %s%s can be \"0\"; test with defined()",
6883                  PL_op_desc[warnop],
6884                  ((warnop == OP_READLINE || warnop == OP_GLOB)
6885                   ? " construct" : "() operator"));
6886             CopLINE_set(PL_curcop, oldline);
6887         }
6888     }
6889
6890     if (type == OP_ANDASSIGN || type == OP_ORASSIGN || type == OP_DORASSIGN)
6891         other->op_private |= OPpASSIGN_BACKWARDS;  /* other is an OP_SASSIGN */
6892
6893     /* optimize AND and OR ops that have NOTs as children */
6894     if (first->op_type == OP_NOT
6895         && (first->op_flags & OPf_KIDS)
6896         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
6897             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
6898         ) {
6899         if (type == OP_AND || type == OP_OR) {
6900             if (type == OP_AND)
6901                 type = OP_OR;
6902             else
6903                 type = OP_AND;
6904             op_null(first);
6905             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
6906                 op_null(other);
6907                 prepend_not = 1; /* prepend a NOT op later */
6908             }
6909         }
6910     }
6911
6912     logop = S_alloc_LOGOP(aTHX_ type, first, LINKLIST(other));
6913     logop->op_flags |= (U8)flags;
6914     logop->op_private = (U8)(1 | (flags >> 8));
6915
6916     /* establish postfix order */
6917     logop->op_next = LINKLIST(first);
6918     first->op_next = (OP*)logop;
6919     assert(!OpHAS_SIBLING(first));
6920     op_sibling_splice((OP*)logop, first, 0, other);
6921
6922     CHECKOP(type,logop);
6923
6924     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
6925                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
6926                 (OP*)logop);
6927     other->op_next = o;
6928
6929     return o;
6930 }
6931
6932 /*
6933 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
6934
6935 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
6936 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6937 will be set automatically, and, shifted up eight bits, the eight bits of
6938 C<op_private>, except that the bit with value 1 is automatically set.
6939 C<first> supplies the expression selecting between the two branches,
6940 and C<trueop> and C<falseop> supply the branches; they are consumed by
6941 this function and become part of the constructed op tree.
6942
6943 =cut
6944 */
6945
6946 OP *
6947 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
6948 {
6949     dVAR;
6950     LOGOP *logop;
6951     OP *start;
6952     OP *o;
6953     OP *cstop;
6954
6955     PERL_ARGS_ASSERT_NEWCONDOP;
6956
6957     if (!falseop)
6958         return newLOGOP(OP_AND, 0, first, trueop);
6959     if (!trueop)
6960         return newLOGOP(OP_OR, 0, first, falseop);
6961
6962     scalarboolean(first);
6963     if ((cstop = search_const(first))) {
6964         /* Left or right arm of the conditional?  */
6965         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
6966         OP *live = left ? trueop : falseop;
6967         OP *const dead = left ? falseop : trueop;
6968         if (cstop->op_private & OPpCONST_BARE &&
6969             cstop->op_private & OPpCONST_STRICT) {
6970             no_bareword_allowed(cstop);
6971         }
6972         op_free(first);
6973         op_free(dead);
6974         if (live->op_type == OP_LEAVE)
6975             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
6976         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
6977               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
6978             /* Mark the op as being unbindable with =~ */
6979             live->op_flags |= OPf_SPECIAL;
6980         live->op_folded = 1;
6981         return live;
6982     }
6983     logop = S_alloc_LOGOP(aTHX_ OP_COND_EXPR, first, LINKLIST(trueop));
6984     logop->op_flags |= (U8)flags;
6985     logop->op_private = (U8)(1 | (flags >> 8));
6986     logop->op_next = LINKLIST(falseop);
6987
6988     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
6989             logop);
6990
6991     /* establish postfix order */
6992     start = LINKLIST(first);
6993     first->op_next = (OP*)logop;
6994
6995     /* make first, trueop, falseop siblings */
6996     op_sibling_splice((OP*)logop, first,  0, trueop);
6997     op_sibling_splice((OP*)logop, trueop, 0, falseop);
6998
6999     o = newUNOP(OP_NULL, 0, (OP*)logop);
7000
7001     trueop->op_next = falseop->op_next = o;
7002
7003     o->op_next = start;
7004     return o;
7005 }
7006
7007 /*
7008 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
7009
7010 Constructs and returns a C<range> op, with subordinate C<flip> and
7011 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
7012 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
7013 for both the C<flip> and C<range> ops, except that the bit with value
7014 1 is automatically set.  C<left> and C<right> supply the expressions
7015 controlling the endpoints of the range; they are consumed by this function
7016 and become part of the constructed op tree.
7017
7018 =cut
7019 */
7020
7021 OP *
7022 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
7023 {
7024     LOGOP *range;
7025     OP *flip;
7026     OP *flop;
7027     OP *leftstart;
7028     OP *o;
7029
7030     PERL_ARGS_ASSERT_NEWRANGE;
7031
7032     range = S_alloc_LOGOP(aTHX_ OP_RANGE, left, LINKLIST(right));
7033     range->op_flags = OPf_KIDS;
7034     leftstart = LINKLIST(left);
7035     range->op_private = (U8)(1 | (flags >> 8));
7036
7037     /* make left and right siblings */
7038     op_sibling_splice((OP*)range, left, 0, right);
7039
7040     range->op_next = (OP*)range;
7041     flip = newUNOP(OP_FLIP, flags, (OP*)range);
7042     flop = newUNOP(OP_FLOP, 0, flip);
7043     o = newUNOP(OP_NULL, 0, flop);
7044     LINKLIST(flop);
7045     range->op_next = leftstart;
7046
7047     left->op_next = flip;
7048     right->op_next = flop;
7049
7050     range->op_targ =
7051         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
7052     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
7053     flip->op_targ =
7054         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
7055     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
7056     SvPADTMP_on(PAD_SV(flip->op_targ));
7057
7058     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
7059     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
7060
7061     /* check barewords before they might be optimized aways */
7062     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
7063         no_bareword_allowed(left);
7064     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
7065         no_bareword_allowed(right);
7066
7067     flip->op_next = o;
7068     if (!flip->op_private || !flop->op_private)
7069         LINKLIST(o);            /* blow off optimizer unless constant */
7070
7071     return o;
7072 }
7073
7074 /*
7075 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
7076
7077 Constructs, checks, and returns an op tree expressing a loop.  This is
7078 only a loop in the control flow through the op tree; it does not have
7079 the heavyweight loop structure that allows exiting the loop by C<last>
7080 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
7081 top-level op, except that some bits will be set automatically as required.
7082 C<expr> supplies the expression controlling loop iteration, and C<block>
7083 supplies the body of the loop; they are consumed by this function and
7084 become part of the constructed op tree.  C<debuggable> is currently
7085 unused and should always be 1.
7086
7087 =cut
7088 */
7089
7090 OP *
7091 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
7092 {
7093     OP* listop;
7094     OP* o;
7095     const bool once = block && block->op_flags & OPf_SPECIAL &&
7096                       block->op_type == OP_NULL;
7097
7098     PERL_UNUSED_ARG(debuggable);
7099
7100     if (expr) {
7101         if (once && (
7102               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
7103            || (  expr->op_type == OP_NOT
7104               && cUNOPx(expr)->op_first->op_type == OP_CONST
7105               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
7106               )
7107            ))
7108             /* Return the block now, so that S_new_logop does not try to
7109                fold it away. */
7110             return block;       /* do {} while 0 does once */
7111         if (expr->op_type == OP_READLINE
7112             || expr->op_type == OP_READDIR
7113             || expr->op_type == OP_GLOB
7114             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7115             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7116             expr = newUNOP(OP_DEFINED, 0,
7117                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7118         } else if (expr->op_flags & OPf_KIDS) {
7119             const OP * const k1 = ((UNOP*)expr)->op_first;
7120             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
7121             switch (expr->op_type) {
7122               case OP_NULL:
7123                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7124                       && (k2->op_flags & OPf_STACKED)
7125                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7126                     expr = newUNOP(OP_DEFINED, 0, expr);
7127                 break;
7128
7129               case OP_SASSIGN:
7130                 if (k1 && (k1->op_type == OP_READDIR
7131                       || k1->op_type == OP_GLOB
7132                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7133                      || k1->op_type == OP_EACH
7134                      || k1->op_type == OP_AEACH))
7135                     expr = newUNOP(OP_DEFINED, 0, expr);
7136                 break;
7137             }
7138         }
7139     }
7140
7141     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
7142      * op, in listop. This is wrong. [perl #27024] */
7143     if (!block)
7144         block = newOP(OP_NULL, 0);
7145     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
7146     o = new_logop(OP_AND, 0, &expr, &listop);
7147
7148     if (once) {
7149         ASSUME(listop);
7150     }
7151
7152     if (listop)
7153         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
7154
7155     if (once && o != listop)
7156     {
7157         assert(cUNOPo->op_first->op_type == OP_AND
7158             || cUNOPo->op_first->op_type == OP_OR);
7159         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
7160     }
7161
7162     if (o == listop)
7163         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
7164
7165     o->op_flags |= flags;
7166     o = op_scope(o);
7167     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
7168     return o;
7169 }
7170
7171 /*
7172 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
7173
7174 Constructs, checks, and returns an op tree expressing a C<while> loop.
7175 This is a heavyweight loop, with structure that allows exiting the loop
7176 by C<last> and suchlike.
7177
7178 C<loop> is an optional preconstructed C<enterloop> op to use in the
7179 loop; if it is null then a suitable op will be constructed automatically.
7180 C<expr> supplies the loop's controlling expression.  C<block> supplies the
7181 main body of the loop, and C<cont> optionally supplies a C<continue> block
7182 that operates as a second half of the body.  All of these optree inputs
7183 are consumed by this function and become part of the constructed op tree.
7184
7185 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7186 op and, shifted up eight bits, the eight bits of C<op_private> for
7187 the C<leaveloop> op, except that (in both cases) some bits will be set
7188 automatically.  C<debuggable> is currently unused and should always be 1.
7189 C<has_my> can be supplied as true to force the
7190 loop body to be enclosed in its own scope.
7191
7192 =cut
7193 */
7194
7195 OP *
7196 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
7197         OP *expr, OP *block, OP *cont, I32 has_my)
7198 {
7199     dVAR;
7200     OP *redo;
7201     OP *next = NULL;
7202     OP *listop;
7203     OP *o;
7204     U8 loopflags = 0;
7205
7206     PERL_UNUSED_ARG(debuggable);
7207
7208     if (expr) {
7209         if (expr->op_type == OP_READLINE
7210          || expr->op_type == OP_READDIR
7211          || expr->op_type == OP_GLOB
7212          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7213                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7214             expr = newUNOP(OP_DEFINED, 0,
7215                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7216         } else if (expr->op_flags & OPf_KIDS) {
7217             const OP * const k1 = ((UNOP*)expr)->op_first;
7218             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
7219             switch (expr->op_type) {
7220               case OP_NULL:
7221                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7222                       && (k2->op_flags & OPf_STACKED)
7223                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7224                     expr = newUNOP(OP_DEFINED, 0, expr);
7225                 break;
7226
7227               case OP_SASSIGN:
7228                 if (k1 && (k1->op_type == OP_READDIR
7229                       || k1->op_type == OP_GLOB
7230                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7231                      || k1->op_type == OP_EACH
7232                      || k1->op_type == OP_AEACH))
7233                     expr = newUNOP(OP_DEFINED, 0, expr);
7234                 break;
7235             }
7236         }
7237     }
7238
7239     if (!block)
7240         block = newOP(OP_NULL, 0);
7241     else if (cont || has_my) {
7242         block = op_scope(block);
7243     }
7244
7245     if (cont) {
7246         next = LINKLIST(cont);
7247     }
7248     if (expr) {
7249         OP * const unstack = newOP(OP_UNSTACK, 0);
7250         if (!next)
7251             next = unstack;
7252         cont = op_append_elem(OP_LINESEQ, cont, unstack);
7253     }
7254
7255     assert(block);
7256     listop = op_append_list(OP_LINESEQ, block, cont);
7257     assert(listop);
7258     redo = LINKLIST(listop);
7259
7260     if (expr) {
7261         scalar(listop);
7262         o = new_logop(OP_AND, 0, &expr, &listop);
7263         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
7264             op_free((OP*)loop);
7265             return expr;                /* listop already freed by new_logop */
7266         }
7267         if (listop)
7268             ((LISTOP*)listop)->op_last->op_next =
7269                 (o == listop ? redo : LINKLIST(o));
7270     }
7271     else
7272         o = listop;
7273
7274     if (!loop) {
7275         NewOp(1101,loop,1,LOOP);
7276         OpTYPE_set(loop, OP_ENTERLOOP);
7277         loop->op_private = 0;
7278         loop->op_next = (OP*)loop;
7279     }
7280
7281     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
7282
7283     loop->op_redoop = redo;
7284     loop->op_lastop = o;
7285     o->op_private |= loopflags;
7286
7287     if (next)
7288         loop->op_nextop = next;
7289     else
7290         loop->op_nextop = o;
7291
7292     o->op_flags |= flags;
7293     o->op_private |= (flags >> 8);
7294     return o;
7295 }
7296
7297 /*
7298 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
7299
7300 Constructs, checks, and returns an op tree expressing a C<foreach>
7301 loop (iteration through a list of values).  This is a heavyweight loop,
7302 with structure that allows exiting the loop by C<last> and suchlike.
7303
7304 C<sv> optionally supplies the variable that will be aliased to each
7305 item in turn; if null, it defaults to C<$_>.
7306 C<expr> supplies the list of values to iterate over.  C<block> supplies
7307 the main body of the loop, and C<cont> optionally supplies a C<continue>
7308 block that operates as a second half of the body.  All of these optree
7309 inputs are consumed by this function and become part of the constructed
7310 op tree.
7311
7312 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7313 op and, shifted up eight bits, the eight bits of C<op_private> for
7314 the C<leaveloop> op, except that (in both cases) some bits will be set
7315 automatically.
7316
7317 =cut
7318 */
7319
7320 OP *
7321 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
7322 {
7323     dVAR;
7324     LOOP *loop;
7325     OP *wop;
7326     PADOFFSET padoff = 0;
7327     I32 iterflags = 0;
7328     I32 iterpflags = 0;
7329
7330     PERL_ARGS_ASSERT_NEWFOROP;
7331
7332     if (sv) {
7333         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
7334             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
7335             OpTYPE_set(sv, OP_RV2GV);
7336
7337             /* The op_type check is needed to prevent a possible segfault
7338              * if the loop variable is undeclared and 'strict vars' is in
7339              * effect. This is illegal but is nonetheless parsed, so we
7340              * may reach this point with an OP_CONST where we're expecting
7341              * an OP_GV.
7342              */
7343             if (cUNOPx(sv)->op_first->op_type == OP_GV
7344              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
7345                 iterpflags |= OPpITER_DEF;
7346         }
7347         else if (sv->op_type == OP_PADSV) { /* private variable */
7348             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
7349             padoff = sv->op_targ;
7350             sv->op_targ = 0;
7351             op_free(sv);
7352             sv = NULL;
7353             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
7354         }
7355         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
7356             NOOP;
7357         else
7358             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
7359         if (padoff) {
7360             PADNAME * const pn = PAD_COMPNAME(padoff);
7361             const char * const name = PadnamePV(pn);
7362
7363             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
7364                 iterpflags |= OPpITER_DEF;
7365         }
7366     }
7367     else {
7368         sv = newGVOP(OP_GV, 0, PL_defgv);
7369         iterpflags |= OPpITER_DEF;
7370     }
7371
7372     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
7373         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
7374         iterflags |= OPf_STACKED;
7375     }
7376     else if (expr->op_type == OP_NULL &&
7377              (expr->op_flags & OPf_KIDS) &&
7378              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
7379     {
7380         /* Basically turn for($x..$y) into the same as for($x,$y), but we
7381          * set the STACKED flag to indicate that these values are to be
7382          * treated as min/max values by 'pp_enteriter'.
7383          */
7384         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
7385         LOGOP* const range = (LOGOP*) flip->op_first;
7386         OP* const left  = range->op_first;
7387         OP* const right = OpSIBLING(left);
7388         LISTOP* listop;
7389
7390         range->op_flags &= ~OPf_KIDS;
7391         /* detach range's children */
7392         op_sibling_splice((OP*)range, NULL, -1, NULL);
7393
7394         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
7395         listop->op_first->op_next = range->op_next;
7396         left->op_next = range->op_other;
7397         right->op_next = (OP*)listop;
7398         listop->op_next = listop->op_first;
7399
7400         op_free(expr);
7401         expr = (OP*)(listop);
7402         op_null(expr);
7403         iterflags |= OPf_STACKED;
7404     }
7405     else {
7406         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
7407     }
7408
7409     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
7410                                   op_append_elem(OP_LIST, list(expr),
7411                                                  scalar(sv)));
7412     assert(!loop->op_next);
7413     /* for my  $x () sets OPpLVAL_INTRO;
7414      * for our $x () sets OPpOUR_INTRO */
7415     loop->op_private = (U8)iterpflags;
7416     if (loop->op_slabbed
7417      && DIFF(loop, OpSLOT(loop)->opslot_next)
7418          < SIZE_TO_PSIZE(sizeof(LOOP)))
7419     {
7420         LOOP *tmp;
7421         NewOp(1234,tmp,1,LOOP);
7422         Copy(loop,tmp,1,LISTOP);
7423 #ifdef PERL_OP_PARENT
7424         assert(loop->op_last->op_sibparent == (OP*)loop);
7425         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
7426 #endif
7427         S_op_destroy(aTHX_ (OP*)loop);
7428         loop = tmp;
7429     }
7430     else if (!loop->op_slabbed)
7431     {
7432         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
7433 #ifdef PERL_OP_PARENT
7434         OpLASTSIB_set(loop->op_last, (OP*)loop);
7435 #endif
7436     }
7437     loop->op_targ = padoff;
7438     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
7439     return wop;
7440 }
7441
7442 /*
7443 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
7444
7445 Constructs, checks, and returns a loop-exiting op (such as C<goto>
7446 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
7447 determining the target of the op; it is consumed by this function and
7448 becomes part of the constructed op tree.
7449
7450 =cut
7451 */
7452
7453 OP*
7454 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
7455 {
7456     OP *o = NULL;
7457
7458     PERL_ARGS_ASSERT_NEWLOOPEX;
7459
7460     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
7461         || type == OP_CUSTOM);
7462
7463     if (type != OP_GOTO) {
7464         /* "last()" means "last" */
7465         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
7466             o = newOP(type, OPf_SPECIAL);
7467         }
7468     }
7469     else {
7470         /* Check whether it's going to be a goto &function */
7471         if (label->op_type == OP_ENTERSUB
7472                 && !(label->op_flags & OPf_STACKED))
7473             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
7474     }
7475
7476     /* Check for a constant argument */
7477     if (label->op_type == OP_CONST) {
7478             SV * const sv = ((SVOP *)label)->op_sv;
7479             STRLEN l;
7480             const char *s = SvPV_const(sv,l);
7481             if (l == strlen(s)) {
7482                 o = newPVOP(type,
7483                             SvUTF8(((SVOP*)label)->op_sv),
7484                             savesharedpv(
7485                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
7486             }
7487     }
7488     
7489     /* If we have already created an op, we do not need the label. */
7490     if (o)
7491                 op_free(label);
7492     else o = newUNOP(type, OPf_STACKED, label);
7493
7494     PL_hints |= HINT_BLOCK_SCOPE;
7495     return o;
7496 }
7497
7498 /* if the condition is a literal array or hash
7499    (or @{ ... } etc), make a reference to it.
7500  */
7501 STATIC OP *
7502 S_ref_array_or_hash(pTHX_ OP *cond)
7503 {
7504     if (cond
7505     && (cond->op_type == OP_RV2AV
7506     ||  cond->op_type == OP_PADAV
7507     ||  cond->op_type == OP_RV2HV
7508     ||  cond->op_type == OP_PADHV))
7509
7510         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
7511
7512     else if(cond
7513     && (cond->op_type == OP_ASLICE
7514     ||  cond->op_type == OP_KVASLICE
7515     ||  cond->op_type == OP_HSLICE
7516     ||  cond->op_type == OP_KVHSLICE)) {
7517
7518         /* anonlist now needs a list from this op, was previously used in
7519          * scalar context */
7520         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
7521         cond->op_flags |= OPf_WANT_LIST;
7522
7523         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
7524     }
7525
7526     else
7527         return cond;
7528 }
7529
7530 /* These construct the optree fragments representing given()
7531    and when() blocks.
7532
7533    entergiven and enterwhen are LOGOPs; the op_other pointer
7534    points up to the associated leave op. We need this so we
7535    can put it in the context and make break/continue work.
7536    (Also, of course, pp_enterwhen will jump straight to
7537    op_other if the match fails.)
7538  */
7539
7540 STATIC OP *
7541 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
7542                    I32 enter_opcode, I32 leave_opcode,
7543                    PADOFFSET entertarg)
7544 {
7545     dVAR;
7546     LOGOP *enterop;
7547     OP *o;
7548
7549     PERL_ARGS_ASSERT_NEWGIVWHENOP;
7550     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
7551
7552     enterop = S_alloc_LOGOP(aTHX_ enter_opcode, block, NULL);
7553     enterop->op_targ = 0;
7554     enterop->op_private = 0;
7555
7556     o = newUNOP(leave_opcode, 0, (OP *) enterop);
7557
7558     if (cond) {
7559         /* prepend cond if we have one */
7560         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
7561
7562         o->op_next = LINKLIST(cond);
7563         cond->op_next = (OP *) enterop;
7564     }
7565     else {
7566         /* This is a default {} block */
7567         enterop->op_flags |= OPf_SPECIAL;
7568         o      ->op_flags |= OPf_SPECIAL;
7569
7570         o->op_next = (OP *) enterop;
7571     }
7572
7573     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
7574                                        entergiven and enterwhen both
7575                                        use ck_null() */
7576
7577     enterop->op_next = LINKLIST(block);
7578     block->op_next = enterop->op_other = o;
7579
7580     return o;
7581 }
7582
7583 /* Does this look like a boolean operation? For these purposes
7584    a boolean operation is:
7585      - a subroutine call [*]
7586      - a logical connective
7587      - a comparison operator
7588      - a filetest operator, with the exception of -s -M -A -C
7589      - defined(), exists() or eof()
7590      - /$re/ or $foo =~ /$re/
7591    
7592    [*] possibly surprising
7593  */
7594 STATIC bool
7595 S_looks_like_bool(pTHX_ const OP *o)
7596 {
7597     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
7598
7599     switch(o->op_type) {
7600         case OP_OR:
7601         case OP_DOR:
7602             return looks_like_bool(cLOGOPo->op_first);
7603
7604         case OP_AND:
7605         {
7606             OP* sibl = OpSIBLING(cLOGOPo->op_first);
7607             ASSUME(sibl);
7608             return (
7609                 looks_like_bool(cLOGOPo->op_first)
7610              && looks_like_bool(sibl));
7611         }
7612
7613         case OP_NULL:
7614         case OP_SCALAR:
7615             return (
7616                 o->op_flags & OPf_KIDS
7617             && looks_like_bool(cUNOPo->op_first));
7618
7619         case OP_ENTERSUB:
7620
7621         case OP_NOT:    case OP_XOR:
7622
7623         case OP_EQ:     case OP_NE:     case OP_LT:
7624         case OP_GT:     case OP_LE:     case OP_GE:
7625
7626         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
7627         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
7628
7629         case OP_SEQ:    case OP_SNE:    case OP_SLT:
7630         case OP_SGT:    case OP_SLE:    case OP_SGE:
7631         
7632         case OP_SMARTMATCH:
7633         
7634         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
7635         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
7636         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
7637         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
7638         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
7639         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
7640         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
7641         case OP_FTTEXT:   case OP_FTBINARY:
7642         
7643         case OP_DEFINED: case OP_EXISTS:
7644         case OP_MATCH:   case OP_EOF:
7645
7646         case OP_FLOP:
7647
7648             return TRUE;
7649         
7650         case OP_CONST:
7651             /* Detect comparisons that have been optimized away */
7652             if (cSVOPo->op_sv == &PL_sv_yes
7653             ||  cSVOPo->op_sv == &PL_sv_no)
7654             
7655                 return TRUE;
7656             else
7657                 return FALSE;
7658
7659         /* FALLTHROUGH */
7660         default:
7661             return FALSE;
7662     }
7663 }
7664
7665 /*
7666 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
7667
7668 Constructs, checks, and returns an op tree expressing a C<given> block.
7669 C<cond> supplies the expression that will be locally assigned to a lexical
7670 variable, and C<block> supplies the body of the C<given> construct; they
7671 are consumed by this function and become part of the constructed op tree.
7672 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
7673
7674 =cut
7675 */
7676
7677 OP *
7678 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
7679 {
7680     PERL_ARGS_ASSERT_NEWGIVENOP;
7681     PERL_UNUSED_ARG(defsv_off);
7682
7683     assert(!defsv_off);
7684     return newGIVWHENOP(
7685         ref_array_or_hash(cond),
7686         block,
7687         OP_ENTERGIVEN, OP_LEAVEGIVEN,
7688         0);
7689 }
7690
7691 /*
7692 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
7693
7694 Constructs, checks, and returns an op tree expressing a C<when> block.
7695 C<cond> supplies the test expression, and C<block> supplies the block
7696 that will be executed if the test evaluates to true; they are consumed
7697 by this function and become part of the constructed op tree.  C<cond>
7698 will be interpreted DWIMically, often as a comparison against C<$_>,
7699 and may be null to generate a C<default> block.
7700
7701 =cut
7702 */
7703
7704 OP *
7705 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
7706 {
7707     const bool cond_llb = (!cond || looks_like_bool(cond));
7708     OP *cond_op;
7709
7710     PERL_ARGS_ASSERT_NEWWHENOP;
7711
7712     if (cond_llb)
7713         cond_op = cond;
7714     else {
7715         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
7716                 newDEFSVOP(),
7717                 scalar(ref_array_or_hash(cond)));
7718     }
7719     
7720     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
7721 }
7722
7723 /* must not conflict with SVf_UTF8 */
7724 #define CV_CKPROTO_CURSTASH     0x1
7725
7726 void
7727 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
7728                     const STRLEN len, const U32 flags)
7729 {
7730     SV *name = NULL, *msg;
7731     const char * cvp = SvROK(cv)
7732                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
7733                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
7734                            : ""
7735                         : CvPROTO(cv);
7736     STRLEN clen = CvPROTOLEN(cv), plen = len;
7737
7738     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
7739
7740     if (p == NULL && cvp == NULL)
7741         return;
7742
7743     if (!ckWARN_d(WARN_PROTOTYPE))
7744         return;
7745
7746     if (p && cvp) {
7747         p = S_strip_spaces(aTHX_ p, &plen);
7748         cvp = S_strip_spaces(aTHX_ cvp, &clen);
7749         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
7750             if (plen == clen && memEQ(cvp, p, plen))
7751                 return;
7752         } else {
7753             if (flags & SVf_UTF8) {
7754                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
7755                     return;
7756             }
7757             else {
7758                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
7759                     return;
7760             }
7761         }
7762     }
7763
7764     msg = sv_newmortal();
7765
7766     if (gv)
7767     {
7768         if (isGV(gv))
7769             gv_efullname3(name = sv_newmortal(), gv, NULL);
7770         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
7771             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
7772         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
7773             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
7774             sv_catpvs(name, "::");
7775             if (SvROK(gv)) {
7776                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
7777                 assert (CvNAMED(SvRV_const(gv)));
7778                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
7779             }
7780             else sv_catsv(name, (SV *)gv);
7781         }
7782         else name = (SV *)gv;
7783     }
7784     sv_setpvs(msg, "Prototype mismatch:");
7785     if (name)
7786         Perl_sv_catpvf(aTHX_ msg, " sub %"SVf, SVfARG(name));
7787     if (cvp)
7788         Perl_sv_catpvf(aTHX_ msg, " (%"UTF8f")", 
7789             UTF8fARG(SvUTF8(cv),clen,cvp)
7790         );
7791     else
7792         sv_catpvs(msg, ": none");
7793     sv_catpvs(msg, " vs ");
7794     if (p)
7795         Perl_sv_catpvf(aTHX_ msg, "(%"UTF8f")", UTF8fARG(flags & SVf_UTF8,len,p));
7796     else
7797         sv_catpvs(msg, "none");
7798     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%"SVf, SVfARG(msg));
7799 }
7800
7801 static void const_sv_xsub(pTHX_ CV* cv);
7802 static void const_av_xsub(pTHX_ CV* cv);
7803
7804 /*
7805
7806 =head1 Optree Manipulation Functions
7807
7808 =for apidoc cv_const_sv
7809
7810 If C<cv> is a constant sub eligible for inlining, returns the constant
7811 value returned by the sub.  Otherwise, returns C<NULL>.
7812
7813 Constant subs can be created with C<newCONSTSUB> or as described in
7814 L<perlsub/"Constant Functions">.
7815
7816 =cut
7817 */
7818 SV *
7819 Perl_cv_const_sv(const CV *const cv)
7820 {
7821     SV *sv;
7822     if (!cv)
7823         return NULL;
7824     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
7825         return NULL;
7826     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7827     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
7828     return sv;
7829 }
7830
7831 SV *
7832 Perl_cv_const_sv_or_av(const CV * const cv)
7833 {
7834     if (!cv)
7835         return NULL;
7836     if (SvROK(cv)) return SvRV((SV *)cv);
7837     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
7838     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7839 }
7840
7841 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
7842  * Can be called in 2 ways:
7843  *
7844  * !allow_lex
7845  *      look for a single OP_CONST with attached value: return the value
7846  *
7847  * allow_lex && !CvCONST(cv);
7848  *
7849  *      examine the clone prototype, and if contains only a single
7850  *      OP_CONST, return the value; or if it contains a single PADSV ref-
7851  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
7852  *      a candidate for "constizing" at clone time, and return NULL.
7853  */
7854
7855 static SV *
7856 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
7857 {
7858     SV *sv = NULL;
7859     bool padsv = FALSE;
7860
7861     assert(o);
7862     assert(cv);
7863
7864     for (; o; o = o->op_next) {
7865         const OPCODE type = o->op_type;
7866
7867         if (type == OP_NEXTSTATE || type == OP_LINESEQ
7868              || type == OP_NULL
7869              || type == OP_PUSHMARK)
7870                 continue;
7871         if (type == OP_DBSTATE)
7872                 continue;
7873         if (type == OP_LEAVESUB)
7874             break;
7875         if (sv)
7876             return NULL;
7877         if (type == OP_CONST && cSVOPo->op_sv)
7878             sv = cSVOPo->op_sv;
7879         else if (type == OP_UNDEF && !o->op_private) {
7880             sv = newSV(0);
7881             SAVEFREESV(sv);
7882         }
7883         else if (allow_lex && type == OP_PADSV) {
7884                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
7885                 {
7886                     sv = &PL_sv_undef; /* an arbitrary non-null value */
7887                     padsv = TRUE;
7888                 }
7889                 else
7890                     return NULL;
7891         }
7892         else {
7893             return NULL;
7894         }
7895     }
7896     if (padsv) {
7897         CvCONST_on(cv);
7898         return NULL;
7899     }
7900     return sv;
7901 }
7902
7903 static bool
7904 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
7905                         PADNAME * const name, SV ** const const_svp)
7906 {
7907     assert (cv);
7908     assert (o || name);
7909     assert (const_svp);
7910     if ((!block
7911          )) {
7912         if (CvFLAGS(PL_compcv)) {
7913             /* might have had built-in attrs applied */
7914             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
7915             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
7916              && ckWARN(WARN_MISC))
7917             {
7918                 /* protect against fatal warnings leaking compcv */
7919                 SAVEFREESV(PL_compcv);
7920                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
7921                 SvREFCNT_inc_simple_void_NN(PL_compcv);
7922             }
7923             CvFLAGS(cv) |=
7924                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
7925                   & ~(CVf_LVALUE * pureperl));
7926         }
7927         return FALSE;
7928     }
7929
7930     /* redundant check for speed: */
7931     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
7932         const line_t oldline = CopLINE(PL_curcop);
7933         SV *namesv = o
7934             ? cSVOPo->op_sv
7935             : sv_2mortal(newSVpvn_utf8(
7936                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
7937               ));
7938         if (PL_parser && PL_parser->copline != NOLINE)
7939             /* This ensures that warnings are reported at the first
7940                line of a redefinition, not the last.  */
7941             CopLINE_set(PL_curcop, PL_parser->copline);
7942         /* protect against fatal warnings leaking compcv */
7943         SAVEFREESV(PL_compcv);
7944         report_redefined_cv(namesv, cv, const_svp);
7945         SvREFCNT_inc_simple_void_NN(PL_compcv);
7946         CopLINE_set(PL_curcop, oldline);
7947     }
7948     SAVEFREESV(cv);
7949     return TRUE;
7950 }
7951
7952 CV *
7953 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
7954 {
7955     CV **spot;
7956     SV **svspot;
7957     const char *ps;
7958     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
7959     U32 ps_utf8 = 0;
7960     CV *cv = NULL;
7961     CV *compcv = PL_compcv;
7962     SV *const_sv;
7963     PADNAME *name;
7964     PADOFFSET pax = o->op_targ;
7965     CV *outcv = CvOUTSIDE(PL_compcv);
7966     CV *clonee = NULL;
7967     HEK *hek = NULL;
7968     bool reusable = FALSE;
7969     OP *start = NULL;
7970 #ifdef PERL_DEBUG_READONLY_OPS
7971     OPSLAB *slab = NULL;
7972 #endif
7973
7974     PERL_ARGS_ASSERT_NEWMYSUB;
7975
7976     /* Find the pad slot for storing the new sub.
7977        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
7978        need to look in CvOUTSIDE and find the pad belonging to the enclos-
7979        ing sub.  And then we need to dig deeper if this is a lexical from
7980        outside, as in:
7981            my sub foo; sub { sub foo { } }
7982      */
7983    redo:
7984     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
7985     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
7986         pax = PARENT_PAD_INDEX(name);
7987         outcv = CvOUTSIDE(outcv);
7988         assert(outcv);
7989         goto redo;
7990     }
7991     svspot =
7992         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
7993                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
7994     spot = (CV **)svspot;
7995
7996     if (!(PL_parser && PL_parser->error_count))
7997         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name));
7998
7999     if (proto) {
8000         assert(proto->op_type == OP_CONST);
8001         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8002         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8003     }
8004     else
8005         ps = NULL;
8006
8007     if (proto)
8008         SAVEFREEOP(proto);
8009     if (attrs)
8010         SAVEFREEOP(attrs);
8011
8012     if (PL_parser && PL_parser->error_count) {
8013         op_free(block);
8014         SvREFCNT_dec(PL_compcv);
8015         PL_compcv = 0;
8016         goto done;
8017     }
8018
8019     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8020         cv = *spot;
8021         svspot = (SV **)(spot = &clonee);
8022     }
8023     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
8024         cv = *spot;
8025     else {
8026         assert (SvTYPE(*spot) == SVt_PVCV);
8027         if (CvNAMED(*spot))
8028             hek = CvNAME_HEK(*spot);
8029         else {
8030             dVAR;
8031             U32 hash;
8032             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8033             CvNAME_HEK_set(*spot, hek =
8034                 share_hek(
8035                     PadnamePV(name)+1,
8036                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8037                     hash
8038                 )
8039             );
8040             CvLEXICAL_on(*spot);
8041         }
8042         cv = PadnamePROTOCV(name);
8043         svspot = (SV **)(spot = &PadnamePROTOCV(name));
8044     }
8045
8046     if (block) {
8047         /* This makes sub {}; work as expected.  */
8048         if (block->op_type == OP_STUB) {
8049             const line_t l = PL_parser->copline;
8050             op_free(block);
8051             block = newSTATEOP(0, NULL, 0);
8052             PL_parser->copline = l;
8053         }
8054         block = CvLVALUE(compcv)
8055              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
8056                    ? newUNOP(OP_LEAVESUBLV, 0,
8057                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8058                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8059         start = LINKLIST(block);
8060         block->op_next = 0;
8061         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
8062             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
8063         else
8064             const_sv = NULL;
8065     }
8066     else
8067         const_sv = NULL;
8068
8069     if (cv) {
8070         const bool exists = CvROOT(cv) || CvXSUB(cv);
8071
8072         /* if the subroutine doesn't exist and wasn't pre-declared
8073          * with a prototype, assume it will be AUTOLOADed,
8074          * skipping the prototype check
8075          */
8076         if (exists || SvPOK(cv))
8077             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
8078                                  ps_utf8);
8079         /* already defined? */
8080         if (exists) {
8081             if (S_already_defined(aTHX_ cv,block,NULL,name,&const_sv))
8082                 cv = NULL;
8083             else {
8084                 if (attrs) goto attrs;
8085                 /* just a "sub foo;" when &foo is already defined */
8086                 SAVEFREESV(compcv);
8087                 goto done;
8088             }
8089         }
8090         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8091             cv = NULL;
8092             reusable = TRUE;
8093         }
8094     }
8095     if (const_sv) {
8096         SvREFCNT_inc_simple_void_NN(const_sv);
8097         SvFLAGS(const_sv) |= SVs_PADTMP;
8098         if (cv) {
8099             assert(!CvROOT(cv) && !CvCONST(cv));
8100             cv_forget_slab(cv);
8101         }
8102         else {
8103             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8104             CvFILE_set_from_cop(cv, PL_curcop);
8105             CvSTASH_set(cv, PL_curstash);
8106             *spot = cv;
8107         }
8108         sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8109         CvXSUBANY(cv).any_ptr = const_sv;
8110         CvXSUB(cv) = const_sv_xsub;
8111         CvCONST_on(cv);
8112         CvISXSUB_on(cv);
8113         PoisonPADLIST(cv);
8114         CvFLAGS(cv) |= CvMETHOD(compcv);
8115         op_free(block);
8116         SvREFCNT_dec(compcv);
8117         PL_compcv = NULL;
8118         goto setname;
8119     }
8120     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
8121        determine whether this sub definition is in the same scope as its
8122        declaration.  If this sub definition is inside an inner named pack-
8123        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
8124        the package sub.  So check PadnameOUTER(name) too.
8125      */
8126     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
8127         assert(!CvWEAKOUTSIDE(compcv));
8128         SvREFCNT_dec(CvOUTSIDE(compcv));
8129         CvWEAKOUTSIDE_on(compcv);
8130     }
8131     /* XXX else do we have a circular reference? */
8132     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
8133         /* transfer PL_compcv to cv */
8134         if (block
8135         ) {
8136             cv_flags_t preserved_flags =
8137                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
8138             PADLIST *const temp_padl = CvPADLIST(cv);
8139             CV *const temp_cv = CvOUTSIDE(cv);
8140             const cv_flags_t other_flags =
8141                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8142             OP * const cvstart = CvSTART(cv);
8143
8144             SvPOK_off(cv);
8145             CvFLAGS(cv) =
8146                 CvFLAGS(compcv) | preserved_flags;
8147             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
8148             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
8149             CvPADLIST_set(cv, CvPADLIST(compcv));
8150             CvOUTSIDE(compcv) = temp_cv;
8151             CvPADLIST_set(compcv, temp_padl);
8152             CvSTART(cv) = CvSTART(compcv);
8153             CvSTART(compcv) = cvstart;
8154             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8155             CvFLAGS(compcv) |= other_flags;
8156
8157             if (CvFILE(cv) && CvDYNFILE(cv)) {
8158                 Safefree(CvFILE(cv));
8159             }
8160
8161             /* inner references to compcv must be fixed up ... */
8162             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
8163             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8164               ++PL_sub_generation;
8165         }
8166         else {
8167             /* Might have had built-in attributes applied -- propagate them. */
8168             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
8169         }
8170         /* ... before we throw it away */
8171         SvREFCNT_dec(compcv);
8172         PL_compcv = compcv = cv;
8173     }
8174     else {
8175         cv = compcv;
8176         *spot = cv;
8177     }
8178    setname:
8179     CvLEXICAL_on(cv);
8180     if (!CvNAME_HEK(cv)) {
8181         if (hek) (void)share_hek_hek(hek);
8182         else {
8183             dVAR;
8184             U32 hash;
8185             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8186             hek = share_hek(PadnamePV(name)+1,
8187                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8188                       hash);
8189         }
8190         CvNAME_HEK_set(cv, hek);
8191     }
8192     if (const_sv) goto clone;
8193
8194     CvFILE_set_from_cop(cv, PL_curcop);
8195     CvSTASH_set(cv, PL_curstash);
8196
8197     if (ps) {
8198         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8199         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8200     }
8201
8202     if (!block)
8203         goto attrs;
8204
8205     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8206        the debugger could be able to set a breakpoint in, so signal to
8207        pp_entereval that it should not throw away any saved lines at scope
8208        exit.  */
8209        
8210     PL_breakable_sub_gen++;
8211     CvROOT(cv) = block;
8212     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8213     OpREFCNT_set(CvROOT(cv), 1);
8214     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8215        itself has a refcount. */
8216     CvSLABBED_off(cv);
8217     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8218 #ifdef PERL_DEBUG_READONLY_OPS
8219     slab = (OPSLAB *)CvSTART(cv);
8220 #endif
8221     CvSTART(cv) = start;
8222     CALL_PEEP(start);
8223     finalize_optree(CvROOT(cv));
8224     S_prune_chain_head(&CvSTART(cv));
8225
8226     /* now that optimizer has done its work, adjust pad values */
8227
8228     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8229
8230   attrs:
8231     if (attrs) {
8232         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8233         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
8234     }
8235
8236     if (block) {
8237         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8238             SV * const tmpstr = sv_newmortal();
8239             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8240                                                   GV_ADDMULTI, SVt_PVHV);
8241             HV *hv;
8242             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8243                                           CopFILE(PL_curcop),
8244                                           (long)PL_subline,
8245                                           (long)CopLINE(PL_curcop));
8246             if (HvNAME_HEK(PL_curstash)) {
8247                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
8248                 sv_catpvs(tmpstr, "::");
8249             }
8250             else sv_setpvs(tmpstr, "__ANON__::");
8251             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
8252                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
8253             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8254                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8255             hv = GvHVn(db_postponed);
8256             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8257                 CV * const pcv = GvCV(db_postponed);
8258                 if (pcv) {
8259                     dSP;
8260                     PUSHMARK(SP);
8261                     XPUSHs(tmpstr);
8262                     PUTBACK;
8263                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8264                 }
8265             }
8266         }
8267     }
8268
8269   clone:
8270     if (clonee) {
8271         assert(CvDEPTH(outcv));
8272         spot = (CV **)
8273             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
8274         if (reusable) cv_clone_into(clonee, *spot);
8275         else *spot = cv_clone(clonee);
8276         SvREFCNT_dec_NN(clonee);
8277         cv = *spot;
8278     }
8279     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
8280         PADOFFSET depth = CvDEPTH(outcv);
8281         while (--depth) {
8282             SV *oldcv;
8283             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
8284             oldcv = *svspot;
8285             *svspot = SvREFCNT_inc_simple_NN(cv);
8286             SvREFCNT_dec(oldcv);
8287         }
8288     }
8289
8290   done:
8291     if (PL_parser)
8292         PL_parser->copline = NOLINE;
8293     LEAVE_SCOPE(floor);
8294 #ifdef PERL_DEBUG_READONLY_OPS
8295     if (slab)
8296         Slab_to_ro(slab);
8297 #endif
8298     op_free(o);
8299     return cv;
8300 }
8301
8302 /* _x = extended */
8303 CV *
8304 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
8305                             OP *block, bool o_is_gv)
8306 {
8307     GV *gv;
8308     const char *ps;
8309     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8310     U32 ps_utf8 = 0;
8311     CV *cv = NULL;
8312     SV *const_sv;
8313     const bool ec = PL_parser && PL_parser->error_count;
8314     /* If the subroutine has no body, no attributes, and no builtin attributes
8315        then it's just a sub declaration, and we may be able to get away with
8316        storing with a placeholder scalar in the symbol table, rather than a
8317        full CV.  If anything is present then it will take a full CV to
8318        store it.  */
8319     const I32 gv_fetch_flags
8320         = ec ? GV_NOADD_NOINIT :
8321         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
8322         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
8323     STRLEN namlen = 0;
8324     const char * const name =
8325          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
8326     bool has_name;
8327     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
8328     bool evanescent = FALSE;
8329     OP *start = NULL;
8330 #ifdef PERL_DEBUG_READONLY_OPS
8331     OPSLAB *slab = NULL;
8332 #endif
8333
8334     if (o_is_gv) {
8335         gv = (GV*)o;
8336         o = NULL;
8337         has_name = TRUE;
8338     } else if (name) {
8339         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
8340            hek and CvSTASH pointer together can imply the GV.  If the name
8341            contains a package name, then GvSTASH(CvGV(cv)) may differ from
8342            CvSTASH, so forego the optimisation if we find any.
8343            Also, we may be called from load_module at run time, so
8344            PL_curstash (which sets CvSTASH) may not point to the stash the
8345            sub is stored in.  */
8346         const I32 flags =
8347            ec ? GV_NOADD_NOINIT
8348               :   PL_curstash != CopSTASH(PL_curcop)
8349                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
8350                     ? gv_fetch_flags
8351                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
8352         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
8353         has_name = TRUE;
8354     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
8355         SV * const sv = sv_newmortal();
8356         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%"IVdf"]",
8357                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8358                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
8359         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
8360         has_name = TRUE;
8361     } else if (PL_curstash) {
8362         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
8363         has_name = FALSE;
8364     } else {
8365         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
8366         has_name = FALSE;
8367     }
8368     if (!ec) {
8369         if (isGV(gv)) {
8370             move_proto_attr(&proto, &attrs, gv);
8371         } else {
8372             assert(cSVOPo);
8373             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv);
8374         }
8375     }
8376
8377     if (proto) {
8378         assert(proto->op_type == OP_CONST);
8379         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8380         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8381     }
8382     else
8383         ps = NULL;
8384
8385     if (o)
8386         SAVEFREEOP(o);
8387     if (proto)
8388         SAVEFREEOP(proto);
8389     if (attrs)
8390         SAVEFREEOP(attrs);
8391
8392     if (ec) {
8393         op_free(block);
8394         if (name) SvREFCNT_dec(PL_compcv);
8395         else cv = PL_compcv;
8396         PL_compcv = 0;
8397         if (name && block) {
8398             const char *s = strrchr(name, ':');
8399             s = s ? s+1 : name;
8400             if (strEQ(s, "BEGIN")) {
8401                 if (PL_in_eval & EVAL_KEEPERR)
8402                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
8403                 else {
8404                     SV * const errsv = ERRSV;
8405                     /* force display of errors found but not reported */
8406                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
8407                     Perl_croak_nocontext("%"SVf, SVfARG(errsv));
8408                 }
8409             }
8410         }
8411         goto done;
8412     }
8413
8414     if (!block && SvTYPE(gv) != SVt_PVGV) {
8415       /* If we are not defining a new sub and the existing one is not a
8416          full GV + CV... */
8417       if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
8418         /* We are applying attributes to an existing sub, so we need it
8419            upgraded if it is a constant.  */
8420         if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
8421             gv_init_pvn(gv, PL_curstash, name, namlen,
8422                         SVf_UTF8 * name_is_utf8);
8423       }
8424       else {                    /* Maybe prototype now, and had at maximum
8425                                    a prototype or const/sub ref before.  */
8426         if (SvTYPE(gv) > SVt_NULL) {
8427             cv_ckproto_len_flags((const CV *)gv,
8428                                  o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8429                                  ps_len, ps_utf8);
8430         }
8431         if (!SvROK(gv)) {
8432           if (ps) {
8433             sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
8434             if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(gv));
8435           }
8436           else
8437             sv_setiv(MUTABLE_SV(gv), -1);
8438         }
8439
8440         SvREFCNT_dec(PL_compcv);
8441         cv = PL_compcv = NULL;
8442         goto done;
8443       }
8444     }
8445
8446     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
8447         ? NULL
8448         : isGV(gv)
8449             ? GvCV(gv)
8450             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
8451                 ? (CV *)SvRV(gv)
8452                 : NULL;
8453
8454     if (block) {
8455         assert(PL_parser);
8456         /* This makes sub {}; work as expected.  */
8457         if (block->op_type == OP_STUB) {
8458             const line_t l = PL_parser->copline;
8459             op_free(block);
8460             block = newSTATEOP(0, NULL, 0);
8461             PL_parser->copline = l;
8462         }
8463         block = CvLVALUE(PL_compcv)
8464              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
8465                     && (!isGV(gv) || !GvASSUMECV(gv)))
8466                    ? newUNOP(OP_LEAVESUBLV, 0,
8467                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8468                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8469         start = LINKLIST(block);
8470         block->op_next = 0;
8471         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
8472             const_sv =
8473                 S_op_const_sv(aTHX_ start, PL_compcv,
8474                                         cBOOL(CvCLONE(PL_compcv)));
8475         else
8476             const_sv = NULL;
8477     }
8478     else
8479         const_sv = NULL;
8480
8481     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
8482         cv_ckproto_len_flags((const CV *)gv,
8483                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8484                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
8485         if (SvROK(gv)) {
8486             /* All the other code for sub redefinition warnings expects the
8487                clobbered sub to be a CV.  Instead of making all those code
8488                paths more complex, just inline the RV version here.  */
8489             const line_t oldline = CopLINE(PL_curcop);
8490             assert(IN_PERL_COMPILETIME);
8491             if (PL_parser && PL_parser->copline != NOLINE)
8492                 /* This ensures that warnings are reported at the first
8493                    line of a redefinition, not the last.  */
8494                 CopLINE_set(PL_curcop, PL_parser->copline);
8495             /* protect against fatal warnings leaking compcv */
8496             SAVEFREESV(PL_compcv);
8497
8498             if (ckWARN(WARN_REDEFINE)
8499              || (  ckWARN_d(WARN_REDEFINE)
8500                 && (  !const_sv || SvRV(gv) == const_sv
8501                    || sv_cmp(SvRV(gv), const_sv)  ))) {
8502                 assert(cSVOPo);
8503                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8504                           "Constant subroutine %"SVf" redefined",
8505                           SVfARG(cSVOPo->op_sv));
8506             }
8507
8508             SvREFCNT_inc_simple_void_NN(PL_compcv);
8509             CopLINE_set(PL_curcop, oldline);
8510             SvREFCNT_dec(SvRV(gv));
8511         }
8512     }
8513
8514     if (cv) {
8515         const bool exists = CvROOT(cv) || CvXSUB(cv);
8516
8517         /* if the subroutine doesn't exist and wasn't pre-declared
8518          * with a prototype, assume it will be AUTOLOADed,
8519          * skipping the prototype check
8520          */
8521         if (exists || SvPOK(cv))
8522             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
8523         /* already defined (or promised)? */
8524         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
8525             if (S_already_defined(aTHX_ cv, block, o, NULL, &const_sv))
8526                 cv = NULL;
8527             else {
8528                 if (attrs) goto attrs;
8529                 /* just a "sub foo;" when &foo is already defined */
8530                 SAVEFREESV(PL_compcv);
8531                 goto done;
8532             }
8533         }
8534     }
8535     if (const_sv) {
8536         SvREFCNT_inc_simple_void_NN(const_sv);
8537         SvFLAGS(const_sv) |= SVs_PADTMP;
8538         if (cv) {
8539             assert(!CvROOT(cv) && !CvCONST(cv));
8540             cv_forget_slab(cv);
8541             sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8542             CvXSUBANY(cv).any_ptr = const_sv;
8543             CvXSUB(cv) = const_sv_xsub;
8544             CvCONST_on(cv);
8545             CvISXSUB_on(cv);
8546             PoisonPADLIST(cv);
8547             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8548         }
8549         else {
8550             if (isGV(gv) || CvMETHOD(PL_compcv)) {
8551                 if (name && isGV(gv))
8552                     GvCV_set(gv, NULL);
8553                 cv = newCONSTSUB_flags(
8554                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
8555                     const_sv
8556                 );
8557                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8558             }
8559             else {
8560                 if (!SvROK(gv)) {
8561                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8562                     prepare_SV_for_RV((SV *)gv);
8563                     SvOK_off((SV *)gv);
8564                     SvROK_on(gv);
8565                 }
8566                 SvRV_set(gv, const_sv);
8567             }
8568         }
8569         op_free(block);
8570         SvREFCNT_dec(PL_compcv);
8571         PL_compcv = NULL;
8572         goto done;
8573     }
8574     if (cv) {                           /* must reuse cv if autoloaded */
8575         /* transfer PL_compcv to cv */
8576         if (block
8577         ) {
8578             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
8579             PADLIST *const temp_av = CvPADLIST(cv);
8580             CV *const temp_cv = CvOUTSIDE(cv);
8581             const cv_flags_t other_flags =
8582                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8583             OP * const cvstart = CvSTART(cv);
8584
8585             if (isGV(gv)) {
8586                 CvGV_set(cv,gv);
8587                 assert(!CvCVGV_RC(cv));
8588                 assert(CvGV(cv) == gv);
8589             }
8590             else {
8591                 dVAR;
8592                 U32 hash;
8593                 PERL_HASH(hash, name, namlen);
8594                 CvNAME_HEK_set(cv,
8595                                share_hek(name,
8596                                          name_is_utf8
8597                                             ? -(SSize_t)namlen
8598                                             :  (SSize_t)namlen,
8599                                          hash));
8600             }
8601
8602             SvPOK_off(cv);
8603             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
8604                                              | CvNAMED(cv);
8605             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
8606             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
8607             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
8608             CvOUTSIDE(PL_compcv) = temp_cv;
8609             CvPADLIST_set(PL_compcv, temp_av);
8610             CvSTART(cv) = CvSTART(PL_compcv);
8611             CvSTART(PL_compcv) = cvstart;
8612             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8613             CvFLAGS(PL_compcv) |= other_flags;
8614
8615             if (CvFILE(cv) && CvDYNFILE(cv)) {
8616                 Safefree(CvFILE(cv));
8617     }
8618             CvFILE_set_from_cop(cv, PL_curcop);
8619             CvSTASH_set(cv, PL_curstash);
8620
8621             /* inner references to PL_compcv must be fixed up ... */
8622             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
8623             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8624               ++PL_sub_generation;
8625         }
8626         else {
8627             /* Might have had built-in attributes applied -- propagate them. */
8628             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
8629         }
8630         /* ... before we throw it away */
8631         SvREFCNT_dec(PL_compcv);
8632         PL_compcv = cv;
8633     }
8634     else {
8635         cv = PL_compcv;
8636         if (name && isGV(gv)) {
8637             GvCV_set(gv, cv);
8638             GvCVGEN(gv) = 0;
8639             if (HvENAME_HEK(GvSTASH(gv)))
8640                 /* sub Foo::bar { (shift)+1 } */
8641                 gv_method_changed(gv);
8642         }
8643         else if (name) {
8644             if (!SvROK(gv)) {
8645                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8646                 prepare_SV_for_RV((SV *)gv);
8647                 SvOK_off((SV *)gv);
8648                 SvROK_on(gv);
8649             }
8650             SvRV_set(gv, (SV *)cv);
8651         }
8652     }
8653     if (!CvHASGV(cv)) {
8654         if (isGV(gv)) CvGV_set(cv, gv);
8655         else {
8656             dVAR;
8657             U32 hash;
8658             PERL_HASH(hash, name, namlen);
8659             CvNAME_HEK_set(cv, share_hek(name,
8660                                          name_is_utf8
8661                                             ? -(SSize_t)namlen
8662                                             :  (SSize_t)namlen,
8663                                          hash));
8664         }
8665         CvFILE_set_from_cop(cv, PL_curcop);
8666         CvSTASH_set(cv, PL_curstash);
8667     }
8668
8669     if (ps) {
8670         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8671         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8672     }
8673
8674     if (!block)
8675         goto attrs;
8676
8677     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8678        the debugger could be able to set a breakpoint in, so signal to
8679        pp_entereval that it should not throw away any saved lines at scope
8680        exit.  */
8681        
8682     PL_breakable_sub_gen++;
8683     CvROOT(cv) = block;
8684     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8685     OpREFCNT_set(CvROOT(cv), 1);
8686     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8687        itself has a refcount. */
8688     CvSLABBED_off(cv);
8689     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8690 #ifdef PERL_DEBUG_READONLY_OPS
8691     slab = (OPSLAB *)CvSTART(cv);
8692 #endif
8693     CvSTART(cv) = start;
8694     CALL_PEEP(start);
8695     finalize_optree(CvROOT(cv));
8696     S_prune_chain_head(&CvSTART(cv));
8697
8698     /* now that optimizer has done its work, adjust pad values */
8699
8700     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8701
8702   attrs:
8703     if (attrs) {
8704         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8705         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
8706                         ? GvSTASH(CvGV(cv))
8707                         : PL_curstash;
8708         if (!name) SAVEFREESV(cv);
8709         apply_attrs(stash, MUTABLE_SV(cv), attrs);
8710         if (!name) SvREFCNT_inc_simple_void_NN(cv);
8711     }
8712
8713     if (block && has_name) {
8714         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8715             SV * const tmpstr = cv_name(cv,NULL,0);
8716             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8717                                                   GV_ADDMULTI, SVt_PVHV);
8718             HV *hv;
8719             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8720                                           CopFILE(PL_curcop),
8721                                           (long)PL_subline,
8722                                           (long)CopLINE(PL_curcop));
8723             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8724                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8725             hv = GvHVn(db_postponed);
8726             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8727                 CV * const pcv = GvCV(db_postponed);
8728                 if (pcv) {
8729                     dSP;
8730                     PUSHMARK(SP);
8731                     XPUSHs(tmpstr);
8732                     PUTBACK;
8733                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8734                 }
8735             }
8736         }
8737
8738         if (name) {
8739             if (PL_parser && PL_parser->error_count)
8740                 clear_special_blocks(name, gv, cv);
8741             else
8742                 evanescent =
8743                     process_special_blocks(floor, name, gv, cv);
8744         }
8745     }
8746
8747   done:
8748     if (PL_parser)
8749         PL_parser->copline = NOLINE;
8750     LEAVE_SCOPE(floor);
8751     if (!evanescent) {
8752 #ifdef PERL_DEBUG_READONLY_OPS
8753       if (slab)
8754         Slab_to_ro(slab);
8755 #endif
8756       if (cv && name && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
8757         pad_add_weakref(cv);
8758     }
8759     return cv;
8760 }
8761
8762 STATIC void
8763 S_clear_special_blocks(pTHX_ const char *const fullname,
8764                        GV *const gv, CV *const cv) {
8765     const char *colon;
8766     const char *name;
8767
8768     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
8769
8770     colon = strrchr(fullname,':');
8771     name = colon ? colon + 1 : fullname;
8772
8773     if ((*name == 'B' && strEQ(name, "BEGIN"))
8774         || (*name == 'E' && strEQ(name, "END"))
8775         || (*name == 'U' && strEQ(name, "UNITCHECK"))
8776         || (*name == 'C' && strEQ(name, "CHECK"))
8777         || (*name == 'I' && strEQ(name, "INIT"))) {
8778         if (!isGV(gv)) {
8779             (void)CvGV(cv);
8780             assert(isGV(gv));
8781         }
8782         GvCV_set(gv, NULL);
8783         SvREFCNT_dec_NN(MUTABLE_SV(cv));
8784     }
8785 }
8786
8787 /* Returns true if the sub has been freed.  */
8788 STATIC bool
8789 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
8790                          GV *const gv,
8791                          CV *const cv)
8792 {
8793     const char *const colon = strrchr(fullname,':');
8794     const char *const name = colon ? colon + 1 : fullname;
8795
8796     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
8797
8798     if (*name == 'B') {
8799         if (strEQ(name, "BEGIN")) {
8800             const I32 oldscope = PL_scopestack_ix;
8801             dSP;
8802             (void)CvGV(cv);
8803             if (floor) LEAVE_SCOPE(floor);
8804             ENTER;
8805             PUSHSTACKi(PERLSI_REQUIRE);
8806             SAVECOPFILE(&PL_compiling);
8807             SAVECOPLINE(&PL_compiling);
8808             SAVEVPTR(PL_curcop);
8809
8810             DEBUG_x( dump_sub(gv) );
8811             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
8812             GvCV_set(gv,0);             /* cv has been hijacked */
8813             call_list(oldscope, PL_beginav);
8814
8815             POPSTACK;
8816             LEAVE;
8817             return !PL_savebegin;
8818         }
8819         else
8820             return FALSE;
8821     } else {
8822         if (*name == 'E') {
8823             if strEQ(name, "END") {
8824                 DEBUG_x( dump_sub(gv) );
8825                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
8826             } else
8827                 return FALSE;
8828         } else if (*name == 'U') {
8829             if (strEQ(name, "UNITCHECK")) {
8830                 /* It's never too late to run a unitcheck block */
8831                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
8832             }
8833             else
8834                 return FALSE;
8835         } else if (*name == 'C') {
8836             if (strEQ(name, "CHECK")) {
8837                 if (PL_main_start)
8838                     /* diag_listed_as: Too late to run %s block */
8839                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8840                                    "Too late to run CHECK block");
8841                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
8842             }
8843             else
8844                 return FALSE;
8845         } else if (*name == 'I') {
8846             if (strEQ(name, "INIT")) {
8847                 if (PL_main_start)
8848                     /* diag_listed_as: Too late to run %s block */
8849                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8850                                    "Too late to run INIT block");
8851                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
8852             }
8853             else
8854                 return FALSE;
8855         } else
8856             return FALSE;
8857         DEBUG_x( dump_sub(gv) );
8858         (void)CvGV(cv);
8859         GvCV_set(gv,0);         /* cv has been hijacked */
8860         return FALSE;
8861     }
8862 }
8863
8864 /*
8865 =for apidoc newCONSTSUB
8866
8867 See L</newCONSTSUB_flags>.
8868
8869 =cut
8870 */
8871
8872 CV *
8873 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
8874 {
8875     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
8876 }
8877
8878 /*
8879 =for apidoc newCONSTSUB_flags
8880
8881 Creates a constant sub equivalent to Perl S<C<sub FOO () { 123 }>> which is
8882 eligible for inlining at compile-time.
8883
8884 Currently, the only useful value for C<flags> is C<SVf_UTF8>.
8885
8886 The newly created subroutine takes ownership of a reference to the passed in
8887 SV.
8888
8889 Passing C<NULL> for SV creates a constant sub equivalent to S<C<sub BAR () {}>>,
8890 which won't be called if used as a destructor, but will suppress the overhead
8891 of a call to C<AUTOLOAD>.  (This form, however, isn't eligible for inlining at
8892 compile time.)
8893
8894 =cut
8895 */
8896
8897 CV *
8898 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
8899                              U32 flags, SV *sv)
8900 {
8901     CV* cv;
8902     const char *const file = CopFILE(PL_curcop);
8903
8904     ENTER;
8905
8906     if (IN_PERL_RUNTIME) {
8907         /* at runtime, it's not safe to manipulate PL_curcop: it may be
8908          * an op shared between threads. Use a non-shared COP for our
8909          * dirty work */
8910          SAVEVPTR(PL_curcop);
8911          SAVECOMPILEWARNINGS();
8912          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8913          PL_curcop = &PL_compiling;
8914     }
8915     SAVECOPLINE(PL_curcop);
8916     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
8917
8918     SAVEHINTS();
8919     PL_hints &= ~HINT_BLOCK_SCOPE;
8920
8921     if (stash) {
8922         SAVEGENERICSV(PL_curstash);
8923         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
8924     }
8925
8926     /* Protect sv against leakage caused by fatal warnings. */
8927     if (sv) SAVEFREESV(sv);
8928
8929     /* file becomes the CvFILE. For an XS, it's usually static storage,
8930        and so doesn't get free()d.  (It's expected to be from the C pre-
8931        processor __FILE__ directive). But we need a dynamically allocated one,
8932        and we need it to get freed.  */
8933     cv = newXS_len_flags(name, len,
8934                          sv && SvTYPE(sv) == SVt_PVAV
8935                              ? const_av_xsub
8936                              : const_sv_xsub,
8937                          file ? file : "", "",
8938                          &sv, XS_DYNAMIC_FILENAME | flags);
8939     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
8940     CvCONST_on(cv);
8941
8942     LEAVE;
8943
8944     return cv;
8945 }
8946
8947 /*
8948 =for apidoc U||newXS
8949
8950 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
8951 static storage, as it is used directly as CvFILE(), without a copy being made.
8952
8953 =cut
8954 */
8955
8956 CV *
8957 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
8958 {
8959     PERL_ARGS_ASSERT_NEWXS;
8960     return newXS_len_flags(
8961         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
8962     );
8963 }
8964
8965 CV *
8966 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
8967                  const char *const filename, const char *const proto,
8968                  U32 flags)
8969 {
8970     PERL_ARGS_ASSERT_NEWXS_FLAGS;
8971     return newXS_len_flags(
8972        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
8973     );
8974 }
8975
8976 CV *
8977 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
8978 {
8979     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
8980     return newXS_len_flags(
8981         name, strlen(name), subaddr, NULL, NULL, NULL, 0
8982     );
8983 }
8984
8985 CV *
8986 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
8987                            XSUBADDR_t subaddr, const char *const filename,
8988                            const char *const proto, SV **const_svp,
8989                            U32 flags)
8990 {
8991     CV *cv;
8992     bool interleave = FALSE;
8993
8994     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
8995
8996     {
8997         GV * const gv = gv_fetchpvn(
8998                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8999                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
9000                                 sizeof("__ANON__::__ANON__") - 1,
9001                             GV_ADDMULTI | flags, SVt_PVCV);
9002
9003         if ((cv = (name ? GvCV(gv) : NULL))) {
9004             if (GvCVGEN(gv)) {
9005                 /* just a cached method */
9006                 SvREFCNT_dec(cv);
9007                 cv = NULL;
9008             }
9009             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
9010                 /* already defined (or promised) */
9011                 /* Redundant check that allows us to avoid creating an SV
9012                    most of the time: */
9013                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
9014                     report_redefined_cv(newSVpvn_flags(
9015                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
9016                                         ),
9017                                         cv, const_svp);
9018                 }
9019                 interleave = TRUE;
9020                 ENTER;
9021                 SAVEFREESV(cv);
9022                 cv = NULL;
9023             }
9024         }
9025     
9026         if (cv)                         /* must reuse cv if autoloaded */
9027             cv_undef(cv);
9028         else {
9029             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9030             if (name) {
9031                 GvCV_set(gv,cv);
9032                 GvCVGEN(gv) = 0;
9033                 if (HvENAME_HEK(GvSTASH(gv)))
9034                     gv_method_changed(gv); /* newXS */
9035             }
9036         }
9037
9038         CvGV_set(cv, gv);
9039         if(filename) {
9040             /* XSUBs can't be perl lang/perl5db.pl debugged
9041             if (PERLDB_LINE_OR_SAVESRC)
9042                 (void)gv_fetchfile(filename); */
9043             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
9044             if (flags & XS_DYNAMIC_FILENAME) {
9045                 CvDYNFILE_on(cv);
9046                 CvFILE(cv) = savepv(filename);
9047             } else {
9048             /* NOTE: not copied, as it is expected to be an external constant string */
9049                 CvFILE(cv) = (char *)filename;
9050             }
9051         } else {
9052             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
9053             CvFILE(cv) = (char*)PL_xsubfilename;
9054         }
9055         CvISXSUB_on(cv);
9056         CvXSUB(cv) = subaddr;
9057 #ifndef PERL_IMPLICIT_CONTEXT
9058         CvHSCXT(cv) = &PL_stack_sp;
9059 #else
9060         PoisonPADLIST(cv);
9061 #endif
9062
9063         if (name)
9064             process_special_blocks(0, name, gv, cv);
9065         else
9066             CvANON_on(cv);
9067     } /* <- not a conditional branch */
9068
9069
9070     sv_setpv(MUTABLE_SV(cv), proto);
9071     if (interleave) LEAVE;
9072     return cv;
9073 }
9074
9075 CV *
9076 Perl_newSTUB(pTHX_ GV *gv, bool fake)
9077 {
9078     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9079     GV *cvgv;
9080     PERL_ARGS_ASSERT_NEWSTUB;
9081     assert(!GvCVu(gv));
9082     GvCV_set(gv, cv);
9083     GvCVGEN(gv) = 0;
9084     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
9085         gv_method_changed(gv);
9086     if (SvFAKE(gv)) {
9087         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
9088         SvFAKE_off(cvgv);
9089     }
9090     else cvgv = gv;
9091     CvGV_set(cv, cvgv);
9092     CvFILE_set_from_cop(cv, PL_curcop);
9093     CvSTASH_set(cv, PL_curstash);
9094     GvMULTI_on(gv);
9095     return cv;
9096 }
9097
9098 void
9099 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
9100 {
9101     CV *cv;
9102
9103     GV *gv;
9104
9105     if (PL_parser && PL_parser->error_count) {
9106         op_free(block);
9107         goto finish;
9108     }
9109
9110     gv = o
9111         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
9112         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
9113
9114     GvMULTI_on(gv);
9115     if ((cv = GvFORM(gv))) {
9116         if (ckWARN(WARN_REDEFINE)) {
9117             const line_t oldline = CopLINE(PL_curcop);
9118             if (PL_parser && PL_parser->copline != NOLINE)
9119                 CopLINE_set(PL_curcop, PL_parser->copline);
9120             if (o) {
9121                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9122                             "Format %"SVf" redefined", SVfARG(cSVOPo->op_sv));
9123             } else {
9124                 /* diag_listed_as: Format %s redefined */
9125                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9126                             "Format STDOUT redefined");
9127             }
9128             CopLINE_set(PL_curcop, oldline);
9129         }
9130         SvREFCNT_dec(cv);
9131     }
9132     cv = PL_compcv;
9133     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
9134     CvGV_set(cv, gv);
9135     CvFILE_set_from_cop(cv, PL_curcop);
9136
9137
9138     pad_tidy(padtidy_FORMAT);
9139     CvROOT(cv) = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
9140     CvROOT(cv)->op_private |= OPpREFCOUNTED;
9141     OpREFCNT_set(CvROOT(cv), 1);
9142     CvSTART(cv) = LINKLIST(CvROOT(cv));
9143     CvROOT(cv)->op_next = 0;
9144     CALL_PEEP(CvSTART(cv));
9145     finalize_optree(CvROOT(cv));
9146     S_prune_chain_head(&CvSTART(cv));
9147     cv_forget_slab(cv);
9148
9149   finish:
9150     op_free(o);
9151     if (PL_parser)
9152         PL_parser->copline = NOLINE;
9153     LEAVE_SCOPE(floor);
9154     PL_compiling.cop_seq = 0;
9155 }
9156
9157 OP *
9158 Perl_newANONLIST(pTHX_ OP *o)
9159 {
9160     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
9161 }
9162
9163 OP *
9164 Perl_newANONHASH(pTHX_ OP *o)
9165 {
9166     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
9167 }
9168
9169 OP *
9170 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
9171 {
9172     return newANONATTRSUB(floor, proto, NULL, block);
9173 }
9174
9175 OP *
9176 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
9177 {
9178     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
9179     OP * anoncode = 
9180         newSVOP(OP_ANONCODE, 0,
9181                 cv);
9182     if (CvANONCONST(cv))
9183         anoncode = newUNOP(OP_ANONCONST, 0,
9184                            op_convert_list(OP_ENTERSUB,
9185                                            OPf_STACKED|OPf_WANT_SCALAR,
9186                                            anoncode));
9187     return newUNOP(OP_REFGEN, 0, anoncode);
9188 }
9189
9190 OP *
9191 Perl_oopsAV(pTHX_ OP *o)
9192 {
9193     dVAR;
9194
9195     PERL_ARGS_ASSERT_OOPSAV;
9196
9197     switch (o->op_type) {
9198     case OP_PADSV:
9199     case OP_PADHV:
9200         OpTYPE_set(o, OP_PADAV);
9201         return ref(o, OP_RV2AV);
9202
9203     case OP_RV2SV:
9204     case OP_RV2HV:
9205         OpTYPE_set(o, OP_RV2AV);
9206         ref(o, OP_RV2AV);
9207         break;
9208
9209     default:
9210         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
9211         break;
9212     }
9213     return o;
9214 }
9215
9216 OP *
9217 Perl_oopsHV(pTHX_ OP *o)
9218 {
9219     dVAR;
9220
9221     PERL_ARGS_ASSERT_OOPSHV;
9222
9223     switch (o->op_type) {
9224     case OP_PADSV:
9225     case OP_PADAV:
9226         OpTYPE_set(o, OP_PADHV);
9227         return ref(o, OP_RV2HV);
9228
9229     case OP_RV2SV:
9230     case OP_RV2AV:
9231         OpTYPE_set(o, OP_RV2HV);
9232         ref(o, OP_RV2HV);
9233         break;
9234
9235     default:
9236         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
9237         break;
9238     }
9239     return o;
9240 }
9241
9242 OP *
9243 Perl_newAVREF(pTHX_ OP *o)
9244 {
9245     dVAR;
9246
9247     PERL_ARGS_ASSERT_NEWAVREF;
9248
9249     if (o->op_type == OP_PADANY) {
9250         OpTYPE_set(o, OP_PADAV);
9251         return o;
9252     }
9253     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
9254         Perl_croak(aTHX_ "Can't use an array as a reference");
9255     }
9256     return newUNOP(OP_RV2AV, 0, scalar(o));
9257 }
9258
9259 OP *
9260 Perl_newGVREF(pTHX_ I32 type, OP *o)
9261 {
9262     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
9263         return newUNOP(OP_NULL, 0, o);
9264     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
9265 }
9266
9267 OP *
9268 Perl_newHVREF(pTHX_ OP *o)
9269 {
9270     dVAR;
9271
9272     PERL_ARGS_ASSERT_NEWHVREF;
9273
9274     if (o->op_type == OP_PADANY) {
9275         OpTYPE_set(o, OP_PADHV);
9276         return o;
9277     }
9278     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
9279         Perl_croak(aTHX_ "Can't use a hash as a reference");
9280     }
9281     return newUNOP(OP_RV2HV, 0, scalar(o));
9282 }
9283
9284 OP *
9285 Perl_newCVREF(pTHX_ I32 flags, OP *o)
9286 {
9287     if (o->op_type == OP_PADANY) {
9288         dVAR;
9289         OpTYPE_set(o, OP_PADCV);
9290     }
9291     return newUNOP(OP_RV2CV, flags, scalar(o));
9292 }
9293
9294 OP *
9295 Perl_newSVREF(pTHX_ OP *o)
9296 {
9297     dVAR;
9298
9299     PERL_ARGS_ASSERT_NEWSVREF;
9300
9301     if (o->op_type == OP_PADANY) {
9302         OpTYPE_set(o, OP_PADSV);
9303         scalar(o);
9304         return o;
9305     }
9306     return newUNOP(OP_RV2SV, 0, scalar(o));
9307 }
9308
9309 /* Check routines. See the comments at the top of this file for details
9310  * on when these are called */
9311
9312 OP *
9313 Perl_ck_anoncode(pTHX_ OP *o)
9314 {
9315     PERL_ARGS_ASSERT_CK_ANONCODE;
9316
9317     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
9318     cSVOPo->op_sv = NULL;
9319     return o;
9320 }
9321
9322 static void
9323 S_io_hints(pTHX_ OP *o)
9324 {
9325 #if O_BINARY != 0 || O_TEXT != 0
9326     HV * const table =
9327         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
9328     if (table) {
9329         SV **svp = hv_fetchs(table, "open_IN", FALSE);
9330         if (svp && *svp) {
9331             STRLEN len = 0;
9332             const char *d = SvPV_const(*svp, len);
9333             const I32 mode = mode_from_discipline(d, len);
9334             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9335 #  if O_BINARY != 0
9336             if (mode & O_BINARY)
9337                 o->op_private |= OPpOPEN_IN_RAW;
9338 #  endif
9339 #  if O_TEXT != 0
9340             if (mode & O_TEXT)
9341                 o->op_private |= OPpOPEN_IN_CRLF;
9342 #  endif
9343         }
9344
9345         svp = hv_fetchs(table, "open_OUT", FALSE);
9346         if (svp && *svp) {
9347             STRLEN len = 0;
9348             const char *d = SvPV_const(*svp, len);
9349             const I32 mode = mode_from_discipline(d, len);
9350             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9351 #  if O_BINARY != 0
9352             if (mode & O_BINARY)
9353                 o->op_private |= OPpOPEN_OUT_RAW;
9354 #  endif
9355 #  if O_TEXT != 0
9356             if (mode & O_TEXT)
9357                 o->op_private |= OPpOPEN_OUT_CRLF;
9358 #  endif
9359         }
9360     }
9361 #else
9362     PERL_UNUSED_CONTEXT;
9363     PERL_UNUSED_ARG(o);
9364 #endif
9365 }
9366
9367 OP *
9368 Perl_ck_backtick(pTHX_ OP *o)
9369 {
9370     GV *gv;
9371     OP *newop = NULL;
9372     OP *sibl;
9373     PERL_ARGS_ASSERT_CK_BACKTICK;
9374     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
9375     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
9376      && (gv = gv_override("readpipe",8)))
9377     {
9378         /* detach rest of siblings from o and its first child */
9379         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
9380         newop = S_new_entersubop(aTHX_ gv, sibl);
9381     }
9382     else if (!(o->op_flags & OPf_KIDS))
9383         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
9384     if (newop) {
9385         op_free(o);
9386         return newop;
9387     }
9388     S_io_hints(aTHX_ o);
9389     return o;
9390 }
9391
9392 OP *
9393 Perl_ck_bitop(pTHX_ OP *o)
9394 {
9395     PERL_ARGS_ASSERT_CK_BITOP;
9396
9397     o->op_private = (U8)(PL_hints & HINT_INTEGER);
9398
9399     if (o->op_type == OP_NBIT_OR     || o->op_type == OP_SBIT_OR
9400      || o->op_type == OP_NBIT_XOR    || o->op_type == OP_SBIT_XOR
9401      || o->op_type == OP_NBIT_AND    || o->op_type == OP_SBIT_AND
9402      || o->op_type == OP_NCOMPLEMENT || o->op_type == OP_SCOMPLEMENT)
9403         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__BITWISE),
9404                               "The bitwise feature is experimental");
9405     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
9406             && OP_IS_INFIX_BIT(o->op_type))
9407     {
9408         const OP * const left = cBINOPo->op_first;
9409         const OP * const right = OpSIBLING(left);
9410         if ((OP_IS_NUMCOMPARE(left->op_type) &&
9411                 (left->op_flags & OPf_PARENS) == 0) ||
9412             (OP_IS_NUMCOMPARE(right->op_type) &&
9413                 (right->op_flags & OPf_PARENS) == 0))
9414             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
9415                           "Possible precedence problem on bitwise %s operator",
9416                            o->op_type ==  OP_BIT_OR
9417                          ||o->op_type == OP_NBIT_OR  ? "|"
9418                         :  o->op_type ==  OP_BIT_AND
9419                          ||o->op_type == OP_NBIT_AND ? "&"
9420                         :  o->op_type ==  OP_BIT_XOR
9421                          ||o->op_type == OP_NBIT_XOR ? "^"
9422                         :  o->op_type == OP_SBIT_OR  ? "|."
9423                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
9424                            );
9425     }
9426     return o;
9427 }
9428
9429 PERL_STATIC_INLINE bool
9430 is_dollar_bracket(pTHX_ const OP * const o)
9431 {
9432     const OP *kid;
9433     PERL_UNUSED_CONTEXT;
9434     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
9435         && (kid = cUNOPx(o)->op_first)
9436         && kid->op_type == OP_GV
9437         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
9438 }
9439
9440 OP *
9441 Perl_ck_cmp(pTHX_ OP *o)
9442 {
9443     PERL_ARGS_ASSERT_CK_CMP;
9444     if (ckWARN(WARN_SYNTAX)) {
9445         const OP *kid = cUNOPo->op_first;
9446         if (kid &&
9447             (
9448                 (   is_dollar_bracket(aTHX_ kid)
9449                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
9450                 )
9451              || (   kid->op_type == OP_CONST
9452                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
9453                 )
9454            )
9455         )
9456             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9457                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
9458     }
9459     return o;
9460 }
9461
9462 OP *
9463 Perl_ck_concat(pTHX_ OP *o)
9464 {
9465     const OP * const kid = cUNOPo->op_first;
9466
9467     PERL_ARGS_ASSERT_CK_CONCAT;
9468     PERL_UNUSED_CONTEXT;
9469
9470     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
9471             !(kUNOP->op_first->op_flags & OPf_MOD))
9472         o->op_flags |= OPf_STACKED;
9473     return o;
9474 }
9475
9476 OP *
9477 Perl_ck_spair(pTHX_ OP *o)
9478 {
9479     dVAR;
9480
9481     PERL_ARGS_ASSERT_CK_SPAIR;
9482
9483     if (o->op_flags & OPf_KIDS) {
9484         OP* newop;
9485         OP* kid;
9486         OP* kidkid;
9487         const OPCODE type = o->op_type;
9488         o = modkids(ck_fun(o), type);
9489         kid    = cUNOPo->op_first;
9490         kidkid = kUNOP->op_first;
9491         newop = OpSIBLING(kidkid);
9492         if (newop) {
9493             const OPCODE type = newop->op_type;
9494             if (OpHAS_SIBLING(newop))
9495                 return o;
9496             if (o->op_type == OP_REFGEN
9497              && (  type == OP_RV2CV
9498                 || (  !(newop->op_flags & OPf_PARENS)
9499                    && (  type == OP_RV2AV || type == OP_PADAV
9500                       || type == OP_RV2HV || type == OP_PADHV))))
9501                 NOOP; /* OK (allow srefgen for \@a and \%h) */
9502             else if (OP_GIMME(newop,0) != G_SCALAR)
9503                 return o;
9504         }
9505         /* excise first sibling */
9506         op_sibling_splice(kid, NULL, 1, NULL);
9507         op_free(kidkid);
9508     }
9509     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
9510      * and OP_CHOMP into OP_SCHOMP */
9511     o->op_ppaddr = PL_ppaddr[++o->op_type];
9512     return ck_fun(o);
9513 }
9514
9515 OP *
9516 Perl_ck_delete(pTHX_ OP *o)
9517 {
9518     PERL_ARGS_ASSERT_CK_DELETE;
9519
9520     o = ck_fun(o);
9521     o->op_private = 0;
9522     if (o->op_flags & OPf_KIDS) {
9523         OP * const kid = cUNOPo->op_first;
9524         switch (kid->op_type) {
9525         case OP_ASLICE:
9526             o->op_flags |= OPf_SPECIAL;
9527             /* FALLTHROUGH */
9528         case OP_HSLICE:
9529             o->op_private |= OPpSLICE;
9530             break;
9531         case OP_AELEM:
9532             o->op_flags |= OPf_SPECIAL;
9533             /* FALLTHROUGH */
9534         case OP_HELEM:
9535             break;
9536         case OP_KVASLICE:
9537             Perl_croak(aTHX_ "delete argument is index/value array slice,"
9538                              " use array slice");
9539         case OP_KVHSLICE:
9540             Perl_croak(aTHX_ "delete argument is key/value hash slice, use"
9541                              " hash slice");
9542         default:
9543             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
9544                              "element or slice");
9545         }
9546         if (kid->op_private & OPpLVAL_INTRO)
9547             o->op_private |= OPpLVAL_INTRO;
9548         op_null(kid);
9549     }
9550     return o;
9551 }
9552
9553 OP *
9554 Perl_ck_eof(pTHX_ OP *o)
9555 {
9556     PERL_ARGS_ASSERT_CK_EOF;
9557
9558     if (o->op_flags & OPf_KIDS) {
9559         OP *kid;
9560         if (cLISTOPo->op_first->op_type == OP_STUB) {
9561             OP * const newop
9562                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
9563             op_free(o);
9564             o = newop;
9565         }
9566         o = ck_fun(o);
9567         kid = cLISTOPo->op_first;
9568         if (kid->op_type == OP_RV2GV)
9569             kid->op_private |= OPpALLOW_FAKE;
9570     }
9571     return o;
9572 }
9573
9574 OP *
9575 Perl_ck_eval(pTHX_ OP *o)
9576 {
9577     dVAR;
9578
9579     PERL_ARGS_ASSERT_CK_EVAL;
9580
9581     PL_hints |= HINT_BLOCK_SCOPE;
9582     if (o->op_flags & OPf_KIDS) {
9583         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9584         assert(kid);
9585
9586         if (o->op_type == OP_ENTERTRY) {
9587             LOGOP *enter;
9588
9589             /* cut whole sibling chain free from o */
9590             op_sibling_splice(o, NULL, -1, NULL);
9591             op_free(o);
9592
9593             enter = S_alloc_LOGOP(aTHX_ OP_ENTERTRY, NULL, NULL);
9594
9595             /* establish postfix order */
9596             enter->op_next = (OP*)enter;
9597
9598             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
9599             OpTYPE_set(o, OP_LEAVETRY);
9600             enter->op_other = o;
9601             return o;
9602         }
9603         else {
9604             scalar((OP*)kid);
9605             S_set_haseval(aTHX);
9606         }
9607     }
9608     else {
9609         const U8 priv = o->op_private;
9610         op_free(o);
9611         /* the newUNOP will recursively call ck_eval(), which will handle
9612          * all the stuff at the end of this function, like adding
9613          * OP_HINTSEVAL
9614          */
9615         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
9616     }
9617     o->op_targ = (PADOFFSET)PL_hints;
9618     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
9619     if ((PL_hints & HINT_LOCALIZE_HH) != 0
9620      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
9621         /* Store a copy of %^H that pp_entereval can pick up. */
9622         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
9623                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
9624         /* append hhop to only child  */
9625         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
9626
9627         o->op_private |= OPpEVAL_HAS_HH;
9628     }
9629     if (!(o->op_private & OPpEVAL_BYTES)
9630          && FEATURE_UNIEVAL_IS_ENABLED)
9631             o->op_private |= OPpEVAL_UNICODE;
9632     return o;
9633 }
9634
9635 OP *
9636 Perl_ck_exec(pTHX_ OP *o)
9637 {
9638     PERL_ARGS_ASSERT_CK_EXEC;
9639
9640     if (o->op_flags & OPf_STACKED) {
9641         OP *kid;
9642         o = ck_fun(o);
9643         kid = OpSIBLING(cUNOPo->op_first);
9644         if (kid->op_type == OP_RV2GV)
9645             op_null(kid);
9646     }
9647     else
9648         o = listkids(o);
9649     return o;
9650 }
9651
9652 OP *
9653 Perl_ck_exists(pTHX_ OP *o)
9654 {
9655     PERL_ARGS_ASSERT_CK_EXISTS;
9656
9657     o = ck_fun(o);
9658     if (o->op_flags & OPf_KIDS) {
9659         OP * const kid = cUNOPo->op_first;
9660         if (kid->op_type == OP_ENTERSUB) {
9661             (void) ref(kid, o->op_type);
9662             if (kid->op_type != OP_RV2CV
9663                         && !(PL_parser && PL_parser->error_count))
9664                 Perl_croak(aTHX_
9665                           "exists argument is not a subroutine name");
9666             o->op_private |= OPpEXISTS_SUB;
9667         }
9668         else if (kid->op_type == OP_AELEM)
9669             o->op_flags |= OPf_SPECIAL;
9670         else if (kid->op_type != OP_HELEM)
9671             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
9672                              "element or a subroutine");
9673         op_null(kid);
9674     }
9675     return o;
9676 }
9677
9678 OP *
9679 Perl_ck_rvconst(pTHX_ OP *o)
9680 {
9681     dVAR;
9682     SVOP * const kid = (SVOP*)cUNOPo->op_first;
9683
9684     PERL_ARGS_ASSERT_CK_RVCONST;
9685
9686     o->op_private |= (PL_hints & HINT_STRICT_REFS);
9687
9688     if (kid->op_type == OP_CONST) {
9689         int iscv;
9690         GV *gv;
9691         SV * const kidsv = kid->op_sv;
9692
9693         /* Is it a constant from cv_const_sv()? */
9694         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
9695             return o;
9696         }
9697         if (SvTYPE(kidsv) == SVt_PVAV) return o;
9698         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
9699             const char *badthing;
9700             switch (o->op_type) {
9701             case OP_RV2SV:
9702                 badthing = "a SCALAR";
9703                 break;
9704             case OP_RV2AV:
9705                 badthing = "an ARRAY";
9706                 break;
9707             case OP_RV2HV:
9708                 badthing = "a HASH";
9709                 break;
9710             default:
9711                 badthing = NULL;
9712                 break;
9713             }
9714             if (badthing)
9715                 Perl_croak(aTHX_
9716                            "Can't use bareword (\"%"SVf"\") as %s ref while \"strict refs\" in use",
9717                            SVfARG(kidsv), badthing);
9718         }
9719         /*
9720          * This is a little tricky.  We only want to add the symbol if we
9721          * didn't add it in the lexer.  Otherwise we get duplicate strict
9722          * warnings.  But if we didn't add it in the lexer, we must at
9723          * least pretend like we wanted to add it even if it existed before,
9724          * or we get possible typo warnings.  OPpCONST_ENTERED says
9725          * whether the lexer already added THIS instance of this symbol.
9726          */
9727         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
9728         gv = gv_fetchsv(kidsv,
9729                 o->op_type == OP_RV2CV
9730                         && o->op_private & OPpMAY_RETURN_CONSTANT
9731                     ? GV_NOEXPAND
9732                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
9733                 iscv
9734                     ? SVt_PVCV
9735                     : o->op_type == OP_RV2SV
9736                         ? SVt_PV
9737                         : o->op_type == OP_RV2AV
9738                             ? SVt_PVAV
9739                             : o->op_type == OP_RV2HV
9740                                 ? SVt_PVHV
9741                                 : SVt_PVGV);
9742         if (gv) {
9743             if (!isGV(gv)) {
9744                 assert(iscv);
9745                 assert(SvROK(gv));
9746                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
9747                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
9748                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
9749             }
9750             OpTYPE_set(kid, OP_GV);
9751             SvREFCNT_dec(kid->op_sv);
9752 #ifdef USE_ITHREADS
9753             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
9754             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
9755             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
9756             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
9757             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
9758 #else
9759             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
9760 #endif
9761             kid->op_private = 0;
9762             /* FAKE globs in the symbol table cause weird bugs (#77810) */
9763             SvFAKE_off(gv);
9764         }
9765     }
9766     return o;
9767 }
9768
9769 OP *
9770 Perl_ck_ftst(pTHX_ OP *o)
9771 {
9772     dVAR;
9773     const I32 type = o->op_type;
9774
9775     PERL_ARGS_ASSERT_CK_FTST;
9776
9777     if (o->op_flags & OPf_REF) {
9778         NOOP;
9779     }
9780     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
9781         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9782         const OPCODE kidtype = kid->op_type;
9783
9784         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
9785          && !kid->op_folded) {
9786             OP * const newop = newGVOP(type, OPf_REF,
9787                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
9788             op_free(o);
9789             return newop;
9790         }
9791
9792         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
9793             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
9794             if (name) {
9795                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
9796                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
9797                             array_passed_to_stat, name);
9798             }
9799             else {
9800                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
9801                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
9802             }
9803        }
9804         scalar((OP *) kid);
9805         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
9806             o->op_private |= OPpFT_ACCESS;
9807         if (type != OP_STAT && type != OP_LSTAT
9808             && PL_check[kidtype] == Perl_ck_ftst
9809             && kidtype != OP_STAT && kidtype != OP_LSTAT
9810         ) {
9811             o->op_private |= OPpFT_STACKED;
9812             kid->op_private |= OPpFT_STACKING;
9813             if (kidtype == OP_FTTTY && (
9814                    !(kid->op_private & OPpFT_STACKED)
9815                 || kid->op_private & OPpFT_AFTER_t
9816                ))
9817                 o->op_private |= OPpFT_AFTER_t;
9818         }
9819     }
9820     else {
9821         op_free(o);
9822         if (type == OP_FTTTY)
9823             o = newGVOP(type, OPf_REF, PL_stdingv);
9824         else
9825             o = newUNOP(type, 0, newDEFSVOP());
9826     }
9827     return o;
9828 }
9829
9830 OP *
9831 Perl_ck_fun(pTHX_ OP *o)
9832 {
9833     const int type = o->op_type;
9834     I32 oa = PL_opargs[type] >> OASHIFT;
9835
9836     PERL_ARGS_ASSERT_CK_FUN;
9837
9838     if (o->op_flags & OPf_STACKED) {
9839         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
9840             oa &= ~OA_OPTIONAL;
9841         else
9842             return no_fh_allowed(o);
9843     }
9844
9845     if (o->op_flags & OPf_KIDS) {
9846         OP *prev_kid = NULL;
9847         OP *kid = cLISTOPo->op_first;
9848         I32 numargs = 0;
9849         bool seen_optional = FALSE;
9850
9851         if (kid->op_type == OP_PUSHMARK ||
9852             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
9853         {
9854             prev_kid = kid;
9855             kid = OpSIBLING(kid);
9856         }
9857         if (kid && kid->op_type == OP_COREARGS) {
9858             bool optional = FALSE;
9859             while (oa) {
9860                 numargs++;
9861                 if (oa & OA_OPTIONAL) optional = TRUE;
9862                 oa = oa >> 4;
9863             }
9864             if (optional) o->op_private |= numargs;
9865             return o;
9866         }
9867
9868         while (oa) {
9869             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
9870                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
9871                     kid = newDEFSVOP();
9872                     /* append kid to chain */
9873                     op_sibling_splice(o, prev_kid, 0, kid);
9874                 }
9875                 seen_optional = TRUE;
9876             }
9877             if (!kid) break;
9878
9879             numargs++;
9880             switch (oa & 7) {
9881             case OA_SCALAR:
9882                 /* list seen where single (scalar) arg expected? */
9883                 if (numargs == 1 && !(oa >> 4)
9884                     && kid->op_type == OP_LIST && type != OP_SCALAR)
9885                 {
9886                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9887                 }
9888                 if (type != OP_DELETE) scalar(kid);
9889                 break;
9890             case OA_LIST:
9891                 if (oa < 16) {
9892                     kid = 0;
9893                     continue;
9894                 }
9895                 else
9896                     list(kid);
9897                 break;
9898             case OA_AVREF:
9899                 if ((type == OP_PUSH || type == OP_UNSHIFT)
9900                     && !OpHAS_SIBLING(kid))
9901                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9902                                    "Useless use of %s with no values",
9903                                    PL_op_desc[type]);
9904
9905                 if (kid->op_type == OP_CONST
9906                       && (  !SvROK(cSVOPx_sv(kid)) 
9907                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
9908                         )
9909                     bad_type_pv(numargs, "array", o, kid);
9910                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
9911                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
9912                                          PL_op_desc[type]), 0);
9913                 }
9914                 else {
9915                     op_lvalue(kid, type);
9916                 }
9917                 break;
9918             case OA_HVREF:
9919                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
9920                     bad_type_pv(numargs, "hash", o, kid);
9921                 op_lvalue(kid, type);
9922                 break;
9923             case OA_CVREF:
9924                 {
9925                     /* replace kid with newop in chain */
9926                     OP * const newop =
9927                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
9928                     newop->op_next = newop;
9929                     kid = newop;
9930                 }
9931                 break;
9932             case OA_FILEREF:
9933                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
9934                     if (kid->op_type == OP_CONST &&
9935                         (kid->op_private & OPpCONST_BARE))
9936                     {
9937                         OP * const newop = newGVOP(OP_GV, 0,
9938                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
9939                         /* replace kid with newop in chain */
9940                         op_sibling_splice(o, prev_kid, 1, newop);
9941                         op_free(kid);
9942                         kid = newop;
9943                     }
9944                     else if (kid->op_type == OP_READLINE) {
9945                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
9946                         bad_type_pv(numargs, "HANDLE", o, kid);
9947                     }
9948                     else {
9949                         I32 flags = OPf_SPECIAL;
9950                         I32 priv = 0;
9951                         PADOFFSET targ = 0;
9952
9953                         /* is this op a FH constructor? */
9954                         if (is_handle_constructor(o,numargs)) {
9955                             const char *name = NULL;
9956                             STRLEN len = 0;
9957                             U32 name_utf8 = 0;
9958                             bool want_dollar = TRUE;
9959
9960                             flags = 0;
9961                             /* Set a flag to tell rv2gv to vivify
9962                              * need to "prove" flag does not mean something
9963                              * else already - NI-S 1999/05/07
9964                              */
9965                             priv = OPpDEREF;
9966                             if (kid->op_type == OP_PADSV) {
9967                                 PADNAME * const pn
9968                                     = PAD_COMPNAME_SV(kid->op_targ);
9969                                 name = PadnamePV (pn);
9970                                 len  = PadnameLEN(pn);
9971                                 name_utf8 = PadnameUTF8(pn);
9972                             }
9973                             else if (kid->op_type == OP_RV2SV
9974                                      && kUNOP->op_first->op_type == OP_GV)
9975                             {
9976                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
9977                                 name = GvNAME(gv);
9978                                 len = GvNAMELEN(gv);
9979                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
9980                             }
9981                             else if (kid->op_type == OP_AELEM
9982                                      || kid->op_type == OP_HELEM)
9983                             {
9984                                  OP *firstop;
9985                                  OP *op = ((BINOP*)kid)->op_first;
9986                                  name = NULL;
9987                                  if (op) {
9988                                       SV *tmpstr = NULL;
9989                                       const char * const a =
9990                                            kid->op_type == OP_AELEM ?
9991                                            "[]" : "{}";
9992                                       if (((op->op_type == OP_RV2AV) ||
9993                                            (op->op_type == OP_RV2HV)) &&
9994                                           (firstop = ((UNOP*)op)->op_first) &&
9995                                           (firstop->op_type == OP_GV)) {
9996                                            /* packagevar $a[] or $h{} */
9997                                            GV * const gv = cGVOPx_gv(firstop);
9998                                            if (gv)
9999                                                 tmpstr =
10000                                                      Perl_newSVpvf(aTHX_
10001                                                                    "%s%c...%c",
10002                                                                    GvNAME(gv),
10003                                                                    a[0], a[1]);
10004                                       }
10005                                       else if (op->op_type == OP_PADAV
10006                                                || op->op_type == OP_PADHV) {
10007                                            /* lexicalvar $a[] or $h{} */
10008                                            const char * const padname =
10009                                                 PAD_COMPNAME_PV(op->op_targ);
10010                                            if (padname)
10011                                                 tmpstr =
10012                                                      Perl_newSVpvf(aTHX_
10013                                                                    "%s%c...%c",
10014                                                                    padname + 1,
10015                                                                    a[0], a[1]);
10016                                       }
10017                                       if (tmpstr) {
10018                                            name = SvPV_const(tmpstr, len);
10019                                            name_utf8 = SvUTF8(tmpstr);
10020                                            sv_2mortal(tmpstr);
10021                                       }
10022                                  }
10023                                  if (!name) {
10024                                       name = "__ANONIO__";
10025                                       len = 10;
10026                                       want_dollar = FALSE;
10027                                  }
10028                                  op_lvalue(kid, type);
10029                             }
10030                             if (name) {
10031                                 SV *namesv;
10032                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
10033                                 namesv = PAD_SVl(targ);
10034                                 if (want_dollar && *name != '$')
10035                                     sv_setpvs(namesv, "$");
10036                                 else
10037                                     sv_setpvs(namesv, "");
10038                                 sv_catpvn(namesv, name, len);
10039                                 if ( name_utf8 ) SvUTF8_on(namesv);
10040                             }
10041                         }
10042                         scalar(kid);
10043                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
10044                                     OP_RV2GV, flags);
10045                         kid->op_targ = targ;
10046                         kid->op_private |= priv;
10047                     }
10048                 }
10049                 scalar(kid);
10050                 break;
10051             case OA_SCALARREF:
10052                 if ((type == OP_UNDEF || type == OP_POS)
10053                     && numargs == 1 && !(oa >> 4)
10054                     && kid->op_type == OP_LIST)
10055                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
10056                 op_lvalue(scalar(kid), type);
10057                 break;
10058             }
10059             oa >>= 4;
10060             prev_kid = kid;
10061             kid = OpSIBLING(kid);
10062         }
10063         /* FIXME - should the numargs or-ing move after the too many
10064          * arguments check? */
10065         o->op_private |= numargs;
10066         if (kid)
10067             return too_many_arguments_pv(o,OP_DESC(o), 0);
10068         listkids(o);
10069     }
10070     else if (PL_opargs[type] & OA_DEFGV) {
10071         /* Ordering of these two is important to keep f_map.t passing.  */
10072         op_free(o);
10073         return newUNOP(type, 0, newDEFSVOP());
10074     }
10075
10076     if (oa) {
10077         while (oa & OA_OPTIONAL)
10078             oa >>= 4;
10079         if (oa && oa != OA_LIST)
10080             return too_few_arguments_pv(o,OP_DESC(o), 0);
10081     }
10082     return o;
10083 }
10084
10085 OP *
10086 Perl_ck_glob(pTHX_ OP *o)
10087 {
10088     GV *gv;
10089
10090     PERL_ARGS_ASSERT_CK_GLOB;
10091
10092     o = ck_fun(o);
10093     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
10094         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
10095
10096     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
10097     {
10098         /* convert
10099          *     glob
10100          *       \ null - const(wildcard)
10101          * into
10102          *     null
10103          *       \ enter
10104          *            \ list
10105          *                 \ mark - glob - rv2cv
10106          *                             |        \ gv(CORE::GLOBAL::glob)
10107          *                             |
10108          *                              \ null - const(wildcard)
10109          */
10110         o->op_flags |= OPf_SPECIAL;
10111         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
10112         o = S_new_entersubop(aTHX_ gv, o);
10113         o = newUNOP(OP_NULL, 0, o);
10114         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
10115         return o;
10116     }
10117     else o->op_flags &= ~OPf_SPECIAL;
10118 #if !defined(PERL_EXTERNAL_GLOB)
10119     if (!PL_globhook) {
10120         ENTER;
10121         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
10122                                newSVpvs("File::Glob"), NULL, NULL, NULL);
10123         LEAVE;
10124     }
10125 #endif /* !PERL_EXTERNAL_GLOB */
10126     gv = (GV *)newSV(0);
10127     gv_init(gv, 0, "", 0, 0);
10128     gv_IOadd(gv);
10129     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
10130     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
10131     scalarkids(o);
10132     return o;
10133 }
10134
10135 OP *
10136 Perl_ck_grep(pTHX_ OP *o)
10137 {
10138     LOGOP *gwop;
10139     OP *kid;
10140     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
10141
10142     PERL_ARGS_ASSERT_CK_GREP;
10143
10144     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
10145
10146     if (o->op_flags & OPf_STACKED) {
10147         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
10148         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
10149             return no_fh_allowed(o);
10150         o->op_flags &= ~OPf_STACKED;
10151     }
10152     kid = OpSIBLING(cLISTOPo->op_first);
10153     if (type == OP_MAPWHILE)
10154         list(kid);
10155     else
10156         scalar(kid);
10157     o = ck_fun(o);
10158     if (PL_parser && PL_parser->error_count)
10159         return o;
10160     kid = OpSIBLING(cLISTOPo->op_first);
10161     if (kid->op_type != OP_NULL)
10162         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
10163     kid = kUNOP->op_first;
10164
10165     gwop = S_alloc_LOGOP(aTHX_ type, o, LINKLIST(kid));
10166     kid->op_next = (OP*)gwop;
10167     o->op_private = gwop->op_private = 0;
10168     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
10169
10170     kid = OpSIBLING(cLISTOPo->op_first);
10171     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
10172         op_lvalue(kid, OP_GREPSTART);
10173
10174     return (OP*)gwop;
10175 }
10176
10177 OP *
10178 Perl_ck_index(pTHX_ OP *o)
10179 {
10180     PERL_ARGS_ASSERT_CK_INDEX;
10181
10182     if (o->op_flags & OPf_KIDS) {
10183         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
10184         if (kid)
10185             kid = OpSIBLING(kid);                       /* get past "big" */
10186         if (kid && kid->op_type == OP_CONST) {
10187             const bool save_taint = TAINT_get;
10188             SV *sv = kSVOP->op_sv;
10189             if ((!SvPOK(sv) || SvNIOKp(sv)) && SvOK(sv) && !SvROK(sv)) {
10190                 sv = newSV(0);
10191                 sv_copypv(sv, kSVOP->op_sv);
10192                 SvREFCNT_dec_NN(kSVOP->op_sv);
10193                 kSVOP->op_sv = sv;
10194             }
10195             if (SvOK(sv)) fbm_compile(sv, 0);
10196             TAINT_set(save_taint);
10197 #ifdef NO_TAINT_SUPPORT
10198             PERL_UNUSED_VAR(save_taint);
10199 #endif
10200         }
10201     }
10202     return ck_fun(o);
10203 }
10204
10205 OP *
10206 Perl_ck_lfun(pTHX_ OP *o)
10207 {
10208     const OPCODE type = o->op_type;
10209
10210     PERL_ARGS_ASSERT_CK_LFUN;
10211
10212     return modkids(ck_fun(o), type);
10213 }
10214
10215 OP *
10216 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
10217 {
10218     PERL_ARGS_ASSERT_CK_DEFINED;
10219
10220     if ((o->op_flags & OPf_KIDS)) {
10221         switch (cUNOPo->op_first->op_type) {
10222         case OP_RV2AV:
10223         case OP_PADAV:
10224             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
10225                              " (Maybe you should just omit the defined()?)");
10226         break;
10227         case OP_RV2HV:
10228         case OP_PADHV:
10229             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
10230                              " (Maybe you should just omit the defined()?)");
10231             break;
10232         default:
10233             /* no warning */
10234             break;
10235         }
10236     }
10237     return ck_rfun(o);
10238 }
10239
10240 OP *
10241 Perl_ck_readline(pTHX_ OP *o)
10242 {
10243     PERL_ARGS_ASSERT_CK_READLINE;
10244
10245     if (o->op_flags & OPf_KIDS) {
10246          OP *kid = cLISTOPo->op_first;
10247          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
10248     }
10249     else {
10250         OP * const newop
10251             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
10252         op_free(o);
10253         return newop;
10254     }
10255     return o;
10256 }
10257
10258 OP *
10259 Perl_ck_rfun(pTHX_ OP *o)
10260 {
10261     const OPCODE type = o->op_type;
10262
10263     PERL_ARGS_ASSERT_CK_RFUN;
10264
10265     return refkids(ck_fun(o), type);
10266 }
10267
10268 OP *
10269 Perl_ck_listiob(pTHX_ OP *o)
10270 {
10271     OP *kid;
10272
10273     PERL_ARGS_ASSERT_CK_LISTIOB;
10274
10275     kid = cLISTOPo->op_first;
10276     if (!kid) {
10277         o = force_list(o, 1);
10278         kid = cLISTOPo->op_first;
10279     }
10280     if (kid->op_type == OP_PUSHMARK)
10281         kid = OpSIBLING(kid);
10282     if (kid && o->op_flags & OPf_STACKED)
10283         kid = OpSIBLING(kid);
10284     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
10285         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
10286          && !kid->op_folded) {
10287             o->op_flags |= OPf_STACKED; /* make it a filehandle */
10288             scalar(kid);
10289             /* replace old const op with new OP_RV2GV parent */
10290             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
10291                                         OP_RV2GV, OPf_REF);
10292             kid = OpSIBLING(kid);
10293         }
10294     }
10295
10296     if (!kid)
10297         op_append_elem(o->op_type, o, newDEFSVOP());
10298
10299     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
10300     return listkids(o);
10301 }
10302
10303 OP *
10304 Perl_ck_smartmatch(pTHX_ OP *o)
10305 {
10306     dVAR;
10307     PERL_ARGS_ASSERT_CK_SMARTMATCH;
10308     if (0 == (o->op_flags & OPf_SPECIAL)) {
10309         OP *first  = cBINOPo->op_first;
10310         OP *second = OpSIBLING(first);
10311         
10312         /* Implicitly take a reference to an array or hash */
10313
10314         /* remove the original two siblings, then add back the
10315          * (possibly different) first and second sibs.
10316          */
10317         op_sibling_splice(o, NULL, 1, NULL);
10318         op_sibling_splice(o, NULL, 1, NULL);
10319         first  = ref_array_or_hash(first);
10320         second = ref_array_or_hash(second);
10321         op_sibling_splice(o, NULL, 0, second);
10322         op_sibling_splice(o, NULL, 0, first);
10323         
10324         /* Implicitly take a reference to a regular expression */
10325         if (first->op_type == OP_MATCH) {
10326             OpTYPE_set(first, OP_QR);
10327         }
10328         if (second->op_type == OP_MATCH) {
10329             OpTYPE_set(second, OP_QR);
10330         }
10331     }
10332     
10333     return o;
10334 }
10335
10336
10337 static OP *
10338 S_maybe_targlex(pTHX_ OP *o)
10339 {
10340     OP * const kid = cLISTOPo->op_first;
10341     /* has a disposable target? */
10342     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
10343         && !(kid->op_flags & OPf_STACKED)
10344         /* Cannot steal the second time! */
10345         && !(kid->op_private & OPpTARGET_MY)
10346         )
10347     {
10348         OP * const kkid = OpSIBLING(kid);
10349
10350         /* Can just relocate the target. */
10351         if (kkid && kkid->op_type == OP_PADSV
10352             && (!(kkid->op_private & OPpLVAL_INTRO)
10353                || kkid->op_private & OPpPAD_STATE))
10354         {
10355             kid->op_targ = kkid->op_targ;
10356             kkid->op_targ = 0;
10357             /* Now we do not need PADSV and SASSIGN.
10358              * Detach kid and free the rest. */
10359             op_sibling_splice(o, NULL, 1, NULL);
10360             op_free(o);
10361             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
10362             return kid;
10363         }
10364     }
10365     return o;
10366 }
10367
10368 OP *
10369 Perl_ck_sassign(pTHX_ OP *o)
10370 {
10371     dVAR;
10372     OP * const kid = cLISTOPo->op_first;
10373
10374     PERL_ARGS_ASSERT_CK_SASSIGN;
10375
10376     if (OpHAS_SIBLING(kid)) {
10377         OP *kkid = OpSIBLING(kid);
10378         /* For state variable assignment with attributes, kkid is a list op
10379            whose op_last is a padsv. */
10380         if ((kkid->op_type == OP_PADSV ||
10381              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
10382               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
10383              )
10384             )
10385                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
10386                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
10387             const PADOFFSET target = kkid->op_targ;
10388             OP *const other = newOP(OP_PADSV,
10389                                     kkid->op_flags
10390                                     | ((kkid->op_private & ~OPpLVAL_INTRO) << 8));
10391             OP *const first = newOP(OP_NULL, 0);
10392             OP *const nullop =
10393                 newCONDOP(0, first, o, other);
10394             /* XXX targlex disabled for now; see ticket #124160
10395                 newCONDOP(0, first, S_maybe_targlex(aTHX_ o), other);
10396              */
10397             OP *const condop = first->op_next;
10398
10399             OpTYPE_set(condop, OP_ONCE);
10400             other->op_targ = target;
10401             nullop->op_flags |= OPf_WANT_SCALAR;
10402
10403             /* Store the initializedness of state vars in a separate
10404                pad entry.  */
10405             condop->op_targ =
10406               pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
10407             /* hijacking PADSTALE for uninitialized state variables */
10408             SvPADSTALE_on(PAD_SVl(condop->op_targ));
10409
10410             return nullop;
10411         }
10412     }
10413     return S_maybe_targlex(aTHX_ o);
10414 }
10415
10416 OP *
10417 Perl_ck_match(pTHX_ OP *o)
10418 {
10419     PERL_UNUSED_CONTEXT;
10420     PERL_ARGS_ASSERT_CK_MATCH;
10421
10422     if (o->op_type == OP_MATCH || o->op_type == OP_QR)
10423         o->op_private |= OPpRUNTIME;
10424     return o;
10425 }
10426
10427 OP *
10428 Perl_ck_method(pTHX_ OP *o)
10429 {
10430     SV *sv, *methsv, *rclass;
10431     const char* method;
10432     char* compatptr;
10433     int utf8;
10434     STRLEN len, nsplit = 0, i;
10435     OP* new_op;
10436     OP * const kid = cUNOPo->op_first;
10437
10438     PERL_ARGS_ASSERT_CK_METHOD;
10439     if (kid->op_type != OP_CONST) return o;
10440
10441     sv = kSVOP->op_sv;
10442
10443     /* replace ' with :: */
10444     while ((compatptr = strchr(SvPVX(sv), '\''))) {
10445         *compatptr = ':';
10446         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
10447     }
10448
10449     method = SvPVX_const(sv);
10450     len = SvCUR(sv);
10451     utf8 = SvUTF8(sv) ? -1 : 1;
10452
10453     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
10454         nsplit = i+1;
10455         break;
10456     }
10457
10458     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
10459
10460     if (!nsplit) { /* $proto->method() */
10461         op_free(o);
10462         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
10463     }
10464
10465     if (nsplit == 7 && memEQ(method, "SUPER::", nsplit)) { /* $proto->SUPER::method() */
10466         op_free(o);
10467         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
10468     }
10469
10470     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
10471     if (nsplit >= 9 && strnEQ(method+nsplit-9, "::SUPER::", 9)) {
10472         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
10473         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
10474     } else {
10475         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
10476         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
10477     }
10478 #ifdef USE_ITHREADS
10479     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
10480 #else
10481     cMETHOPx(new_op)->op_rclass_sv = rclass;
10482 #endif
10483     op_free(o);
10484     return new_op;
10485 }
10486
10487 OP *
10488 Perl_ck_null(pTHX_ OP *o)
10489 {
10490     PERL_ARGS_ASSERT_CK_NULL;
10491     PERL_UNUSED_CONTEXT;
10492     return o;
10493 }
10494
10495 OP *
10496 Perl_ck_open(pTHX_ OP *o)
10497 {
10498     PERL_ARGS_ASSERT_CK_OPEN;
10499
10500     S_io_hints(aTHX_ o);
10501     {
10502          /* In case of three-arg dup open remove strictness
10503           * from the last arg if it is a bareword. */
10504          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
10505          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
10506          OP *oa;
10507          const char *mode;
10508
10509          if ((last->op_type == OP_CONST) &&             /* The bareword. */
10510              (last->op_private & OPpCONST_BARE) &&
10511              (last->op_private & OPpCONST_STRICT) &&
10512              (oa = OpSIBLING(first)) &&         /* The fh. */
10513              (oa = OpSIBLING(oa)) &&                    /* The mode. */
10514              (oa->op_type == OP_CONST) &&
10515              SvPOK(((SVOP*)oa)->op_sv) &&
10516              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
10517              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
10518              (last == OpSIBLING(oa)))                   /* The bareword. */
10519               last->op_private &= ~OPpCONST_STRICT;
10520     }
10521     return ck_fun(o);
10522 }
10523
10524 OP *
10525 Perl_ck_prototype(pTHX_ OP *o)
10526 {
10527     PERL_ARGS_ASSERT_CK_PROTOTYPE;
10528     if (!(o->op_flags & OPf_KIDS)) {
10529         op_free(o);
10530         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
10531     }
10532     return o;
10533 }
10534
10535 OP *
10536 Perl_ck_refassign(pTHX_ OP *o)
10537 {
10538     OP * const right = cLISTOPo->op_first;
10539     OP * const left = OpSIBLING(right);
10540     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
10541     bool stacked = 0;
10542
10543     PERL_ARGS_ASSERT_CK_REFASSIGN;
10544     assert (left);
10545     assert (left->op_type == OP_SREFGEN);
10546
10547     o->op_private = 0;
10548     /* we use OPpPAD_STATE in refassign to mean either of those things,
10549      * and the code assumes the two flags occupy the same bit position
10550      * in the various ops below */
10551     assert(OPpPAD_STATE == OPpOUR_INTRO);
10552
10553     switch (varop->op_type) {
10554     case OP_PADAV:
10555         o->op_private |= OPpLVREF_AV;
10556         goto settarg;
10557     case OP_PADHV:
10558         o->op_private |= OPpLVREF_HV;
10559         /* FALLTHROUGH */
10560     case OP_PADSV:
10561       settarg:
10562         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
10563         o->op_targ = varop->op_targ;
10564         varop->op_targ = 0;
10565         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
10566         break;
10567
10568     case OP_RV2AV:
10569         o->op_private |= OPpLVREF_AV;
10570         goto checkgv;
10571         NOT_REACHED; /* NOTREACHED */
10572     case OP_RV2HV:
10573         o->op_private |= OPpLVREF_HV;
10574         /* FALLTHROUGH */
10575     case OP_RV2SV:
10576       checkgv:
10577         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
10578         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
10579       detach_and_stack:
10580         /* Point varop to its GV kid, detached.  */
10581         varop = op_sibling_splice(varop, NULL, -1, NULL);
10582         stacked = TRUE;
10583         break;
10584     case OP_RV2CV: {
10585         OP * const kidparent =
10586             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
10587         OP * const kid = cUNOPx(kidparent)->op_first;
10588         o->op_private |= OPpLVREF_CV;
10589         if (kid->op_type == OP_GV) {
10590             varop = kidparent;
10591             goto detach_and_stack;
10592         }
10593         if (kid->op_type != OP_PADCV)   goto bad;
10594         o->op_targ = kid->op_targ;
10595         kid->op_targ = 0;
10596         break;
10597     }
10598     case OP_AELEM:
10599     case OP_HELEM:
10600         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
10601         o->op_private |= OPpLVREF_ELEM;
10602         op_null(varop);
10603         stacked = TRUE;
10604         /* Detach varop.  */
10605         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
10606         break;
10607     default:
10608       bad:
10609         /* diag_listed_as: Can't modify reference to %s in %s assignment */
10610         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
10611                                 "assignment",
10612                                  OP_DESC(varop)));
10613         return o;
10614     }
10615     if (!FEATURE_REFALIASING_IS_ENABLED)
10616         Perl_croak(aTHX_
10617                   "Experimental aliasing via reference not enabled");
10618     Perl_ck_warner_d(aTHX_
10619                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
10620                     "Aliasing via reference is experimental");
10621     if (stacked) {
10622         o->op_flags |= OPf_STACKED;
10623         op_sibling_splice(o, right, 1, varop);
10624     }
10625     else {
10626         o->op_flags &=~ OPf_STACKED;
10627         op_sibling_splice(o, right, 1, NULL);
10628     }
10629     op_free(left);
10630     return o;
10631 }
10632
10633 OP *
10634 Perl_ck_repeat(pTHX_ OP *o)
10635 {
10636     PERL_ARGS_ASSERT_CK_REPEAT;
10637
10638     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
10639         OP* kids;
10640         o->op_private |= OPpREPEAT_DOLIST;
10641         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
10642         kids = force_list(kids, 1); /* promote it to a list */
10643         op_sibling_splice(o, NULL, 0, kids); /* and add back */
10644     }
10645     else
10646         scalar(o);
10647     return o;
10648 }
10649
10650 OP *
10651 Perl_ck_require(pTHX_ OP *o)
10652 {
10653     GV* gv;
10654
10655     PERL_ARGS_ASSERT_CK_REQUIRE;
10656
10657     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
10658         SVOP * const kid = (SVOP*)cUNOPo->op_first;
10659         HEK *hek;
10660         U32 hash;
10661         char *s;
10662         STRLEN len;
10663         if (kid->op_type == OP_CONST) {
10664           SV * const sv = kid->op_sv;
10665           U32 const was_readonly = SvREADONLY(sv);
10666           if (kid->op_private & OPpCONST_BARE) {
10667             dVAR;
10668             const char *end;
10669
10670             if (was_readonly) {
10671                     SvREADONLY_off(sv);
10672             }   
10673             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
10674
10675             s = SvPVX(sv);
10676             len = SvCUR(sv);
10677             end = s + len;
10678             /* treat ::foo::bar as foo::bar */
10679             if (len >= 2 && s[0] == ':' && s[1] == ':')
10680                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
10681             if (s == end)
10682                 DIE(aTHX_ "Bareword in require maps to empty filename");
10683
10684             for (; s < end; s++) {
10685                 if (*s == ':' && s[1] == ':') {
10686                     *s = '/';
10687                     Move(s+2, s+1, end - s - 1, char);
10688                     --end;
10689                 }
10690             }
10691             SvEND_set(sv, end);
10692             sv_catpvs(sv, ".pm");
10693             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
10694             hek = share_hek(SvPVX(sv),
10695                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
10696                             hash);
10697             sv_sethek(sv, hek);
10698             unshare_hek(hek);
10699             SvFLAGS(sv) |= was_readonly;
10700           }
10701           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
10702                 && !SvVOK(sv)) {
10703             s = SvPV(sv, len);
10704             if (SvREFCNT(sv) > 1) {
10705                 kid->op_sv = newSVpvn_share(
10706                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
10707                 SvREFCNT_dec_NN(sv);
10708             }
10709             else {
10710                 dVAR;
10711                 if (was_readonly) SvREADONLY_off(sv);
10712                 PERL_HASH(hash, s, len);
10713                 hek = share_hek(s,
10714                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
10715                                 hash);
10716                 sv_sethek(sv, hek);
10717                 unshare_hek(hek);
10718                 SvFLAGS(sv) |= was_readonly;
10719             }
10720           }
10721         }
10722     }
10723
10724     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
10725         /* handle override, if any */
10726      && (gv = gv_override("require", 7))) {
10727         OP *kid, *newop;
10728         if (o->op_flags & OPf_KIDS) {
10729             kid = cUNOPo->op_first;
10730             op_sibling_splice(o, NULL, -1, NULL);
10731         }
10732         else {
10733             kid = newDEFSVOP();
10734         }
10735         op_free(o);
10736         newop = S_new_entersubop(aTHX_ gv, kid);
10737         return newop;
10738     }
10739
10740     return ck_fun(o);
10741 }
10742
10743 OP *
10744 Perl_ck_return(pTHX_ OP *o)
10745 {
10746     OP *kid;
10747
10748     PERL_ARGS_ASSERT_CK_RETURN;
10749
10750     kid = OpSIBLING(cLISTOPo->op_first);
10751     if (CvLVALUE(PL_compcv)) {
10752         for (; kid; kid = OpSIBLING(kid))
10753             op_lvalue(kid, OP_LEAVESUBLV);
10754     }
10755
10756     return o;
10757 }
10758
10759 OP *
10760 Perl_ck_select(pTHX_ OP *o)
10761 {
10762     dVAR;
10763     OP* kid;
10764
10765     PERL_ARGS_ASSERT_CK_SELECT;
10766
10767     if (o->op_flags & OPf_KIDS) {
10768         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
10769         if (kid && OpHAS_SIBLING(kid)) {
10770             OpTYPE_set(o, OP_SSELECT);
10771             o = ck_fun(o);
10772             return fold_constants(op_integerize(op_std_init(o)));
10773         }
10774     }
10775     o = ck_fun(o);
10776     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10777     if (kid && kid->op_type == OP_RV2GV)
10778         kid->op_private &= ~HINT_STRICT_REFS;
10779     return o;
10780 }
10781
10782 OP *
10783 Perl_ck_shift(pTHX_ OP *o)
10784 {
10785     const I32 type = o->op_type;
10786
10787     PERL_ARGS_ASSERT_CK_SHIFT;
10788
10789     if (!(o->op_flags & OPf_KIDS)) {
10790         OP *argop;
10791
10792         if (!CvUNIQUE(PL_compcv)) {
10793             o->op_flags |= OPf_SPECIAL;
10794             return o;
10795         }
10796
10797         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
10798         op_free(o);
10799         return newUNOP(type, 0, scalar(argop));
10800     }
10801     return scalar(ck_fun(o));
10802 }
10803
10804 OP *
10805 Perl_ck_sort(pTHX_ OP *o)
10806 {
10807     OP *firstkid;
10808     OP *kid;
10809     HV * const hinthv =
10810         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
10811     U8 stacked;
10812
10813     PERL_ARGS_ASSERT_CK_SORT;
10814
10815     if (hinthv) {
10816             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
10817             if (svp) {
10818                 const I32 sorthints = (I32)SvIV(*svp);
10819                 if ((sorthints & HINT_SORT_QUICKSORT) != 0)
10820                     o->op_private |= OPpSORT_QSORT;
10821                 if ((sorthints & HINT_SORT_STABLE) != 0)
10822                     o->op_private |= OPpSORT_STABLE;
10823             }
10824     }
10825
10826     if (o->op_flags & OPf_STACKED)
10827         simplify_sort(o);
10828     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
10829
10830     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
10831         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
10832
10833         /* if the first arg is a code block, process it and mark sort as
10834          * OPf_SPECIAL */
10835         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
10836             LINKLIST(kid);
10837             if (kid->op_type == OP_LEAVE)
10838                     op_null(kid);                       /* wipe out leave */
10839             /* Prevent execution from escaping out of the sort block. */
10840             kid->op_next = 0;
10841
10842             /* provide scalar context for comparison function/block */
10843             kid = scalar(firstkid);
10844             kid->op_next = kid;
10845             o->op_flags |= OPf_SPECIAL;
10846         }
10847         else if (kid->op_type == OP_CONST
10848               && kid->op_private & OPpCONST_BARE) {
10849             char tmpbuf[256];
10850             STRLEN len;
10851             PADOFFSET off;
10852             const char * const name = SvPV(kSVOP_sv, len);
10853             *tmpbuf = '&';
10854             assert (len < 256);
10855             Copy(name, tmpbuf+1, len, char);
10856             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
10857             if (off != NOT_IN_PAD) {
10858                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
10859                     SV * const fq =
10860                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
10861                     sv_catpvs(fq, "::");
10862                     sv_catsv(fq, kSVOP_sv);
10863                     SvREFCNT_dec_NN(kSVOP_sv);
10864                     kSVOP->op_sv = fq;
10865                 }
10866                 else {
10867                     OP * const padop = newOP(OP_PADCV, 0);
10868                     padop->op_targ = off;
10869                     /* replace the const op with the pad op */
10870                     op_sibling_splice(firstkid, NULL, 1, padop);
10871                     op_free(kid);
10872                 }
10873             }
10874         }
10875
10876         firstkid = OpSIBLING(firstkid);
10877     }
10878
10879     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
10880         /* provide list context for arguments */
10881         list(kid);
10882         if (stacked)
10883             op_lvalue(kid, OP_GREPSTART);
10884     }
10885
10886     return o;
10887 }
10888
10889 /* for sort { X } ..., where X is one of
10890  *   $a <=> $b, $b <= $a, $a cmp $b, $b cmp $a
10891  * elide the second child of the sort (the one containing X),
10892  * and set these flags as appropriate
10893         OPpSORT_NUMERIC;
10894         OPpSORT_INTEGER;
10895         OPpSORT_DESCEND;
10896  * Also, check and warn on lexical $a, $b.
10897  */
10898
10899 STATIC void
10900 S_simplify_sort(pTHX_ OP *o)
10901 {
10902     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10903     OP *k;
10904     int descending;
10905     GV *gv;
10906     const char *gvname;
10907     bool have_scopeop;
10908
10909     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
10910
10911     kid = kUNOP->op_first;                              /* get past null */
10912     if (!(have_scopeop = kid->op_type == OP_SCOPE)
10913      && kid->op_type != OP_LEAVE)
10914         return;
10915     kid = kLISTOP->op_last;                             /* get past scope */
10916     switch(kid->op_type) {
10917         case OP_NCMP:
10918         case OP_I_NCMP:
10919         case OP_SCMP:
10920             if (!have_scopeop) goto padkids;
10921             break;
10922         default:
10923             return;
10924     }
10925     k = kid;                                            /* remember this node*/
10926     if (kBINOP->op_first->op_type != OP_RV2SV
10927      || kBINOP->op_last ->op_type != OP_RV2SV)
10928     {
10929         /*
10930            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
10931            then used in a comparison.  This catches most, but not
10932            all cases.  For instance, it catches
10933                sort { my($a); $a <=> $b }
10934            but not
10935                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
10936            (although why you'd do that is anyone's guess).
10937         */
10938
10939        padkids:
10940         if (!ckWARN(WARN_SYNTAX)) return;
10941         kid = kBINOP->op_first;
10942         do {
10943             if (kid->op_type == OP_PADSV) {
10944                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
10945                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
10946                  && (  PadnamePV(name)[1] == 'a'
10947                     || PadnamePV(name)[1] == 'b'  ))
10948                     /* diag_listed_as: "my %s" used in sort comparison */
10949                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10950                                      "\"%s %s\" used in sort comparison",
10951                                       PadnameIsSTATE(name)
10952                                         ? "state"
10953                                         : "my",
10954                                       PadnamePV(name));
10955             }
10956         } while ((kid = OpSIBLING(kid)));
10957         return;
10958     }
10959     kid = kBINOP->op_first;                             /* get past cmp */
10960     if (kUNOP->op_first->op_type != OP_GV)
10961         return;
10962     kid = kUNOP->op_first;                              /* get past rv2sv */
10963     gv = kGVOP_gv;
10964     if (GvSTASH(gv) != PL_curstash)
10965         return;
10966     gvname = GvNAME(gv);
10967     if (*gvname == 'a' && gvname[1] == '\0')
10968         descending = 0;
10969     else if (*gvname == 'b' && gvname[1] == '\0')
10970         descending = 1;
10971     else
10972         return;
10973
10974     kid = k;                                            /* back to cmp */
10975     /* already checked above that it is rv2sv */
10976     kid = kBINOP->op_last;                              /* down to 2nd arg */
10977     if (kUNOP->op_first->op_type != OP_GV)
10978         return;
10979     kid = kUNOP->op_first;                              /* get past rv2sv */
10980     gv = kGVOP_gv;
10981     if (GvSTASH(gv) != PL_curstash)
10982         return;
10983     gvname = GvNAME(gv);
10984     if ( descending
10985          ? !(*gvname == 'a' && gvname[1] == '\0')
10986          : !(*gvname == 'b' && gvname[1] == '\0'))
10987         return;
10988     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
10989     if (descending)
10990         o->op_private |= OPpSORT_DESCEND;
10991     if (k->op_type == OP_NCMP)
10992         o->op_private |= OPpSORT_NUMERIC;
10993     if (k->op_type == OP_I_NCMP)
10994         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
10995     kid = OpSIBLING(cLISTOPo->op_first);
10996     /* cut out and delete old block (second sibling) */
10997     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
10998     op_free(kid);
10999 }
11000
11001 OP *
11002 Perl_ck_split(pTHX_ OP *o)
11003 {
11004     dVAR;
11005     OP *kid;
11006
11007     PERL_ARGS_ASSERT_CK_SPLIT;
11008
11009     if (o->op_flags & OPf_STACKED)
11010         return no_fh_allowed(o);
11011
11012     kid = cLISTOPo->op_first;
11013     if (kid->op_type != OP_NULL)
11014         Perl_croak(aTHX_ "panic: ck_split, type=%u", (unsigned) kid->op_type);
11015     /* delete leading NULL node, then add a CONST if no other nodes */
11016     op_sibling_splice(o, NULL, 1,
11017         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
11018     op_free(kid);
11019     kid = cLISTOPo->op_first;
11020
11021     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
11022         /* remove kid, and replace with new optree */
11023         op_sibling_splice(o, NULL, 1, NULL);
11024         /* OPf_SPECIAL is used to trigger split " " behavior */
11025         kid = pmruntime( newPMOP(OP_MATCH, OPf_SPECIAL), kid, NULL, 0, 0);
11026         op_sibling_splice(o, NULL, 0, kid);
11027     }
11028     OpTYPE_set(kid, OP_PUSHRE);
11029     /* target implies @ary=..., so wipe it */
11030     kid->op_targ = 0;
11031     scalar(kid);
11032     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
11033       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
11034                      "Use of /g modifier is meaningless in split");
11035     }
11036
11037     if (!OpHAS_SIBLING(kid))
11038         op_append_elem(OP_SPLIT, o, newDEFSVOP());
11039
11040     kid = OpSIBLING(kid);
11041     assert(kid);
11042     scalar(kid);
11043
11044     if (!OpHAS_SIBLING(kid))
11045     {
11046         op_append_elem(OP_SPLIT, o, newSVOP(OP_CONST, 0, newSViv(0)));
11047         o->op_private |= OPpSPLIT_IMPLIM;
11048     }
11049     assert(OpHAS_SIBLING(kid));
11050
11051     kid = OpSIBLING(kid);
11052     scalar(kid);
11053
11054     if (OpHAS_SIBLING(kid))
11055         return too_many_arguments_pv(o,OP_DESC(o), 0);
11056
11057     return o;
11058 }
11059
11060 OP *
11061 Perl_ck_stringify(pTHX_ OP *o)
11062 {
11063     OP * const kid = OpSIBLING(cUNOPo->op_first);
11064     PERL_ARGS_ASSERT_CK_STRINGIFY;
11065     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
11066          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
11067          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
11068         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
11069     {
11070         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
11071         op_free(o);
11072         return kid;
11073     }
11074     return ck_fun(o);
11075 }
11076         
11077 OP *
11078 Perl_ck_join(pTHX_ OP *o)
11079 {
11080     OP * const kid = OpSIBLING(cLISTOPo->op_first);
11081
11082     PERL_ARGS_ASSERT_CK_JOIN;
11083
11084     if (kid && kid->op_type == OP_MATCH) {
11085         if (ckWARN(WARN_SYNTAX)) {
11086             const REGEXP *re = PM_GETRE(kPMOP);
11087             const SV *msg = re
11088                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
11089                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
11090                     : newSVpvs_flags( "STRING", SVs_TEMP );
11091             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11092                         "/%"SVf"/ should probably be written as \"%"SVf"\"",
11093                         SVfARG(msg), SVfARG(msg));
11094         }
11095     }
11096     if (kid
11097      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
11098         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
11099         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
11100            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
11101     {
11102         const OP * const bairn = OpSIBLING(kid); /* the list */
11103         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
11104          && OP_GIMME(bairn,0) == G_SCALAR)
11105         {
11106             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
11107                                      op_sibling_splice(o, kid, 1, NULL));
11108             op_free(o);
11109             return ret;
11110         }
11111     }
11112
11113     return ck_fun(o);
11114 }
11115
11116 /*
11117 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
11118
11119 Examines an op, which is expected to identify a subroutine at runtime,
11120 and attempts to determine at compile time which subroutine it identifies.
11121 This is normally used during Perl compilation to determine whether
11122 a prototype can be applied to a function call.  C<cvop> is the op
11123 being considered, normally an C<rv2cv> op.  A pointer to the identified
11124 subroutine is returned, if it could be determined statically, and a null
11125 pointer is returned if it was not possible to determine statically.
11126
11127 Currently, the subroutine can be identified statically if the RV that the
11128 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
11129 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
11130 suitable if the constant value must be an RV pointing to a CV.  Details of
11131 this process may change in future versions of Perl.  If the C<rv2cv> op
11132 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
11133 the subroutine statically: this flag is used to suppress compile-time
11134 magic on a subroutine call, forcing it to use default runtime behaviour.
11135
11136 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
11137 of a GV reference is modified.  If a GV was examined and its CV slot was
11138 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
11139 If the op is not optimised away, and the CV slot is later populated with
11140 a subroutine having a prototype, that flag eventually triggers the warning
11141 "called too early to check prototype".
11142
11143 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
11144 of returning a pointer to the subroutine it returns a pointer to the
11145 GV giving the most appropriate name for the subroutine in this context.
11146 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
11147 (C<CvANON>) subroutine that is referenced through a GV it will be the
11148 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
11149 A null pointer is returned as usual if there is no statically-determinable
11150 subroutine.
11151
11152 =cut
11153 */
11154
11155 /* shared by toke.c:yylex */
11156 CV *
11157 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
11158 {
11159     PADNAME *name = PAD_COMPNAME(off);
11160     CV *compcv = PL_compcv;
11161     while (PadnameOUTER(name)) {
11162         assert(PARENT_PAD_INDEX(name));
11163         compcv = CvOUTSIDE(compcv);
11164         name = PadlistNAMESARRAY(CvPADLIST(compcv))
11165                 [off = PARENT_PAD_INDEX(name)];
11166     }
11167     assert(!PadnameIsOUR(name));
11168     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
11169         return PadnamePROTOCV(name);
11170     }
11171     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
11172 }
11173
11174 CV *
11175 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
11176 {
11177     OP *rvop;
11178     CV *cv;
11179     GV *gv;
11180     PERL_ARGS_ASSERT_RV2CV_OP_CV;
11181     if (flags & ~RV2CVOPCV_FLAG_MASK)
11182         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
11183     if (cvop->op_type != OP_RV2CV)
11184         return NULL;
11185     if (cvop->op_private & OPpENTERSUB_AMPER)
11186         return NULL;
11187     if (!(cvop->op_flags & OPf_KIDS))
11188         return NULL;
11189     rvop = cUNOPx(cvop)->op_first;
11190     switch (rvop->op_type) {
11191         case OP_GV: {
11192             gv = cGVOPx_gv(rvop);
11193             if (!isGV(gv)) {
11194                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
11195                     cv = MUTABLE_CV(SvRV(gv));
11196                     gv = NULL;
11197                     break;
11198                 }
11199                 if (flags & RV2CVOPCV_RETURN_STUB)
11200                     return (CV *)gv;
11201                 else return NULL;
11202             }
11203             cv = GvCVu(gv);
11204             if (!cv) {
11205                 if (flags & RV2CVOPCV_MARK_EARLY)
11206                     rvop->op_private |= OPpEARLY_CV;
11207                 return NULL;
11208             }
11209         } break;
11210         case OP_CONST: {
11211             SV *rv = cSVOPx_sv(rvop);
11212             if (!SvROK(rv))
11213                 return NULL;
11214             cv = (CV*)SvRV(rv);
11215             gv = NULL;
11216         } break;
11217         case OP_PADCV: {
11218             cv = find_lexical_cv(rvop->op_targ);
11219             gv = NULL;
11220         } break;
11221         default: {
11222             return NULL;
11223         } NOT_REACHED; /* NOTREACHED */
11224     }
11225     if (SvTYPE((SV*)cv) != SVt_PVCV)
11226         return NULL;
11227     if (flags & (RV2CVOPCV_RETURN_NAME_GV|RV2CVOPCV_MAYBE_NAME_GV)) {
11228         if ((!CvANON(cv) || !gv) && !CvLEXICAL(cv)
11229          && ((flags & RV2CVOPCV_RETURN_NAME_GV) || !CvNAMED(cv)))
11230             gv = CvGV(cv);
11231         return (CV*)gv;
11232     } else {
11233         return cv;
11234     }
11235 }
11236
11237 /*
11238 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
11239
11240 Performs the default fixup of the arguments part of an C<entersub>
11241 op tree.  This consists of applying list context to each of the
11242 argument ops.  This is the standard treatment used on a call marked
11243 with C<&>, or a method call, or a call through a subroutine reference,
11244 or any other call where the callee can't be identified at compile time,
11245 or a call where the callee has no prototype.
11246
11247 =cut
11248 */
11249
11250 OP *
11251 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
11252 {
11253     OP *aop;
11254
11255     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
11256
11257     aop = cUNOPx(entersubop)->op_first;
11258     if (!OpHAS_SIBLING(aop))
11259         aop = cUNOPx(aop)->op_first;
11260     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
11261         /* skip the extra attributes->import() call implicitly added in
11262          * something like foo(my $x : bar)
11263          */
11264         if (   aop->op_type == OP_ENTERSUB
11265             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
11266         )
11267             continue;
11268         list(aop);
11269         op_lvalue(aop, OP_ENTERSUB);
11270     }
11271     return entersubop;
11272 }
11273
11274 /*
11275 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
11276
11277 Performs the fixup of the arguments part of an C<entersub> op tree
11278 based on a subroutine prototype.  This makes various modifications to
11279 the argument ops, from applying context up to inserting C<refgen> ops,
11280 and checking the number and syntactic types of arguments, as directed by
11281 the prototype.  This is the standard treatment used on a subroutine call,
11282 not marked with C<&>, where the callee can be identified at compile time
11283 and has a prototype.
11284
11285 C<protosv> supplies the subroutine prototype to be applied to the call.
11286 It may be a normal defined scalar, of which the string value will be used.
11287 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11288 that has been cast to C<SV*>) which has a prototype.  The prototype
11289 supplied, in whichever form, does not need to match the actual callee
11290 referenced by the op tree.
11291
11292 If the argument ops disagree with the prototype, for example by having
11293 an unacceptable number of arguments, a valid op tree is returned anyway.
11294 The error is reflected in the parser state, normally resulting in a single
11295 exception at the top level of parsing which covers all the compilation
11296 errors that occurred.  In the error message, the callee is referred to
11297 by the name defined by the C<namegv> parameter.
11298
11299 =cut
11300 */
11301
11302 OP *
11303 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11304 {
11305     STRLEN proto_len;
11306     const char *proto, *proto_end;
11307     OP *aop, *prev, *cvop, *parent;
11308     int optional = 0;
11309     I32 arg = 0;
11310     I32 contextclass = 0;
11311     const char *e = NULL;
11312     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
11313     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
11314         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
11315                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
11316     if (SvTYPE(protosv) == SVt_PVCV)
11317          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
11318     else proto = SvPV(protosv, proto_len);
11319     proto = S_strip_spaces(aTHX_ proto, &proto_len);
11320     proto_end = proto + proto_len;
11321     parent = entersubop;
11322     aop = cUNOPx(entersubop)->op_first;
11323     if (!OpHAS_SIBLING(aop)) {
11324         parent = aop;
11325         aop = cUNOPx(aop)->op_first;
11326     }
11327     prev = aop;
11328     aop = OpSIBLING(aop);
11329     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11330     while (aop != cvop) {
11331         OP* o3 = aop;
11332
11333         if (proto >= proto_end)
11334         {
11335             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11336             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf,
11337                                         SVfARG(namesv)), SvUTF8(namesv));
11338             return entersubop;
11339         }
11340
11341         switch (*proto) {
11342             case ';':
11343                 optional = 1;
11344                 proto++;
11345                 continue;
11346             case '_':
11347                 /* _ must be at the end */
11348                 if (proto[1] && !strchr(";@%", proto[1]))
11349                     goto oops;
11350                 /* FALLTHROUGH */
11351             case '$':
11352                 proto++;
11353                 arg++;
11354                 scalar(aop);
11355                 break;
11356             case '%':
11357             case '@':
11358                 list(aop);
11359                 arg++;
11360                 break;
11361             case '&':
11362                 proto++;
11363                 arg++;
11364                 if (    o3->op_type != OP_UNDEF
11365                     && (o3->op_type != OP_SREFGEN
11366                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11367                                 != OP_ANONCODE
11368                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11369                                 != OP_RV2CV)))
11370                     bad_type_gv(arg, namegv, o3,
11371                             arg == 1 ? "block or sub {}" : "sub {}");
11372                 break;
11373             case '*':
11374                 /* '*' allows any scalar type, including bareword */
11375                 proto++;
11376                 arg++;
11377                 if (o3->op_type == OP_RV2GV)
11378                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
11379                 else if (o3->op_type == OP_CONST)
11380                     o3->op_private &= ~OPpCONST_STRICT;
11381                 scalar(aop);
11382                 break;
11383             case '+':
11384                 proto++;
11385                 arg++;
11386                 if (o3->op_type == OP_RV2AV ||
11387                     o3->op_type == OP_PADAV ||
11388                     o3->op_type == OP_RV2HV ||
11389                     o3->op_type == OP_PADHV
11390                 ) {
11391                     goto wrapref;
11392                 }
11393                 scalar(aop);
11394                 break;
11395             case '[': case ']':
11396                 goto oops;
11397
11398             case '\\':
11399                 proto++;
11400                 arg++;
11401             again:
11402                 switch (*proto++) {
11403                     case '[':
11404                         if (contextclass++ == 0) {
11405                             e = strchr(proto, ']');
11406                             if (!e || e == proto)
11407                                 goto oops;
11408                         }
11409                         else
11410                             goto oops;
11411                         goto again;
11412
11413                     case ']':
11414                         if (contextclass) {
11415                             const char *p = proto;
11416                             const char *const end = proto;
11417                             contextclass = 0;
11418                             while (*--p != '[')
11419                                 /* \[$] accepts any scalar lvalue */
11420                                 if (*p == '$'
11421                                  && Perl_op_lvalue_flags(aTHX_
11422                                      scalar(o3),
11423                                      OP_READ, /* not entersub */
11424                                      OP_LVALUE_NO_CROAK
11425                                     )) goto wrapref;
11426                             bad_type_gv(arg, namegv, o3,
11427                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
11428                         } else
11429                             goto oops;
11430                         break;
11431                     case '*':
11432                         if (o3->op_type == OP_RV2GV)
11433                             goto wrapref;
11434                         if (!contextclass)
11435                             bad_type_gv(arg, namegv, o3, "symbol");
11436                         break;
11437                     case '&':
11438                         if (o3->op_type == OP_ENTERSUB
11439                          && !(o3->op_flags & OPf_STACKED))
11440                             goto wrapref;
11441                         if (!contextclass)
11442                             bad_type_gv(arg, namegv, o3, "subroutine");
11443                         break;
11444                     case '$':
11445                         if (o3->op_type == OP_RV2SV ||
11446                                 o3->op_type == OP_PADSV ||
11447                                 o3->op_type == OP_HELEM ||
11448                                 o3->op_type == OP_AELEM)
11449                             goto wrapref;
11450                         if (!contextclass) {
11451                             /* \$ accepts any scalar lvalue */
11452                             if (Perl_op_lvalue_flags(aTHX_
11453                                     scalar(o3),
11454                                     OP_READ,  /* not entersub */
11455                                     OP_LVALUE_NO_CROAK
11456                                )) goto wrapref;
11457                             bad_type_gv(arg, namegv, o3, "scalar");
11458                         }
11459                         break;
11460                     case '@':
11461                         if (o3->op_type == OP_RV2AV ||
11462                                 o3->op_type == OP_PADAV)
11463                         {
11464                             o3->op_flags &=~ OPf_PARENS;
11465                             goto wrapref;
11466                         }
11467                         if (!contextclass)
11468                             bad_type_gv(arg, namegv, o3, "array");
11469                         break;
11470                     case '%':
11471                         if (o3->op_type == OP_RV2HV ||
11472                                 o3->op_type == OP_PADHV)
11473                         {
11474                             o3->op_flags &=~ OPf_PARENS;
11475                             goto wrapref;
11476                         }
11477                         if (!contextclass)
11478                             bad_type_gv(arg, namegv, o3, "hash");
11479                         break;
11480                     wrapref:
11481                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
11482                                                 OP_REFGEN, 0);
11483                         if (contextclass && e) {
11484                             proto = e + 1;
11485                             contextclass = 0;
11486                         }
11487                         break;
11488                     default: goto oops;
11489                 }
11490                 if (contextclass)
11491                     goto again;
11492                 break;
11493             case ' ':
11494                 proto++;
11495                 continue;
11496             default:
11497             oops: {
11498                 Perl_croak(aTHX_ "Malformed prototype for %"SVf": %"SVf,
11499                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
11500                                   SVfARG(protosv));
11501             }
11502         }
11503
11504         op_lvalue(aop, OP_ENTERSUB);
11505         prev = aop;
11506         aop = OpSIBLING(aop);
11507     }
11508     if (aop == cvop && *proto == '_') {
11509         /* generate an access to $_ */
11510         op_sibling_splice(parent, prev, 0, newDEFSVOP());
11511     }
11512     if (!optional && proto_end > proto &&
11513         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
11514     {
11515         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11516         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf,
11517                                     SVfARG(namesv)), SvUTF8(namesv));
11518     }
11519     return entersubop;
11520 }
11521
11522 /*
11523 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
11524
11525 Performs the fixup of the arguments part of an C<entersub> op tree either
11526 based on a subroutine prototype or using default list-context processing.
11527 This is the standard treatment used on a subroutine call, not marked
11528 with C<&>, where the callee can be identified at compile time.
11529
11530 C<protosv> supplies the subroutine prototype to be applied to the call,
11531 or indicates that there is no prototype.  It may be a normal scalar,
11532 in which case if it is defined then the string value will be used
11533 as a prototype, and if it is undefined then there is no prototype.
11534 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11535 that has been cast to C<SV*>), of which the prototype will be used if it
11536 has one.  The prototype (or lack thereof) supplied, in whichever form,
11537 does not need to match the actual callee referenced by the op tree.
11538
11539 If the argument ops disagree with the prototype, for example by having
11540 an unacceptable number of arguments, a valid op tree is returned anyway.
11541 The error is reflected in the parser state, normally resulting in a single
11542 exception at the top level of parsing which covers all the compilation
11543 errors that occurred.  In the error message, the callee is referred to
11544 by the name defined by the C<namegv> parameter.
11545
11546 =cut
11547 */
11548
11549 OP *
11550 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
11551         GV *namegv, SV *protosv)
11552 {
11553     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
11554     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
11555         return ck_entersub_args_proto(entersubop, namegv, protosv);
11556     else
11557         return ck_entersub_args_list(entersubop);
11558 }
11559
11560 OP *
11561 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11562 {
11563     int opnum = SvTYPE(protosv) == SVt_PVCV ? 0 : (int)SvUV(protosv);
11564     OP *aop = cUNOPx(entersubop)->op_first;
11565
11566     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
11567
11568     if (!opnum) {
11569         OP *cvop;
11570         if (!OpHAS_SIBLING(aop))
11571             aop = cUNOPx(aop)->op_first;
11572         aop = OpSIBLING(aop);
11573         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11574         if (aop != cvop)
11575             (void)too_many_arguments_pv(entersubop, GvNAME(namegv), 0);
11576         
11577         op_free(entersubop);
11578         switch(GvNAME(namegv)[2]) {
11579         case 'F': return newSVOP(OP_CONST, 0,
11580                                         newSVpv(CopFILE(PL_curcop),0));
11581         case 'L': return newSVOP(
11582                            OP_CONST, 0,
11583                            Perl_newSVpvf(aTHX_
11584                              "%"IVdf, (IV)CopLINE(PL_curcop)
11585                            )
11586                          );
11587         case 'P': return newSVOP(OP_CONST, 0,
11588                                    (PL_curstash
11589                                      ? newSVhek(HvNAME_HEK(PL_curstash))
11590                                      : &PL_sv_undef
11591                                    )
11592                                 );
11593         }
11594         NOT_REACHED; /* NOTREACHED */
11595     }
11596     else {
11597         OP *prev, *cvop, *first, *parent;
11598         U32 flags = 0;
11599
11600         parent = entersubop;
11601         if (!OpHAS_SIBLING(aop)) {
11602             parent = aop;
11603             aop = cUNOPx(aop)->op_first;
11604         }
11605         
11606         first = prev = aop;
11607         aop = OpSIBLING(aop);
11608         /* find last sibling */
11609         for (cvop = aop;
11610              OpHAS_SIBLING(cvop);
11611              prev = cvop, cvop = OpSIBLING(cvop))
11612             ;
11613         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
11614             /* Usually, OPf_SPECIAL on an op with no args means that it had
11615              * parens, but these have their own meaning for that flag: */
11616             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
11617             && opnum != OP_DELETE && opnum != OP_EXISTS)
11618                 flags |= OPf_SPECIAL;
11619         /* excise cvop from end of sibling chain */
11620         op_sibling_splice(parent, prev, 1, NULL);
11621         op_free(cvop);
11622         if (aop == cvop) aop = NULL;
11623
11624         /* detach remaining siblings from the first sibling, then
11625          * dispose of original optree */
11626
11627         if (aop)
11628             op_sibling_splice(parent, first, -1, NULL);
11629         op_free(entersubop);
11630
11631         if (opnum == OP_ENTEREVAL
11632          && GvNAMELEN(namegv)==9 && strnEQ(GvNAME(namegv), "evalbytes", 9))
11633             flags |= OPpEVAL_BYTES <<8;
11634         
11635         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
11636         case OA_UNOP:
11637         case OA_BASEOP_OR_UNOP:
11638         case OA_FILESTATOP:
11639             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
11640         case OA_BASEOP:
11641             if (aop) {
11642                     (void)too_many_arguments_pv(aop, GvNAME(namegv), 0);
11643                 op_free(aop);
11644             }
11645             return opnum == OP_RUNCV
11646                 ? newPVOP(OP_RUNCV,0,NULL)
11647                 : newOP(opnum,0);
11648         default:
11649             return op_convert_list(opnum,0,aop);
11650         }
11651     }
11652     NOT_REACHED; /* NOTREACHED */
11653     return entersubop;
11654 }
11655
11656 /*
11657 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
11658
11659 Retrieves the function that will be used to fix up a call to C<cv>.
11660 Specifically, the function is applied to an C<entersub> op tree for a
11661 subroutine call, not marked with C<&>, where the callee can be identified
11662 at compile time as C<cv>.
11663
11664 The C-level function pointer is returned in C<*ckfun_p>, and an SV
11665 argument for it is returned in C<*ckobj_p>.  The function is intended
11666 to be called in this manner:
11667
11668  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
11669
11670 In this call, C<entersubop> is a pointer to the C<entersub> op,
11671 which may be replaced by the check function, and C<namegv> is a GV
11672 supplying the name that should be used by the check function to refer
11673 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11674 It is permitted to apply the check function in non-standard situations,
11675 such as to a call to a different subroutine or to a method call.
11676
11677 By default, the function is
11678 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
11679 and the SV parameter is C<cv> itself.  This implements standard
11680 prototype processing.  It can be changed, for a particular subroutine,
11681 by L</cv_set_call_checker>.
11682
11683 =cut
11684 */
11685
11686 static void
11687 S_cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p,
11688                       U8 *flagsp)
11689 {
11690     MAGIC *callmg;
11691     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
11692     if (callmg) {
11693         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
11694         *ckobj_p = callmg->mg_obj;
11695         if (flagsp) *flagsp = callmg->mg_flags;
11696     } else {
11697         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
11698         *ckobj_p = (SV*)cv;
11699         if (flagsp) *flagsp = 0;
11700     }
11701 }
11702
11703 void
11704 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
11705 {
11706     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
11707     PERL_UNUSED_CONTEXT;
11708     S_cv_get_call_checker(cv, ckfun_p, ckobj_p, NULL);
11709 }
11710
11711 /*
11712 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 flags
11713
11714 Sets the function that will be used to fix up a call to C<cv>.
11715 Specifically, the function is applied to an C<entersub> op tree for a
11716 subroutine call, not marked with C<&>, where the callee can be identified
11717 at compile time as C<cv>.
11718
11719 The C-level function pointer is supplied in C<ckfun>, and an SV argument
11720 for it is supplied in C<ckobj>.  The function should be defined like this:
11721
11722     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
11723
11724 It is intended to be called in this manner:
11725
11726     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
11727
11728 In this call, C<entersubop> is a pointer to the C<entersub> op,
11729 which may be replaced by the check function, and C<namegv> supplies
11730 the name that should be used by the check function to refer
11731 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11732 It is permitted to apply the check function in non-standard situations,
11733 such as to a call to a different subroutine or to a method call.
11734
11735 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
11736 CV or other SV instead.  Whatever is passed can be used as the first
11737 argument to L</cv_name>.  You can force perl to pass a GV by including
11738 C<CALL_CHECKER_REQUIRE_GV> in the C<flags>.
11739
11740 The current setting for a particular CV can be retrieved by
11741 L</cv_get_call_checker>.
11742
11743 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
11744
11745 The original form of L</cv_set_call_checker_flags>, which passes it the
11746 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.
11747
11748 =cut
11749 */
11750
11751 void
11752 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
11753 {
11754     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
11755     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
11756 }
11757
11758 void
11759 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
11760                                      SV *ckobj, U32 flags)
11761 {
11762     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
11763     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
11764         if (SvMAGICAL((SV*)cv))
11765             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
11766     } else {
11767         MAGIC *callmg;
11768         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
11769         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
11770         assert(callmg);
11771         if (callmg->mg_flags & MGf_REFCOUNTED) {
11772             SvREFCNT_dec(callmg->mg_obj);
11773             callmg->mg_flags &= ~MGf_REFCOUNTED;
11774         }
11775         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
11776         callmg->mg_obj = ckobj;
11777         if (ckobj != (SV*)cv) {
11778             SvREFCNT_inc_simple_void_NN(ckobj);
11779             callmg->mg_flags |= MGf_REFCOUNTED;
11780         }
11781         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
11782                          | (U8)(flags & MGf_REQUIRE_GV) | MGf_COPY;
11783     }
11784 }
11785
11786 static void
11787 S_entersub_alloc_targ(pTHX_ OP * const o)
11788 {
11789     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
11790     o->op_private |= OPpENTERSUB_HASTARG;
11791 }
11792
11793 OP *
11794 Perl_ck_subr(pTHX_ OP *o)
11795 {
11796     OP *aop, *cvop;
11797     CV *cv;
11798     GV *namegv;
11799     SV **const_class = NULL;
11800
11801     PERL_ARGS_ASSERT_CK_SUBR;
11802
11803     aop = cUNOPx(o)->op_first;
11804     if (!OpHAS_SIBLING(aop))
11805         aop = cUNOPx(aop)->op_first;
11806     aop = OpSIBLING(aop);
11807     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11808     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
11809     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
11810
11811     o->op_private &= ~1;
11812     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11813     if (PERLDB_SUB && PL_curstash != PL_debstash)
11814         o->op_private |= OPpENTERSUB_DB;
11815     switch (cvop->op_type) {
11816         case OP_RV2CV:
11817             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
11818             op_null(cvop);
11819             break;
11820         case OP_METHOD:
11821         case OP_METHOD_NAMED:
11822         case OP_METHOD_SUPER:
11823         case OP_METHOD_REDIR:
11824         case OP_METHOD_REDIR_SUPER:
11825             if (aop->op_type == OP_CONST) {
11826                 aop->op_private &= ~OPpCONST_STRICT;
11827                 const_class = &cSVOPx(aop)->op_sv;
11828             }
11829             else if (aop->op_type == OP_LIST) {
11830                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
11831                 if (sib && sib->op_type == OP_CONST) {
11832                     sib->op_private &= ~OPpCONST_STRICT;
11833                     const_class = &cSVOPx(sib)->op_sv;
11834                 }
11835             }
11836             /* make class name a shared cow string to speedup method calls */
11837             /* constant string might be replaced with object, f.e. bigint */
11838             if (const_class && SvPOK(*const_class)) {
11839                 STRLEN len;
11840                 const char* str = SvPV(*const_class, len);
11841                 if (len) {
11842                     SV* const shared = newSVpvn_share(
11843                         str, SvUTF8(*const_class)
11844                                     ? -(SSize_t)len : (SSize_t)len,
11845                         0
11846                     );
11847                     if (SvREADONLY(*const_class))
11848                         SvREADONLY_on(shared);
11849                     SvREFCNT_dec(*const_class);
11850                     *const_class = shared;
11851                 }
11852             }
11853             break;
11854     }
11855
11856     if (!cv) {
11857         S_entersub_alloc_targ(aTHX_ o);
11858         return ck_entersub_args_list(o);
11859     } else {
11860         Perl_call_checker ckfun;
11861         SV *ckobj;
11862         U8 flags;
11863         S_cv_get_call_checker(cv, &ckfun, &ckobj, &flags);
11864         if (CvISXSUB(cv) || !CvROOT(cv))
11865             S_entersub_alloc_targ(aTHX_ o);
11866         if (!namegv) {
11867             /* The original call checker API guarantees that a GV will be
11868                be provided with the right name.  So, if the old API was
11869                used (or the REQUIRE_GV flag was passed), we have to reify
11870                the CV’s GV, unless this is an anonymous sub.  This is not
11871                ideal for lexical subs, as its stringification will include
11872                the package.  But it is the best we can do.  */
11873             if (flags & MGf_REQUIRE_GV) {
11874                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
11875                     namegv = CvGV(cv);
11876             }
11877             else namegv = MUTABLE_GV(cv);
11878             /* After a syntax error in a lexical sub, the cv that
11879                rv2cv_op_cv returns may be a nameless stub. */
11880             if (!namegv) return ck_entersub_args_list(o);
11881
11882         }
11883         return ckfun(aTHX_ o, namegv, ckobj);
11884     }
11885 }
11886
11887 OP *
11888 Perl_ck_svconst(pTHX_ OP *o)
11889 {
11890     SV * const sv = cSVOPo->op_sv;
11891     PERL_ARGS_ASSERT_CK_SVCONST;
11892     PERL_UNUSED_CONTEXT;
11893 #ifdef PERL_COPY_ON_WRITE
11894     /* Since the read-only flag may be used to protect a string buffer, we
11895        cannot do copy-on-write with existing read-only scalars that are not
11896        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
11897        that constant, mark the constant as COWable here, if it is not
11898        already read-only. */
11899     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
11900         SvIsCOW_on(sv);
11901         CowREFCNT(sv) = 0;
11902 # ifdef PERL_DEBUG_READONLY_COW
11903         sv_buf_to_ro(sv);
11904 # endif
11905     }
11906 #endif
11907     SvREADONLY_on(sv);
11908     return o;
11909 }
11910
11911 OP *
11912 Perl_ck_trunc(pTHX_ OP *o)
11913 {
11914     PERL_ARGS_ASSERT_CK_TRUNC;
11915
11916     if (o->op_flags & OPf_KIDS) {
11917         SVOP *kid = (SVOP*)cUNOPo->op_first;
11918
11919         if (kid->op_type == OP_NULL)
11920             kid = (SVOP*)OpSIBLING(kid);
11921         if (kid && kid->op_type == OP_CONST &&
11922             (kid->op_private & OPpCONST_BARE) &&
11923             !kid->op_folded)
11924         {
11925             o->op_flags |= OPf_SPECIAL;
11926             kid->op_private &= ~OPpCONST_STRICT;
11927         }
11928     }
11929     return ck_fun(o);
11930 }
11931
11932 OP *
11933 Perl_ck_substr(pTHX_ OP *o)
11934 {
11935     PERL_ARGS_ASSERT_CK_SUBSTR;
11936
11937     o = ck_fun(o);
11938     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
11939         OP *kid = cLISTOPo->op_first;
11940
11941         if (kid->op_type == OP_NULL)
11942             kid = OpSIBLING(kid);
11943         if (kid)
11944             kid->op_flags |= OPf_MOD;
11945
11946     }
11947     return o;
11948 }
11949
11950 OP *
11951 Perl_ck_tell(pTHX_ OP *o)
11952 {
11953     PERL_ARGS_ASSERT_CK_TELL;
11954     o = ck_fun(o);
11955     if (o->op_flags & OPf_KIDS) {
11956      OP *kid = cLISTOPo->op_first;
11957      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
11958      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
11959     }
11960     return o;
11961 }
11962
11963 OP *
11964 Perl_ck_each(pTHX_ OP *o)
11965 {
11966     dVAR;
11967     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
11968     const unsigned orig_type  = o->op_type;
11969
11970     PERL_ARGS_ASSERT_CK_EACH;
11971
11972     if (kid) {
11973         switch (kid->op_type) {
11974             case OP_PADHV:
11975             case OP_RV2HV:
11976                 break;
11977             case OP_PADAV:
11978             case OP_RV2AV:
11979                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
11980                             : orig_type == OP_KEYS ? OP_AKEYS
11981                             :                        OP_AVALUES);
11982                 break;
11983             case OP_CONST:
11984                 if (kid->op_private == OPpCONST_BARE
11985                  || !SvROK(cSVOPx_sv(kid))
11986                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
11987                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
11988                    )
11989                     goto bad;
11990             default:
11991                 qerror(Perl_mess(aTHX_
11992                     "Experimental %s on scalar is now forbidden",
11993                      PL_op_desc[orig_type]));
11994                bad:
11995                 bad_type_pv(1, "hash or array", o, kid);
11996                 return o;
11997         }
11998     }
11999     return ck_fun(o);
12000 }
12001
12002 OP *
12003 Perl_ck_length(pTHX_ OP *o)
12004 {
12005     PERL_ARGS_ASSERT_CK_LENGTH;
12006
12007     o = ck_fun(o);
12008
12009     if (ckWARN(WARN_SYNTAX)) {
12010         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
12011
12012         if (kid) {
12013             SV *name = NULL;
12014             const bool hash = kid->op_type == OP_PADHV
12015                            || kid->op_type == OP_RV2HV;
12016             switch (kid->op_type) {
12017                 case OP_PADHV:
12018                 case OP_PADAV:
12019                 case OP_RV2HV:
12020                 case OP_RV2AV:
12021                     name = S_op_varname(aTHX_ kid);
12022                     break;
12023                 default:
12024                     return o;
12025             }
12026             if (name)
12027                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12028                     "length() used on %"SVf" (did you mean \"scalar(%s%"SVf
12029                     ")\"?)",
12030                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
12031                 );
12032             else if (hash)
12033      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
12034                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12035                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
12036             else
12037      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
12038                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12039                     "length() used on @array (did you mean \"scalar(@array)\"?)");
12040         }
12041     }
12042
12043     return o;
12044 }
12045
12046
12047
12048 /* 
12049    ---------------------------------------------------------
12050  
12051    Common vars in list assignment
12052
12053    There now follows some enums and static functions for detecting
12054    common variables in list assignments. Here is a little essay I wrote
12055    for myself when trying to get my head around this. DAPM.
12056
12057    ----
12058
12059    First some random observations:
12060    
12061    * If a lexical var is an alias of something else, e.g.
12062        for my $x ($lex, $pkg, $a[0]) {...}
12063      then the act of aliasing will increase the reference count of the SV
12064    
12065    * If a package var is an alias of something else, it may still have a
12066      reference count of 1, depending on how the alias was created, e.g.
12067      in *a = *b, $a may have a refcount of 1 since the GP is shared
12068      with a single GvSV pointer to the SV. So If it's an alias of another
12069      package var, then RC may be 1; if it's an alias of another scalar, e.g.
12070      a lexical var or an array element, then it will have RC > 1.
12071    
12072    * There are many ways to create a package alias; ultimately, XS code
12073      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
12074      run-time tracing mechanisms are unlikely to be able to catch all cases.
12075    
12076    * When the LHS is all my declarations, the same vars can't appear directly
12077      on the RHS, but they can indirectly via closures, aliasing and lvalue
12078      subs. But those techniques all involve an increase in the lexical
12079      scalar's ref count.
12080    
12081    * When the LHS is all lexical vars (but not necessarily my declarations),
12082      it is possible for the same lexicals to appear directly on the RHS, and
12083      without an increased ref count, since the stack isn't refcounted.
12084      This case can be detected at compile time by scanning for common lex
12085      vars with PL_generation.
12086    
12087    * lvalue subs defeat common var detection, but they do at least
12088      return vars with a temporary ref count increment. Also, you can't
12089      tell at compile time whether a sub call is lvalue.
12090    
12091     
12092    So...
12093          
12094    A: There are a few circumstances where there definitely can't be any
12095      commonality:
12096    
12097        LHS empty:  () = (...);
12098        RHS empty:  (....) = ();
12099        RHS contains only constants or other 'can't possibly be shared'
12100            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
12101            i.e. they only contain ops not marked as dangerous, whose children
12102            are also not dangerous;
12103        LHS ditto;
12104        LHS contains a single scalar element: e.g. ($x) = (....); because
12105            after $x has been modified, it won't be used again on the RHS;
12106        RHS contains a single element with no aggregate on LHS: e.g.
12107            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
12108            won't be used again.
12109    
12110    B: If LHS are all 'my' lexical var declarations (or safe ops, which
12111      we can ignore):
12112    
12113        my ($a, $b, @c) = ...;
12114    
12115        Due to closure and goto tricks, these vars may already have content.
12116        For the same reason, an element on the RHS may be a lexical or package
12117        alias of one of the vars on the left, or share common elements, for
12118        example:
12119    
12120            my ($x,$y) = f(); # $x and $y on both sides
12121            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
12122    
12123        and
12124    
12125            my $ra = f();
12126            my @a = @$ra;  # elements of @a on both sides
12127            sub f { @a = 1..4; \@a }
12128    
12129    
12130        First, just consider scalar vars on LHS:
12131    
12132            RHS is safe only if (A), or in addition,
12133                * contains only lexical *scalar* vars, where neither side's
12134                  lexicals have been flagged as aliases 
12135    
12136            If RHS is not safe, then it's always legal to check LHS vars for
12137            RC==1, since the only RHS aliases will always be associated
12138            with an RC bump.
12139    
12140            Note that in particular, RHS is not safe if:
12141    
12142                * it contains package scalar vars; e.g.:
12143    
12144                    f();
12145                    my ($x, $y) = (2, $x_alias);
12146                    sub f { $x = 1; *x_alias = \$x; }
12147    
12148                * It contains other general elements, such as flattened or
12149                * spliced or single array or hash elements, e.g.
12150    
12151                    f();
12152                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc 
12153    
12154                    sub f {
12155                        ($x, $y) = (1,2);
12156                        use feature 'refaliasing';
12157                        \($a[0], $a[1]) = \($y,$x);
12158                    }
12159    
12160                  It doesn't matter if the array/hash is lexical or package.
12161    
12162                * it contains a function call that happens to be an lvalue
12163                  sub which returns one or more of the above, e.g.
12164    
12165                    f();
12166                    my ($x,$y) = f();
12167    
12168                    sub f : lvalue {
12169                        ($x, $y) = (1,2);
12170                        *x1 = \$x;
12171                        $y, $x1;
12172                    }
12173    
12174                    (so a sub call on the RHS should be treated the same
12175                    as having a package var on the RHS).
12176    
12177                * any other "dangerous" thing, such an op or built-in that
12178                  returns one of the above, e.g. pp_preinc
12179    
12180    
12181            If RHS is not safe, what we can do however is at compile time flag
12182            that the LHS are all my declarations, and at run time check whether
12183            all the LHS have RC == 1, and if so skip the full scan.
12184    
12185        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
12186    
12187            Here the issue is whether there can be elements of @a on the RHS
12188            which will get prematurely freed when @a is cleared prior to
12189            assignment. This is only a problem if the aliasing mechanism
12190            is one which doesn't increase the refcount - only if RC == 1
12191            will the RHS element be prematurely freed.
12192    
12193            Because the array/hash is being INTROed, it or its elements
12194            can't directly appear on the RHS:
12195    
12196                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
12197    
12198            but can indirectly, e.g.:
12199    
12200                my $r = f();
12201                my (@a) = @$r;
12202                sub f { @a = 1..3; \@a }
12203    
12204            So if the RHS isn't safe as defined by (A), we must always
12205            mortalise and bump the ref count of any remaining RHS elements
12206            when assigning to a non-empty LHS aggregate.
12207    
12208            Lexical scalars on the RHS aren't safe if they've been involved in
12209            aliasing, e.g.
12210    
12211                use feature 'refaliasing';
12212    
12213                f();
12214                \(my $lex) = \$pkg;
12215                my @a = ($lex,3); # equivalent to ($a[0],3)
12216    
12217                sub f {
12218                    @a = (1,2);
12219                    \$pkg = \$a[0];
12220                }
12221    
12222            Similarly with lexical arrays and hashes on the RHS:
12223    
12224                f();
12225                my @b;
12226                my @a = (@b);
12227    
12228                sub f {
12229                    @a = (1,2);
12230                    \$b[0] = \$a[1];
12231                    \$b[1] = \$a[0];
12232                }
12233    
12234    
12235    
12236    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
12237        my $a; ($a, my $b) = (....);
12238    
12239        The difference between (B) and (C) is that it is now physically
12240        possible for the LHS vars to appear on the RHS too, where they
12241        are not reference counted; but in this case, the compile-time
12242        PL_generation sweep will detect such common vars.
12243    
12244        So the rules for (C) differ from (B) in that if common vars are
12245        detected, the runtime "test RC==1" optimisation can no longer be used,
12246        and a full mark and sweep is required
12247    
12248    D: As (C), but in addition the LHS may contain package vars.
12249    
12250        Since package vars can be aliased without a corresponding refcount
12251        increase, all bets are off. It's only safe if (A). E.g.
12252    
12253            my ($x, $y) = (1,2);
12254    
12255            for $x_alias ($x) {
12256                ($x_alias, $y) = (3, $x); # whoops
12257            }
12258    
12259        Ditto for LHS aggregate package vars.
12260    
12261    E: Any other dangerous ops on LHS, e.g.
12262            (f(), $a[0], @$r) = (...);
12263    
12264        this is similar to (E) in that all bets are off. In addition, it's
12265        impossible to determine at compile time whether the LHS
12266        contains a scalar or an aggregate, e.g.
12267    
12268            sub f : lvalue { @a }
12269            (f()) = 1..3;
12270
12271 * ---------------------------------------------------------
12272 */
12273
12274
12275 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
12276  * that at least one of the things flagged was seen.
12277  */
12278
12279 enum {
12280     AAS_MY_SCALAR       = 0x001, /* my $scalar */
12281     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
12282     AAS_LEX_SCALAR      = 0x004, /* $lexical */
12283     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
12284     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
12285     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
12286     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
12287     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
12288                                          that's flagged OA_DANGEROUS */
12289     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
12290                                         not in any of the categories above */
12291     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
12292 };
12293
12294
12295
12296 /* helper function for S_aassign_scan().
12297  * check a PAD-related op for commonality and/or set its generation number.
12298  * Returns a boolean indicating whether its shared */
12299
12300 static bool
12301 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
12302 {
12303     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
12304         /* lexical used in aliasing */
12305         return TRUE;
12306
12307     if (rhs)
12308         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
12309     else
12310         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
12311
12312     return FALSE;
12313 }
12314
12315
12316 /*
12317   Helper function for OPpASSIGN_COMMON* detection in rpeep().
12318   It scans the left or right hand subtree of the aassign op, and returns a
12319   set of flags indicating what sorts of things it found there.
12320   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
12321   set PL_generation on lexical vars; if the latter, we see if
12322   PL_generation matches.
12323   'top' indicates whether we're recursing or at the top level.
12324   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
12325   This fn will increment it by the number seen. It's not intended to
12326   be an accurate count (especially as many ops can push a variable
12327   number of SVs onto the stack); rather it's used as to test whether there
12328   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
12329 */
12330
12331 static int
12332 S_aassign_scan(pTHX_ OP* o, bool rhs, bool top, int *scalars_p)
12333 {
12334     int flags = 0;
12335     bool kid_top = FALSE;
12336
12337     /* first, look for a solitary @_ on the RHS */
12338     if (   rhs
12339         && top
12340         && (o->op_flags & OPf_KIDS)
12341         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
12342     ) {
12343         OP *kid = cUNOPo->op_first;
12344         if (   (   kid->op_type == OP_PUSHMARK
12345                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
12346             && ((kid = OpSIBLING(kid)))
12347             && !OpHAS_SIBLING(kid)
12348             && kid->op_type == OP_RV2AV
12349             && !(kid->op_flags & OPf_REF)
12350             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
12351             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
12352             && ((kid = cUNOPx(kid)->op_first))
12353             && kid->op_type == OP_GV
12354             && cGVOPx_gv(kid) == PL_defgv
12355         )
12356             flags |= AAS_DEFAV;
12357     }
12358
12359     switch (o->op_type) {
12360     case OP_GVSV:
12361         (*scalars_p)++;
12362         return AAS_PKG_SCALAR;
12363
12364     case OP_PADAV:
12365     case OP_PADHV:
12366         (*scalars_p) += 2;
12367         if (top && (o->op_flags & OPf_REF))
12368             return (o->op_private & OPpLVAL_INTRO)
12369                 ? AAS_MY_AGG : AAS_LEX_AGG;
12370         return AAS_DANGEROUS;
12371
12372     case OP_PADSV:
12373         {
12374             int comm = S_aassign_padcheck(aTHX_ o, rhs)
12375                         ?  AAS_LEX_SCALAR_COMM : 0;
12376             (*scalars_p)++;
12377             return (o->op_private & OPpLVAL_INTRO)
12378                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
12379         }
12380
12381     case OP_RV2AV:
12382     case OP_RV2HV:
12383         (*scalars_p) += 2;
12384         if (cUNOPx(o)->op_first->op_type != OP_GV)
12385             return AAS_DANGEROUS; /* @{expr}, %{expr} */
12386         /* @pkg, %pkg */
12387         if (top && (o->op_flags & OPf_REF))
12388             return AAS_PKG_AGG;
12389         return AAS_DANGEROUS;
12390
12391     case OP_RV2SV:
12392         (*scalars_p)++;
12393         if (cUNOPx(o)->op_first->op_type != OP_GV) {
12394             (*scalars_p) += 2;
12395             return AAS_DANGEROUS; /* ${expr} */
12396         }
12397         return AAS_PKG_SCALAR; /* $pkg */
12398
12399     case OP_SPLIT:
12400         if (cLISTOPo->op_first->op_type == OP_PUSHRE) {
12401             /* "@foo = split... " optimises away the aassign and stores its
12402              * destination array in the OP_PUSHRE that precedes it.
12403              * A flattened array is always dangerous.
12404              */
12405             (*scalars_p) += 2;
12406             return AAS_DANGEROUS;
12407         }
12408         break;
12409
12410     case OP_UNDEF:
12411         /* undef counts as a scalar on the RHS:
12412          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
12413          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
12414          */
12415         if (rhs)
12416             (*scalars_p)++;
12417         flags = AAS_SAFE_SCALAR;
12418         break;
12419
12420     case OP_PUSHMARK:
12421     case OP_STUB:
12422         /* these are all no-ops; they don't push a potentially common SV
12423          * onto the stack, so they are neither AAS_DANGEROUS nor
12424          * AAS_SAFE_SCALAR */
12425         return 0;
12426
12427     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
12428         break;
12429
12430     case OP_NULL:
12431     case OP_LIST:
12432         /* these do nothing but may have children; but their children
12433          * should also be treated as top-level */
12434         kid_top = top;
12435         break;
12436
12437     default:
12438         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
12439             (*scalars_p) += 2;
12440             flags = AAS_DANGEROUS;
12441             break;
12442         }
12443
12444         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
12445             && (o->op_private & OPpTARGET_MY))
12446         {
12447             (*scalars_p)++;
12448             return S_aassign_padcheck(aTHX_ o, rhs)
12449                 ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
12450         }
12451
12452         /* if its an unrecognised, non-dangerous op, assume that it
12453          * it the cause of at least one safe scalar */
12454         (*scalars_p)++;
12455         flags = AAS_SAFE_SCALAR;
12456         break;
12457     }
12458
12459     if (o->op_flags & OPf_KIDS) {
12460         OP *kid;
12461         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
12462             flags |= S_aassign_scan(aTHX_ kid, rhs, kid_top, scalars_p);
12463     }
12464     return flags;
12465 }
12466
12467
12468 /* Check for in place reverse and sort assignments like "@a = reverse @a"
12469    and modify the optree to make them work inplace */
12470
12471 STATIC void
12472 S_inplace_aassign(pTHX_ OP *o) {
12473
12474     OP *modop, *modop_pushmark;
12475     OP *oright;
12476     OP *oleft, *oleft_pushmark;
12477
12478     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
12479
12480     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
12481
12482     assert(cUNOPo->op_first->op_type == OP_NULL);
12483     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
12484     assert(modop_pushmark->op_type == OP_PUSHMARK);
12485     modop = OpSIBLING(modop_pushmark);
12486
12487     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
12488         return;
12489
12490     /* no other operation except sort/reverse */
12491     if (OpHAS_SIBLING(modop))
12492         return;
12493
12494     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
12495     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
12496
12497     if (modop->op_flags & OPf_STACKED) {
12498         /* skip sort subroutine/block */
12499         assert(oright->op_type == OP_NULL);
12500         oright = OpSIBLING(oright);
12501     }
12502
12503     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
12504     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
12505     assert(oleft_pushmark->op_type == OP_PUSHMARK);
12506     oleft = OpSIBLING(oleft_pushmark);
12507
12508     /* Check the lhs is an array */
12509     if (!oleft ||
12510         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
12511         || OpHAS_SIBLING(oleft)
12512         || (oleft->op_private & OPpLVAL_INTRO)
12513     )
12514         return;
12515
12516     /* Only one thing on the rhs */
12517     if (OpHAS_SIBLING(oright))
12518         return;
12519
12520     /* check the array is the same on both sides */
12521     if (oleft->op_type == OP_RV2AV) {
12522         if (oright->op_type != OP_RV2AV
12523             || !cUNOPx(oright)->op_first
12524             || cUNOPx(oright)->op_first->op_type != OP_GV
12525             || cUNOPx(oleft )->op_first->op_type != OP_GV
12526             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
12527                cGVOPx_gv(cUNOPx(oright)->op_first)
12528         )
12529             return;
12530     }
12531     else if (oright->op_type != OP_PADAV
12532         || oright->op_targ != oleft->op_targ
12533     )
12534         return;
12535
12536     /* This actually is an inplace assignment */
12537
12538     modop->op_private |= OPpSORT_INPLACE;
12539
12540     /* transfer MODishness etc from LHS arg to RHS arg */
12541     oright->op_flags = oleft->op_flags;
12542
12543     /* remove the aassign op and the lhs */
12544     op_null(o);
12545     op_null(oleft_pushmark);
12546     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
12547         op_null(cUNOPx(oleft)->op_first);
12548     op_null(oleft);
12549 }
12550
12551
12552
12553 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
12554  * that potentially represent a series of one or more aggregate derefs
12555  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
12556  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
12557  * additional ops left in too).
12558  *
12559  * The caller will have already verified that the first few ops in the
12560  * chain following 'start' indicate a multideref candidate, and will have
12561  * set 'orig_o' to the point further on in the chain where the first index
12562  * expression (if any) begins.  'orig_action' specifies what type of
12563  * beginning has already been determined by the ops between start..orig_o
12564  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
12565  *
12566  * 'hints' contains any hints flags that need adding (currently just
12567  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
12568  */
12569
12570 STATIC void
12571 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
12572 {
12573     dVAR;
12574     int pass;
12575     UNOP_AUX_item *arg_buf = NULL;
12576     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
12577     int index_skip         = -1;    /* don't output index arg on this action */
12578
12579     /* similar to regex compiling, do two passes; the first pass
12580      * determines whether the op chain is convertible and calculates the
12581      * buffer size; the second pass populates the buffer and makes any
12582      * changes necessary to ops (such as moving consts to the pad on
12583      * threaded builds).
12584      *
12585      * NB: for things like Coverity, note that both passes take the same
12586      * path through the logic tree (except for 'if (pass)' bits), since
12587      * both passes are following the same op_next chain; and in
12588      * particular, if it would return early on the second pass, it would
12589      * already have returned early on the first pass.
12590      */
12591     for (pass = 0; pass < 2; pass++) {
12592         OP *o                = orig_o;
12593         UV action            = orig_action;
12594         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
12595         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
12596         int action_count     = 0;     /* number of actions seen so far */
12597         int action_ix        = 0;     /* action_count % (actions per IV) */
12598         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
12599         bool is_last         = FALSE; /* no more derefs to follow */
12600         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
12601         UNOP_AUX_item *arg     = arg_buf;
12602         UNOP_AUX_item *action_ptr = arg_buf;
12603
12604         if (pass)
12605             action_ptr->uv = 0;
12606         arg++;
12607
12608         switch (action) {
12609         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
12610         case MDEREF_HV_gvhv_helem:
12611             next_is_hash = TRUE;
12612             /* FALLTHROUGH */
12613         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
12614         case MDEREF_AV_gvav_aelem:
12615             if (pass) {
12616 #ifdef USE_ITHREADS
12617                 arg->pad_offset = cPADOPx(start)->op_padix;
12618                 /* stop it being swiped when nulled */
12619                 cPADOPx(start)->op_padix = 0;
12620 #else
12621                 arg->sv = cSVOPx(start)->op_sv;
12622                 cSVOPx(start)->op_sv = NULL;
12623 #endif
12624             }
12625             arg++;
12626             break;
12627
12628         case MDEREF_HV_padhv_helem:
12629         case MDEREF_HV_padsv_vivify_rv2hv_helem:
12630             next_is_hash = TRUE;
12631             /* FALLTHROUGH */
12632         case MDEREF_AV_padav_aelem:
12633         case MDEREF_AV_padsv_vivify_rv2av_aelem:
12634             if (pass) {
12635                 arg->pad_offset = start->op_targ;
12636                 /* we skip setting op_targ = 0 for now, since the intact
12637                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
12638                 reset_start_targ = TRUE;
12639             }
12640             arg++;
12641             break;
12642
12643         case MDEREF_HV_pop_rv2hv_helem:
12644             next_is_hash = TRUE;
12645             /* FALLTHROUGH */
12646         case MDEREF_AV_pop_rv2av_aelem:
12647             break;
12648
12649         default:
12650             NOT_REACHED; /* NOTREACHED */
12651             return;
12652         }
12653
12654         while (!is_last) {
12655             /* look for another (rv2av/hv; get index;
12656              * aelem/helem/exists/delele) sequence */
12657
12658             OP *kid;
12659             bool is_deref;
12660             bool ok;
12661             UV index_type = MDEREF_INDEX_none;
12662
12663             if (action_count) {
12664                 /* if this is not the first lookup, consume the rv2av/hv  */
12665
12666                 /* for N levels of aggregate lookup, we normally expect
12667                  * that the first N-1 [ah]elem ops will be flagged as
12668                  * /DEREF (so they autovivifiy if necessary), and the last
12669                  * lookup op not to be.
12670                  * For other things (like @{$h{k1}{k2}}) extra scope or
12671                  * leave ops can appear, so abandon the effort in that
12672                  * case */
12673                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
12674                     return;
12675
12676                 /* rv2av or rv2hv sKR/1 */
12677
12678                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12679                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12680                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
12681                     return;
12682
12683                 /* at this point, we wouldn't expect any of these
12684                  * possible private flags:
12685                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
12686                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
12687                  */
12688                 ASSUME(!(o->op_private &
12689                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
12690
12691                 hints = (o->op_private & OPpHINT_STRICT_REFS);
12692
12693                 /* make sure the type of the previous /DEREF matches the
12694                  * type of the next lookup */
12695                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
12696                 top_op = o;
12697
12698                 action = next_is_hash
12699                             ? MDEREF_HV_vivify_rv2hv_helem
12700                             : MDEREF_AV_vivify_rv2av_aelem;
12701                 o = o->op_next;
12702             }
12703
12704             /* if this is the second pass, and we're at the depth where
12705              * previously we encountered a non-simple index expression,
12706              * stop processing the index at this point */
12707             if (action_count != index_skip) {
12708
12709                 /* look for one or more simple ops that return an array
12710                  * index or hash key */
12711
12712                 switch (o->op_type) {
12713                 case OP_PADSV:
12714                     /* it may be a lexical var index */
12715                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
12716                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12717                     ASSUME(!(o->op_private &
12718                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12719
12720                     if (   OP_GIMME(o,0) == G_SCALAR
12721                         && !(o->op_flags & (OPf_REF|OPf_MOD))
12722                         && o->op_private == 0)
12723                     {
12724                         if (pass)
12725                             arg->pad_offset = o->op_targ;
12726                         arg++;
12727                         index_type = MDEREF_INDEX_padsv;
12728                         o = o->op_next;
12729                     }
12730                     break;
12731
12732                 case OP_CONST:
12733                     if (next_is_hash) {
12734                         /* it's a constant hash index */
12735                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
12736                             /* "use constant foo => FOO; $h{+foo}" for
12737                              * some weird FOO, can leave you with constants
12738                              * that aren't simple strings. It's not worth
12739                              * the extra hassle for those edge cases */
12740                             break;
12741
12742                         if (pass) {
12743                             UNOP *rop = NULL;
12744                             OP * helem_op = o->op_next;
12745
12746                             ASSUME(   helem_op->op_type == OP_HELEM
12747                                    || helem_op->op_type == OP_NULL);
12748                             if (helem_op->op_type == OP_HELEM) {
12749                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
12750                                 if (   helem_op->op_private & OPpLVAL_INTRO
12751                                     || rop->op_type != OP_RV2HV
12752                                 )
12753                                     rop = NULL;
12754                             }
12755                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo);
12756
12757 #ifdef USE_ITHREADS
12758                             /* Relocate sv to the pad for thread safety */
12759                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
12760                             arg->pad_offset = o->op_targ;
12761                             o->op_targ = 0;
12762 #else
12763                             arg->sv = cSVOPx_sv(o);
12764 #endif
12765                         }
12766                     }
12767                     else {
12768                         /* it's a constant array index */
12769                         IV iv;
12770                         SV *ix_sv = cSVOPo->op_sv;
12771                         if (!SvIOK(ix_sv))
12772                             break;
12773                         iv = SvIV(ix_sv);
12774
12775                         if (   action_count == 0
12776                             && iv >= -128
12777                             && iv <= 127
12778                             && (   action == MDEREF_AV_padav_aelem
12779                                 || action == MDEREF_AV_gvav_aelem)
12780                         )
12781                             maybe_aelemfast = TRUE;
12782
12783                         if (pass) {
12784                             arg->iv = iv;
12785                             SvREFCNT_dec_NN(cSVOPo->op_sv);
12786                         }
12787                     }
12788                     if (pass)
12789                         /* we've taken ownership of the SV */
12790                         cSVOPo->op_sv = NULL;
12791                     arg++;
12792                     index_type = MDEREF_INDEX_const;
12793                     o = o->op_next;
12794                     break;
12795
12796                 case OP_GV:
12797                     /* it may be a package var index */
12798
12799                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_SPECIAL)));
12800                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
12801                     if (  (o->op_flags &~ OPf_SPECIAL) != OPf_WANT_SCALAR
12802                         || o->op_private != 0
12803                     )
12804                         break;
12805
12806                     kid = o->op_next;
12807                     if (kid->op_type != OP_RV2SV)
12808                         break;
12809
12810                     ASSUME(!(kid->op_flags &
12811                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
12812                              |OPf_SPECIAL|OPf_PARENS)));
12813                     ASSUME(!(kid->op_private &
12814                                     ~(OPpARG1_MASK
12815                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
12816                                      |OPpDEREF|OPpLVAL_INTRO)));
12817                     if(   (kid->op_flags &~ OPf_PARENS)
12818                             != (OPf_WANT_SCALAR|OPf_KIDS)
12819                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
12820                     )
12821                         break;
12822
12823                     if (pass) {
12824 #ifdef USE_ITHREADS
12825                         arg->pad_offset = cPADOPx(o)->op_padix;
12826                         /* stop it being swiped when nulled */
12827                         cPADOPx(o)->op_padix = 0;
12828 #else
12829                         arg->sv = cSVOPx(o)->op_sv;
12830                         cSVOPo->op_sv = NULL;
12831 #endif
12832                     }
12833                     arg++;
12834                     index_type = MDEREF_INDEX_gvsv;
12835                     o = kid->op_next;
12836                     break;
12837
12838                 } /* switch */
12839             } /* action_count != index_skip */
12840
12841             action |= index_type;
12842
12843
12844             /* at this point we have either:
12845              *   * detected what looks like a simple index expression,
12846              *     and expect the next op to be an [ah]elem, or
12847              *     an nulled  [ah]elem followed by a delete or exists;
12848              *  * found a more complex expression, so something other
12849              *    than the above follows.
12850              */
12851
12852             /* possibly an optimised away [ah]elem (where op_next is
12853              * exists or delete) */
12854             if (o->op_type == OP_NULL)
12855                 o = o->op_next;
12856
12857             /* at this point we're looking for an OP_AELEM, OP_HELEM,
12858              * OP_EXISTS or OP_DELETE */
12859
12860             /* if something like arybase (a.k.a $[ ) is in scope,
12861              * abandon optimisation attempt */
12862             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12863                && PL_check[o->op_type] != Perl_ck_null)
12864                 return;
12865
12866             if (   o->op_type != OP_AELEM
12867                 || (o->op_private &
12868                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
12869                 )
12870                 maybe_aelemfast = FALSE;
12871
12872             /* look for aelem/helem/exists/delete. If it's not the last elem
12873              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
12874              * flags; if it's the last, then it mustn't have
12875              * OPpDEREF_AV/HV, but may have lots of other flags, like
12876              * OPpLVAL_INTRO etc
12877              */
12878
12879             if (   index_type == MDEREF_INDEX_none
12880                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
12881                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
12882             )
12883                 ok = FALSE;
12884             else {
12885                 /* we have aelem/helem/exists/delete with valid simple index */
12886
12887                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12888                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
12889                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
12890
12891                 if (is_deref) {
12892                     ASSUME(!(o->op_flags &
12893                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
12894                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
12895
12896                     ok =    (o->op_flags &~ OPf_PARENS)
12897                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
12898                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
12899                 }
12900                 else if (o->op_type == OP_EXISTS) {
12901                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12902                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12903                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
12904                     ok =  !(o->op_private & ~OPpARG1_MASK);
12905                 }
12906                 else if (o->op_type == OP_DELETE) {
12907                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12908                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12909                     ASSUME(!(o->op_private &
12910                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
12911                     /* don't handle slices or 'local delete'; the latter
12912                      * is fairly rare, and has a complex runtime */
12913                     ok =  !(o->op_private & ~OPpARG1_MASK);
12914                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
12915                         /* skip handling run-tome error */
12916                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
12917                 }
12918                 else {
12919                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
12920                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
12921                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
12922                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
12923                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
12924                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
12925                 }
12926             }
12927
12928             if (ok) {
12929                 if (!first_elem_op)
12930                     first_elem_op = o;
12931                 top_op = o;
12932                 if (is_deref) {
12933                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
12934                     o = o->op_next;
12935                 }
12936                 else {
12937                     is_last = TRUE;
12938                     action |= MDEREF_FLAG_last;
12939                 }
12940             }
12941             else {
12942                 /* at this point we have something that started
12943                  * promisingly enough (with rv2av or whatever), but failed
12944                  * to find a simple index followed by an
12945                  * aelem/helem/exists/delete. If this is the first action,
12946                  * give up; but if we've already seen at least one
12947                  * aelem/helem, then keep them and add a new action with
12948                  * MDEREF_INDEX_none, which causes it to do the vivify
12949                  * from the end of the previous lookup, and do the deref,
12950                  * but stop at that point. So $a[0][expr] will do one
12951                  * av_fetch, vivify and deref, then continue executing at
12952                  * expr */
12953                 if (!action_count)
12954                     return;
12955                 is_last = TRUE;
12956                 index_skip = action_count;
12957                 action |= MDEREF_FLAG_last;
12958             }
12959
12960             if (pass)
12961                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
12962             action_ix++;
12963             action_count++;
12964             /* if there's no space for the next action, create a new slot
12965              * for it *before* we start adding args for that action */
12966             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
12967                 action_ptr = arg;
12968                 if (pass)
12969                     arg->uv = 0;
12970                 arg++;
12971                 action_ix = 0;
12972             }
12973         } /* while !is_last */
12974
12975         /* success! */
12976
12977         if (pass) {
12978             OP *mderef;
12979             OP *p, *q;
12980
12981             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
12982             if (index_skip == -1) {
12983                 mderef->op_flags = o->op_flags
12984                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
12985                 if (o->op_type == OP_EXISTS)
12986                     mderef->op_private = OPpMULTIDEREF_EXISTS;
12987                 else if (o->op_type == OP_DELETE)
12988                     mderef->op_private = OPpMULTIDEREF_DELETE;
12989                 else
12990                     mderef->op_private = o->op_private
12991                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
12992             }
12993             /* accumulate strictness from every level (although I don't think
12994              * they can actually vary) */
12995             mderef->op_private |= hints;
12996
12997             /* integrate the new multideref op into the optree and the
12998              * op_next chain.
12999              *
13000              * In general an op like aelem or helem has two child
13001              * sub-trees: the aggregate expression (a_expr) and the
13002              * index expression (i_expr):
13003              *
13004              *     aelem
13005              *       |
13006              *     a_expr - i_expr
13007              *
13008              * The a_expr returns an AV or HV, while the i-expr returns an
13009              * index. In general a multideref replaces most or all of a
13010              * multi-level tree, e.g.
13011              *
13012              *     exists
13013              *       |
13014              *     ex-aelem
13015              *       |
13016              *     rv2av  - i_expr1
13017              *       |
13018              *     helem
13019              *       |
13020              *     rv2hv  - i_expr2
13021              *       |
13022              *     aelem
13023              *       |
13024              *     a_expr - i_expr3
13025              *
13026              * With multideref, all the i_exprs will be simple vars or
13027              * constants, except that i_expr1 may be arbitrary in the case
13028              * of MDEREF_INDEX_none.
13029              *
13030              * The bottom-most a_expr will be either:
13031              *   1) a simple var (so padXv or gv+rv2Xv);
13032              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
13033              *      so a simple var with an extra rv2Xv;
13034              *   3) or an arbitrary expression.
13035              *
13036              * 'start', the first op in the execution chain, will point to
13037              *   1),2): the padXv or gv op;
13038              *   3):    the rv2Xv which forms the last op in the a_expr
13039              *          execution chain, and the top-most op in the a_expr
13040              *          subtree.
13041              *
13042              * For all cases, the 'start' node is no longer required,
13043              * but we can't free it since one or more external nodes
13044              * may point to it. E.g. consider
13045              *     $h{foo} = $a ? $b : $c
13046              * Here, both the op_next and op_other branches of the
13047              * cond_expr point to the gv[*h] of the hash expression, so
13048              * we can't free the 'start' op.
13049              *
13050              * For expr->[...], we need to save the subtree containing the
13051              * expression; for the other cases, we just need to save the
13052              * start node.
13053              * So in all cases, we null the start op and keep it around by
13054              * making it the child of the multideref op; for the expr->
13055              * case, the expr will be a subtree of the start node.
13056              *
13057              * So in the simple 1,2 case the  optree above changes to
13058              *
13059              *     ex-exists
13060              *       |
13061              *     multideref
13062              *       |
13063              *     ex-gv (or ex-padxv)
13064              *
13065              *  with the op_next chain being
13066              *
13067              *  -> ex-gv -> multideref -> op-following-ex-exists ->
13068              *
13069              *  In the 3 case, we have
13070              *
13071              *     ex-exists
13072              *       |
13073              *     multideref
13074              *       |
13075              *     ex-rv2xv
13076              *       |
13077              *    rest-of-a_expr
13078              *      subtree
13079              *
13080              *  and
13081              *
13082              *  -> rest-of-a_expr subtree ->
13083              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
13084              *
13085              *
13086              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
13087              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
13088              * multideref attached as the child, e.g.
13089              *
13090              *     exists
13091              *       |
13092              *     ex-aelem
13093              *       |
13094              *     ex-rv2av  - i_expr1
13095              *       |
13096              *     multideref
13097              *       |
13098              *     ex-whatever
13099              *
13100              */
13101
13102             /* if we free this op, don't free the pad entry */
13103             if (reset_start_targ)
13104                 start->op_targ = 0;
13105
13106
13107             /* Cut the bit we need to save out of the tree and attach to
13108              * the multideref op, then free the rest of the tree */
13109
13110             /* find parent of node to be detached (for use by splice) */
13111             p = first_elem_op;
13112             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
13113                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
13114             {
13115                 /* there is an arbitrary expression preceding us, e.g.
13116                  * expr->[..]? so we need to save the 'expr' subtree */
13117                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
13118                     p = cUNOPx(p)->op_first;
13119                 ASSUME(   start->op_type == OP_RV2AV
13120                        || start->op_type == OP_RV2HV);
13121             }
13122             else {
13123                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
13124                  * above for exists/delete. */
13125                 while (   (p->op_flags & OPf_KIDS)
13126                        && cUNOPx(p)->op_first != start
13127                 )
13128                     p = cUNOPx(p)->op_first;
13129             }
13130             ASSUME(cUNOPx(p)->op_first == start);
13131
13132             /* detach from main tree, and re-attach under the multideref */
13133             op_sibling_splice(mderef, NULL, 0,
13134                     op_sibling_splice(p, NULL, 1, NULL));
13135             op_null(start);
13136
13137             start->op_next = mderef;
13138
13139             mderef->op_next = index_skip == -1 ? o->op_next : o;
13140
13141             /* excise and free the original tree, and replace with
13142              * the multideref op */
13143             p = op_sibling_splice(top_op, NULL, -1, mderef);
13144             while (p) {
13145                 q = OpSIBLING(p);
13146                 op_free(p);
13147                 p = q;
13148             }
13149             op_null(top_op);
13150         }
13151         else {
13152             Size_t size = arg - arg_buf;
13153
13154             if (maybe_aelemfast && action_count == 1)
13155                 return;
13156
13157             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
13158                                 sizeof(UNOP_AUX_item) * (size + 1));
13159             /* for dumping etc: store the length in a hidden first slot;
13160              * we set the op_aux pointer to the second slot */
13161             arg_buf->uv = size;
13162             arg_buf++;
13163         }
13164     } /* for (pass = ...) */
13165 }
13166
13167
13168
13169 /* mechanism for deferring recursion in rpeep() */
13170
13171 #define MAX_DEFERRED 4
13172
13173 #define DEFER(o) \
13174   STMT_START { \
13175     if (defer_ix == (MAX_DEFERRED-1)) { \
13176         OP **defer = defer_queue[defer_base]; \
13177         CALL_RPEEP(*defer); \
13178         S_prune_chain_head(defer); \
13179         defer_base = (defer_base + 1) % MAX_DEFERRED; \
13180         defer_ix--; \
13181     } \
13182     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
13183   } STMT_END
13184
13185 #define IS_AND_OP(o)   (o->op_type == OP_AND)
13186 #define IS_OR_OP(o)    (o->op_type == OP_OR)
13187
13188
13189 /* A peephole optimizer.  We visit the ops in the order they're to execute.
13190  * See the comments at the top of this file for more details about when
13191  * peep() is called */
13192
13193 void
13194 Perl_rpeep(pTHX_ OP *o)
13195 {
13196     dVAR;
13197     OP* oldop = NULL;
13198     OP* oldoldop = NULL;
13199     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
13200     int defer_base = 0;
13201     int defer_ix = -1;
13202     OP *fop;
13203     OP *sop;
13204
13205     if (!o || o->op_opt)
13206         return;
13207     ENTER;
13208     SAVEOP();
13209     SAVEVPTR(PL_curcop);
13210     for (;; o = o->op_next) {
13211         if (o && o->op_opt)
13212             o = NULL;
13213         if (!o) {
13214             while (defer_ix >= 0) {
13215                 OP **defer =
13216                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
13217                 CALL_RPEEP(*defer);
13218                 S_prune_chain_head(defer);
13219             }
13220             break;
13221         }
13222
13223       redo:
13224
13225         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
13226         assert(!oldoldop || oldoldop->op_next == oldop);
13227         assert(!oldop    || oldop->op_next    == o);
13228
13229         /* By default, this op has now been optimised. A couple of cases below
13230            clear this again.  */
13231         o->op_opt = 1;
13232         PL_op = o;
13233
13234         /* look for a series of 1 or more aggregate derefs, e.g.
13235          *   $a[1]{foo}[$i]{$k}
13236          * and replace with a single OP_MULTIDEREF op.
13237          * Each index must be either a const, or a simple variable,
13238          *
13239          * First, look for likely combinations of starting ops,
13240          * corresponding to (global and lexical variants of)
13241          *     $a[...]   $h{...}
13242          *     $r->[...] $r->{...}
13243          *     (preceding expression)->[...]
13244          *     (preceding expression)->{...}
13245          * and if so, call maybe_multideref() to do a full inspection
13246          * of the op chain and if appropriate, replace with an
13247          * OP_MULTIDEREF
13248          */
13249         {
13250             UV action;
13251             OP *o2 = o;
13252             U8 hints = 0;
13253
13254             switch (o2->op_type) {
13255             case OP_GV:
13256                 /* $pkg[..]   :   gv[*pkg]
13257                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
13258
13259                 /* Fail if there are new op flag combinations that we're
13260                  * not aware of, rather than:
13261                  *  * silently failing to optimise, or
13262                  *  * silently optimising the flag away.
13263                  * If this ASSUME starts failing, examine what new flag
13264                  * has been added to the op, and decide whether the
13265                  * optimisation should still occur with that flag, then
13266                  * update the code accordingly. This applies to all the
13267                  * other ASSUMEs in the block of code too.
13268                  */
13269                 ASSUME(!(o2->op_flags &
13270                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
13271                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
13272
13273                 o2 = o2->op_next;
13274
13275                 if (o2->op_type == OP_RV2AV) {
13276                     action = MDEREF_AV_gvav_aelem;
13277                     goto do_deref;
13278                 }
13279
13280                 if (o2->op_type == OP_RV2HV) {
13281                     action = MDEREF_HV_gvhv_helem;
13282                     goto do_deref;
13283                 }
13284
13285                 if (o2->op_type != OP_RV2SV)
13286                     break;
13287
13288                 /* at this point we've seen gv,rv2sv, so the only valid
13289                  * construct left is $pkg->[] or $pkg->{} */
13290
13291                 ASSUME(!(o2->op_flags & OPf_STACKED));
13292                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13293                             != (OPf_WANT_SCALAR|OPf_MOD))
13294                     break;
13295
13296                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
13297                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
13298                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
13299                     break;
13300                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
13301                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
13302                     break;
13303
13304                 o2 = o2->op_next;
13305                 if (o2->op_type == OP_RV2AV) {
13306                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
13307                     goto do_deref;
13308                 }
13309                 if (o2->op_type == OP_RV2HV) {
13310                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
13311                     goto do_deref;
13312                 }
13313                 break;
13314
13315             case OP_PADSV:
13316                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
13317
13318                 ASSUME(!(o2->op_flags &
13319                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
13320                 if ((o2->op_flags &
13321                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13322                      != (OPf_WANT_SCALAR|OPf_MOD))
13323                     break;
13324
13325                 ASSUME(!(o2->op_private &
13326                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
13327                 /* skip if state or intro, or not a deref */
13328                 if (      o2->op_private != OPpDEREF_AV
13329                        && o2->op_private != OPpDEREF_HV)
13330                     break;
13331
13332                 o2 = o2->op_next;
13333                 if (o2->op_type == OP_RV2AV) {
13334                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
13335                     goto do_deref;
13336                 }
13337                 if (o2->op_type == OP_RV2HV) {
13338                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
13339                     goto do_deref;
13340                 }
13341                 break;
13342
13343             case OP_PADAV:
13344             case OP_PADHV:
13345                 /*    $lex[..]:  padav[@lex:1,2] sR *
13346                  * or $lex{..}:  padhv[%lex:1,2] sR */
13347                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
13348                                             OPf_REF|OPf_SPECIAL)));
13349                 if ((o2->op_flags &
13350                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13351                      != (OPf_WANT_SCALAR|OPf_REF))
13352                     break;
13353                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
13354                     break;
13355                 /* OPf_PARENS isn't currently used in this case;
13356                  * if that changes, let us know! */
13357                 ASSUME(!(o2->op_flags & OPf_PARENS));
13358
13359                 /* at this point, we wouldn't expect any of the remaining
13360                  * possible private flags:
13361                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
13362                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
13363                  *
13364                  * OPpSLICEWARNING shouldn't affect runtime
13365                  */
13366                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
13367
13368                 action = o2->op_type == OP_PADAV
13369                             ? MDEREF_AV_padav_aelem
13370                             : MDEREF_HV_padhv_helem;
13371                 o2 = o2->op_next;
13372                 S_maybe_multideref(aTHX_ o, o2, action, 0);
13373                 break;
13374
13375
13376             case OP_RV2AV:
13377             case OP_RV2HV:
13378                 action = o2->op_type == OP_RV2AV
13379                             ? MDEREF_AV_pop_rv2av_aelem
13380                             : MDEREF_HV_pop_rv2hv_helem;
13381                 /* FALLTHROUGH */
13382             do_deref:
13383                 /* (expr)->[...]:  rv2av sKR/1;
13384                  * (expr)->{...}:  rv2hv sKR/1; */
13385
13386                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
13387
13388                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
13389                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
13390                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
13391                     break;
13392
13393                 /* at this point, we wouldn't expect any of these
13394                  * possible private flags:
13395                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
13396                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
13397                  */
13398                 ASSUME(!(o2->op_private &
13399                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
13400                      |OPpOUR_INTRO)));
13401                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
13402
13403                 o2 = o2->op_next;
13404
13405                 S_maybe_multideref(aTHX_ o, o2, action, hints);
13406                 break;
13407
13408             default:
13409                 break;
13410             }
13411         }
13412
13413
13414         switch (o->op_type) {
13415         case OP_DBSTATE:
13416             PL_curcop = ((COP*)o);              /* for warnings */
13417             break;
13418         case OP_NEXTSTATE:
13419             PL_curcop = ((COP*)o);              /* for warnings */
13420
13421             /* Optimise a "return ..." at the end of a sub to just be "...".
13422              * This saves 2 ops. Before:
13423              * 1  <;> nextstate(main 1 -e:1) v ->2
13424              * 4  <@> return K ->5
13425              * 2    <0> pushmark s ->3
13426              * -    <1> ex-rv2sv sK/1 ->4
13427              * 3      <#> gvsv[*cat] s ->4
13428              *
13429              * After:
13430              * -  <@> return K ->-
13431              * -    <0> pushmark s ->2
13432              * -    <1> ex-rv2sv sK/1 ->-
13433              * 2      <$> gvsv(*cat) s ->3
13434              */
13435             {
13436                 OP *next = o->op_next;
13437                 OP *sibling = OpSIBLING(o);
13438                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
13439                     && OP_TYPE_IS(sibling, OP_RETURN)
13440                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
13441                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
13442                        ||OP_TYPE_IS(sibling->op_next->op_next,
13443                                     OP_LEAVESUBLV))
13444                     && cUNOPx(sibling)->op_first == next
13445                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
13446                     && next->op_next
13447                 ) {
13448                     /* Look through the PUSHMARK's siblings for one that
13449                      * points to the RETURN */
13450                     OP *top = OpSIBLING(next);
13451                     while (top && top->op_next) {
13452                         if (top->op_next == sibling) {
13453                             top->op_next = sibling->op_next;
13454                             o->op_next = next->op_next;
13455                             break;
13456                         }
13457                         top = OpSIBLING(top);
13458                     }
13459                 }
13460             }
13461
13462             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
13463              *
13464              * This latter form is then suitable for conversion into padrange
13465              * later on. Convert:
13466              *
13467              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
13468              *
13469              * into:
13470              *
13471              *   nextstate1 ->     listop     -> nextstate3
13472              *                 /            \
13473              *         pushmark -> padop1 -> padop2
13474              */
13475             if (o->op_next && (
13476                     o->op_next->op_type == OP_PADSV
13477                  || o->op_next->op_type == OP_PADAV
13478                  || o->op_next->op_type == OP_PADHV
13479                 )
13480                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
13481                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
13482                 && o->op_next->op_next->op_next && (
13483                     o->op_next->op_next->op_next->op_type == OP_PADSV
13484                  || o->op_next->op_next->op_next->op_type == OP_PADAV
13485                  || o->op_next->op_next->op_next->op_type == OP_PADHV
13486                 )
13487                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
13488                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
13489                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
13490                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
13491             ) {
13492                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
13493
13494                 pad1 =    o->op_next;
13495                 ns2  = pad1->op_next;
13496                 pad2 =  ns2->op_next;
13497                 ns3  = pad2->op_next;
13498
13499                 /* we assume here that the op_next chain is the same as
13500                  * the op_sibling chain */
13501                 assert(OpSIBLING(o)    == pad1);
13502                 assert(OpSIBLING(pad1) == ns2);
13503                 assert(OpSIBLING(ns2)  == pad2);
13504                 assert(OpSIBLING(pad2) == ns3);
13505
13506                 /* excise and delete ns2 */
13507                 op_sibling_splice(NULL, pad1, 1, NULL);
13508                 op_free(ns2);
13509
13510                 /* excise pad1 and pad2 */
13511                 op_sibling_splice(NULL, o, 2, NULL);
13512
13513                 /* create new listop, with children consisting of:
13514                  * a new pushmark, pad1, pad2. */
13515                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
13516                 newop->op_flags |= OPf_PARENS;
13517                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13518
13519                 /* insert newop between o and ns3 */
13520                 op_sibling_splice(NULL, o, 0, newop);
13521
13522                 /*fixup op_next chain */
13523                 newpm = cUNOPx(newop)->op_first; /* pushmark */
13524                 o    ->op_next = newpm;
13525                 newpm->op_next = pad1;
13526                 pad1 ->op_next = pad2;
13527                 pad2 ->op_next = newop; /* listop */
13528                 newop->op_next = ns3;
13529
13530                 /* Ensure pushmark has this flag if padops do */
13531                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
13532                     newpm->op_flags |= OPf_MOD;
13533                 }
13534
13535                 break;
13536             }
13537
13538             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
13539                to carry two labels. For now, take the easier option, and skip
13540                this optimisation if the first NEXTSTATE has a label.  */
13541             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
13542                 OP *nextop = o->op_next;
13543                 while (nextop && nextop->op_type == OP_NULL)
13544                     nextop = nextop->op_next;
13545
13546                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
13547                     op_null(o);
13548                     if (oldop)
13549                         oldop->op_next = nextop;
13550                     o = nextop;
13551                     /* Skip (old)oldop assignment since the current oldop's
13552                        op_next already points to the next op.  */
13553                     goto redo;
13554                 }
13555             }
13556             break;
13557
13558         case OP_CONCAT:
13559             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
13560                 if (o->op_next->op_private & OPpTARGET_MY) {
13561                     if (o->op_flags & OPf_STACKED) /* chained concats */
13562                         break; /* ignore_optimization */
13563                     else {
13564                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
13565                         o->op_targ = o->op_next->op_targ;
13566                         o->op_next->op_targ = 0;
13567                         o->op_private |= OPpTARGET_MY;
13568                     }
13569                 }
13570                 op_null(o->op_next);
13571             }
13572             break;
13573         case OP_STUB:
13574             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
13575                 break; /* Scalar stub must produce undef.  List stub is noop */
13576             }
13577             goto nothin;
13578         case OP_NULL:
13579             if (o->op_targ == OP_NEXTSTATE
13580                 || o->op_targ == OP_DBSTATE)
13581             {
13582                 PL_curcop = ((COP*)o);
13583             }
13584             /* XXX: We avoid setting op_seq here to prevent later calls
13585                to rpeep() from mistakenly concluding that optimisation
13586                has already occurred. This doesn't fix the real problem,
13587                though (See 20010220.007). AMS 20010719 */
13588             /* op_seq functionality is now replaced by op_opt */
13589             o->op_opt = 0;
13590             /* FALLTHROUGH */
13591         case OP_SCALAR:
13592         case OP_LINESEQ:
13593         case OP_SCOPE:
13594         nothin:
13595             if (oldop) {
13596                 oldop->op_next = o->op_next;
13597                 o->op_opt = 0;
13598                 continue;
13599             }
13600             break;
13601
13602         case OP_PUSHMARK:
13603
13604             /* Given
13605                  5 repeat/DOLIST
13606                  3   ex-list
13607                  1     pushmark
13608                  2     scalar or const
13609                  4   const[0]
13610                convert repeat into a stub with no kids.
13611              */
13612             if (o->op_next->op_type == OP_CONST
13613              || (  o->op_next->op_type == OP_PADSV
13614                 && !(o->op_next->op_private & OPpLVAL_INTRO))
13615              || (  o->op_next->op_type == OP_GV
13616                 && o->op_next->op_next->op_type == OP_RV2SV
13617                 && !(o->op_next->op_next->op_private
13618                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
13619             {
13620                 const OP *kid = o->op_next->op_next;
13621                 if (o->op_next->op_type == OP_GV)
13622                    kid = kid->op_next;
13623                 /* kid is now the ex-list.  */
13624                 if (kid->op_type == OP_NULL
13625                  && (kid = kid->op_next)->op_type == OP_CONST
13626                     /* kid is now the repeat count.  */
13627                  && kid->op_next->op_type == OP_REPEAT
13628                  && kid->op_next->op_private & OPpREPEAT_DOLIST
13629                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
13630                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0)
13631                 {
13632                     o = kid->op_next; /* repeat */
13633                     assert(oldop);
13634                     oldop->op_next = o;
13635                     op_free(cBINOPo->op_first);
13636                     op_free(cBINOPo->op_last );
13637                     o->op_flags &=~ OPf_KIDS;
13638                     /* stub is a baseop; repeat is a binop */
13639                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
13640                     OpTYPE_set(o, OP_STUB);
13641                     o->op_private = 0;
13642                     break;
13643                 }
13644             }
13645
13646             /* Convert a series of PAD ops for my vars plus support into a
13647              * single padrange op. Basically
13648              *
13649              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
13650              *
13651              * becomes, depending on circumstances, one of
13652              *
13653              *    padrange  ----------------------------------> (list) -> rest
13654              *    padrange  --------------------------------------------> rest
13655              *
13656              * where all the pad indexes are sequential and of the same type
13657              * (INTRO or not).
13658              * We convert the pushmark into a padrange op, then skip
13659              * any other pad ops, and possibly some trailing ops.
13660              * Note that we don't null() the skipped ops, to make it
13661              * easier for Deparse to undo this optimisation (and none of
13662              * the skipped ops are holding any resourses). It also makes
13663              * it easier for find_uninit_var(), as it can just ignore
13664              * padrange, and examine the original pad ops.
13665              */
13666         {
13667             OP *p;
13668             OP *followop = NULL; /* the op that will follow the padrange op */
13669             U8 count = 0;
13670             U8 intro = 0;
13671             PADOFFSET base = 0; /* init only to stop compiler whining */
13672             bool gvoid = 0;     /* init only to stop compiler whining */
13673             bool defav = 0;  /* seen (...) = @_ */
13674             bool reuse = 0;  /* reuse an existing padrange op */
13675
13676             /* look for a pushmark -> gv[_] -> rv2av */
13677
13678             {
13679                 OP *rv2av, *q;
13680                 p = o->op_next;
13681                 if (   p->op_type == OP_GV
13682                     && cGVOPx_gv(p) == PL_defgv
13683                     && (rv2av = p->op_next)
13684                     && rv2av->op_type == OP_RV2AV
13685                     && !(rv2av->op_flags & OPf_REF)
13686                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
13687                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
13688                 ) {
13689                     q = rv2av->op_next;
13690                     if (q->op_type == OP_NULL)
13691                         q = q->op_next;
13692                     if (q->op_type == OP_PUSHMARK) {
13693                         defav = 1;
13694                         p = q;
13695                     }
13696                 }
13697             }
13698             if (!defav) {
13699                 p = o;
13700             }
13701
13702             /* scan for PAD ops */
13703
13704             for (p = p->op_next; p; p = p->op_next) {
13705                 if (p->op_type == OP_NULL)
13706                     continue;
13707
13708                 if ((     p->op_type != OP_PADSV
13709                        && p->op_type != OP_PADAV
13710                        && p->op_type != OP_PADHV
13711                     )
13712                       /* any private flag other than INTRO? e.g. STATE */
13713                    || (p->op_private & ~OPpLVAL_INTRO)
13714                 )
13715                     break;
13716
13717                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
13718                  * instead */
13719                 if (   p->op_type == OP_PADAV
13720                     && p->op_next
13721                     && p->op_next->op_type == OP_CONST
13722                     && p->op_next->op_next
13723                     && p->op_next->op_next->op_type == OP_AELEM
13724                 )
13725                     break;
13726
13727                 /* for 1st padop, note what type it is and the range
13728                  * start; for the others, check that it's the same type
13729                  * and that the targs are contiguous */
13730                 if (count == 0) {
13731                     intro = (p->op_private & OPpLVAL_INTRO);
13732                     base = p->op_targ;
13733                     gvoid = OP_GIMME(p,0) == G_VOID;
13734                 }
13735                 else {
13736                     if ((p->op_private & OPpLVAL_INTRO) != intro)
13737                         break;
13738                     /* Note that you'd normally  expect targs to be
13739                      * contiguous in my($a,$b,$c), but that's not the case
13740                      * when external modules start doing things, e.g.
13741                      * Function::Parameters */
13742                     if (p->op_targ != base + count)
13743                         break;
13744                     assert(p->op_targ == base + count);
13745                     /* Either all the padops or none of the padops should
13746                        be in void context.  Since we only do the optimisa-
13747                        tion for av/hv when the aggregate itself is pushed
13748                        on to the stack (one item), there is no need to dis-
13749                        tinguish list from scalar context.  */
13750                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
13751                         break;
13752                 }
13753
13754                 /* for AV, HV, only when we're not flattening */
13755                 if (   p->op_type != OP_PADSV
13756                     && !gvoid
13757                     && !(p->op_flags & OPf_REF)
13758                 )
13759                     break;
13760
13761                 if (count >= OPpPADRANGE_COUNTMASK)
13762                     break;
13763
13764                 /* there's a biggest base we can fit into a
13765                  * SAVEt_CLEARPADRANGE in pp_padrange.
13766                  * (The sizeof() stuff will be constant-folded, and is
13767                  * intended to avoid getting "comparison is always false"
13768                  * compiler warnings. See the comments above
13769                  * MEM_WRAP_CHECK for more explanation on why we do this
13770                  * in a weird way to avoid compiler warnings.)
13771                  */
13772                 if (   intro
13773                     && (8*sizeof(base) >
13774                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
13775                         ? base
13776                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
13777                         ) >
13778                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
13779                 )
13780                     break;
13781
13782                 /* Success! We've got another valid pad op to optimise away */
13783                 count++;
13784                 followop = p->op_next;
13785             }
13786
13787             if (count < 1 || (count == 1 && !defav))
13788                 break;
13789
13790             /* pp_padrange in specifically compile-time void context
13791              * skips pushing a mark and lexicals; in all other contexts
13792              * (including unknown till runtime) it pushes a mark and the
13793              * lexicals. We must be very careful then, that the ops we
13794              * optimise away would have exactly the same effect as the
13795              * padrange.
13796              * In particular in void context, we can only optimise to
13797              * a padrange if we see the complete sequence
13798              *     pushmark, pad*v, ...., list
13799              * which has the net effect of leaving the markstack as it
13800              * was.  Not pushing onto the stack (whereas padsv does touch
13801              * the stack) makes no difference in void context.
13802              */
13803             assert(followop);
13804             if (gvoid) {
13805                 if (followop->op_type == OP_LIST
13806                         && OP_GIMME(followop,0) == G_VOID
13807                    )
13808                 {
13809                     followop = followop->op_next; /* skip OP_LIST */
13810
13811                     /* consolidate two successive my(...);'s */
13812
13813                     if (   oldoldop
13814                         && oldoldop->op_type == OP_PADRANGE
13815                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
13816                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
13817                         && !(oldoldop->op_flags & OPf_SPECIAL)
13818                     ) {
13819                         U8 old_count;
13820                         assert(oldoldop->op_next == oldop);
13821                         assert(   oldop->op_type == OP_NEXTSTATE
13822                                || oldop->op_type == OP_DBSTATE);
13823                         assert(oldop->op_next == o);
13824
13825                         old_count
13826                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
13827
13828                        /* Do not assume pad offsets for $c and $d are con-
13829                           tiguous in
13830                             my ($a,$b,$c);
13831                             my ($d,$e,$f);
13832                         */
13833                         if (  oldoldop->op_targ + old_count == base
13834                            && old_count < OPpPADRANGE_COUNTMASK - count) {
13835                             base = oldoldop->op_targ;
13836                             count += old_count;
13837                             reuse = 1;
13838                         }
13839                     }
13840
13841                     /* if there's any immediately following singleton
13842                      * my var's; then swallow them and the associated
13843                      * nextstates; i.e.
13844                      *    my ($a,$b); my $c; my $d;
13845                      * is treated as
13846                      *    my ($a,$b,$c,$d);
13847                      */
13848
13849                     while (    ((p = followop->op_next))
13850                             && (  p->op_type == OP_PADSV
13851                                || p->op_type == OP_PADAV
13852                                || p->op_type == OP_PADHV)
13853                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
13854                             && (p->op_private & OPpLVAL_INTRO) == intro
13855                             && !(p->op_private & ~OPpLVAL_INTRO)
13856                             && p->op_next
13857                             && (   p->op_next->op_type == OP_NEXTSTATE
13858                                 || p->op_next->op_type == OP_DBSTATE)
13859                             && count < OPpPADRANGE_COUNTMASK
13860                             && base + count == p->op_targ
13861                     ) {
13862                         count++;
13863                         followop = p->op_next;
13864                     }
13865                 }
13866                 else
13867                     break;
13868             }
13869
13870             if (reuse) {
13871                 assert(oldoldop->op_type == OP_PADRANGE);
13872                 oldoldop->op_next = followop;
13873                 oldoldop->op_private = (intro | count);
13874                 o = oldoldop;
13875                 oldop = NULL;
13876                 oldoldop = NULL;
13877             }
13878             else {
13879                 /* Convert the pushmark into a padrange.
13880                  * To make Deparse easier, we guarantee that a padrange was
13881                  * *always* formerly a pushmark */
13882                 assert(o->op_type == OP_PUSHMARK);
13883                 o->op_next = followop;
13884                 OpTYPE_set(o, OP_PADRANGE);
13885                 o->op_targ = base;
13886                 /* bit 7: INTRO; bit 6..0: count */
13887                 o->op_private = (intro | count);
13888                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
13889                               | gvoid * OPf_WANT_VOID
13890                               | (defav ? OPf_SPECIAL : 0));
13891             }
13892             break;
13893         }
13894
13895         case OP_PADAV:
13896         case OP_PADSV:
13897         case OP_PADHV:
13898         /* Skip over state($x) in void context.  */
13899         if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
13900          && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
13901         {
13902             oldop->op_next = o->op_next;
13903             goto redo_nextstate;
13904         }
13905         if (o->op_type != OP_PADAV)
13906             break;
13907         /* FALLTHROUGH */
13908         case OP_GV:
13909             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
13910                 OP* const pop = (o->op_type == OP_PADAV) ?
13911                             o->op_next : o->op_next->op_next;
13912                 IV i;
13913                 if (pop && pop->op_type == OP_CONST &&
13914                     ((PL_op = pop->op_next)) &&
13915                     pop->op_next->op_type == OP_AELEM &&
13916                     !(pop->op_next->op_private &
13917                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
13918                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
13919                 {
13920                     GV *gv;
13921                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
13922                         no_bareword_allowed(pop);
13923                     if (o->op_type == OP_GV)
13924                         op_null(o->op_next);
13925                     op_null(pop->op_next);
13926                     op_null(pop);
13927                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
13928                     o->op_next = pop->op_next->op_next;
13929                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
13930                     o->op_private = (U8)i;
13931                     if (o->op_type == OP_GV) {
13932                         gv = cGVOPo_gv;
13933                         GvAVn(gv);
13934                         o->op_type = OP_AELEMFAST;
13935                     }
13936                     else
13937                         o->op_type = OP_AELEMFAST_LEX;
13938                 }
13939                 if (o->op_type != OP_GV)
13940                     break;
13941             }
13942
13943             /* Remove $foo from the op_next chain in void context.  */
13944             if (oldop
13945              && (  o->op_next->op_type == OP_RV2SV
13946                 || o->op_next->op_type == OP_RV2AV
13947                 || o->op_next->op_type == OP_RV2HV  )
13948              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13949              && !(o->op_next->op_private & OPpLVAL_INTRO))
13950             {
13951                 oldop->op_next = o->op_next->op_next;
13952                 /* Reprocess the previous op if it is a nextstate, to
13953                    allow double-nextstate optimisation.  */
13954               redo_nextstate:
13955                 if (oldop->op_type == OP_NEXTSTATE) {
13956                     oldop->op_opt = 0;
13957                     o = oldop;
13958                     oldop = oldoldop;
13959                     oldoldop = NULL;
13960                     goto redo;
13961                 }
13962                 o = oldop->op_next;
13963                 goto redo;
13964             }
13965             else if (o->op_next->op_type == OP_RV2SV) {
13966                 if (!(o->op_next->op_private & OPpDEREF)) {
13967                     op_null(o->op_next);
13968                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
13969                                                                | OPpOUR_INTRO);
13970                     o->op_next = o->op_next->op_next;
13971                     OpTYPE_set(o, OP_GVSV);
13972                 }
13973             }
13974             else if (o->op_next->op_type == OP_READLINE
13975                     && o->op_next->op_next->op_type == OP_CONCAT
13976                     && (o->op_next->op_next->op_flags & OPf_STACKED))
13977             {
13978                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
13979                 OpTYPE_set(o, OP_RCATLINE);
13980                 o->op_flags |= OPf_STACKED;
13981                 op_null(o->op_next->op_next);
13982                 op_null(o->op_next);
13983             }
13984
13985             break;
13986         
13987 #define HV_OR_SCALARHV(op)                                   \
13988     (  (op)->op_type == OP_PADHV || (op)->op_type == OP_RV2HV \
13989        ? (op)                                                  \
13990        : (op)->op_type == OP_SCALAR && (op)->op_flags & OPf_KIDS \
13991        && (  cUNOPx(op)->op_first->op_type == OP_PADHV          \
13992           || cUNOPx(op)->op_first->op_type == OP_RV2HV)          \
13993          ? cUNOPx(op)->op_first                                   \
13994          : NULL)
13995
13996         case OP_NOT:
13997             if ((fop = HV_OR_SCALARHV(cUNOP->op_first)))
13998                 fop->op_private |= OPpTRUEBOOL;
13999             break;
14000
14001         case OP_AND:
14002         case OP_OR:
14003         case OP_DOR:
14004             fop = cLOGOP->op_first;
14005             sop = OpSIBLING(fop);
14006             while (cLOGOP->op_other->op_type == OP_NULL)
14007                 cLOGOP->op_other = cLOGOP->op_other->op_next;
14008             while (o->op_next && (   o->op_type == o->op_next->op_type
14009                                   || o->op_next->op_type == OP_NULL))
14010                 o->op_next = o->op_next->op_next;
14011
14012             /* If we're an OR and our next is an AND in void context, we'll
14013                follow its op_other on short circuit, same for reverse.
14014                We can't do this with OP_DOR since if it's true, its return
14015                value is the underlying value which must be evaluated
14016                by the next op. */
14017             if (o->op_next &&
14018                 (
14019                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
14020                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
14021                 )
14022                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
14023             ) {
14024                 o->op_next = ((LOGOP*)o->op_next)->op_other;
14025             }
14026             DEFER(cLOGOP->op_other);
14027           
14028             o->op_opt = 1;
14029             fop = HV_OR_SCALARHV(fop);
14030             if (sop) sop = HV_OR_SCALARHV(sop);
14031             if (fop || sop
14032             ){  
14033                 OP * nop = o;
14034                 OP * lop = o;
14035                 if (!((nop->op_flags & OPf_WANT) == OPf_WANT_VOID)) {
14036                     while (nop && nop->op_next) {
14037                         switch (nop->op_next->op_type) {
14038                             case OP_NOT:
14039                             case OP_AND:
14040                             case OP_OR:
14041                             case OP_DOR:
14042                                 lop = nop = nop->op_next;
14043                                 break;
14044                             case OP_NULL:
14045                                 nop = nop->op_next;
14046                                 break;
14047                             default:
14048                                 nop = NULL;
14049                                 break;
14050                         }
14051                     }            
14052                 }
14053                 if (fop) {
14054                     if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
14055                       || o->op_type == OP_AND  )
14056                         fop->op_private |= OPpTRUEBOOL;
14057                     else if (!(lop->op_flags & OPf_WANT))
14058                         fop->op_private |= OPpMAYBE_TRUEBOOL;
14059                 }
14060                 if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
14061                    && sop)
14062                     sop->op_private |= OPpTRUEBOOL;
14063             }                  
14064             
14065             
14066             break;
14067         
14068         case OP_COND_EXPR:
14069             if ((fop = HV_OR_SCALARHV(cLOGOP->op_first)))
14070                 fop->op_private |= OPpTRUEBOOL;
14071 #undef HV_OR_SCALARHV
14072             /* GERONIMO! */ /* FALLTHROUGH */
14073
14074         case OP_MAPWHILE:
14075         case OP_GREPWHILE:
14076         case OP_ANDASSIGN:
14077         case OP_ORASSIGN:
14078         case OP_DORASSIGN:
14079         case OP_RANGE:
14080         case OP_ONCE:
14081             while (cLOGOP->op_other->op_type == OP_NULL)
14082                 cLOGOP->op_other = cLOGOP->op_other->op_next;
14083             DEFER(cLOGOP->op_other);
14084             break;
14085
14086         case OP_ENTERLOOP:
14087         case OP_ENTERITER:
14088             while (cLOOP->op_redoop->op_type == OP_NULL)
14089                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
14090             while (cLOOP->op_nextop->op_type == OP_NULL)
14091                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
14092             while (cLOOP->op_lastop->op_type == OP_NULL)
14093                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
14094             /* a while(1) loop doesn't have an op_next that escapes the
14095              * loop, so we have to explicitly follow the op_lastop to
14096              * process the rest of the code */
14097             DEFER(cLOOP->op_lastop);
14098             break;
14099
14100         case OP_ENTERTRY:
14101             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
14102             DEFER(cLOGOPo->op_other);
14103             break;
14104
14105         case OP_SUBST:
14106             assert(!(cPMOP->op_pmflags & PMf_ONCE));
14107             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
14108                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
14109                 cPMOP->op_pmstashstartu.op_pmreplstart
14110                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
14111             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
14112             break;
14113
14114         case OP_SORT: {
14115             OP *oright;
14116
14117             if (o->op_flags & OPf_SPECIAL) {
14118                 /* first arg is a code block */
14119                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
14120                 OP * kid          = cUNOPx(nullop)->op_first;
14121
14122                 assert(nullop->op_type == OP_NULL);
14123                 assert(kid->op_type == OP_SCOPE
14124                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
14125                 /* since OP_SORT doesn't have a handy op_other-style
14126                  * field that can point directly to the start of the code
14127                  * block, store it in the otherwise-unused op_next field
14128                  * of the top-level OP_NULL. This will be quicker at
14129                  * run-time, and it will also allow us to remove leading
14130                  * OP_NULLs by just messing with op_nexts without
14131                  * altering the basic op_first/op_sibling layout. */
14132                 kid = kLISTOP->op_first;
14133                 assert(
14134                       (kid->op_type == OP_NULL
14135                       && (  kid->op_targ == OP_NEXTSTATE
14136                          || kid->op_targ == OP_DBSTATE  ))
14137                     || kid->op_type == OP_STUB
14138                     || kid->op_type == OP_ENTER);
14139                 nullop->op_next = kLISTOP->op_next;
14140                 DEFER(nullop->op_next);
14141             }
14142
14143             /* check that RHS of sort is a single plain array */
14144             oright = cUNOPo->op_first;
14145             if (!oright || oright->op_type != OP_PUSHMARK)
14146                 break;
14147
14148             if (o->op_private & OPpSORT_INPLACE)
14149                 break;
14150
14151             /* reverse sort ... can be optimised.  */
14152             if (!OpHAS_SIBLING(cUNOPo)) {
14153                 /* Nothing follows us on the list. */
14154                 OP * const reverse = o->op_next;
14155
14156                 if (reverse->op_type == OP_REVERSE &&
14157                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
14158                     OP * const pushmark = cUNOPx(reverse)->op_first;
14159                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
14160                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
14161                         /* reverse -> pushmark -> sort */
14162                         o->op_private |= OPpSORT_REVERSE;
14163                         op_null(reverse);
14164                         pushmark->op_next = oright->op_next;
14165                         op_null(oright);
14166                     }
14167                 }
14168             }
14169
14170             break;
14171         }
14172
14173         case OP_REVERSE: {
14174             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
14175             OP *gvop = NULL;
14176             LISTOP *enter, *exlist;
14177
14178             if (o->op_private & OPpSORT_INPLACE)
14179                 break;
14180
14181             enter = (LISTOP *) o->op_next;
14182             if (!enter)
14183                 break;
14184             if (enter->op_type == OP_NULL) {
14185                 enter = (LISTOP *) enter->op_next;
14186                 if (!enter)
14187                     break;
14188             }
14189             /* for $a (...) will have OP_GV then OP_RV2GV here.
14190                for (...) just has an OP_GV.  */
14191             if (enter->op_type == OP_GV) {
14192                 gvop = (OP *) enter;
14193                 enter = (LISTOP *) enter->op_next;
14194                 if (!enter)
14195                     break;
14196                 if (enter->op_type == OP_RV2GV) {
14197                   enter = (LISTOP *) enter->op_next;
14198                   if (!enter)
14199                     break;
14200                 }
14201             }
14202
14203             if (enter->op_type != OP_ENTERITER)
14204                 break;
14205
14206             iter = enter->op_next;
14207             if (!iter || iter->op_type != OP_ITER)
14208                 break;
14209             
14210             expushmark = enter->op_first;
14211             if (!expushmark || expushmark->op_type != OP_NULL
14212                 || expushmark->op_targ != OP_PUSHMARK)
14213                 break;
14214
14215             exlist = (LISTOP *) OpSIBLING(expushmark);
14216             if (!exlist || exlist->op_type != OP_NULL
14217                 || exlist->op_targ != OP_LIST)
14218                 break;
14219
14220             if (exlist->op_last != o) {
14221                 /* Mmm. Was expecting to point back to this op.  */
14222                 break;
14223             }
14224             theirmark = exlist->op_first;
14225             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
14226                 break;
14227
14228             if (OpSIBLING(theirmark) != o) {
14229                 /* There's something between the mark and the reverse, eg
14230                    for (1, reverse (...))
14231                    so no go.  */
14232                 break;
14233             }
14234
14235             ourmark = ((LISTOP *)o)->op_first;
14236             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
14237                 break;
14238
14239             ourlast = ((LISTOP *)o)->op_last;
14240             if (!ourlast || ourlast->op_next != o)
14241                 break;
14242
14243             rv2av = OpSIBLING(ourmark);
14244             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
14245                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
14246                 /* We're just reversing a single array.  */
14247                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
14248                 enter->op_flags |= OPf_STACKED;
14249             }
14250
14251             /* We don't have control over who points to theirmark, so sacrifice
14252                ours.  */
14253             theirmark->op_next = ourmark->op_next;
14254             theirmark->op_flags = ourmark->op_flags;
14255             ourlast->op_next = gvop ? gvop : (OP *) enter;
14256             op_null(ourmark);
14257             op_null(o);
14258             enter->op_private |= OPpITER_REVERSED;
14259             iter->op_private |= OPpITER_REVERSED;
14260
14261             oldoldop = NULL;
14262             oldop    = ourlast;
14263             o        = oldop->op_next;
14264             goto redo;
14265             
14266             break;
14267         }
14268
14269         case OP_QR:
14270         case OP_MATCH:
14271             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
14272                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
14273             }
14274             break;
14275
14276         case OP_RUNCV:
14277             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
14278              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
14279             {
14280                 SV *sv;
14281                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
14282                 else {
14283                     sv = newRV((SV *)PL_compcv);
14284                     sv_rvweaken(sv);
14285                     SvREADONLY_on(sv);
14286                 }
14287                 OpTYPE_set(o, OP_CONST);
14288                 o->op_flags |= OPf_SPECIAL;
14289                 cSVOPo->op_sv = sv;
14290             }
14291             break;
14292
14293         case OP_SASSIGN:
14294             if (OP_GIMME(o,0) == G_VOID
14295              || (  o->op_next->op_type == OP_LINESEQ
14296                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
14297                    || (  o->op_next->op_next->op_type == OP_RETURN
14298                       && !CvLVALUE(PL_compcv)))))
14299             {
14300                 OP *right = cBINOP->op_first;
14301                 if (right) {
14302                     /*   sassign
14303                     *      RIGHT
14304                     *      substr
14305                     *         pushmark
14306                     *         arg1
14307                     *         arg2
14308                     *         ...
14309                     * becomes
14310                     *
14311                     *  ex-sassign
14312                     *     substr
14313                     *        pushmark
14314                     *        RIGHT
14315                     *        arg1
14316                     *        arg2
14317                     *        ...
14318                     */
14319                     OP *left = OpSIBLING(right);
14320                     if (left->op_type == OP_SUBSTR
14321                          && (left->op_private & 7) < 4) {
14322                         op_null(o);
14323                         /* cut out right */
14324                         op_sibling_splice(o, NULL, 1, NULL);
14325                         /* and insert it as second child of OP_SUBSTR */
14326                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
14327                                     right);
14328                         left->op_private |= OPpSUBSTR_REPL_FIRST;
14329                         left->op_flags =
14330                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
14331                     }
14332                 }
14333             }
14334             break;
14335
14336         case OP_AASSIGN: {
14337             int l, r, lr, lscalars, rscalars;
14338
14339             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
14340                Note that we do this now rather than in newASSIGNOP(),
14341                since only by now are aliased lexicals flagged as such
14342
14343                See the essay "Common vars in list assignment" above for
14344                the full details of the rationale behind all the conditions
14345                below.
14346
14347                PL_generation sorcery:
14348                To detect whether there are common vars, the global var
14349                PL_generation is incremented for each assign op we scan.
14350                Then we run through all the lexical variables on the LHS,
14351                of the assignment, setting a spare slot in each of them to
14352                PL_generation.  Then we scan the RHS, and if any lexicals
14353                already have that value, we know we've got commonality.
14354                Also, if the generation number is already set to
14355                PERL_INT_MAX, then the variable is involved in aliasing, so
14356                we also have potential commonality in that case.
14357              */
14358
14359             PL_generation++;
14360             /* scan LHS */
14361             lscalars = 0;
14362             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, 1, &lscalars);
14363             /* scan RHS */
14364             rscalars = 0;
14365             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, 1, &rscalars);
14366             lr = (l|r);
14367
14368
14369             /* After looking for things which are *always* safe, this main
14370              * if/else chain selects primarily based on the type of the
14371              * LHS, gradually working its way down from the more dangerous
14372              * to the more restrictive and thus safer cases */
14373
14374             if (   !l                      /* () = ....; */
14375                 || !r                      /* .... = (); */
14376                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
14377                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
14378                 || (lscalars < 2)          /* ($x, undef) = ... */
14379             ) {
14380                 NOOP; /* always safe */
14381             }
14382             else if (l & AAS_DANGEROUS) {
14383                 /* always dangerous */
14384                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
14385                 o->op_private |= OPpASSIGN_COMMON_AGG;
14386             }
14387             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
14388                 /* package vars are always dangerous - too many
14389                  * aliasing possibilities */
14390                 if (l & AAS_PKG_SCALAR)
14391                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
14392                 if (l & AAS_PKG_AGG)
14393                     o->op_private |= OPpASSIGN_COMMON_AGG;
14394             }
14395             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
14396                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
14397             {
14398                 /* LHS contains only lexicals and safe ops */
14399
14400                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
14401                     o->op_private |= OPpASSIGN_COMMON_AGG;
14402
14403                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
14404                     if (lr & AAS_LEX_SCALAR_COMM)
14405                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
14406                     else if (   !(l & AAS_LEX_SCALAR)
14407                              && (r & AAS_DEFAV))
14408                     {
14409                         /* falsely mark
14410                          *    my (...) = @_
14411                          * as scalar-safe for performance reasons.
14412                          * (it will still have been marked _AGG if necessary */
14413                         NOOP;
14414                     }
14415                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
14416                         o->op_private |= OPpASSIGN_COMMON_RC1;
14417                 }
14418             }
14419
14420             /* ... = ($x)
14421              * may have to handle aggregate on LHS, but we can't
14422              * have common scalars. */
14423             if (rscalars < 2)
14424                 o->op_private &=
14425                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
14426
14427             break;
14428         }
14429
14430         case OP_CUSTOM: {
14431             Perl_cpeep_t cpeep = 
14432                 XopENTRYCUSTOM(o, xop_peep);
14433             if (cpeep)
14434                 cpeep(aTHX_ o, oldop);
14435             break;
14436         }
14437             
14438         }
14439         /* did we just null the current op? If so, re-process it to handle
14440          * eliding "empty" ops from the chain */
14441         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
14442             o->op_opt = 0;
14443             o = oldop;
14444         }
14445         else {
14446             oldoldop = oldop;
14447             oldop = o;
14448         }
14449     }
14450     LEAVE;
14451 }
14452
14453 void
14454 Perl_peep(pTHX_ OP *o)
14455 {
14456     CALL_RPEEP(o);
14457 }
14458
14459 /*
14460 =head1 Custom Operators
14461
14462 =for apidoc Ao||custom_op_xop
14463 Return the XOP structure for a given custom op.  This macro should be
14464 considered internal to C<OP_NAME> and the other access macros: use them instead.
14465 This macro does call a function.  Prior
14466 to 5.19.6, this was implemented as a
14467 function.
14468
14469 =cut
14470 */
14471
14472 XOPRETANY
14473 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
14474 {
14475     SV *keysv;
14476     HE *he = NULL;
14477     XOP *xop;
14478
14479     static const XOP xop_null = { 0, 0, 0, 0, 0 };
14480
14481     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
14482     assert(o->op_type == OP_CUSTOM);
14483
14484     /* This is wrong. It assumes a function pointer can be cast to IV,
14485      * which isn't guaranteed, but this is what the old custom OP code
14486      * did. In principle it should be safer to Copy the bytes of the
14487      * pointer into a PV: since the new interface is hidden behind
14488      * functions, this can be changed later if necessary.  */
14489     /* Change custom_op_xop if this ever happens */
14490     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
14491
14492     if (PL_custom_ops)
14493         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14494
14495     /* assume noone will have just registered a desc */
14496     if (!he && PL_custom_op_names &&
14497         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
14498     ) {
14499         const char *pv;
14500         STRLEN l;
14501
14502         /* XXX does all this need to be shared mem? */
14503         Newxz(xop, 1, XOP);
14504         pv = SvPV(HeVAL(he), l);
14505         XopENTRY_set(xop, xop_name, savepvn(pv, l));
14506         if (PL_custom_op_descs &&
14507             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
14508         ) {
14509             pv = SvPV(HeVAL(he), l);
14510             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
14511         }
14512         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
14513     }
14514     else {
14515         if (!he)
14516             xop = (XOP *)&xop_null;
14517         else
14518             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
14519     }
14520     {
14521         XOPRETANY any;
14522         if(field == XOPe_xop_ptr) {
14523             any.xop_ptr = xop;
14524         } else {
14525             const U32 flags = XopFLAGS(xop);
14526             if(flags & field) {
14527                 switch(field) {
14528                 case XOPe_xop_name:
14529                     any.xop_name = xop->xop_name;
14530                     break;
14531                 case XOPe_xop_desc:
14532                     any.xop_desc = xop->xop_desc;
14533                     break;
14534                 case XOPe_xop_class:
14535                     any.xop_class = xop->xop_class;
14536                     break;
14537                 case XOPe_xop_peep:
14538                     any.xop_peep = xop->xop_peep;
14539                     break;
14540                 default:
14541                     NOT_REACHED; /* NOTREACHED */
14542                     break;
14543                 }
14544             } else {
14545                 switch(field) {
14546                 case XOPe_xop_name:
14547                     any.xop_name = XOPd_xop_name;
14548                     break;
14549                 case XOPe_xop_desc:
14550                     any.xop_desc = XOPd_xop_desc;
14551                     break;
14552                 case XOPe_xop_class:
14553                     any.xop_class = XOPd_xop_class;
14554                     break;
14555                 case XOPe_xop_peep:
14556                     any.xop_peep = XOPd_xop_peep;
14557                     break;
14558                 default:
14559                     NOT_REACHED; /* NOTREACHED */
14560                     break;
14561                 }
14562             }
14563         }
14564         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
14565          * op.c: In function 'Perl_custom_op_get_field':
14566          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
14567          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
14568          * expands to assert(0), which expands to ((0) ? (void)0 :
14569          * __assert(...)), and gcc doesn't know that __assert can never return. */
14570         return any;
14571     }
14572 }
14573
14574 /*
14575 =for apidoc Ao||custom_op_register
14576 Register a custom op.  See L<perlguts/"Custom Operators">.
14577
14578 =cut
14579 */
14580
14581 void
14582 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
14583 {
14584     SV *keysv;
14585
14586     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
14587
14588     /* see the comment in custom_op_xop */
14589     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
14590
14591     if (!PL_custom_ops)
14592         PL_custom_ops = newHV();
14593
14594     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
14595         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
14596 }
14597
14598 /*
14599
14600 =for apidoc core_prototype
14601
14602 This function assigns the prototype of the named core function to C<sv>, or
14603 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
14604 C<NULL> if the core function has no prototype.  C<code> is a code as returned
14605 by C<keyword()>.  It must not be equal to 0.
14606
14607 =cut
14608 */
14609
14610 SV *
14611 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
14612                           int * const opnum)
14613 {
14614     int i = 0, n = 0, seen_question = 0, defgv = 0;
14615     I32 oa;
14616 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
14617     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
14618     bool nullret = FALSE;
14619
14620     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
14621
14622     assert (code);
14623
14624     if (!sv) sv = sv_newmortal();
14625
14626 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
14627
14628     switch (code < 0 ? -code : code) {
14629     case KEY_and   : case KEY_chop: case KEY_chomp:
14630     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
14631     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
14632     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
14633     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
14634     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
14635     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
14636     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
14637     case KEY_x     : case KEY_xor    :
14638         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
14639     case KEY_glob:    retsetpvs("_;", OP_GLOB);
14640     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
14641     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
14642     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
14643     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
14644     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
14645         retsetpvs("", 0);
14646     case KEY_evalbytes:
14647         name = "entereval"; break;
14648     case KEY_readpipe:
14649         name = "backtick";
14650     }
14651
14652 #undef retsetpvs
14653
14654   findopnum:
14655     while (i < MAXO) {  /* The slow way. */
14656         if (strEQ(name, PL_op_name[i])
14657             || strEQ(name, PL_op_desc[i]))
14658         {
14659             if (nullret) { assert(opnum); *opnum = i; return NULL; }
14660             goto found;
14661         }
14662         i++;
14663     }
14664     return NULL;
14665   found:
14666     defgv = PL_opargs[i] & OA_DEFGV;
14667     oa = PL_opargs[i] >> OASHIFT;
14668     while (oa) {
14669         if (oa & OA_OPTIONAL && !seen_question && (
14670               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
14671         )) {
14672             seen_question = 1;
14673             str[n++] = ';';
14674         }
14675         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
14676             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
14677             /* But globs are already references (kinda) */
14678             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
14679         ) {
14680             str[n++] = '\\';
14681         }
14682         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
14683          && !scalar_mod_type(NULL, i)) {
14684             str[n++] = '[';
14685             str[n++] = '$';
14686             str[n++] = '@';
14687             str[n++] = '%';
14688             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
14689             str[n++] = '*';
14690             str[n++] = ']';
14691         }
14692         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
14693         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
14694             str[n-1] = '_'; defgv = 0;
14695         }
14696         oa = oa >> 4;
14697     }
14698     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
14699     str[n++] = '\0';
14700     sv_setpvn(sv, str, n - 1);
14701     if (opnum) *opnum = i;
14702     return sv;
14703 }
14704
14705 OP *
14706 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
14707                       const int opnum)
14708 {
14709     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
14710     OP *o;
14711
14712     PERL_ARGS_ASSERT_CORESUB_OP;
14713
14714     switch(opnum) {
14715     case 0:
14716         return op_append_elem(OP_LINESEQ,
14717                        argop,
14718                        newSLICEOP(0,
14719                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
14720                                   newOP(OP_CALLER,0)
14721                        )
14722                );
14723     case OP_EACH:
14724     case OP_KEYS:
14725     case OP_VALUES:
14726         o = newUNOP(OP_AVHVSWITCH,0,argop);
14727         o->op_private = opnum-OP_EACH;
14728         return o;
14729     case OP_SELECT: /* which represents OP_SSELECT as well */
14730         if (code)
14731             return newCONDOP(
14732                          0,
14733                          newBINOP(OP_GT, 0,
14734                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
14735                                   newSVOP(OP_CONST, 0, newSVuv(1))
14736                                  ),
14737                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
14738                                     OP_SSELECT),
14739                          coresub_op(coreargssv, 0, OP_SELECT)
14740                    );
14741         /* FALLTHROUGH */
14742     default:
14743         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14744         case OA_BASEOP:
14745             return op_append_elem(
14746                         OP_LINESEQ, argop,
14747                         newOP(opnum,
14748                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
14749                                 ? OPpOFFBYONE << 8 : 0)
14750                    );
14751         case OA_BASEOP_OR_UNOP:
14752             if (opnum == OP_ENTEREVAL) {
14753                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
14754                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
14755             }
14756             else o = newUNOP(opnum,0,argop);
14757             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
14758             else {
14759           onearg:
14760               if (is_handle_constructor(o, 1))
14761                 argop->op_private |= OPpCOREARGS_DEREF1;
14762               if (scalar_mod_type(NULL, opnum))
14763                 argop->op_private |= OPpCOREARGS_SCALARMOD;
14764             }
14765             return o;
14766         default:
14767             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
14768             if (is_handle_constructor(o, 2))
14769                 argop->op_private |= OPpCOREARGS_DEREF2;
14770             if (opnum == OP_SUBSTR) {
14771                 o->op_private |= OPpMAYBE_LVSUB;
14772                 return o;
14773             }
14774             else goto onearg;
14775         }
14776     }
14777 }
14778
14779 void
14780 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
14781                                SV * const *new_const_svp)
14782 {
14783     const char *hvname;
14784     bool is_const = !!CvCONST(old_cv);
14785     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
14786
14787     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
14788
14789     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
14790         return;
14791         /* They are 2 constant subroutines generated from
14792            the same constant. This probably means that
14793            they are really the "same" proxy subroutine
14794            instantiated in 2 places. Most likely this is
14795            when a constant is exported twice.  Don't warn.
14796         */
14797     if (
14798         (ckWARN(WARN_REDEFINE)
14799          && !(
14800                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
14801              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
14802              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
14803                  strEQ(hvname, "autouse"))
14804              )
14805         )
14806      || (is_const
14807          && ckWARN_d(WARN_REDEFINE)
14808          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
14809         )
14810     )
14811         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
14812                           is_const
14813                             ? "Constant subroutine %"SVf" redefined"
14814                             : "Subroutine %"SVf" redefined",
14815                           SVfARG(name));
14816 }
14817
14818 /*
14819 =head1 Hook manipulation
14820
14821 These functions provide convenient and thread-safe means of manipulating
14822 hook variables.
14823
14824 =cut
14825 */
14826
14827 /*
14828 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
14829
14830 Puts a C function into the chain of check functions for a specified op
14831 type.  This is the preferred way to manipulate the L</PL_check> array.
14832 C<opcode> specifies which type of op is to be affected.  C<new_checker>
14833 is a pointer to the C function that is to be added to that opcode's
14834 check chain, and C<old_checker_p> points to the storage location where a
14835 pointer to the next function in the chain will be stored.  The value of
14836 C<new_pointer> is written into the L</PL_check> array, while the value
14837 previously stored there is written to C<*old_checker_p>.
14838
14839 The function should be defined like this:
14840
14841     static OP *new_checker(pTHX_ OP *op) { ... }
14842
14843 It is intended to be called in this manner:
14844
14845     new_checker(aTHX_ op)
14846
14847 C<old_checker_p> should be defined like this:
14848
14849     static Perl_check_t old_checker_p;
14850
14851 L</PL_check> is global to an entire process, and a module wishing to
14852 hook op checking may find itself invoked more than once per process,
14853 typically in different threads.  To handle that situation, this function
14854 is idempotent.  The location C<*old_checker_p> must initially (once
14855 per process) contain a null pointer.  A C variable of static duration
14856 (declared at file scope, typically also marked C<static> to give
14857 it internal linkage) will be implicitly initialised appropriately,
14858 if it does not have an explicit initialiser.  This function will only
14859 actually modify the check chain if it finds C<*old_checker_p> to be null.
14860 This function is also thread safe on the small scale.  It uses appropriate
14861 locking to avoid race conditions in accessing L</PL_check>.
14862
14863 When this function is called, the function referenced by C<new_checker>
14864 must be ready to be called, except for C<*old_checker_p> being unfilled.
14865 In a threading situation, C<new_checker> may be called immediately,
14866 even before this function has returned.  C<*old_checker_p> will always
14867 be appropriately set before C<new_checker> is called.  If C<new_checker>
14868 decides not to do anything special with an op that it is given (which
14869 is the usual case for most uses of op check hooking), it must chain the
14870 check function referenced by C<*old_checker_p>.
14871
14872 If you want to influence compilation of calls to a specific subroutine,
14873 then use L</cv_set_call_checker> rather than hooking checking of all
14874 C<entersub> ops.
14875
14876 =cut
14877 */
14878
14879 void
14880 Perl_wrap_op_checker(pTHX_ Optype opcode,
14881     Perl_check_t new_checker, Perl_check_t *old_checker_p)
14882 {
14883     dVAR;
14884
14885     PERL_UNUSED_CONTEXT;
14886     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
14887     if (*old_checker_p) return;
14888     OP_CHECK_MUTEX_LOCK;
14889     if (!*old_checker_p) {
14890         *old_checker_p = PL_check[opcode];
14891         PL_check[opcode] = new_checker;
14892     }
14893     OP_CHECK_MUTEX_UNLOCK;
14894 }
14895
14896 #include "XSUB.h"
14897
14898 /* Efficient sub that returns a constant scalar value. */
14899 static void
14900 const_sv_xsub(pTHX_ CV* cv)
14901 {
14902     dXSARGS;
14903     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
14904     PERL_UNUSED_ARG(items);
14905     if (!sv) {
14906         XSRETURN(0);
14907     }
14908     EXTEND(sp, 1);
14909     ST(0) = sv;
14910     XSRETURN(1);
14911 }
14912
14913 static void
14914 const_av_xsub(pTHX_ CV* cv)
14915 {
14916     dXSARGS;
14917     AV * const av = MUTABLE_AV(XSANY.any_ptr);
14918     SP -= items;
14919     assert(av);
14920 #ifndef DEBUGGING
14921     if (!av) {
14922         XSRETURN(0);
14923     }
14924 #endif
14925     if (SvRMAGICAL(av))
14926         Perl_croak(aTHX_ "Magical list constants are not supported");
14927     if (GIMME_V != G_ARRAY) {
14928         EXTEND(SP, 1);
14929         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
14930         XSRETURN(1);
14931     }
14932     EXTEND(SP, AvFILLp(av)+1);
14933     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
14934     XSRETURN(AvFILLp(av)+1);
14935 }
14936
14937 /*
14938  * ex: set ts=8 sts=4 sw=4 et:
14939  */