]> git.vpit.fr Git - perl/modules/autovivification.git/blob - autovivification.xs
Add a missing aTHX for Win32 builds
[perl/modules/autovivification.git] / autovivification.xs
1 /* This file is part of the autovivification Perl module.
2  * See http://search.cpan.org/dist/autovivification/ */
3
4 #define PERL_NO_GET_CONTEXT
5 #include "EXTERN.h"
6 #include "perl.h"
7 #include "XSUB.h"
8
9 #define __PACKAGE__     "autovivification"
10 #define __PACKAGE_LEN__ (sizeof(__PACKAGE__)-1)
11
12 /* --- Compatibility wrappers ---------------------------------------------- */
13
14 #ifndef HvNAME_get
15 # define HvNAME_get(H) HvNAME(H)
16 #endif
17
18 #ifndef HvNAMELEN_get
19 # define HvNAMELEN_get(H) strlen(HvNAME_get(H))
20 #endif
21
22 #define A_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
23
24 #ifndef A_WORKAROUND_REQUIRE_PROPAGATION
25 # define A_WORKAROUND_REQUIRE_PROPAGATION !A_HAS_PERL(5, 10, 1)
26 #endif
27
28 #ifndef A_HAS_RPEEP
29 # define A_HAS_RPEEP A_HAS_PERL(5, 13, 5)
30 #endif
31
32 #ifndef A_HAS_MULTIDEREF
33 # define A_HAS_MULTIDEREF A_HAS_PERL(5, 21, 7)
34 #endif
35
36 #ifndef OpSIBLING
37 # ifdef OP_SIBLING
38 #  define OpSIBLING(O) OP_SIBLING(O)
39 # else
40 #  define OpSIBLING(O) ((O)->op_sibling)
41 # endif
42 #endif
43
44 /* ... Thread safety and multiplicity ...................................... */
45
46 /* Always safe when the workaround isn't needed */
47 #if !A_WORKAROUND_REQUIRE_PROPAGATION
48 # undef A_FORKSAFE
49 # define A_FORKSAFE 1
50 /* Otherwise, safe unless Makefile.PL says it's Win32 */
51 #elif !defined(A_FORKSAFE)
52 # define A_FORKSAFE 1
53 #endif
54
55 #ifndef A_MULTIPLICITY
56 # if defined(MULTIPLICITY)
57 #  define A_MULTIPLICITY 1
58 # else
59 #  define A_MULTIPLICITY 0
60 # endif
61 #endif
62 #if A_MULTIPLICITY
63 # ifndef PERL_IMPLICIT_CONTEXT
64 #  error MULTIPLICITY builds must set PERL_IMPLICIT_CONTEXT
65 # endif
66 #endif
67
68 #ifndef tTHX
69 # define tTHX PerlInterpreter*
70 #endif
71
72 #if A_MULTIPLICITY && defined(USE_ITHREADS) && defined(dMY_CXT) && defined(MY_CXT) && defined(START_MY_CXT) && defined(MY_CXT_INIT) && (defined(MY_CXT_CLONE) || defined(dMY_CXT_SV))
73 # define A_THREADSAFE 1
74 # ifndef MY_CXT_CLONE
75 #  define MY_CXT_CLONE \
76     dMY_CXT_SV;                                                      \
77     my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
78     Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
79     sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
80 # endif
81 #else
82 # define A_THREADSAFE 0
83 # undef  dMY_CXT
84 # define dMY_CXT      dNOOP
85 # undef  MY_CXT
86 # define MY_CXT       a_globaldata
87 # undef  START_MY_CXT
88 # define START_MY_CXT static my_cxt_t MY_CXT;
89 # undef  MY_CXT_INIT
90 # define MY_CXT_INIT  NOOP
91 # undef  MY_CXT_CLONE
92 # define MY_CXT_CLONE NOOP
93 #endif
94
95 #if A_THREADSAFE
96 /* We must use preexistent global mutexes or we will never be able to destroy
97  * them. */
98 # if A_HAS_PERL(5, 9, 3)
99 #  define A_LOADED_LOCK   MUTEX_LOCK(&PL_my_ctx_mutex)
100 #  define A_LOADED_UNLOCK MUTEX_UNLOCK(&PL_my_ctx_mutex)
101 # else
102 #  define A_LOADED_LOCK   OP_REFCNT_LOCK
103 #  define A_LOADED_UNLOCK OP_REFCNT_UNLOCK
104 # endif
105 #else
106 # define A_LOADED_LOCK   NOOP
107 # define A_LOADED_UNLOCK NOOP
108 #endif
109
110 #if defined(OP_CHECK_MUTEX_LOCK) && defined(OP_CHECK_MUTEX_UNLOCK)
111 # define A_CHECK_LOCK   OP_CHECK_MUTEX_LOCK
112 # define A_CHECK_UNLOCK OP_CHECK_MUTEX_UNLOCK
113 #elif A_HAS_PERL(5, 9, 3)
114 # define A_CHECK_LOCK   OP_REFCNT_LOCK
115 # define A_CHECK_UNLOCK OP_REFCNT_UNLOCK
116 #else
117 /* Before perl 5.9.3, indirect_ck_*() calls are already protected by the
118  * A_LOADED mutex, which falls back to the OP_REFCNT mutex. Make sure we don't
119  * lock it twice. */
120 # define A_CHECK_LOCK   NOOP
121 # define A_CHECK_UNLOCK NOOP
122 #endif
123
124 typedef OP *(*a_ck_t)(pTHX_ OP *);
125
126 #ifdef wrap_op_checker
127
128 # define a_ck_replace(T, NC, OCP) wrap_op_checker((T), (NC), (OCP))
129
130 #else
131
132 static void a_ck_replace(pTHX_ OPCODE type, a_ck_t new_ck, a_ck_t *old_ck_p) {
133 #define a_ck_replace(T, NC, OCP) a_ck_replace(aTHX_ (T), (NC), (OCP))
134  A_CHECK_LOCK;
135  if (!*old_ck_p) {
136   *old_ck_p      = PL_check[type];
137   PL_check[type] = new_ck;
138  }
139  A_CHECK_UNLOCK;
140 }
141
142 #endif
143
144 static void a_ck_restore(pTHX_ OPCODE type, a_ck_t *old_ck_p) {
145 #define a_ck_restore(T, OCP) a_ck_restore(aTHX_ (T), (OCP))
146  A_CHECK_LOCK;
147  if (*old_ck_p) {
148   PL_check[type] = *old_ck_p;
149   *old_ck_p      = 0;
150  }
151  A_CHECK_UNLOCK;
152 }
153
154 /* --- Helpers ------------------------------------------------------------- */
155
156 /* ... Check if the module is loaded ....................................... */
157
158 static I32 a_loaded = 0;
159
160 #if A_THREADSAFE
161
162 #define PTABLE_NAME        ptable_loaded
163 #define PTABLE_NEED_DELETE 1
164 #define PTABLE_NEED_WALK   0
165
166 #include "ptable.h"
167
168 #define ptable_loaded_store(T, K, V) ptable_loaded_store(aPTBLMS_ (T), (K), (V))
169 #define ptable_loaded_delete(T, K)   ptable_loaded_delete(aPTBLMS_ (T), (K))
170 #define ptable_loaded_free(T)        ptable_loaded_free(aPTBLMS_ (T))
171
172 static ptable *a_loaded_cxts = NULL;
173
174 static int a_is_loaded(pTHX_ void *cxt) {
175 #define a_is_loaded(C) a_is_loaded(aTHX_ (C))
176  int res = 0;
177
178  A_LOADED_LOCK;
179  if (a_loaded_cxts && ptable_fetch(a_loaded_cxts, cxt))
180   res = 1;
181  A_LOADED_UNLOCK;
182
183  return res;
184 }
185
186 static int a_set_loaded_locked(pTHX_ void *cxt) {
187 #define a_set_loaded_locked(C) a_set_loaded_locked(aTHX_ (C))
188  int global_setup = 0;
189
190  if (a_loaded <= 0) {
191   assert(a_loaded == 0);
192   assert(!a_loaded_cxts);
193   a_loaded_cxts = ptable_new();
194   global_setup  = 1;
195  }
196  ++a_loaded;
197  assert(a_loaded_cxts);
198  ptable_loaded_store(a_loaded_cxts, cxt, cxt);
199
200  return global_setup;
201 }
202
203 static int a_clear_loaded_locked(pTHX_ void *cxt) {
204 #define a_clear_loaded_locked(C) a_clear_loaded_locked(aTHX_ (C))
205  int global_teardown = 0;
206
207  if (a_loaded > 1) {
208   assert(a_loaded_cxts);
209   ptable_loaded_delete(a_loaded_cxts, cxt);
210   --a_loaded;
211  } else if (a_loaded_cxts) {
212   assert(a_loaded == 1);
213   ptable_loaded_free(a_loaded_cxts);
214   a_loaded_cxts   = NULL;
215   a_loaded        = 0;
216   global_teardown = 1;
217  }
218
219  return global_teardown;
220 }
221
222 #else
223
224 #define a_is_loaded(C)           (a_loaded > 0)
225 #define a_set_loaded_locked(C)   ((a_loaded++ <= 0) ? 1 : 0)
226 #define a_clear_loaded_locked(C) ((--a_loaded <= 0) ? 1 : 0)
227
228 #endif
229
230 /* ... Thread-safe hints ................................................... */
231
232 #if A_WORKAROUND_REQUIRE_PROPAGATION
233
234 typedef struct {
235  U32 bits;
236  IV  require_tag;
237 } a_hint_t;
238
239 #define A_HINT_FREE(H) PerlMemShared_free(H)
240
241 #if A_THREADSAFE
242
243 #define PTABLE_NAME        ptable_hints
244 #define PTABLE_VAL_FREE(V) A_HINT_FREE(V)
245 #define PTABLE_NEED_DELETE 0
246 #define PTABLE_NEED_WALK   1
247
248 #define pPTBL  pTHX
249 #define pPTBL_ pTHX_
250 #define aPTBL  aTHX
251 #define aPTBL_ aTHX_
252
253 #include "ptable.h"
254
255 #define ptable_hints_store(T, K, V) ptable_hints_store(aTHX_ (T), (K), (V))
256 #define ptable_hints_free(T)        ptable_hints_free(aTHX_ (T))
257
258 #endif /* A_THREADSAFE */
259
260 #endif /* A_WORKAROUND_REQUIRE_PROPAGATION */
261
262 #define PTABLE_NAME        ptable_seen
263 #define PTABLE_NEED_DELETE 0
264 #define PTABLE_NEED_WALK   0
265
266 #include "ptable.h"
267
268 /* PerlMemShared_free() needs the [ap]PTBLMS_? default values */
269 #define ptable_seen_store(T, K, V) ptable_seen_store(aPTBLMS_ (T), (K), (V))
270 #define ptable_seen_clear(T)       ptable_seen_clear(aPTBLMS_ (T))
271 #define ptable_seen_free(T)        ptable_seen_free(aPTBLMS_ (T))
272
273 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
274
275 typedef struct {
276  peep_t  old_peep; /* This is actually the rpeep past 5.13.5 */
277  ptable *seen;     /* It really is a ptable_seen */
278 #if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
279  ptable *tbl;      /* It really is a ptable_hints */
280  tTHX    owner;
281 #endif /* A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION */
282 } my_cxt_t;
283
284 START_MY_CXT
285
286 #if A_WORKAROUND_REQUIRE_PROPAGATION
287
288 #if A_THREADSAFE
289
290 typedef struct {
291  ptable       *tbl;
292 #if A_HAS_PERL(5, 13, 2)
293  CLONE_PARAMS *params;
294 #else
295  CLONE_PARAMS  params;
296 #endif
297 } a_ptable_clone_ud;
298
299 #if A_HAS_PERL(5, 13, 2)
300 # define a_ptable_clone_ud_init(U, T, O) \
301    (U).tbl    = (T); \
302    (U).params = Perl_clone_params_new((O), aTHX)
303 # define a_ptable_clone_ud_deinit(U) Perl_clone_params_del((U).params)
304 # define a_dup_inc(S, U)             SvREFCNT_inc(sv_dup((S), (U)->params))
305 #else
306 # define a_ptable_clone_ud_init(U, T, O) \
307    (U).tbl               = (T);     \
308    (U).params.stashes    = newAV(); \
309    (U).params.flags      = 0;       \
310    (U).params.proto_perl = (O)
311 # define a_ptable_clone_ud_deinit(U) SvREFCNT_dec((U).params.stashes)
312 # define a_dup_inc(S, U)             SvREFCNT_inc(sv_dup((S), &((U)->params)))
313 #endif
314
315 static void a_ptable_clone(pTHX_ ptable_ent *ent, void *ud_) {
316  a_ptable_clone_ud *ud = ud_;
317  a_hint_t *h1 = ent->val;
318  a_hint_t *h2;
319
320  h2              = PerlMemShared_malloc(sizeof *h2);
321  h2->bits        = h1->bits;
322  h2->require_tag = PTR2IV(a_dup_inc(INT2PTR(SV *, h1->require_tag), ud));
323
324  ptable_hints_store(ud->tbl, ent->key, h2);
325 }
326
327 #endif /* A_THREADSAFE */
328
329 static IV a_require_tag(pTHX) {
330 #define a_require_tag() a_require_tag(aTHX)
331  const CV *cv, *outside;
332
333  cv = PL_compcv;
334
335  if (!cv) {
336   /* If for some reason the pragma is operational at run-time, try to discover
337    * the current cv in use. */
338   const PERL_SI *si;
339
340   for (si = PL_curstackinfo; si; si = si->si_prev) {
341    I32 cxix;
342
343    for (cxix = si->si_cxix; cxix >= 0; --cxix) {
344     const PERL_CONTEXT *cx = si->si_cxstack + cxix;
345
346     switch (CxTYPE(cx)) {
347      case CXt_SUB:
348      case CXt_FORMAT:
349       /* The propagation workaround is only needed up to 5.10.0 and at that
350        * time format and sub contexts were still identical. And even later the
351        * cv members offsets should have been kept the same. */
352       cv = cx->blk_sub.cv;
353       goto get_enclosing_cv;
354      case CXt_EVAL:
355       cv = cx->blk_eval.cv;
356       goto get_enclosing_cv;
357      default:
358       break;
359     }
360    }
361   }
362
363   cv = PL_main_cv;
364  }
365
366 get_enclosing_cv:
367  for (outside = CvOUTSIDE(cv); outside; outside = CvOUTSIDE(cv))
368   cv = outside;
369
370  return PTR2IV(cv);
371 }
372
373 static SV *a_tag(pTHX_ UV bits) {
374 #define a_tag(B) a_tag(aTHX_ (B))
375  a_hint_t *h;
376 #if A_THREADSAFE
377  dMY_CXT;
378
379  if (!MY_CXT.tbl)
380   return newSViv(0);
381 #endif /* A_THREADSAFE */
382
383  h              = PerlMemShared_malloc(sizeof *h);
384  h->bits        = bits;
385  h->require_tag = a_require_tag();
386
387 #if A_THREADSAFE
388  /* We only need for the key to be an unique tag for looking up the value later
389   * Allocated memory provides convenient unique identifiers, so that's why we
390   * use the hint as the key itself. */
391  ptable_hints_store(MY_CXT.tbl, h, h);
392 #endif /* A_THREADSAFE */
393
394  return newSViv(PTR2IV(h));
395 }
396
397 static UV a_detag(pTHX_ const SV *hint) {
398 #define a_detag(H) a_detag(aTHX_ (H))
399  a_hint_t *h;
400 #if A_THREADSAFE
401  dMY_CXT;
402
403  if (!MY_CXT.tbl)
404   return 0;
405 #endif /* A_THREADSAFE */
406
407  if (!(hint && SvIOK(hint)))
408   return 0;
409
410  h = INT2PTR(a_hint_t *, SvIVX(hint));
411 #if A_THREADSAFE
412  h = ptable_fetch(MY_CXT.tbl, h);
413 #endif /* A_THREADSAFE */
414
415  if (a_require_tag() != h->require_tag)
416   return 0;
417
418  return h->bits;
419 }
420
421 #else /* A_WORKAROUND_REQUIRE_PROPAGATION */
422
423 #define a_tag(B)   newSVuv(B)
424 /* PVs fetched from the hints chain have their SvLEN set to zero, so get the UV
425  * from a copy. */
426 #define a_detag(H) \
427  ((H)              \
428   ? (SvIOK(H)      \
429      ? SvUVX(H)    \
430      : (SvPOK(H)   \
431         ? sv_2uv(SvLEN(H) ? (H) : sv_mortalcopy(H)) \
432         : 0        \
433        )           \
434      )             \
435   : 0)
436
437 #endif /* !A_WORKAROUND_REQUIRE_PROPAGATION */
438
439 /* Used both for hints and op flags */
440 #define A_HINT_STRICT 1
441 #define A_HINT_WARN   2
442 #define A_HINT_FETCH  4
443 #define A_HINT_STORE  8
444 #define A_HINT_EXISTS 16
445 #define A_HINT_DELETE 32
446 #define A_HINT_NOTIFY (A_HINT_STRICT|A_HINT_WARN)
447 #define A_HINT_DO     (A_HINT_FETCH|A_HINT_STORE|A_HINT_EXISTS|A_HINT_DELETE)
448 #define A_HINT_MASK   (A_HINT_NOTIFY|A_HINT_DO)
449
450 /* Only used in op flags */
451 #define A_HINT_ROOT   64
452 #define A_HINT_DEREF  128
453
454 static VOL U32 a_hash = 0;
455
456 static UV a_hint(pTHX) {
457 #define a_hint() a_hint(aTHX)
458  SV *hint;
459 #ifdef cop_hints_fetch_pvn
460  hint = cop_hints_fetch_pvn(PL_curcop, __PACKAGE__, __PACKAGE_LEN__, a_hash, 0);
461 #elif A_HAS_PERL(5, 9, 5)
462  hint = Perl_refcounted_he_fetch(aTHX_ PL_curcop->cop_hints_hash,
463                                        NULL,
464                                        __PACKAGE__, __PACKAGE_LEN__,
465                                        0,
466                                        a_hash);
467 #else
468  SV **val = hv_fetch(GvHV(PL_hintgv), __PACKAGE__, __PACKAGE_LEN__, 0);
469  if (!val)
470   return 0;
471  hint = *val;
472 #endif
473  return a_detag(hint);
474 }
475
476 /* ... op => info map ...................................................... */
477
478 typedef struct {
479  OP   *(*old_pp)(pTHX);
480  void   *next;
481  UV      flags;
482 } a_op_info;
483
484 #define PTABLE_NAME        ptable_map
485 #define PTABLE_VAL_FREE(V) PerlMemShared_free(V)
486 #define PTABLE_NEED_DELETE 1
487 #define PTABLE_NEED_WALK   0
488
489 #include "ptable.h"
490
491 /* PerlMemShared_free() needs the [ap]PTBLMS_? default values */
492 #define ptable_map_store(T, K, V) ptable_map_store(aPTBLMS_ (T), (K), (V))
493 #define ptable_map_delete(T, K)   ptable_map_delete(aPTBLMS_ (T), (K))
494 #define ptable_map_free(T)        ptable_map_free(aPTBLMS_ (T))
495
496 static ptable *a_op_map = NULL;
497
498 #ifdef USE_ITHREADS
499
500 #define dA_MAP_THX a_op_info a_op_map_tmp_oi
501
502 static perl_mutex a_op_map_mutex;
503
504 #define A_LOCK(M)   MUTEX_LOCK(M)
505 #define A_UNLOCK(M) MUTEX_UNLOCK(M)
506
507 static const a_op_info *a_map_fetch(const OP *o, a_op_info *oi) {
508  const a_op_info *val;
509
510  A_LOCK(&a_op_map_mutex);
511
512  val = ptable_fetch(a_op_map, o);
513  if (val) {
514   *oi = *val;
515   val = oi;
516  }
517
518  A_UNLOCK(&a_op_map_mutex);
519
520  return val;
521 }
522
523 #define a_map_fetch(O) a_map_fetch((O), &a_op_map_tmp_oi)
524
525 #else /* USE_ITHREADS */
526
527 #define dA_MAP_THX dNOOP
528
529 #define A_LOCK(M)   NOOP
530 #define A_UNLOCK(M) NOOP
531
532 #define a_map_fetch(O) ptable_fetch(a_op_map, (O))
533
534 #endif /* !USE_ITHREADS */
535
536 static const a_op_info *a_map_store_locked(pPTBLMS_ const OP *o, OP *(*old_pp)(pTHX), void *next, UV flags) {
537 #define a_map_store_locked(O, PP, N, F) a_map_store_locked(aPTBLMS_ (O), (PP), (N), (F))
538  a_op_info *oi;
539
540  if (!(oi = ptable_fetch(a_op_map, o))) {
541   oi = PerlMemShared_malloc(sizeof *oi);
542   ptable_map_store(a_op_map, o, oi);
543  }
544
545  oi->old_pp = old_pp;
546  oi->next   = next;
547  oi->flags  = flags;
548
549  return oi;
550 }
551
552 static void a_map_store(pPTBLMS_ const OP *o, OP *(*old_pp)(pTHX), void *next, UV flags) {
553 #define a_map_store(O, PP, N, F) a_map_store(aPTBLMS_ (O), (PP), (N), (F))
554  A_LOCK(&a_op_map_mutex);
555
556  a_map_store_locked(o, old_pp, next, flags);
557
558  A_UNLOCK(&a_op_map_mutex);
559 }
560
561 static void a_map_delete(pTHX_ const OP *o) {
562 #define a_map_delete(O) a_map_delete(aTHX_ (O))
563  A_LOCK(&a_op_map_mutex);
564
565  ptable_map_delete(a_op_map, o);
566
567  A_UNLOCK(&a_op_map_mutex);
568 }
569
570 static const OP *a_map_descend(const OP *o) {
571  switch (PL_opargs[o->op_type] & OA_CLASS_MASK) {
572   case OA_BASEOP:
573   case OA_UNOP:
574   case OA_BINOP:
575   case OA_BASEOP_OR_UNOP:
576    return cUNOPo->op_first;
577   case OA_LIST:
578   case OA_LISTOP:
579    return cLISTOPo->op_last;
580  }
581
582  return NULL;
583 }
584
585 static void a_map_store_root(pPTBLMS_ const OP *root, OP *(*old_pp)(pTHX), UV flags) {
586 #define a_map_store_root(R, PP, F) a_map_store_root(aPTBLMS_ (R), (PP), (F))
587  const a_op_info *roi;
588  a_op_info *oi;
589  const OP *o = root;
590
591  A_LOCK(&a_op_map_mutex);
592
593  roi = a_map_store_locked(o, old_pp, (OP *) root, flags | A_HINT_ROOT);
594
595  while (o->op_flags & OPf_KIDS) {
596   o = a_map_descend(o);
597   if (!o)
598    break;
599   if ((oi = ptable_fetch(a_op_map, o))) {
600    oi->flags &= ~A_HINT_ROOT;
601    oi->next   = (a_op_info *) roi;
602    break;
603   }
604  }
605
606  A_UNLOCK(&a_op_map_mutex);
607
608  return;
609 }
610
611 static void a_map_update_flags_topdown(const OP *root, UV flags) {
612  a_op_info *oi;
613  const OP *o = root;
614
615  A_LOCK(&a_op_map_mutex);
616
617  flags &= ~A_HINT_ROOT;
618
619  do {
620   if ((oi = ptable_fetch(a_op_map, o)))
621    oi->flags = (oi->flags & A_HINT_ROOT) | flags;
622   if (!(o->op_flags & OPf_KIDS))
623    break;
624   o = a_map_descend(o);
625  } while (o);
626
627  A_UNLOCK(&a_op_map_mutex);
628
629  return;
630 }
631
632 #define a_map_cancel(R) a_map_update_flags_topdown((R), 0)
633
634 static void a_map_update_flags_bottomup(const OP *o, UV flags, UV rflags) {
635  a_op_info *oi;
636
637  A_LOCK(&a_op_map_mutex);
638
639  flags  &= ~A_HINT_ROOT;
640  rflags |=  A_HINT_ROOT;
641
642  oi = ptable_fetch(a_op_map, o);
643  while (!(oi->flags & A_HINT_ROOT)) {
644   oi->flags = flags;
645   oi        = oi->next;
646  }
647  oi->flags = rflags;
648
649  A_UNLOCK(&a_op_map_mutex);
650
651  return;
652 }
653
654 /* ... Decide whether this expression should be autovivified or not ........ */
655
656 static UV a_map_resolve(const OP *o, const a_op_info *oi) {
657  UV flags = 0, rflags;
658  const OP *root;
659  const a_op_info *roi = oi;
660
661  while (!(roi->flags & A_HINT_ROOT))
662   roi = roi->next;
663  if (!roi)
664   goto cancel;
665
666  rflags = roi->flags & ~A_HINT_ROOT;
667  if (!rflags)
668   goto cancel;
669
670  root = roi->next;
671  if (root->op_flags & OPf_MOD) {
672   if (rflags & A_HINT_STORE)
673    flags = (A_HINT_STORE|A_HINT_DEREF);
674  } else if (rflags & A_HINT_FETCH)
675    flags = (A_HINT_FETCH|A_HINT_DEREF);
676
677  if (!flags) {
678 cancel:
679   a_map_update_flags_bottomup(o, 0, 0);
680   return 0;
681  }
682
683  flags |= (rflags & A_HINT_NOTIFY);
684  a_map_update_flags_bottomup(o, flags, 0);
685
686  return oi->flags & A_HINT_ROOT ? 0 : flags;
687 }
688
689 /* ... Inspired from pp_defined() .......................................... */
690
691 static int a_undef(pTHX_ SV *sv) {
692 #define a_undef(S) a_undef(aTHX_ (S))
693  switch (SvTYPE(sv)) {
694   case SVt_NULL:
695    return 1;
696   case SVt_PVAV:
697    if (AvMAX(sv) >= 0 || SvGMAGICAL(sv)
698                       || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
699     return 0;
700    break;
701   case SVt_PVHV:
702    if (HvARRAY(sv) || SvGMAGICAL(sv)
703                    || (SvRMAGICAL(sv) && mg_find(sv, PERL_MAGIC_tied)))
704     return 0;
705    break;
706   default:
707    SvGETMAGIC(sv);
708    if (SvOK(sv))
709     return 0;
710  }
711
712  return 1;
713 }
714
715 /* --- PP functions -------------------------------------------------------- */
716
717 /* Be aware that we restore PL_op->op_ppaddr from the pointer table old_pp
718  * value, another extension might have saved our pp replacement as the ppaddr
719  * for this op, so this doesn't ensure that our function will never be called
720  * again. That's why we don't remove the op info from our map, so that it can
721  * still run correctly if required. */
722
723 /* ... pp_rv2av ............................................................ */
724
725 static OP *a_pp_rv2av(pTHX) {
726  dA_MAP_THX;
727  const a_op_info *oi;
728  dSP;
729
730  oi = a_map_fetch(PL_op);
731
732  if (oi->flags & A_HINT_DEREF) {
733   if (a_undef(TOPs)) {
734    /* We always need to push an empty array to fool the pp_aelem() that comes
735     * later. */
736    SV *av;
737    (void) POPs;
738    av = sv_2mortal((SV *) newAV());
739    PUSHs(av);
740    RETURN;
741   }
742  }
743
744  return oi->old_pp(aTHX);
745 }
746
747 /* ... pp_rv2hv ............................................................ */
748
749 static OP *a_pp_rv2hv_simple(pTHX) {
750  dA_MAP_THX;
751  const a_op_info *oi;
752  dSP;
753
754  oi = a_map_fetch(PL_op);
755
756  if (oi->flags & A_HINT_DEREF) {
757   if (a_undef(TOPs))
758    RETURN;
759  }
760
761  return oi->old_pp(aTHX);
762 }
763
764 static OP *a_pp_rv2hv(pTHX) {
765  dA_MAP_THX;
766  const a_op_info *oi;
767  dSP;
768
769  oi = a_map_fetch(PL_op);
770
771  if (oi->flags & A_HINT_DEREF) {
772   if (a_undef(TOPs)) {
773    SV *hv;
774    (void) POPs;
775    hv = sv_2mortal((SV *) newHV());
776    PUSHs(hv);
777    RETURN;
778   }
779  }
780
781  return oi->old_pp(aTHX);
782 }
783
784 /* ... pp_deref (aelem,helem,rv2sv,padsv) .................................. */
785
786 static void a_cannot_vivify(pTHX_ UV flags) {
787 #define a_cannot_vivify(F) a_cannot_vivify(aTHX_ (F))
788  if (flags & A_HINT_STRICT)
789   croak("Reference vivification forbidden");
790  else if (flags & A_HINT_WARN)
791   warn("Reference was vivified");
792  else /* A_HINT_STORE */
793   croak("Can't vivify reference");
794 }
795
796 static OP *a_pp_deref(pTHX) {
797  dA_MAP_THX;
798  const a_op_info *oi;
799  UV flags;
800  dSP;
801
802  oi = a_map_fetch(PL_op);
803
804  flags = oi->flags;
805  if (flags & A_HINT_DEREF) {
806   OP *o;
807
808   o = oi->old_pp(aTHX);
809
810   if (flags & (A_HINT_NOTIFY|A_HINT_STORE)) {
811    SPAGAIN;
812    if (a_undef(TOPs))
813     a_cannot_vivify(flags);
814   }
815
816   return o;
817  }
818
819  return oi->old_pp(aTHX);
820 }
821
822 /* ... pp_root (exists,delete,keys,values) ................................. */
823
824 static OP *a_pp_root_unop(pTHX) {
825  dSP;
826
827  if (a_undef(TOPs)) {
828   (void) POPs;
829   /* Can only be reached by keys or values */
830   if (GIMME_V == G_SCALAR) {
831    dTARGET;
832    PUSHi(0);
833   }
834   RETURN;
835  }
836
837  {
838   dA_MAP_THX;
839   const a_op_info *oi = a_map_fetch(PL_op);
840   return oi->old_pp(aTHX);
841  }
842 }
843
844 static OP *a_pp_root_binop(pTHX) {
845  dSP;
846
847  if (a_undef(TOPm1s)) {
848   (void) POPs;
849   (void) POPs;
850   if (PL_op->op_type == OP_EXISTS)
851    RETPUSHNO;
852   else
853    RETPUSHUNDEF;
854  }
855
856  {
857   dA_MAP_THX;
858   const a_op_info *oi = a_map_fetch(PL_op);
859   return oi->old_pp(aTHX);
860  }
861 }
862
863 #if A_HAS_MULTIDEREF
864
865 /* ... pp_multideref ....................................................... */
866
867 /* This pp replacement is actually only called for topmost exists/delete ops,
868  * because we hijack the [ah]elem check functions and this disables the
869  * optimization for lvalue and rvalue dereferencing. In particular, the
870  * OPf_MOD branches should never be covered. In the future, the multideref
871  * optimization might also be disabled for custom exists/delete check functions,
872  * which will make this section unnecessary. However, the code tries to be as
873  * general as possible in case I think of a way to reenable the multideref
874  * optimization even when this module is in use. */
875
876 static UV a_do_multideref(const OP *o, UV flags) {
877  UV isexdel, other_flags;
878
879  assert(o->op_type == OP_MULTIDEREF);
880
881  other_flags = flags & ~A_HINT_DO;
882
883  isexdel = o->op_private & (OPpMULTIDEREF_EXISTS|OPpMULTIDEREF_DELETE);
884  if (isexdel) {
885   if (isexdel & OPpMULTIDEREF_EXISTS) {
886    flags &= A_HINT_EXISTS;
887   } else {
888    flags &= A_HINT_DELETE;
889   }
890  } else {
891   if (o->op_flags & OPf_MOD) {
892    flags &= A_HINT_STORE;
893   } else {
894    flags &= A_HINT_FETCH;
895   }
896  }
897
898  return flags ? (flags | other_flags) : 0;
899 }
900
901 static SV *a_do_fake_pp(pTHX_ OP *op) {
902 #define a_do_fake_pp(O) a_do_fake_pp(aTHX_ (O))
903  {
904   OP *o = PL_op;
905   ENTER;
906   SAVEOP();
907   PL_op = op;
908   PL_op->op_ppaddr(aTHX);
909   PL_op = o;
910   LEAVE;
911  }
912
913  {
914   SV *ret;
915   dSP;
916   ret = POPs;
917   PUTBACK;
918   return ret;
919  }
920 }
921
922 static void a_do_fake_pp_unop_init(pTHX_ UNOP *unop, U32 type, U32 flags) {
923 #define a_do_fake_pp_unop_init(O, T, F) a_do_fake_pp_unop_init(aTHX_ (O), (T), (F))
924  unop->op_type    = type;
925  unop->op_flags   = OPf_WANT_SCALAR | (~OPf_WANT & flags);
926  unop->op_private = 0;
927  unop->op_first   = NULL;
928  unop->op_ppaddr  = PL_ppaddr[type];
929 }
930
931 static SV *a_do_fake_pp_unop_arg1(pTHX_ U32 type, U32 flags, SV *arg) {
932 #define a_do_fake_pp_unop_arg1(T, F, A) a_do_fake_pp_unop_arg1(aTHX_ (T), (F), (A))
933  UNOP unop;
934  dSP;
935
936  a_do_fake_pp_unop_init(&unop, type, flags);
937
938  EXTEND(SP, 1);
939  PUSHs(arg);
940  PUTBACK;
941
942  return a_do_fake_pp((OP *) &unop);
943 }
944
945 static SV *a_do_fake_pp_unop_arg2(pTHX_ U32 type, U32 flags, SV *arg1, SV *arg2) {
946 #define a_do_fake_pp_unop_arg2(T, F, A1, A2) a_do_fake_pp_unop_arg2(aTHX_ (T), (F), (A1), (A2))
947  UNOP unop;
948  dSP;
949
950  a_do_fake_pp_unop_init(&unop, type, flags);
951
952  EXTEND(SP, 2);
953  PUSHs(arg1);
954  PUSHs(arg2);
955  PUTBACK;
956
957  return a_do_fake_pp((OP *) &unop);
958 }
959
960 #define a_do_pp_rv2av(R)        a_do_fake_pp_unop_arg1(OP_RV2AV,  OPf_REF,     (R))
961 #define a_do_pp_afetch(A, I)    a_do_fake_pp_unop_arg2(OP_AELEM,  0,           (A), (I))
962 #define a_do_pp_afetch_lv(A, I) a_do_fake_pp_unop_arg2(OP_AELEM,  OPf_MOD,     (A), (I))
963 #define a_do_pp_aexists(A, I)   a_do_fake_pp_unop_arg2(OP_EXISTS, OPf_SPECIAL, (A), (I))
964 #define a_do_pp_adelete(A, I)   a_do_fake_pp_unop_arg2(OP_DELETE, OPf_SPECIAL, (A), (I))
965
966 #define a_do_pp_rv2hv(R)        a_do_fake_pp_unop_arg1(OP_RV2HV,  OPf_REF, (R))
967 #define a_do_pp_hfetch(H, K)    a_do_fake_pp_unop_arg2(OP_HELEM,  0,       (H), (K))
968 #define a_do_pp_hfetch_lv(H, K) a_do_fake_pp_unop_arg2(OP_HELEM,  OPf_MOD, (H), (K))
969 #define a_do_pp_hexists(H, K)   a_do_fake_pp_unop_arg2(OP_EXISTS, 0,  (H), (K))
970 #define a_do_pp_hdelete(H, K)   a_do_fake_pp_unop_arg2(OP_DELETE, 0,  (H), (K))
971
972 static OP *a_pp_multideref(pTHX) {
973  UNOP_AUX_item *items;
974  UV  actions;
975  UV  flags = 0;
976  SV *sv    = NULL;
977  dSP;
978
979  {
980   dA_MAP_THX;
981   const a_op_info *oi = a_map_fetch(PL_op);
982   assert(oi);
983   flags = a_do_multideref(PL_op, oi->flags);
984   if (!flags)
985    return oi->old_pp(aTHX);
986  }
987
988  items   = cUNOP_AUXx(PL_op)->op_aux;
989  actions = items->uv;
990
991  PL_multideref_pc = items;
992
993  while (1) {
994   switch (actions & MDEREF_ACTION_MASK) {
995    case MDEREF_reload:
996     actions = (++items)->uv;
997     continue;
998    case MDEREF_AV_padav_aelem: /* $lex[...] */
999     sv = PAD_SVl((++items)->pad_offset);
1000     if (a_undef(sv))
1001      goto ret_undef;
1002     goto do_AV_aelem;
1003    case MDEREF_AV_gvav_aelem: /* $pkg[...] */
1004     sv = UNOP_AUX_item_sv(++items);
1005     assert(isGV_with_GP(sv));
1006     sv = (SV *) GvAVn((GV *) sv);
1007     if (a_undef(sv))
1008      goto ret_undef;
1009     goto do_AV_aelem;
1010    case MDEREF_AV_pop_rv2av_aelem: /* expr->[...] */
1011     sv = POPs;
1012     if (a_undef(sv))
1013      goto ret_undef;
1014     goto do_AV_rv2av_aelem;
1015    case MDEREF_AV_gvsv_vivify_rv2av_aelem: /* $pkg->[...] */
1016     sv = UNOP_AUX_item_sv(++items);
1017     assert(isGV_with_GP(sv));
1018     sv = GvSVn((GV *) sv);
1019     if (a_undef(sv))
1020      goto ret_undef;
1021     goto do_AV_vivify_rv2av_aelem;
1022    case MDEREF_AV_padsv_vivify_rv2av_aelem: /* $lex->[...] */
1023     sv = PAD_SVl((++items)->pad_offset);
1024     /* FALLTHROUGH */
1025    case MDEREF_AV_vivify_rv2av_aelem: /* vivify, ->[...] */
1026     if (a_undef(sv))
1027      goto ret_undef;
1028 do_AV_vivify_rv2av_aelem:
1029     sv = Perl_vivify_ref(aTHX_ sv, OPpDEREF_AV);
1030 do_AV_rv2av_aelem:
1031     sv = a_do_pp_rv2av(sv);
1032 do_AV_aelem:
1033     {
1034      SV *esv;
1035      assert(SvTYPE(sv) == SVt_PVAV);
1036      switch (actions & MDEREF_INDEX_MASK) {
1037       case MDEREF_INDEX_none:
1038        goto finish;
1039       case MDEREF_INDEX_const:
1040        esv = sv_2mortal(newSViv((++items)->iv));
1041        break;
1042       case MDEREF_INDEX_padsv:
1043        esv = PAD_SVl((++items)->pad_offset);
1044        goto check_elem;
1045       case MDEREF_INDEX_gvsv:
1046        esv = UNOP_AUX_item_sv(++items);
1047        assert(isGV_with_GP(esv));
1048        esv = GvSVn((GV *) esv);
1049 check_elem:
1050        if (UNLIKELY(SvROK(esv) && !SvGAMAGIC(esv) && ckWARN(WARN_MISC)))
1051         Perl_warner(aTHX_ packWARN(WARN_MISC),
1052                           "Use of reference \"%"SVf"\" as array index",
1053                           SVfARG(esv));
1054        break;
1055      }
1056      PL_multideref_pc = items;
1057      if (actions & MDEREF_FLAG_last) {
1058       switch (flags & A_HINT_DO) {
1059        case A_HINT_FETCH:
1060         sv = a_do_pp_afetch(sv, esv);
1061         break;
1062        case A_HINT_STORE:
1063         sv = a_do_pp_afetch_lv(sv, esv);
1064         break;
1065        case A_HINT_EXISTS:
1066         sv = a_do_pp_aexists(sv, esv);
1067         break;
1068        case A_HINT_DELETE:
1069         sv = a_do_pp_adelete(sv, esv);
1070         break;
1071       }
1072       goto finish;
1073      }
1074      sv = a_do_pp_afetch(sv, esv);
1075      break;
1076     }
1077    case MDEREF_HV_padhv_helem: /* $lex{...} */
1078     sv = PAD_SVl((++items)->pad_offset);
1079     if (a_undef(sv))
1080      goto ret_undef;
1081     goto do_HV_helem;
1082    case MDEREF_HV_gvhv_helem: /* $pkg{...} */
1083     sv = UNOP_AUX_item_sv(++items);
1084     assert(isGV_with_GP(sv));
1085     sv = (SV *) GvHVn((GV *) sv);
1086     if (a_undef(sv))
1087      goto ret_undef;
1088     goto do_HV_helem;
1089    case MDEREF_HV_pop_rv2hv_helem: /* expr->{...} */
1090     sv = POPs;
1091     if (a_undef(sv))
1092      goto ret_undef;
1093     goto do_HV_rv2hv_helem;
1094    case MDEREF_HV_gvsv_vivify_rv2hv_helem: /* $pkg->{...} */
1095     sv = UNOP_AUX_item_sv(++items);
1096     assert(isGV_with_GP(sv));
1097     sv = GvSVn((GV *) sv);
1098     if (a_undef(sv))
1099      goto ret_undef;
1100     goto do_HV_vivify_rv2hv_helem;
1101    case MDEREF_HV_padsv_vivify_rv2hv_helem: /* $lex->{...} */
1102     sv = PAD_SVl((++items)->pad_offset);
1103     /* FALLTHROUGH */
1104    case MDEREF_HV_vivify_rv2hv_helem: /* vivify, ->{...} */
1105     if (a_undef(sv))
1106      goto ret_undef;
1107 do_HV_vivify_rv2hv_helem:
1108     sv = Perl_vivify_ref(aTHX_ sv, OPpDEREF_HV);
1109 do_HV_rv2hv_helem:
1110     sv = a_do_pp_rv2hv(sv);
1111 do_HV_helem:
1112     {
1113      SV *key;
1114      assert(SvTYPE(sv) == SVt_PVHV);
1115      switch (actions & MDEREF_INDEX_MASK) {
1116       case MDEREF_INDEX_none:
1117        goto finish;
1118       case MDEREF_INDEX_const:
1119        key = UNOP_AUX_item_sv(++items);
1120        break;
1121       case MDEREF_INDEX_padsv:
1122        key = PAD_SVl((++items)->pad_offset);
1123        break;
1124       case MDEREF_INDEX_gvsv:
1125        key = UNOP_AUX_item_sv(++items);
1126        assert(isGV_with_GP(key));
1127        key = GvSVn((GV *) key);
1128        break;
1129      }
1130      PL_multideref_pc = items;
1131      if (actions & MDEREF_FLAG_last) {
1132       switch (flags & A_HINT_DO) {
1133        case A_HINT_FETCH:
1134         sv = a_do_pp_hfetch(sv, key);
1135         break;
1136        case A_HINT_STORE:
1137         sv = a_do_pp_hfetch_lv(sv, key);
1138         break;
1139        case A_HINT_EXISTS:
1140         sv = a_do_pp_hexists(sv, key);
1141         break;
1142        case A_HINT_DELETE:
1143         sv = a_do_pp_hdelete(sv, key);
1144         break;
1145        default:
1146         break;
1147       }
1148       goto finish;
1149      }
1150      sv = a_do_pp_hfetch(sv, key);
1151      break;
1152     }
1153   }
1154
1155   actions >>= MDEREF_SHIFT;
1156  }
1157
1158 ret_undef:
1159  if (flags & (A_HINT_NOTIFY|A_HINT_STORE))
1160   a_cannot_vivify(flags);
1161  if (flags & A_HINT_EXISTS)
1162   sv = &PL_sv_no;
1163  else
1164   sv = &PL_sv_undef;
1165 finish:
1166  XPUSHs(sv);
1167  RETURN;
1168 }
1169
1170 #endif /* A_HAS_MULTIDEREF */
1171
1172 /* --- Check functions ----------------------------------------------------- */
1173
1174 static void a_recheck_rv2xv(pTHX_ OP *o, OPCODE type, OP *(*new_pp)(pTHX)) {
1175 #define a_recheck_rv2xv(O, T, PP) a_recheck_rv2xv(aTHX_ (O), (T), (PP))
1176
1177  if (o->op_type == type && o->op_ppaddr != new_pp
1178                         && cUNOPo->op_first->op_type != OP_GV) {
1179   dA_MAP_THX;
1180   const a_op_info *oi = a_map_fetch(o);
1181   if (oi) {
1182    a_map_store(o, o->op_ppaddr, oi->next, oi->flags);
1183    o->op_ppaddr = new_pp;
1184   }
1185  }
1186
1187  return;
1188 }
1189
1190 /* ... ck_pad{any,sv} ...................................................... */
1191
1192 /* Sadly, the padsv OPs we are interested in don't trigger the padsv check
1193  * function, but are instead manually mutated from a padany. So we store
1194  * the op entry in the op map in the padany check function, and we set their
1195  * op_ppaddr member in our peephole optimizer replacement below. */
1196
1197 static OP *(*a_old_ck_padany)(pTHX_ OP *) = 0;
1198
1199 static OP *a_ck_padany(pTHX_ OP *o) {
1200  UV hint;
1201
1202  o = a_old_ck_padany(aTHX_ o);
1203
1204  hint = a_hint();
1205  if (hint & A_HINT_DO)
1206   a_map_store_root(o, o->op_ppaddr, hint);
1207  else
1208   a_map_delete(o);
1209
1210  return o;
1211 }
1212
1213 static OP *(*a_old_ck_padsv)(pTHX_ OP *) = 0;
1214
1215 static OP *a_ck_padsv(pTHX_ OP *o) {
1216  UV hint;
1217
1218  o = a_old_ck_padsv(aTHX_ o);
1219
1220  hint = a_hint();
1221  if (hint & A_HINT_DO) {
1222   a_map_store_root(o, o->op_ppaddr, hint);
1223   o->op_ppaddr = a_pp_deref;
1224  } else
1225   a_map_delete(o);
1226
1227  return o;
1228 }
1229
1230 /* ... ck_deref (aelem,helem,rv2sv) ........................................ */
1231
1232 /* Those ops appear both at the root and inside an expression but there's no
1233  * way to distinguish both situations. Worse, we can't even know if we are in a
1234  * modifying context, so the expression can't be resolved yet. It will be at the
1235  * first invocation of a_pp_deref() for this expression. */
1236
1237 static OP *(*a_old_ck_aelem)(pTHX_ OP *) = 0;
1238 static OP *(*a_old_ck_helem)(pTHX_ OP *) = 0;
1239 static OP *(*a_old_ck_rv2sv)(pTHX_ OP *) = 0;
1240
1241 static OP *a_ck_deref(pTHX_ OP *o) {
1242  OP * (*old_ck)(pTHX_ OP *o) = 0;
1243  UV hint = a_hint();
1244
1245  switch (o->op_type) {
1246   case OP_AELEM:
1247    old_ck = a_old_ck_aelem;
1248    if ((hint & A_HINT_DO) && !(hint & A_HINT_STRICT))
1249     a_recheck_rv2xv(cUNOPo->op_first, OP_RV2AV, a_pp_rv2av);
1250    break;
1251   case OP_HELEM:
1252    old_ck = a_old_ck_helem;
1253    if ((hint & A_HINT_DO) && !(hint & A_HINT_STRICT))
1254     a_recheck_rv2xv(cUNOPo->op_first, OP_RV2HV, a_pp_rv2hv_simple);
1255    break;
1256   case OP_RV2SV:
1257    old_ck = a_old_ck_rv2sv;
1258    break;
1259  }
1260  o = old_ck(aTHX_ o);
1261
1262 #if A_HAS_MULTIDEREF
1263  if (old_ck == a_old_ck_rv2sv && o->op_flags & OPf_KIDS) {
1264   OP *kid = cUNOPo->op_first;
1265   if (kid && kid->op_type == OP_GV) {
1266    if (hint & A_HINT_DO)
1267     a_map_store(kid, kid->op_ppaddr, NULL, hint);
1268    else
1269     a_map_delete(kid);
1270   }
1271  }
1272 #endif
1273
1274  if (hint & A_HINT_DO) {
1275   a_map_store_root(o, o->op_ppaddr, hint);
1276   o->op_ppaddr = a_pp_deref;
1277  } else
1278   a_map_delete(o);
1279
1280  return o;
1281 }
1282
1283 /* ... ck_rv2xv (rv2av,rv2hv) .............................................. */
1284
1285 /* Those ops also appear both inisde and at the root, hence the caveats for
1286  * a_ck_deref() still apply here. Since a padsv/rv2sv must appear before a
1287  * rv2[ah]v, resolution is handled by the first call to a_pp_deref() in the
1288  * expression. */
1289
1290 static OP *(*a_old_ck_rv2av)(pTHX_ OP *) = 0;
1291 static OP *(*a_old_ck_rv2hv)(pTHX_ OP *) = 0;
1292
1293 static OP *a_ck_rv2xv(pTHX_ OP *o) {
1294  OP * (*old_ck)(pTHX_ OP *o) = 0;
1295  OP * (*new_pp)(pTHX)        = 0;
1296  UV hint;
1297
1298  switch (o->op_type) {
1299   case OP_RV2AV: old_ck = a_old_ck_rv2av; new_pp = a_pp_rv2av; break;
1300   case OP_RV2HV: old_ck = a_old_ck_rv2hv; new_pp = a_pp_rv2hv_simple; break;
1301  }
1302  o = old_ck(aTHX_ o);
1303
1304  if (cUNOPo->op_first->op_type == OP_GV)
1305   return o;
1306
1307  hint = a_hint();
1308  if (hint & A_HINT_DO && !(hint & A_HINT_STRICT)) {
1309   a_map_store_root(o, o->op_ppaddr, hint);
1310   o->op_ppaddr = new_pp;
1311  } else
1312   a_map_delete(o);
1313
1314  return o;
1315 }
1316
1317 /* ... ck_xslice (aslice,hslice) ........................................... */
1318
1319 /* I think those are only found at the root, but there's nothing that really
1320  * prevent them to be inside the expression too. We only need to update the
1321  * root so that the rest of the expression will see the right context when
1322  * resolving. That's why we don't replace the ppaddr. */
1323
1324 static OP *(*a_old_ck_aslice)(pTHX_ OP *) = 0;
1325 static OP *(*a_old_ck_hslice)(pTHX_ OP *) = 0;
1326
1327 static OP *a_ck_xslice(pTHX_ OP *o) {
1328  OP * (*old_ck)(pTHX_ OP *o) = 0;
1329  UV hint = a_hint();
1330
1331  switch (o->op_type) {
1332   case OP_ASLICE:
1333    old_ck = a_old_ck_aslice;
1334    break;
1335   case OP_HSLICE:
1336    old_ck = a_old_ck_hslice;
1337    if (hint & A_HINT_DO)
1338     a_recheck_rv2xv(OpSIBLING(cUNOPo->op_first), OP_RV2HV, a_pp_rv2hv);
1339    break;
1340  }
1341  o = old_ck(aTHX_ o);
1342
1343  if (hint & A_HINT_DO) {
1344   a_map_store_root(o, 0, hint);
1345  } else
1346   a_map_delete(o);
1347
1348  return o;
1349 }
1350
1351 /* ... ck_root (exists,delete,keys,values) ................................. */
1352
1353 /* Those ops are only found at the root of a dereferencing expression. We can
1354  * then resolve at compile time if vivification must take place or not. */
1355
1356 static OP *(*a_old_ck_exists)(pTHX_ OP *) = 0;
1357 static OP *(*a_old_ck_delete)(pTHX_ OP *) = 0;
1358 static OP *(*a_old_ck_keys)  (pTHX_ OP *) = 0;
1359 static OP *(*a_old_ck_values)(pTHX_ OP *) = 0;
1360
1361 static OP *a_ck_root(pTHX_ OP *o) {
1362  OP * (*old_ck)(pTHX_ OP *o) = 0;
1363  OP * (*new_pp)(pTHX)        = 0;
1364  bool enabled = FALSE;
1365  UV hint = a_hint();
1366
1367  switch (o->op_type) {
1368   case OP_EXISTS:
1369    old_ck  = a_old_ck_exists;
1370    new_pp  = a_pp_root_binop;
1371    enabled = hint & A_HINT_EXISTS;
1372    break;
1373   case OP_DELETE:
1374    old_ck  = a_old_ck_delete;
1375    new_pp  = a_pp_root_binop;
1376    enabled = hint & A_HINT_DELETE;
1377    break;
1378   case OP_KEYS:
1379    old_ck  = a_old_ck_keys;
1380    new_pp  = a_pp_root_unop;
1381    enabled = hint & A_HINT_FETCH;
1382    break;
1383   case OP_VALUES:
1384    old_ck  = a_old_ck_values;
1385    new_pp  = a_pp_root_unop;
1386    enabled = hint & A_HINT_FETCH;
1387    break;
1388  }
1389  o = old_ck(aTHX_ o);
1390
1391  if (hint & A_HINT_DO) {
1392   if (enabled) {
1393    a_map_update_flags_topdown(o, hint | A_HINT_DEREF);
1394    a_map_store_root(o, o->op_ppaddr, hint);
1395    o->op_ppaddr = new_pp;
1396   } else {
1397    a_map_cancel(o);
1398   }
1399  } else
1400   a_map_delete(o);
1401
1402  return o;
1403 }
1404
1405 /* ... Our peephole optimizer .............................................. */
1406
1407 static void a_peep_rec(pTHX_ OP *o, ptable *seen);
1408
1409 static void a_peep_rec(pTHX_ OP *o, ptable *seen) {
1410 #define a_peep_rec(O) a_peep_rec(aTHX_ (O), seen)
1411  for (; o; o = o->op_next) {
1412   dA_MAP_THX;
1413   const a_op_info *oi = NULL;
1414   UV flags = 0;
1415
1416 #if !A_HAS_RPEEP
1417   if (ptable_fetch(seen, o))
1418    break;
1419   ptable_seen_store(seen, o, o);
1420 #endif
1421
1422   switch (o->op_type) {
1423 #if A_HAS_RPEEP
1424    case OP_NEXTSTATE:
1425    case OP_DBSTATE:
1426    case OP_STUB:
1427    case OP_UNSTACK:
1428     if (ptable_fetch(seen, o))
1429      return;
1430     ptable_seen_store(seen, o, o);
1431     break;
1432 #endif
1433    case OP_PADSV:
1434     if (o->op_ppaddr != a_pp_deref) {
1435      oi = a_map_fetch(o);
1436      if (oi && (oi->flags & A_HINT_DO)) {
1437       a_map_store(o, o->op_ppaddr, oi->next, oi->flags);
1438       o->op_ppaddr = a_pp_deref;
1439      }
1440     }
1441     /* FALLTHROUGH */
1442    case OP_AELEM:
1443    case OP_AELEMFAST:
1444    case OP_HELEM:
1445    case OP_RV2SV:
1446     if (o->op_ppaddr != a_pp_deref)
1447      break;
1448     oi = a_map_fetch(o);
1449     if (!oi)
1450      break;
1451     flags = oi->flags;
1452     if (!(flags & A_HINT_DEREF)
1453         && (flags & A_HINT_DO)
1454         && (o->op_private & OPpDEREF || flags & A_HINT_ROOT)) {
1455      /* Decide if the expression must autovivify or not. */
1456      flags = a_map_resolve(o, oi);
1457     }
1458     if (flags & A_HINT_DEREF)
1459      o->op_private = ((o->op_private & ~OPpDEREF) | OPpLVAL_DEFER);
1460     else
1461      o->op_ppaddr  = oi->old_pp;
1462     break;
1463    case OP_RV2AV:
1464    case OP_RV2HV:
1465     if (   o->op_ppaddr != a_pp_rv2av
1466         && o->op_ppaddr != a_pp_rv2hv
1467         && o->op_ppaddr != a_pp_rv2hv_simple)
1468      break;
1469     oi = a_map_fetch(o);
1470     if (!oi)
1471      break;
1472     if (!(oi->flags & A_HINT_DEREF))
1473      o->op_ppaddr  = oi->old_pp;
1474     break;
1475 #if A_HAS_MULTIDEREF
1476    case OP_MULTIDEREF:
1477     if (o->op_ppaddr != a_pp_multideref) {
1478      oi = a_map_fetch(cUNOPo->op_first);
1479      if (!oi)
1480       break;
1481      flags = oi->flags;
1482      if (a_do_multideref(o, flags)) {
1483       a_map_store_root(o, o->op_ppaddr, flags & ~A_HINT_DEREF);
1484       o->op_ppaddr = a_pp_multideref;
1485      }
1486     }
1487     break;
1488 #endif
1489 #if !A_HAS_RPEEP
1490    case OP_MAPWHILE:
1491    case OP_GREPWHILE:
1492    case OP_AND:
1493    case OP_OR:
1494    case OP_ANDASSIGN:
1495    case OP_ORASSIGN:
1496    case OP_COND_EXPR:
1497    case OP_RANGE:
1498 # if A_HAS_PERL(5, 10, 0)
1499    case OP_ONCE:
1500    case OP_DOR:
1501    case OP_DORASSIGN:
1502 # endif
1503     a_peep_rec(cLOGOPo->op_other);
1504     break;
1505    case OP_ENTERLOOP:
1506    case OP_ENTERITER:
1507     a_peep_rec(cLOOPo->op_redoop);
1508     a_peep_rec(cLOOPo->op_nextop);
1509     a_peep_rec(cLOOPo->op_lastop);
1510     break;
1511 # if A_HAS_PERL(5, 9, 5)
1512    case OP_SUBST:
1513     a_peep_rec(cPMOPo->op_pmstashstartu.op_pmreplstart);
1514     break;
1515 # else
1516    case OP_QR:
1517    case OP_MATCH:
1518    case OP_SUBST:
1519     a_peep_rec(cPMOPo->op_pmreplstart);
1520     break;
1521 # endif
1522 #endif /* !A_HAS_RPEEP */
1523    default:
1524     break;
1525   }
1526  }
1527 }
1528
1529 static void a_peep(pTHX_ OP *o) {
1530  ptable *seen;
1531  dMY_CXT;
1532
1533  assert(a_is_loaded(&MY_CXT));
1534
1535  MY_CXT.old_peep(aTHX_ o);
1536
1537  seen = MY_CXT.seen;
1538  if (seen) {
1539   ptable_seen_clear(seen);
1540   a_peep_rec(o);
1541   ptable_seen_clear(seen);
1542  }
1543 }
1544
1545 /* --- Module setup/teardown ----------------------------------------------- */
1546
1547 static void a_teardown(pTHX_ void *root) {
1548  dMY_CXT;
1549
1550  A_LOADED_LOCK;
1551
1552  if (a_clear_loaded_locked(&MY_CXT)) {
1553   a_ck_restore(OP_PADANY, &a_old_ck_padany);
1554   a_ck_restore(OP_PADSV,  &a_old_ck_padsv);
1555
1556   a_ck_restore(OP_AELEM,  &a_old_ck_aelem);
1557   a_ck_restore(OP_HELEM,  &a_old_ck_helem);
1558   a_ck_restore(OP_RV2SV,  &a_old_ck_rv2sv);
1559
1560   a_ck_restore(OP_RV2AV,  &a_old_ck_rv2av);
1561   a_ck_restore(OP_RV2HV,  &a_old_ck_rv2hv);
1562
1563   a_ck_restore(OP_ASLICE, &a_old_ck_aslice);
1564   a_ck_restore(OP_HSLICE, &a_old_ck_hslice);
1565
1566   a_ck_restore(OP_EXISTS, &a_old_ck_exists);
1567   a_ck_restore(OP_DELETE, &a_old_ck_delete);
1568   a_ck_restore(OP_KEYS,   &a_old_ck_keys);
1569   a_ck_restore(OP_VALUES, &a_old_ck_values);
1570
1571   ptable_map_free(a_op_map);
1572   a_op_map = NULL;
1573  }
1574
1575  A_LOADED_UNLOCK;
1576
1577  if (MY_CXT.old_peep) {
1578 #if A_HAS_RPEEP
1579   PL_rpeepp = MY_CXT.old_peep;
1580 #else
1581   PL_peepp  = MY_CXT.old_peep;
1582 #endif
1583   MY_CXT.old_peep = 0;
1584  }
1585
1586  ptable_seen_free(MY_CXT.seen);
1587  MY_CXT.seen = NULL;
1588
1589 #if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
1590  ptable_hints_free(MY_CXT.tbl);
1591  MY_CXT.tbl  = NULL;
1592 #endif /* A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION */
1593
1594  return;
1595 }
1596
1597 static void a_setup(pTHX) {
1598 #define a_setup() a_setup(aTHX)
1599  MY_CXT_INIT; /* Takes/release PL_my_ctx_mutex */
1600
1601  A_LOADED_LOCK;
1602
1603  if (a_set_loaded_locked(&MY_CXT)) {
1604   PERL_HASH(a_hash, __PACKAGE__, __PACKAGE_LEN__);
1605
1606   a_op_map = ptable_new();
1607 #ifdef USE_ITHREADS
1608   MUTEX_INIT(&a_op_map_mutex);
1609 #endif
1610
1611   a_ck_replace(OP_PADANY, a_ck_padany, &a_old_ck_padany);
1612   a_ck_replace(OP_PADSV,  a_ck_padsv,  &a_old_ck_padsv);
1613
1614   a_ck_replace(OP_AELEM,  a_ck_deref,  &a_old_ck_aelem);
1615   a_ck_replace(OP_HELEM,  a_ck_deref,  &a_old_ck_helem);
1616   a_ck_replace(OP_RV2SV,  a_ck_deref,  &a_old_ck_rv2sv);
1617
1618   a_ck_replace(OP_RV2AV,  a_ck_rv2xv,  &a_old_ck_rv2av);
1619   a_ck_replace(OP_RV2HV,  a_ck_rv2xv,  &a_old_ck_rv2hv);
1620
1621   a_ck_replace(OP_ASLICE, a_ck_xslice, &a_old_ck_aslice);
1622   a_ck_replace(OP_HSLICE, a_ck_xslice, &a_old_ck_hslice);
1623
1624   a_ck_replace(OP_EXISTS, a_ck_root,   &a_old_ck_exists);
1625   a_ck_replace(OP_DELETE, a_ck_root,   &a_old_ck_delete);
1626   a_ck_replace(OP_KEYS,   a_ck_root,   &a_old_ck_keys);
1627   a_ck_replace(OP_VALUES, a_ck_root,   &a_old_ck_values);
1628  }
1629
1630  A_LOADED_UNLOCK;
1631
1632  {
1633   HV *stash;
1634
1635   stash = gv_stashpvn(__PACKAGE__, __PACKAGE_LEN__, 1);
1636   newCONSTSUB(stash, "A_HINT_STRICT", newSVuv(A_HINT_STRICT));
1637   newCONSTSUB(stash, "A_HINT_WARN",   newSVuv(A_HINT_WARN));
1638   newCONSTSUB(stash, "A_HINT_FETCH",  newSVuv(A_HINT_FETCH));
1639   newCONSTSUB(stash, "A_HINT_STORE",  newSVuv(A_HINT_STORE));
1640   newCONSTSUB(stash, "A_HINT_EXISTS", newSVuv(A_HINT_EXISTS));
1641   newCONSTSUB(stash, "A_HINT_DELETE", newSVuv(A_HINT_DELETE));
1642   newCONSTSUB(stash, "A_HINT_MASK",   newSVuv(A_HINT_MASK));
1643   newCONSTSUB(stash, "A_THREADSAFE",  newSVuv(A_THREADSAFE));
1644   newCONSTSUB(stash, "A_FORKSAFE",    newSVuv(A_FORKSAFE));
1645  }
1646
1647 #if A_HAS_RPEEP
1648  if (PL_rpeepp != a_peep) {
1649   MY_CXT.old_peep = PL_rpeepp;
1650   PL_rpeepp       = a_peep;
1651  }
1652 #else
1653  if (PL_peepp != a_peep) {
1654   MY_CXT.old_peep = PL_peepp;
1655   PL_peepp        = a_peep;
1656  }
1657 #endif
1658  else {
1659   MY_CXT.old_peep = 0;
1660  }
1661
1662  MY_CXT.seen = ptable_new();
1663
1664 #if A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION
1665  MY_CXT.tbl   = ptable_new();
1666  MY_CXT.owner = aTHX;
1667 #endif /* A_THREADSAFE && A_WORKAROUND_REQUIRE_PROPAGATION */
1668
1669  call_atexit(a_teardown, NULL);
1670
1671  return;
1672 }
1673
1674 /* --- XS ------------------------------------------------------------------ */
1675
1676 MODULE = autovivification      PACKAGE = autovivification
1677
1678 PROTOTYPES: ENABLE
1679
1680 BOOT:
1681 {
1682  a_setup();
1683 }
1684
1685 #if A_THREADSAFE
1686
1687 void
1688 CLONE(...)
1689 PROTOTYPE: DISABLE
1690 PREINIT:
1691 #if A_WORKAROUND_REQUIRE_PROPAGATION
1692  ptable *t;
1693 #endif
1694 PPCODE:
1695 #if A_WORKAROUND_REQUIRE_PROPAGATION
1696  {
1697   a_ptable_clone_ud ud;
1698   dMY_CXT;
1699   t = ptable_new();
1700   a_ptable_clone_ud_init(ud, t, MY_CXT.owner);
1701   ptable_walk(MY_CXT.tbl, a_ptable_clone, &ud);
1702   a_ptable_clone_ud_deinit(ud);
1703  }
1704 #endif
1705  {
1706   MY_CXT_CLONE;
1707 #if A_WORKAROUND_REQUIRE_PROPAGATION
1708   MY_CXT.tbl   = t;
1709   MY_CXT.owner = aTHX;
1710 #endif
1711   MY_CXT.seen  = ptable_new();
1712   {
1713    int global_setup;
1714    A_LOADED_LOCK;
1715    global_setup = a_set_loaded_locked(&MY_CXT);
1716    assert(!global_setup);
1717    A_LOADED_UNLOCK;
1718   }
1719  }
1720  XSRETURN(0);
1721
1722 #endif /* A_THREADSAFE */
1723
1724 SV *
1725 _tag(SV *hint)
1726 PROTOTYPE: $
1727 CODE:
1728  RETVAL = a_tag(SvOK(hint) ? SvUV(hint) : 0);
1729 OUTPUT:
1730  RETVAL
1731
1732 SV *
1733 _detag(SV *tag)
1734 PROTOTYPE: $
1735 CODE:
1736  if (!SvOK(tag))
1737   XSRETURN_UNDEF;
1738  RETVAL = newSVuv(a_detag(tag));
1739 OUTPUT:
1740  RETVAL