forked from facebook/hhvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathframe-state.cpp
More file actions
1591 lines (1367 loc) · 49 KB
/
frame-state.cpp
File metadata and controls
1591 lines (1367 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/frame-state.h"
#include "hphp/runtime/vm/jit/alias-class.h"
#include "hphp/runtime/vm/jit/analysis.h"
#include "hphp/runtime/vm/jit/cfg.h"
#include "hphp/runtime/vm/jit/ir-instruction.h"
#include "hphp/runtime/vm/jit/location.h"
#include "hphp/runtime/vm/jit/memory-effects.h"
#include "hphp/runtime/vm/jit/minstr-effects.h"
#include "hphp/runtime/vm/jit/simplify.h"
#include "hphp/runtime/vm/jit/ssa-tmp.h"
#include "hphp/runtime/vm/jit/stack-offsets.h"
#include "hphp/runtime/vm/jit/translator.h"
#include "hphp/util/dataflow-worklist.h"
#include "hphp/util/trace.h"
#include <boost/range/adaptor/reversed.hpp>
#include <folly/Optional.h>
#include <algorithm>
TRACE_SET_MOD(hhir);
namespace HPHP { namespace jit { namespace irgen {
namespace {
using Trace::Indent;
///////////////////////////////////////////////////////////////////////////////
/*
* Helper that sets a value to a new value and also returns whether it changed.
*/
template<class T>
bool merge_util(T& oldVal, const T& newVal) {
auto changed = oldVal != newVal;
oldVal = newVal;
return changed;
}
/*
* Merge TypeSourceSets, returning whether anything changed.
*
* TypeSourceSets are merged a join points by unioning the type sources. The
* reason for this is that if a type is constrained, we need to be able to find
* "all" possible sources of the type and constrain them.
*/
bool merge_into(TypeSourceSet& dst, const TypeSourceSet& src) {
auto changed = false;
for (auto x : src) changed = dst.insert(x).second || changed;
return changed;
}
/*
* Merge LocationStates, returning whether anything changed.
*/
template<LTag tag>
bool merge_into(LocationState<tag>& dst, const LocationState<tag>& src) {
auto changed = false;
changed |= merge_util(dst.type, dst.type | src.type);
// Get the least common ancestor across both states.
changed |= merge_util(dst.value, least_common_ancestor(dst.value, src.value));
// We may have changed either dst.value or dst.type in a way that could fail
// to preserve LocationState invariants. So check if we can't keep the value.
if (dst.value != nullptr && dst.value->type() != dst.type) {
dst.value = nullptr;
changed = true;
}
changed |= merge_into(dst.typeSrcs, src.typeSrcs);
if (!dst.maybeChanged && src.maybeChanged) {
dst.maybeChanged = true;
changed = true;
}
changed |= merge_util(dst.predictedType,
dst.predictedType | src.predictedType);
return changed;
}
bool merge_memory_stack_into(jit::vector<StackState>& dst,
const jit::vector<StackState>& src) {
auto changed = false;
// We may need to merge different-sized memory stacks, because a predecessor
// may not touch some stack memory that another pred did. We just need to
// conservatively throw away slots that aren't tracked on all preds.
auto const result_size = std::min(dst.size(), src.size());
dst.resize(result_size);
for (auto i = uint32_t{0}; i < result_size; ++i) {
changed |= merge_into(dst[i], src[i]);
}
return changed;
}
/*
* Merge one FrameState into another, returning whether it changed. Frame
* pointers and stack depth must match. If the stack pointer tmps are
* different, clear the tracked value (we can make a new one, given fp and
* irSPOff).
*/
bool merge_into(FrameState& dst, const FrameState& src) {
auto changed = false;
// Cannot merge irSPOff state, so assert they match.
always_assert(dst.irSPOff == src.irSPOff);
always_assert(dst.curFunc == src.curFunc);
// The only thing that can change the FP is inlining, but we can't have one
// of the predecessors in an inlined callee while the other isn't.
always_assert(dst.fpValue == src.fpValue);
// FrameState for the same function must always have the same number of
// locals.
always_assert(src.locals.size() == dst.locals.size());
// We must always have the same spValue.
always_assert(dst.spValue == src.spValue);
if (dst.needRatchet != src.needRatchet) {
dst.needRatchet = true;
changed = true;
}
if (dst.mbase.value != src.mbase.value) {
dst.mbase.value = nullptr;
changed = true;
}
if (dst.mbr.ptr != src.mbr.ptr) {
dst.mbr.ptr = nullptr;
changed = true;
}
changed |= merge_util(dst.mbr.pointee, dst.mbr.pointee | src.mbr.pointee);
changed |= merge_util(dst.mbr.ptrType, dst.mbr.ptrType | src.mbr.ptrType);
// The tracked FPI state must always be the same, notice that the size of the
// FPI stacks may differ as the FPush associated with one of the merged blocks
// may be outside the region. In this case we must drop the unknown state.
dst.fpiStack.resize(std::min(dst.fpiStack.size(), src.fpiStack.size()));
for (int i = 0; i < dst.fpiStack.size(); ++i) {
auto& dstInfo = dst.fpiStack[i];
auto const& srcInfo = src.fpiStack[i];
always_assert(dstInfo.returnSP == srcInfo.returnSP);
always_assert(dstInfo.returnSPOff == srcInfo.returnSPOff);
always_assert(isFPush(dstInfo.fpushOpc) &&
dstInfo.fpushOpc == srcInfo.fpushOpc);
// If one of the merged edges was interp'ed mark the result as interp'ed
if (!dstInfo.interp && srcInfo.interp) {
dstInfo.interp = true;
changed = true;
}
// If one of the merged edges spans a call then mark them both as spanning
if (!dstInfo.spansCall && srcInfo.spansCall) {
dstInfo.spansCall = true;
changed = true;
}
// Merge the contexts from the respective spills
if (dstInfo.ctx != srcInfo.ctx) {
dstInfo.ctx = least_common_ancestor(dstInfo.ctx, srcInfo.ctx);
changed = true;
}
if (dstInfo.ctxType != srcInfo.ctxType) {
dstInfo.ctxType |= srcInfo.ctxType;
changed = true;
}
// Merge the Funcs
if (dstInfo.func != nullptr && dstInfo.func != srcInfo.func) {
dstInfo.func = nullptr;
changed = true;
}
}
// This is available iff it's available in both states
changed |= merge_util(dst.thisAvailable,
dst.thisAvailable && src.thisAvailable);
// The frame may span a call if it could have done so in either state.
changed |= merge_util(dst.frameMaySpanCall,
dst.frameMaySpanCall || src.frameMaySpanCall);
for (auto i = uint32_t{0}; i < src.locals.size(); ++i) {
changed |= merge_into(dst.locals[i], src.locals[i]);
}
changed |= merge_memory_stack_into(dst.stack, src.stack);
changed |= merge_util(dst.stackModified,
dst.stackModified || src.stackModified);
// Eval stack depth should be the same at merge points.
assertx(dst.bcSPOff == src.bcSPOff);
for (auto const& srcPair : src.predictedTypes) {
auto dstIt = dst.predictedTypes.find(srcPair.first);
if (dstIt == dst.predictedTypes.end()) {
dst.predictedTypes.emplace(srcPair);
changed = true;
continue;
}
auto const newType = dstIt->second | srcPair.second;
if (newType != dstIt->second) {
dstIt->second = newType;
changed = true;
}
}
return changed;
}
/*
* Merge two state-stacks. The stacks must have the same depth. Returns
* whether any states changed.
*/
bool merge_into(jit::vector<FrameState>& dst, const jit::vector<FrameState>& src) {
always_assert(src.size() == dst.size());
auto changed = false;
for (auto idx = uint32_t{0}; idx < dst.size(); ++idx) {
changed |= merge_into(dst[idx], src[idx]);
}
return changed;
}
///////////////////////////////////////////////////////////////////////////////
bool check_invariants(const FrameState& state) {
for (auto id = uint32_t{0}; id < state.locals.size(); ++id) {
auto const& local = state.locals[id];
always_assert_flog(
local.predictedType <= local.type,
"local {} failed prediction invariants; pred = {}, type = {}\n",
id,
local.predictedType,
local.type
);
always_assert_flog(
local.value == nullptr || local.value->type() == local.type,
"local {} had type {}, but value {}\n",
id,
local.type,
local.value->toString()
);
if (state.curFunc->isPseudoMain()) {
always_assert_flog(
local.value == nullptr,
"We should never be tracking values for locals in a pseudomain "
"right now. Local {} had value {}",
id,
local.value->toString()
);
always_assert_flog(
local.type == TGen,
"We should never be tracking non-predicted types for locals in "
"a pseudomain right now. Local {} had type {}",
id,
local.type.toString()
);
}
}
// We require the memory stack is always at least as big as the irSPOff,
// unless irSPOff went negative (because we're returning and have freed the
// ActRec). Note that there are some "wasted" slots where locals/iterators
// would be in the vector right now.
always_assert_flog(
state.irSPOff < FPInvOffset{0} ||
state.stack.size() >= state.irSPOff.offset,
"stack was smaller than possible"
);
return true;
}
///////////////////////////////////////////////////////////////////////////////
/*
* Recompute a predicted type for when the proven type changes (or when a new
* prediction is made and we want to discard the old one).
*
* This maintains the invariant `predicted <= proven'.
*/
Type updatePrediction(Type predicted, Type proven) {
always_assert(predicted != TBottom);
return predicted < proven ? predicted : proven;
}
/*
* Compute the refinement of `oldPredicted' with `newPredicted', maintaining
* the invariant that `refined <= proven'.
*/
Type refinePrediction(Type oldPredicted, Type newPredicted, Type proven) {
auto refined = oldPredicted & newPredicted;
if (refined == TBottom) refined = newPredicted;
return updatePrediction(refined, proven);
}
///////////////////////////////////////////////////////////////////////////////
}
FrameStateMgr::FrameStateMgr(BCMarker marker) {
m_stack.push_back(FrameState{});
cur().curFunc = marker.func();
cur().irSPOff = marker.spOff();
cur().bcSPOff = marker.spOff();
cur().locals.resize(marker.func()->numLocals());
cur().stack.resize(marker.spOff().offset);
}
void FrameStateMgr::update(const IRInstruction* inst) {
ITRACE(3, "FrameStateMgr::update processing {}\n", *inst);
Indent _i;
if (auto const taken = inst->taken()) {
/*
* TODO(#4323657): we should make this assertion for all non-empty blocks
* (exits in addition to catches). It would fail right now for exit
* traces.
*
* If you hit this assertion: you've created a catch block and then
* modified tracked state, then generated a potentially exception-throwing
* instruction using that catch block as a target. This is not allowed.
*/
if (debug && taken->isCatch()) {
auto const tmp = save(taken);
always_assert_flog(
!tmp,
"catch block B{} had non-matching in state",
taken->id()
);
}
// When we're building the IR, we append a conditional jump after
// generating its target block: see emitJmpCondHelper, where we
// call makeExit() before gen(JmpZero). It doesn't make sense to
// update the target block state at this point, so don't. The
// state doesn't have this problem during optimization passes,
// because we'll always process the jump before the target block.
if (taken->empty()) save(taken);
}
auto killIterLocals = [&](const std::initializer_list<uint32_t>& ids) {
for (auto id : ids) {
setValue(loc(id), nullptr);
}
};
assertx(checkInvariants());
switch (inst->op()) {
case DefInlineFP: trackDefInlineFP(inst); break;
case InlineReturn: trackInlineReturn(); break;
case Call:
{
auto const extra = inst->extra<Call>();
// Remove tracked state for the slots for args and the actrec.
for (auto i = uint32_t{0}; i < kNumActRecCells + extra->numParams; ++i) {
setValue(stk(extra->spOffset + i), nullptr);
}
trackCall(extra->destroyLocals);
// The return value is known to be at least a Gen.
setType(
stk(extra->spOffset + kNumActRecCells + extra->numParams - 1),
TGen
);
// We consider popping an ActRec and args to be synced to memory.
assertx(cur().bcSPOff == inst->marker().spOff());
cur().bcSPOff -= extra->numParams + kNumActRecCells;
if (!cur().fpiStack.empty()) {
cur().fpiStack.pop_back();
}
for (auto& st : m_stack) {
for (auto& fpi : st.fpiStack) fpi.spansCall = true;
}
}
break;
case CallArray:
{
auto const extra = inst->extra<CallArray>();
// Remove tracked state for the actrec and array arg.
uint32_t numCells = kNumActRecCells +
(extra->numParams ? extra->numParams : 1);
for (auto i = uint32_t{0}; i < numCells; ++i) {
setValue(stk(extra->spOffset + i), nullptr);
}
trackCall(extra->destroyLocals);
setType(stk(extra->spOffset + numCells - 1), TGen);
// A CallArray pops the ActRec, actual args, and an array arg.
assertx(cur().bcSPOff == inst->marker().spOff());
cur().bcSPOff -= numCells;
if (!cur().fpiStack.empty()) {
cur().fpiStack.pop_back();
}
for (auto& st : m_stack) {
for (auto& fpi : st.fpiStack) fpi.spansCall = true;
}
}
break;
case CallBuiltin:
if (inst->extra<CallBuiltin>()->destroyLocals) clearLocals();
break;
case ContEnter:
{
auto const extra = inst->extra<ContEnter>();
trackCall(false);
setType(stk(extra->spOffset), TGen);
// ContEnter pops a cell and pushes a yielded value.
assertx(cur().bcSPOff == inst->marker().spOff());
}
break;
case DefFP:
case FreeActRec:
cur().fpValue = inst->dst();
break;
case RetCtrl:
cur().spValue = nullptr;
cur().fpValue = nullptr;
break;
case DefSP:
cur().spValue = inst->dst();
cur().irSPOff = inst->extra<DefSP>()->offset;
break;
case StMem:
// If we ever start using StMem to store to pointers that might be
// stack/locals, we have to update tracked state here.
always_assert(!inst->src(0)->type().maybe(TPtrToFrameGen));
always_assert(!inst->src(0)->type().maybe(TPtrToStkGen));
break;
case LdStk:
{
auto const offset = inst->extra<LdStk>()->offset;
auto const& state = stack(offset);
refinePredictedTmpType(inst->dst(), state.predictedType);
// Nearly all callers of setValue() for stack slots represent a
// modification of the stack, so it sets stackModified. LdStk is the one
// exception, so we compensate for that here.
auto oldModified = cur().stackModified;
setValue(stk(offset), inst->dst());
cur().stackModified = oldModified;
}
break;
case StStk:
setValue(stk(inst->extra<StStk>()->offset), inst->src(1));
break;
case CheckType:
case AssertType:
for (auto& frame : m_stack) {
for (auto& state : frame.locals) {
refineValue(state, inst->src(0), inst->dst());
}
for (auto& state : frame.stack) {
refineValue(state, inst->src(0), inst->dst());
}
}
break;
case CheckStk:
case AssertStk:
refineType(stk(inst->extra<IRSPRelOffsetData>()->offset),
inst->typeParam(),
TypeSource::makeGuard(inst));
break;
case AssertLoc:
case CheckLoc: {
auto const id = inst->extra<LocalId>()->locId;
if (inst->marker().func()->isPseudoMain()) {
setLocalPredictedType(id, inst->typeParam());
} else {
refineType(loc(id), inst->typeParam(), TypeSource::makeGuard(inst));
}
} break;
case HintStkInner:
setBoxedPrediction(stk(inst->extra<HintStkInner>()->offset),
inst->typeParam());
break;
case HintLocInner:
setBoxedPrediction(loc(inst->extra<HintLocInner>()->locId),
inst->typeParam());
break;
case StLoc:
setValue(loc(inst->extra<LocalId>()->locId), inst->src(1));
break;
case LdLoc:
{
auto const id = inst->extra<LdLoc>()->locId;
refinePredictedTmpType(inst->dst(), cur().locals[id].predictedType);
setValue(loc(id), inst->dst());
}
break;
case StLocPseudoMain:
setLocalPredictedType(inst->extra<LocalId>()->locId,
inst->src(1)->type());
break;
case CastStk:
setType(stk(inst->extra<CastStk>()->offset), inst->typeParam());
break;
case CoerceStk:
setType(stk(inst->extra<CoerceStk>()->offset), inst->typeParam());
break;
case StRef:
updateLocalRefPredictions(inst->src(0), inst->src(1));
break;
case CastMem:
case CoerceMem: {
auto addr = inst->src(0);
if (!addr->inst()->is(LdLocAddr)) break;
auto locId = addr->inst()->extra<LdLocAddr>()->locId;
setValue(loc(locId), nullptr);
setType(loc(locId), inst->typeParam());
break;
}
case EndCatch:
/*
* Hitting this means we've messed up with syncing the stack in a catch
* trace. If the stack isn't clean or doesn't match the marker's irSPOff,
* the unwinder won't see what we expect.
*/
always_assert_flog(
inst->extra<EndCatch>()->offset.to<FPInvOffset>(cur().irSPOff) ==
inst->marker().spOff(),
"EndCatch stack didn't seem right:\n"
" spOff: {}\n"
" EndCatch offset: {}\n"
" marker's spOff: {}\n",
cur().irSPOff.offset,
inst->extra<EndCatch>()->offset.offset,
inst->marker().spOff().offset
);
break;
case CufIterSpillFrame:
spillFrameStack(inst->extra<CufIterSpillFrame>()->spOffset,
cur().irSPOff, inst);
break;
case SpillFrame:
spillFrameStack(inst->extra<SpillFrame>()->spOffset,
cur().bcSPOff, inst);
break;
case InterpOne:
case InterpOneCF: {
auto const& extra = *inst->extra<InterpOneData>();
if (isFPush(extra.opcode)) {
cur().fpiStack.push_back(FPIInfo { cur().spValue,
cur().irSPOff,
TCtx,
nullptr,
extra.opcode,
nullptr,
true /* interp */,
false /* spansCall */});
} else if (isFCallStar(extra.opcode) && !cur().fpiStack.empty()) {
cur().fpiStack.pop_back();
}
assertx(!extra.smashesAllLocals || extra.nChangedLocals == 0);
if (extra.smashesAllLocals || inst->marker().func()->isPseudoMain()) {
clearLocals();
} else {
auto it = extra.changedLocals;
auto const end = it + extra.nChangedLocals;
for (; it != end; ++it) {
auto& local = *it;
// If changing the inner type of a boxed local, also drop the
// information about inner types for any other boxed locals.
if (local.type <= TBoxedCell) dropLocalRefsInnerTypes();
setType(loc(local.id), local.type);
}
}
// Offset of the bytecode stack top relative to the IR stack pointer.
auto const bcSPOff = extra.spOffset;
// Clear tracked information for slots pushed and popped.
for (auto i = uint32_t{0}; i < extra.cellsPopped; ++i) {
setValue(stk(bcSPOff + i), nullptr);
}
for (auto i = uint32_t{0}; i < extra.cellsPushed; ++i) {
setValue(stk(bcSPOff + extra.cellsPopped - 1 - i), nullptr);
}
auto adjustedTop = bcSPOff + extra.cellsPopped - extra.cellsPushed;
switch (extra.opcode) {
case Op::CGetL2:
setType(stk(adjustedTop + 1), inst->typeParam());
break;
case Op::CGetL3:
setType(stk(adjustedTop + 2), inst->typeParam());
break;
default:
// We don't track cells pushed by interp one except the top of the
// stack, aside from the above special cases.
if (inst->hasTypeParam()) {
auto const instrInfo = getInstrInfo(extra.opcode);
if (instrInfo.out & InstrFlags::Stack1) {
setType(stk(adjustedTop), inst->typeParam());
}
}
break;
}
cur().bcSPOff += extra.cellsPushed;
cur().bcSPOff -= extra.cellsPopped;
if (isMemberBaseOp(extra.opcode) || isMemberDimOp(extra.opcode) ||
isMemberFinalOp(extra.opcode)) {
cur().mbr = MBRState{};
cur().mbase = MBaseState{};
}
break;
}
case CheckCtxThis:
cur().thisAvailable = true;
break;
case IterInitK:
case WIterInitK:
// kill the locals to which this instruction stores iter's key and value
killIterLocals({inst->extra<IterData>()->keyId,
inst->extra<IterData>()->valId});
break;
case IterInit:
case WIterInit:
// kill the local to which this instruction stores iter's value
killIterLocals({inst->extra<IterData>()->valId});
break;
case IterNextK:
case WIterNextK:
// kill the locals to which this instruction stores iter's key and value
killIterLocals({inst->extra<IterData>()->keyId,
inst->extra<IterData>()->valId});
break;
case IterNext:
case WIterNext:
// kill the local to which this instruction stores iter's value
killIterLocals({inst->extra<IterData>()->valId});
break;
case StMBase: {
auto const mbr = inst->src(0);
cur().mbr.ptr = mbr;
cur().mbr.pointee = mbr ? pointee(mbr) : AUnknownTV;
cur().mbr.ptrType = mbr->type();
cur().mbase.value = nullptr;
} break;
case FinishMemberOp:
cur().mbr = MBRState{};
cur().mbase = MBaseState{};
break;
case VerifyRetFail:
if (!func()->unit()->useStrictTypes()) {
// In PHP 7 mode scalar types can sometimes coerce; we do this during the
// VerifyRetFail call -- we never allow this in HH files.
auto const offset = BCSPRelOffset{0}
.to<FPInvOffset>(inst->marker().spOff())
.to<IRSPRelOffset>(irSPOff());
setType(stk(offset), TGen);
}
break;
case VerifyParamFail:
if (!func()->unit()->isHHFile() && !RuntimeOption::EnableHipHopSyntax &&
RuntimeOption::PHP7_ScalarTypes) {
// In PHP 7 mode scalar types can sometimes coerce; we do this during the
// VerifyParamFail call -- we never allow this in HH files.
auto id = inst->src(0)->intVal();
setType(loc(id), TGen);
}
break;
default:
if (MInstrEffects::supported(inst)) {
updateMInstr(inst);
}
break;
}
}
void FrameStateMgr::updateMInstr(const IRInstruction* inst) {
// We don't update tracked local types for pseudomains, but we do care about
// stack types.
auto const isPM = cur().curFunc->isPseudoMain();
auto const baseTmp = inst->src(minstrBaseIdx(inst->op()));
if (!baseTmp->type().maybe(TPtrToGen)) return;
auto const base = pointee(baseTmp);
auto const effect_on = [&] (Type ty) -> folly::Optional<Type> {
auto const effects = MInstrEffects(inst->op(), ty);
if (effects.baseTypeChanged || effects.baseValChanged) {
return effects.baseType;
}
return folly::none;
};
if (base.isSingleLocation()) {
// When the member base register refers to a single known memory location
// `l' (with corresponding Ptr type `kind'), we apply the effect of `inst'
// only to `l'. Returns the base value type if `inst' had an effect.
auto const apply_one = [&] (Location l, Ptr kind) -> folly::Optional<Type> {
auto const oldTy = typeOf(l) & TGen; // exclude TCls from ptr()
if (auto const ptrTy = effect_on(oldTy.ptr(kind))) {
auto const baseTy = ptrTy->derefIfPtr();
setType(l, baseTy <= TBoxedCell ? TBoxedInitCell : baseTy);
return baseTy;
}
return folly::none;
};
if (auto const bframe = base.frame()) {
if (!isPM) {
auto const l = loc(bframe->ids.singleValue());
if (auto const ty = apply_one(l, Ptr::Frame)) {
if (*ty <= TBoxedCell) setBoxedPrediction(l, *ty);
}
}
}
if (auto const bstack = base.stack()) {
assertx(bstack->size == 1);
auto const l = stk(bstack->offset.to<IRSPRelOffset>(irSPOff()));
apply_one(l, Ptr::Stk);
}
// We don't track anything else.
return;
}
// If we don't know exactly where the base is, we have to be conservative and
// apply the operation to all locals/stack slots that could be affected.
auto const apply = [&] (Location l) {
auto const oldType = typeOf(l);
auto const maxType = [&] {
switch (l.tag()) {
case LTag::Local: return LocationState<LTag::Local>::default_type();
case LTag::Stack: return LocationState<LTag::Stack>::default_type();
}
not_reached();
}();
if (maxType <= oldType) {
// Drop the value and don't bother with precise effects.
return setType(l, oldType);
}
if (oldType <= TBoxedCell) return;
if (auto const baseType = effect_on(oldType)) {
widenType(l, oldType | *baseType);
}
};
if (base.maybe(AFrameAny) && !isPM) {
for (auto i = 0; i < cur().locals.size(); ++i) {
if (base.maybe(AFrame { fp(), i })) {
apply(loc(i));
}
}
}
if (base.maybe(AStackAny)) {
for (auto i = 0; i < cur().stack.size(); ++i) {
// The FPInvOffset of the stack slot is just its 1-indexed slot.
auto const fpRel = -FPInvOffset{i + 1};
if (base.maybe(AStack { fpRel, 1 })) {
apply(stk(fpRel.to<IRSPRelOffset>(irSPOff())));
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
/*
* syncPrediction() is called after we update the predictedType and/or value
* for a LocationState. It looks up the predicted type for the value in
* cur().predictedTypes and ensures both locations have the most refined
* predicted type possible.
*/
template<LTag tag>
void FrameStateMgr::syncPrediction(LocationState<tag>& state) {
if (!state.value) return;
ITRACE(3, "Syncing prediction for {}\n", *state.value);
auto const canonValue = canonical(state.value);
auto& prediction = state.predictedType;
auto& map = cur().predictedTypes;
auto it = map.find(canonValue);
if (it == map.end()) {
ITRACE(4, "No prediction in map; state has {}\n", prediction);
if (prediction < state.default_type()) map.emplace(canonValue, prediction);
return;
}
if (prediction == state.default_type()) {
ITRACE(4, "No prediction in state; map has {}\n", it->second);
prediction = it->second;
return;
}
auto const newPred = prediction & it->second;
ITRACE(3, "New prediction: {} & {} -> {}\n",
prediction, it->second, newPred);
if (newPred == TBottom) return;
if (newPred < prediction) prediction = newPred;
if (newPred < it->second) it->second = newPred;
}
/*
* Collects the post-conditions associated with the current state, which is
* essentially a list of local/stack locations and their known types at the end
* of `block'.
*/
void FrameStateMgr::collectPostConds(Block* block) {
assertx(block->isExitNoThrow());
PostConditions& pConds = m_exitPostConds[block];
pConds.changed.clear();
pConds.refined.clear();
if (sp() != nullptr) {
auto const& lastInst = block->back();
auto const bcSPOff = lastInst.marker().spOff();
auto const resumed = lastInst.marker().resumed();
auto const skipCells = FPInvOffset{resumed ? 0 : func()->numSlotsInFrame()};
auto const evalStkCells = bcSPOff - skipCells;
for (int32_t i = 0; i < evalStkCells; i++) {
auto const bcSPRel = BCSPRelOffset{i};
auto const irSPRel = bcSPRel
.to<FPInvOffset>(bcSPOff)
.to<IRSPRelOffset>(irSPOff());
auto const type = stack(irSPRel).type;
auto const changed = stack(irSPRel).maybeChanged;
if (changed || type < TGen) {
auto const fpRel = bcSPRel.to<FPInvOffset>(bcSPOff);
FTRACE(1, "Stack({}, {}): {} ({})\n", bcSPRel.offset, fpRel.offset,
type, changed ? "changed" : "refined");
auto& vec = changed ? pConds.changed : pConds.refined;
vec.push_back({ Location::Stack{fpRel}, type });
}
}
}
if (fp() != nullptr) {
for (unsigned i = 0; i < func()->numLocals(); i++) {
auto t = local(i).type;
const bool changed = local(i).maybeChanged;
if (changed || t < TGen) {
FTRACE(1, "Local {}: {} ({})\n", i, t.toString(),
changed ? "changed" : "refined");
auto& vec = changed ? pConds.changed : pConds.refined;
vec.push_back({ Location::Local{i}, t });
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Per-block state.
bool FrameStateMgr::hasStateFor(Block* block) const {
return m_states.count(block);
}
void FrameStateMgr::startBlock(Block* block, bool hasUnprocessedPred,
Block* pred) {
ITRACE(3, "FrameStateMgr::startBlock: {}\n", block->id());
auto const it = m_states.find(block);
auto const end = m_states.end();
if (it != end) {
always_assert_flog(
block->empty(),
"tried to startBlock a non-empty block while building\n"
);
ITRACE(4, "Loading state for B{}: {}\n", block->id(), show(*this));
m_stack = it->second.in;
if (m_stack.empty()) {
always_assert_flog(0, "invalid startBlock for B{}", block->id());
}
} else if (debug || pred) {
save(block, pred);
if (pred) {
assertx(hasStateFor(block));
m_stack = m_states[block].in;
}
}
assertx(!m_stack.empty());
// Reset state if the block has any predecessor that we haven't processed yet.
if (hasUnprocessedPred) {
Indent _;
ITRACE(4, "B{} is a loop header; resetting state\n", block->id());
clearForUnprocessedPred();
}
}
bool FrameStateMgr::finishBlock(Block* block) {
assertx(block->back().isTerminal() == !block->next());
if (block->isExitNoThrow()) {
collectPostConds(block);
FTRACE(2, "PostConditions for exit Block {}:\n{}\n",
block->id(), show(m_exitPostConds[block]));
}
assertx(hasStateFor(block));
if (m_states[block].out) {
assertx(m_states[block].out->empty());
m_states[block].out = m_stack;
}
auto changed = false;
if (!block->back().isTerminal()) changed |= save(block->next());
return changed;
}
void FrameStateMgr::setSaveOutState(Block* block) {
assertx(hasStateFor(block));
assertx(!m_states[block].out || m_states[block].out->empty());
m_states[block].out.emplace();
}
void FrameStateMgr::pauseBlock(Block* block) {
// Note: this can't use std::move, because pauseBlock must leave the current
// state alone so startBlock can use it as the in state for another block.
m_states[block].paused = m_stack;
}
void FrameStateMgr::unpauseBlock(Block* block) {
assertx(hasStateFor(block));
m_stack = *m_states[block].paused;
}
const PostConditions& FrameStateMgr::postConds(Block* exitBlock) const {
assertx(exitBlock->isExitNoThrow());
auto it = m_exitPostConds.find(exitBlock);