forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemorySSA.cpp
2686 lines (2340 loc) · 98.1 KB
/
MemorySSA.cpp
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
//===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the MemorySSA class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/iterator.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/Analysis/IteratedDominanceFrontier.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Use.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <iterator>
#include <memory>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "memoryssa"
static cl::opt<std::string>
DotCFGMSSA("dot-cfg-mssa",
cl::value_desc("file name for generated dot file"),
cl::desc("file name for generated dot file"), cl::init(""));
INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
true)
INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
"Memory SSA Printer", false, false)
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
"Memory SSA Printer", false, false)
static cl::opt<unsigned> MaxCheckLimit(
"memssa-check-limit", cl::Hidden, cl::init(100),
cl::desc("The maximum number of stores/phis MemorySSA"
"will consider trying to walk past (default = 100)"));
// Always verify MemorySSA if expensive checking is enabled.
#ifdef EXPENSIVE_CHECKS
bool llvm::VerifyMemorySSA = true;
#else
bool llvm::VerifyMemorySSA = false;
#endif
static cl::opt<bool, true>
VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
cl::Hidden, cl::desc("Enable verification of MemorySSA."));
const static char LiveOnEntryStr[] = "liveOnEntry";
namespace {
/// An assembly annotator class to print Memory SSA information in
/// comments.
class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
const MemorySSA *MSSA;
public:
MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
void emitBasicBlockStartAnnot(const BasicBlock *BB,
formatted_raw_ostream &OS) override {
if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
OS << "; " << *MA << "\n";
}
void emitInstructionAnnot(const Instruction *I,
formatted_raw_ostream &OS) override {
if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
OS << "; " << *MA << "\n";
}
};
/// An assembly annotator class to print Memory SSA information in
/// comments.
class MemorySSAWalkerAnnotatedWriter : public AssemblyAnnotationWriter {
MemorySSA *MSSA;
MemorySSAWalker *Walker;
public:
MemorySSAWalkerAnnotatedWriter(MemorySSA *M)
: MSSA(M), Walker(M->getWalker()) {}
void emitInstructionAnnot(const Instruction *I,
formatted_raw_ostream &OS) override {
if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
MemoryAccess *Clobber = Walker->getClobberingMemoryAccess(MA);
OS << "; " << *MA;
if (Clobber) {
OS << " - clobbered by ";
if (MSSA->isLiveOnEntryDef(Clobber))
OS << LiveOnEntryStr;
else
OS << *Clobber;
}
OS << "\n";
}
}
};
} // namespace
namespace {
/// Our current alias analysis API differentiates heavily between calls and
/// non-calls, and functions called on one usually assert on the other.
/// This class encapsulates the distinction to simplify other code that wants
/// "Memory affecting instructions and related data" to use as a key.
/// For example, this class is used as a densemap key in the use optimizer.
class MemoryLocOrCall {
public:
bool IsCall = false;
MemoryLocOrCall(MemoryUseOrDef *MUD)
: MemoryLocOrCall(MUD->getMemoryInst()) {}
MemoryLocOrCall(const MemoryUseOrDef *MUD)
: MemoryLocOrCall(MUD->getMemoryInst()) {}
MemoryLocOrCall(Instruction *Inst) {
if (auto *C = dyn_cast<CallBase>(Inst)) {
IsCall = true;
Call = C;
} else {
IsCall = false;
// There is no such thing as a memorylocation for a fence inst, and it is
// unique in that regard.
if (!isa<FenceInst>(Inst))
Loc = MemoryLocation::get(Inst);
}
}
explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
const CallBase *getCall() const {
assert(IsCall);
return Call;
}
MemoryLocation getLoc() const {
assert(!IsCall);
return Loc;
}
bool operator==(const MemoryLocOrCall &Other) const {
if (IsCall != Other.IsCall)
return false;
if (!IsCall)
return Loc == Other.Loc;
if (Call->getCalledOperand() != Other.Call->getCalledOperand())
return false;
return Call->arg_size() == Other.Call->arg_size() &&
std::equal(Call->arg_begin(), Call->arg_end(),
Other.Call->arg_begin());
}
private:
union {
const CallBase *Call;
MemoryLocation Loc;
};
};
} // end anonymous namespace
namespace llvm {
template <> struct DenseMapInfo<MemoryLocOrCall> {
static inline MemoryLocOrCall getEmptyKey() {
return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
}
static inline MemoryLocOrCall getTombstoneKey() {
return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
}
static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
if (!MLOC.IsCall)
return hash_combine(
MLOC.IsCall,
DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
hash_code hash =
hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
MLOC.getCall()->getCalledOperand()));
for (const Value *Arg : MLOC.getCall()->args())
hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
return hash;
}
static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
return LHS == RHS;
}
};
} // end namespace llvm
/// This does one-way checks to see if Use could theoretically be hoisted above
/// MayClobber. This will not check the other way around.
///
/// This assumes that, for the purposes of MemorySSA, Use comes directly after
/// MayClobber, with no potentially clobbering operations in between them.
/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
static bool areLoadsReorderable(const LoadInst *Use,
const LoadInst *MayClobber) {
bool VolatileUse = Use->isVolatile();
bool VolatileClobber = MayClobber->isVolatile();
// Volatile operations may never be reordered with other volatile operations.
if (VolatileUse && VolatileClobber)
return false;
// Otherwise, volatile doesn't matter here. From the language reference:
// 'optimizers may change the order of volatile operations relative to
// non-volatile operations.'"
// If a load is seq_cst, it cannot be moved above other loads. If its ordering
// is weaker, it can be moved above other loads. We just need to be sure that
// MayClobber isn't an acquire load, because loads can't be moved above
// acquire loads.
//
// Note that this explicitly *does* allow the free reordering of monotonic (or
// weaker) loads of the same address.
bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
AtomicOrdering::Acquire);
return !(SeqCstUse || MayClobberIsAcquire);
}
namespace {
struct ClobberAlias {
bool IsClobber;
Optional<AliasResult> AR;
};
} // end anonymous namespace
// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
// ignored if IsClobber = false.
template <typename AliasAnalysisType>
static ClobberAlias
instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
const Instruction *UseInst, AliasAnalysisType &AA) {
Instruction *DefInst = MD->getMemoryInst();
assert(DefInst && "Defining instruction not actually an instruction");
Optional<AliasResult> AR;
if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
// These intrinsics will show up as affecting memory, but they are just
// markers, mostly.
//
// FIXME: We probably don't actually want MemorySSA to model these at all
// (including creating MemoryAccesses for them): we just end up inventing
// clobbers where they don't really exist at all. Please see D43269 for
// context.
switch (II->getIntrinsicID()) {
case Intrinsic::invariant_start:
case Intrinsic::invariant_end:
case Intrinsic::assume:
case Intrinsic::experimental_noalias_scope_decl:
case Intrinsic::pseudoprobe:
return {false, AliasResult(AliasResult::NoAlias)};
case Intrinsic::dbg_addr:
case Intrinsic::dbg_declare:
case Intrinsic::dbg_label:
case Intrinsic::dbg_value:
llvm_unreachable("debuginfo shouldn't have associated defs!");
default:
break;
}
}
if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) {
ModRefInfo I = AA.getModRefInfo(DefInst, CB);
AR = isMustSet(I) ? AliasResult::MustAlias : AliasResult::MayAlias;
return {isModOrRefSet(I), AR};
}
if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst))
return {!areLoadsReorderable(UseLoad, DefLoad),
AliasResult(AliasResult::MayAlias)};
ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
AR = isMustSet(I) ? AliasResult::MustAlias : AliasResult::MayAlias;
return {isModSet(I), AR};
}
template <typename AliasAnalysisType>
static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
const MemoryUseOrDef *MU,
const MemoryLocOrCall &UseMLOC,
AliasAnalysisType &AA) {
// FIXME: This is a temporary hack to allow a single instructionClobbersQuery
// to exist while MemoryLocOrCall is pushed through places.
if (UseMLOC.IsCall)
return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
AA);
return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
AA);
}
// Return true when MD may alias MU, return false otherwise.
bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
AliasAnalysis &AA) {
return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
}
namespace {
struct UpwardsMemoryQuery {
// True if our original query started off as a call
bool IsCall = false;
// The pointer location we started the query with. This will be empty if
// IsCall is true.
MemoryLocation StartingLoc;
// This is the instruction we were querying about.
const Instruction *Inst = nullptr;
// The MemoryAccess we actually got called with, used to test local domination
const MemoryAccess *OriginalAccess = nullptr;
Optional<AliasResult> AR = AliasResult(AliasResult::MayAlias);
bool SkipSelfAccess = false;
UpwardsMemoryQuery() = default;
UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
: IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
if (!IsCall)
StartingLoc = MemoryLocation::get(Inst);
}
};
} // end anonymous namespace
template <typename AliasAnalysisType>
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
const Instruction *I) {
// If the memory can't be changed, then loads of the memory can't be
// clobbered.
if (auto *LI = dyn_cast<LoadInst>(I))
return I->hasMetadata(LLVMContext::MD_invariant_load) ||
AA.pointsToConstantMemory(MemoryLocation::get(LI));
return false;
}
/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
///
/// This is meant to be as simple and self-contained as possible. Because it
/// uses no cache, etc., it can be relatively expensive.
///
/// \param Start The MemoryAccess that we want to walk from.
/// \param ClobberAt A clobber for Start.
/// \param StartLoc The MemoryLocation for Start.
/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
/// \param Query The UpwardsMemoryQuery we used for our search.
/// \param AA The AliasAnalysis we used for our search.
/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
template <typename AliasAnalysisType>
LLVM_ATTRIBUTE_UNUSED static void
checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
const MemoryLocation &StartLoc, const MemorySSA &MSSA,
const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
bool AllowImpreciseClobber = false) {
assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
if (MSSA.isLiveOnEntryDef(Start)) {
assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
"liveOnEntry must clobber itself");
return;
}
bool FoundClobber = false;
DenseSet<ConstMemoryAccessPair> VisitedPhis;
SmallVector<ConstMemoryAccessPair, 8> Worklist;
Worklist.emplace_back(Start, StartLoc);
// Walk all paths from Start to ClobberAt, while looking for clobbers. If one
// is found, complain.
while (!Worklist.empty()) {
auto MAP = Worklist.pop_back_val();
// All we care about is that nothing from Start to ClobberAt clobbers Start.
// We learn nothing from revisiting nodes.
if (!VisitedPhis.insert(MAP).second)
continue;
for (const auto *MA : def_chain(MAP.first)) {
if (MA == ClobberAt) {
if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
// instructionClobbersQuery isn't essentially free, so don't use `|=`,
// since it won't let us short-circuit.
//
// Also, note that this can't be hoisted out of the `Worklist` loop,
// since MD may only act as a clobber for 1 of N MemoryLocations.
FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
if (!FoundClobber) {
ClobberAlias CA =
instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
if (CA.IsClobber) {
FoundClobber = true;
// Not used: CA.AR;
}
}
}
break;
}
// We should never hit liveOnEntry, unless it's the clobber.
assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
// If Start is a Def, skip self.
if (MD == Start)
continue;
assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
.IsClobber &&
"Found clobber before reaching ClobberAt!");
continue;
}
if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
(void)MU;
assert (MU == Start &&
"Can only find use in def chain if Start is a use");
continue;
}
assert(isa<MemoryPhi>(MA));
// Add reachable phi predecessors
for (auto ItB = upward_defs_begin(
{const_cast<MemoryAccess *>(MA), MAP.second},
MSSA.getDomTree()),
ItE = upward_defs_end();
ItB != ItE; ++ItB)
if (MSSA.getDomTree().isReachableFromEntry(ItB.getPhiArgBlock()))
Worklist.emplace_back(*ItB);
}
}
// If the verify is done following an optimization, it's possible that
// ClobberAt was a conservative clobbering, that we can now infer is not a
// true clobbering access. Don't fail the verify if that's the case.
// We do have accesses that claim they're optimized, but could be optimized
// further. Updating all these can be expensive, so allow it for now (FIXME).
if (AllowImpreciseClobber)
return;
// If ClobberAt is a MemoryPhi, we can assume something above it acted as a
// clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
"ClobberAt never acted as a clobber");
}
namespace {
/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
/// in one class.
template <class AliasAnalysisType> class ClobberWalker {
/// Save a few bytes by using unsigned instead of size_t.
using ListIndex = unsigned;
/// Represents a span of contiguous MemoryDefs, potentially ending in a
/// MemoryPhi.
struct DefPath {
MemoryLocation Loc;
// Note that, because we always walk in reverse, Last will always dominate
// First. Also note that First and Last are inclusive.
MemoryAccess *First;
MemoryAccess *Last;
Optional<ListIndex> Previous;
DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
Optional<ListIndex> Previous)
: Loc(Loc), First(First), Last(Last), Previous(Previous) {}
DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
Optional<ListIndex> Previous)
: DefPath(Loc, Init, Init, Previous) {}
};
const MemorySSA &MSSA;
AliasAnalysisType &AA;
DominatorTree &DT;
UpwardsMemoryQuery *Query;
unsigned *UpwardWalkLimit;
// Phi optimization bookkeeping:
// List of DefPath to process during the current phi optimization walk.
SmallVector<DefPath, 32> Paths;
// List of visited <Access, Location> pairs; we can skip paths already
// visited with the same memory location.
DenseSet<ConstMemoryAccessPair> VisitedPhis;
// Record if phi translation has been performed during the current phi
// optimization walk, as merging alias results after phi translation can
// yield incorrect results. Context in PR46156.
bool PerformedPhiTranslation = false;
/// Find the nearest def or phi that `From` can legally be optimized to.
const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
assert(From->getNumOperands() && "Phi with no operands?");
BasicBlock *BB = From->getBlock();
MemoryAccess *Result = MSSA.getLiveOnEntryDef();
DomTreeNode *Node = DT.getNode(BB);
while ((Node = Node->getIDom())) {
auto *Defs = MSSA.getBlockDefs(Node->getBlock());
if (Defs)
return &*Defs->rbegin();
}
return Result;
}
/// Result of calling walkToPhiOrClobber.
struct UpwardsWalkResult {
/// The "Result" of the walk. Either a clobber, the last thing we walked, or
/// both. Include alias info when clobber found.
MemoryAccess *Result;
bool IsKnownClobber;
Optional<AliasResult> AR;
};
/// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
/// This will update Desc.Last as it walks. It will (optionally) also stop at
/// StopAt.
///
/// This does not test for whether StopAt is a clobber
UpwardsWalkResult
walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
const MemoryAccess *SkipStopAt = nullptr) const {
assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
assert(UpwardWalkLimit && "Need a valid walk limit");
bool LimitAlreadyReached = false;
// (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
// it to 1. This will not do any alias() calls. It either returns in the
// first iteration in the loop below, or is set back to 0 if all def chains
// are free of MemoryDefs.
if (!*UpwardWalkLimit) {
*UpwardWalkLimit = 1;
LimitAlreadyReached = true;
}
for (MemoryAccess *Current : def_chain(Desc.Last)) {
Desc.Last = Current;
if (Current == StopAt || Current == SkipStopAt)
return {Current, false, AliasResult(AliasResult::MayAlias)};
if (auto *MD = dyn_cast<MemoryDef>(Current)) {
if (MSSA.isLiveOnEntryDef(MD))
return {MD, true, AliasResult(AliasResult::MustAlias)};
if (!--*UpwardWalkLimit)
return {Current, true, AliasResult(AliasResult::MayAlias)};
ClobberAlias CA =
instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
if (CA.IsClobber)
return {MD, true, CA.AR};
}
}
if (LimitAlreadyReached)
*UpwardWalkLimit = 0;
assert(isa<MemoryPhi>(Desc.Last) &&
"Ended at a non-clobber that's not a phi?");
return {Desc.Last, false, AliasResult(AliasResult::MayAlias)};
}
void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
ListIndex PriorNode) {
auto UpwardDefsBegin = upward_defs_begin({Phi, Paths[PriorNode].Loc}, DT,
&PerformedPhiTranslation);
auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end());
for (const MemoryAccessPair &P : UpwardDefs) {
PausedSearches.push_back(Paths.size());
Paths.emplace_back(P.second, P.first, PriorNode);
}
}
/// Represents a search that terminated after finding a clobber. This clobber
/// may or may not be present in the path of defs from LastNode..SearchStart,
/// since it may have been retrieved from cache.
struct TerminatedPath {
MemoryAccess *Clobber;
ListIndex LastNode;
};
/// Get an access that keeps us from optimizing to the given phi.
///
/// PausedSearches is an array of indices into the Paths array. Its incoming
/// value is the indices of searches that stopped at the last phi optimization
/// target. It's left in an unspecified state.
///
/// If this returns None, NewPaused is a vector of searches that terminated
/// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
Optional<TerminatedPath>
getBlockingAccess(const MemoryAccess *StopWhere,
SmallVectorImpl<ListIndex> &PausedSearches,
SmallVectorImpl<ListIndex> &NewPaused,
SmallVectorImpl<TerminatedPath> &Terminated) {
assert(!PausedSearches.empty() && "No searches to continue?");
// BFS vs DFS really doesn't make a difference here, so just do a DFS with
// PausedSearches as our stack.
while (!PausedSearches.empty()) {
ListIndex PathIndex = PausedSearches.pop_back_val();
DefPath &Node = Paths[PathIndex];
// If we've already visited this path with this MemoryLocation, we don't
// need to do so again.
//
// NOTE: That we just drop these paths on the ground makes caching
// behavior sporadic. e.g. given a diamond:
// A
// B C
// D
//
// ...If we walk D, B, A, C, we'll only cache the result of phi
// optimization for A, B, and D; C will be skipped because it dies here.
// This arguably isn't the worst thing ever, since:
// - We generally query things in a top-down order, so if we got below D
// without needing cache entries for {C, MemLoc}, then chances are
// that those cache entries would end up ultimately unused.
// - We still cache things for A, so C only needs to walk up a bit.
// If this behavior becomes problematic, we can fix without a ton of extra
// work.
if (!VisitedPhis.insert({Node.Last, Node.Loc}).second) {
if (PerformedPhiTranslation) {
// If visiting this path performed Phi translation, don't continue,
// since it may not be correct to merge results from two paths if one
// relies on the phi translation.
TerminatedPath Term{Node.Last, PathIndex};
return Term;
}
continue;
}
const MemoryAccess *SkipStopWhere = nullptr;
if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
assert(isa<MemoryDef>(Query->OriginalAccess));
SkipStopWhere = Query->OriginalAccess;
}
UpwardsWalkResult Res = walkToPhiOrClobber(Node,
/*StopAt=*/StopWhere,
/*SkipStopAt=*/SkipStopWhere);
if (Res.IsKnownClobber) {
assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
// If this wasn't a cache hit, we hit a clobber when walking. That's a
// failure.
TerminatedPath Term{Res.Result, PathIndex};
if (!MSSA.dominates(Res.Result, StopWhere))
return Term;
// Otherwise, it's a valid thing to potentially optimize to.
Terminated.push_back(Term);
continue;
}
if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
// We've hit our target. Save this path off for if we want to continue
// walking. If we are in the mode of skipping the OriginalAccess, and
// we've reached back to the OriginalAccess, do not save path, we've
// just looped back to self.
if (Res.Result != SkipStopWhere)
NewPaused.push_back(PathIndex);
continue;
}
assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
}
return None;
}
template <typename T, typename Walker>
struct generic_def_path_iterator
: public iterator_facade_base<generic_def_path_iterator<T, Walker>,
std::forward_iterator_tag, T *> {
generic_def_path_iterator() = default;
generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
T &operator*() const { return curNode(); }
generic_def_path_iterator &operator++() {
N = curNode().Previous;
return *this;
}
bool operator==(const generic_def_path_iterator &O) const {
if (N.hasValue() != O.N.hasValue())
return false;
return !N.hasValue() || *N == *O.N;
}
private:
T &curNode() const { return W->Paths[*N]; }
Walker *W = nullptr;
Optional<ListIndex> N = None;
};
using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
using const_def_path_iterator =
generic_def_path_iterator<const DefPath, const ClobberWalker>;
iterator_range<def_path_iterator> def_path(ListIndex From) {
return make_range(def_path_iterator(this, From), def_path_iterator());
}
iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
return make_range(const_def_path_iterator(this, From),
const_def_path_iterator());
}
struct OptznResult {
/// The path that contains our result.
TerminatedPath PrimaryClobber;
/// The paths that we can legally cache back from, but that aren't
/// necessarily the result of the Phi optimization.
SmallVector<TerminatedPath, 4> OtherClobbers;
};
ListIndex defPathIndex(const DefPath &N) const {
// The assert looks nicer if we don't need to do &N
const DefPath *NP = &N;
assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
"Out of bounds DefPath!");
return NP - &Paths.front();
}
/// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
/// that act as legal clobbers. Note that this won't return *all* clobbers.
///
/// Phi optimization algorithm tl;dr:
/// - Find the earliest def/phi, A, we can optimize to
/// - Find if all paths from the starting memory access ultimately reach A
/// - If not, optimization isn't possible.
/// - Otherwise, walk from A to another clobber or phi, A'.
/// - If A' is a def, we're done.
/// - If A' is a phi, try to optimize it.
///
/// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
/// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
const MemoryLocation &Loc) {
assert(Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation &&
"Reset the optimization state.");
Paths.emplace_back(Loc, Start, Phi, None);
// Stores how many "valid" optimization nodes we had prior to calling
// addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
auto PriorPathsSize = Paths.size();
SmallVector<ListIndex, 16> PausedSearches;
SmallVector<ListIndex, 8> NewPaused;
SmallVector<TerminatedPath, 4> TerminatedPaths;
addSearches(Phi, PausedSearches, 0);
// Moves the TerminatedPath with the "most dominated" Clobber to the end of
// Paths.
auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
assert(!Paths.empty() && "Need a path to move");
auto Dom = Paths.begin();
for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
if (!MSSA.dominates(I->Clobber, Dom->Clobber))
Dom = I;
auto Last = Paths.end() - 1;
if (Last != Dom)
std::iter_swap(Last, Dom);
};
MemoryPhi *Current = Phi;
while (true) {
assert(!MSSA.isLiveOnEntryDef(Current) &&
"liveOnEntry wasn't treated as a clobber?");
const auto *Target = getWalkTarget(Current);
// If a TerminatedPath doesn't dominate Target, then it wasn't a legal
// optimization for the prior phi.
assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
return MSSA.dominates(P.Clobber, Target);
}));
// FIXME: This is broken, because the Blocker may be reported to be
// liveOnEntry, and we'll happily wait for that to disappear (read: never)
// For the moment, this is fine, since we do nothing with blocker info.
if (Optional<TerminatedPath> Blocker = getBlockingAccess(
Target, PausedSearches, NewPaused, TerminatedPaths)) {
// Find the node we started at. We can't search based on N->Last, since
// we may have gone around a loop with a different MemoryLocation.
auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
return defPathIndex(N) < PriorPathsSize;
});
assert(Iter != def_path_iterator());
DefPath &CurNode = *Iter;
assert(CurNode.Last == Current);
// Two things:
// A. We can't reliably cache all of NewPaused back. Consider a case
// where we have two paths in NewPaused; one of which can't optimize
// above this phi, whereas the other can. If we cache the second path
// back, we'll end up with suboptimal cache entries. We can handle
// cases like this a bit better when we either try to find all
// clobbers that block phi optimization, or when our cache starts
// supporting unfinished searches.
// B. We can't reliably cache TerminatedPaths back here without doing
// extra checks; consider a case like:
// T
// / \
// D C
// \ /
// S
// Where T is our target, C is a node with a clobber on it, D is a
// diamond (with a clobber *only* on the left or right node, N), and
// S is our start. Say we walk to D, through the node opposite N
// (read: ignoring the clobber), and see a cache entry in the top
// node of D. That cache entry gets put into TerminatedPaths. We then
// walk up to C (N is later in our worklist), find the clobber, and
// quit. If we append TerminatedPaths to OtherClobbers, we'll cache
// the bottom part of D to the cached clobber, ignoring the clobber
// in N. Again, this problem goes away if we start tracking all
// blockers for a given phi optimization.
TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
return {Result, {}};
}
// If there's nothing left to search, then all paths led to valid clobbers
// that we got from our cache; pick the nearest to the start, and allow
// the rest to be cached back.
if (NewPaused.empty()) {
MoveDominatedPathToEnd(TerminatedPaths);
TerminatedPath Result = TerminatedPaths.pop_back_val();
return {Result, std::move(TerminatedPaths)};
}
MemoryAccess *DefChainEnd = nullptr;
SmallVector<TerminatedPath, 4> Clobbers;
for (ListIndex Paused : NewPaused) {
UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
if (WR.IsKnownClobber)
Clobbers.push_back({WR.Result, Paused});
else
// Micro-opt: If we hit the end of the chain, save it.
DefChainEnd = WR.Result;
}
if (!TerminatedPaths.empty()) {
// If we couldn't find the dominating phi/liveOnEntry in the above loop,
// do it now.
if (!DefChainEnd)
for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
DefChainEnd = MA;
assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
// If any of the terminated paths don't dominate the phi we'll try to
// optimize, we need to figure out what they are and quit.
const BasicBlock *ChainBB = DefChainEnd->getBlock();
for (const TerminatedPath &TP : TerminatedPaths) {
// Because we know that DefChainEnd is as "high" as we can go, we
// don't need local dominance checks; BB dominance is sufficient.
if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
Clobbers.push_back(TP);
}
}
// If we have clobbers in the def chain, find the one closest to Current
// and quit.
if (!Clobbers.empty()) {
MoveDominatedPathToEnd(Clobbers);
TerminatedPath Result = Clobbers.pop_back_val();
return {Result, std::move(Clobbers)};
}
assert(all_of(NewPaused,
[&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
// Because liveOnEntry is a clobber, this must be a phi.
auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
PriorPathsSize = Paths.size();
PausedSearches.clear();
for (ListIndex I : NewPaused)
addSearches(DefChainPhi, PausedSearches, I);
NewPaused.clear();
Current = DefChainPhi;
}
}
void verifyOptResult(const OptznResult &R) const {
assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
}));
}
void resetPhiOptznState() {
Paths.clear();
VisitedPhis.clear();
PerformedPhiTranslation = false;
}
public:
ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
: MSSA(MSSA), AA(AA), DT(DT) {}
AliasAnalysisType *getAA() { return &AA; }
/// Finds the nearest clobber for the given query, optimizing phis if
/// possible.
MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
unsigned &UpWalkLimit) {
Query = &Q;
UpwardWalkLimit = &UpWalkLimit;
// Starting limit must be > 0.
if (!UpWalkLimit)
UpWalkLimit++;
MemoryAccess *Current = Start;
// This walker pretends uses don't exist. If we're handed one, silently grab
// its def. (This has the nice side-effect of ensuring we never cache uses)
if (auto *MU = dyn_cast<MemoryUse>(Start))
Current = MU->getDefiningAccess();
DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
// Fast path for the overly-common case (no crazy phi optimization
// necessary)
UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
MemoryAccess *Result;
if (WalkResult.IsKnownClobber) {
Result = WalkResult.Result;
Q.AR = WalkResult.AR;
} else {
OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
Current, Q.StartingLoc);
verifyOptResult(OptRes);
resetPhiOptznState();
Result = OptRes.PrimaryClobber.Clobber;
}
#ifdef EXPENSIVE_CHECKS
if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)