blob: d13cfe354703ad29729e563f74f757c282e0e87e [file] [log] [blame]
George Burgess IVe1100f52016-02-02 22:46:49 +00001//===-- MemorySSA.cpp - Memory SSA Builder---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSA class.
11//
12//===----------------------------------------------------------------===//
Daniel Berlin16ed57c2016-06-27 18:22:27 +000013#include "llvm/Transforms/Utils/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/CFG.h"
25#include "llvm/Analysis/GlobalsModRef.h"
26#include "llvm/Analysis/IteratedDominanceFrontier.h"
27#include "llvm/Analysis/MemoryLocation.h"
28#include "llvm/Analysis/PHITransAddr.h"
29#include "llvm/IR/AssemblyAnnotationWriter.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/PatternMatch.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/FormattedStream.h"
41#include "llvm/Transforms/Scalar.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000042#include <algorithm>
43
44#define DEBUG_TYPE "memoryssa"
45using namespace llvm;
46STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
47STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
48STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
Geoff Berryb96d3b22016-06-01 21:30:40 +000049
Geoff Berryefb0dd12016-06-14 21:19:40 +000050INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000051 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000052INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
53INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000054INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
55 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000056
57namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000058/// \brief An assembly annotator class to print Memory SSA information in
59/// comments.
60class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
61 friend class MemorySSA;
62 const MemorySSA *MSSA;
63
64public:
65 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
66
67 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
68 formatted_raw_ostream &OS) {
69 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
70 OS << "; " << *MA << "\n";
71 }
72
73 virtual void emitInstructionAnnot(const Instruction *I,
74 formatted_raw_ostream &OS) {
75 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
76 OS << "; " << *MA << "\n";
77 }
78};
George Burgess IVfd1f2f82016-06-24 21:02:12 +000079
80/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
81/// disambiguate accesses.
82///
83/// FIXME: The current implementation of this can take quadratic space in rare
84/// cases. This can be fixed, but it is something to note until it is fixed.
85///
86/// In order to trigger this behavior, you need to store to N distinct locations
87/// (that AA can prove don't alias), perform M stores to other memory
88/// locations that AA can prove don't alias any of the initial N locations, and
89/// then load from all of the N locations. In this case, we insert M cache
90/// entries for each of the N loads.
91///
92/// For example:
93/// define i32 @foo() {
94/// %a = alloca i32, align 4
95/// %b = alloca i32, align 4
96/// store i32 0, i32* %a, align 4
97/// store i32 0, i32* %b, align 4
98///
99/// ; Insert M stores to other memory that doesn't alias %a or %b here
100///
101/// %c = load i32, i32* %a, align 4 ; Caches M entries in
102/// ; CachedUpwardsClobberingAccess for the
103/// ; MemoryLocation %a
104/// %d = load i32, i32* %b, align 4 ; Caches M entries in
105/// ; CachedUpwardsClobberingAccess for the
106/// ; MemoryLocation %b
107///
108/// ; For completeness' sake, loading %a or %b again would not cache *another*
109/// ; M entries.
110/// %r = add i32 %c, %d
111/// ret i32 %r
112/// }
113class MemorySSA::CachingWalker final : public MemorySSAWalker {
114public:
115 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
116 ~CachingWalker() override;
117
118 MemoryAccess *getClobberingMemoryAccess(const Instruction *) override;
119 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
120 MemoryLocation &) override;
121 void invalidateInfo(MemoryAccess *) override;
122
123protected:
124 struct UpwardsMemoryQuery;
125 MemoryAccess *doCacheLookup(const MemoryAccess *, const UpwardsMemoryQuery &,
126 const MemoryLocation &);
127
128 void doCacheInsert(const MemoryAccess *, MemoryAccess *,
129 const UpwardsMemoryQuery &, const MemoryLocation &);
130
131 void doCacheRemove(const MemoryAccess *, const UpwardsMemoryQuery &,
132 const MemoryLocation &);
133
134private:
135 MemoryAccessPair UpwardsDFSWalk(MemoryAccess *, const MemoryLocation &,
136 UpwardsMemoryQuery &, bool);
137 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
138 bool instructionClobbersQuery(const MemoryDef *, UpwardsMemoryQuery &,
139 const MemoryLocation &Loc) const;
140 void verifyRemoved(MemoryAccess *);
141 SmallDenseMap<ConstMemoryAccessPair, MemoryAccess *>
142 CachedUpwardsClobberingAccess;
143 DenseMap<const MemoryAccess *, MemoryAccess *> CachedUpwardsClobberingCall;
144 AliasAnalysis *AA;
145 DominatorTree *DT;
146};
George Burgess IVe1100f52016-02-02 22:46:49 +0000147}
148
149namespace {
150struct RenamePassData {
151 DomTreeNode *DTN;
152 DomTreeNode::const_iterator ChildIt;
153 MemoryAccess *IncomingVal;
154
155 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
156 MemoryAccess *M)
157 : DTN(D), ChildIt(It), IncomingVal(M) {}
158 void swap(RenamePassData &RHS) {
159 std::swap(DTN, RHS.DTN);
160 std::swap(ChildIt, RHS.ChildIt);
161 std::swap(IncomingVal, RHS.IncomingVal);
162 }
163};
164}
165
166namespace llvm {
167/// \brief Rename a single basic block into MemorySSA form.
168/// Uses the standard SSA renaming algorithm.
169/// \returns The new incoming value.
170MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
171 MemoryAccess *IncomingVal) {
172 auto It = PerBlockAccesses.find(BB);
173 // Skip most processing if the list is empty.
174 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000175 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000176 for (MemoryAccess &L : *Accesses) {
177 switch (L.getValueID()) {
178 case Value::MemoryUseVal:
179 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
180 break;
181 case Value::MemoryDefVal:
182 // We can't legally optimize defs, because we only allow single
183 // memory phis/uses on operations, and if we optimize these, we can
184 // end up with multiple reaching defs. Uses do not have this
185 // problem, since they do not produce a value
186 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
187 IncomingVal = &L;
188 break;
189 case Value::MemoryPhiVal:
190 IncomingVal = &L;
191 break;
192 }
193 }
194 }
195
196 // Pass through values to our successors
197 for (const BasicBlock *S : successors(BB)) {
198 auto It = PerBlockAccesses.find(S);
199 // Rename the phi nodes in our successor block
200 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
201 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000202 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000203 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +0000204 Phi->addIncoming(IncomingVal, BB);
205 }
206
207 return IncomingVal;
208}
209
210/// \brief This is the standard SSA renaming algorithm.
211///
212/// We walk the dominator tree in preorder, renaming accesses, and then filling
213/// in phi nodes in our successors.
214void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
215 SmallPtrSet<BasicBlock *, 16> &Visited) {
216 SmallVector<RenamePassData, 32> WorkStack;
217 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
218 WorkStack.push_back({Root, Root->begin(), IncomingVal});
219 Visited.insert(Root->getBlock());
220
221 while (!WorkStack.empty()) {
222 DomTreeNode *Node = WorkStack.back().DTN;
223 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
224 IncomingVal = WorkStack.back().IncomingVal;
225
226 if (ChildIt == Node->end()) {
227 WorkStack.pop_back();
228 } else {
229 DomTreeNode *Child = *ChildIt;
230 ++WorkStack.back().ChildIt;
231 BasicBlock *BB = Child->getBlock();
232 Visited.insert(BB);
233 IncomingVal = renameBlock(BB, IncomingVal);
234 WorkStack.push_back({Child, Child->begin(), IncomingVal});
235 }
236 }
237}
238
239/// \brief Compute dominator levels, used by the phi insertion algorithm above.
240void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
241 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
242 DFI != DFE; ++DFI)
243 DomLevels[*DFI] = DFI.getPathLength() - 1;
244}
245
George Burgess IVa362b092016-07-06 00:28:43 +0000246/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000247/// unreachable blocks, and marking all other unreachable MemoryAccess's as
248/// being uses of the live on entry definition.
249void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
250 assert(!DT->isReachableFromEntry(BB) &&
251 "Reachable block found while handling unreachable blocks");
252
Daniel Berlinfc7e6512016-07-06 05:32:05 +0000253 // Make sure phi nodes in our reachable successors end up with a
254 // LiveOnEntryDef for our incoming edge, even though our block is forward
255 // unreachable. We could just disconnect these blocks from the CFG fully,
256 // but we do not right now.
257 for (const BasicBlock *S : successors(BB)) {
258 if (!DT->isReachableFromEntry(S))
259 continue;
260 auto It = PerBlockAccesses.find(S);
261 // Rename the phi nodes in our successor block
262 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
263 continue;
264 AccessList *Accesses = It->second.get();
265 auto *Phi = cast<MemoryPhi>(&Accesses->front());
266 Phi->addIncoming(LiveOnEntryDef.get(), BB);
267 }
268
George Burgess IVe1100f52016-02-02 22:46:49 +0000269 auto It = PerBlockAccesses.find(BB);
270 if (It == PerBlockAccesses.end())
271 return;
272
273 auto &Accesses = It->second;
274 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
275 auto Next = std::next(AI);
276 // If we have a phi, just remove it. We are going to replace all
277 // users with live on entry.
278 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
279 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
280 else
281 Accesses->erase(AI);
282 AI = Next;
283 }
284}
285
Geoff Berryb96d3b22016-06-01 21:30:40 +0000286MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
287 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
288 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000289 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +0000290}
291
292MemorySSA::MemorySSA(MemorySSA &&MSSA)
293 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
294 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
295 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
296 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
297 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
298 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
299 // object any more.
300 Walker->MSSA = this;
301}
George Burgess IVe1100f52016-02-02 22:46:49 +0000302
303MemorySSA::~MemorySSA() {
304 // Drop all our references
305 for (const auto &Pair : PerBlockAccesses)
306 for (MemoryAccess &MA : *Pair.second)
307 MA.dropAllReferences();
308}
309
Daniel Berlin14300262016-06-21 18:39:20 +0000310MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000311 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
312
313 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +0000314 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000315 return Res.first->second.get();
316}
317
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000318void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +0000319 // We create an access to represent "live on entry", for things like
320 // arguments or users of globals, where the memory they use is defined before
321 // the beginning of the function. We do not actually insert it into the IR.
322 // We do not define a live on exit for the immediate uses, and thus our
323 // semantics do *not* imply that something with no immediate uses can simply
324 // be removed.
325 BasicBlock &StartingPoint = F.getEntryBlock();
326 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
327 &StartingPoint, NextID++);
328
329 // We maintain lists of memory accesses per-block, trading memory for time. We
330 // could just look up the memory access for every possible instruction in the
331 // stream.
332 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000333 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +0000334 // Go through each block, figure out where defs occur, and chain together all
335 // the accesses.
336 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +0000337 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +0000338 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +0000339 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +0000340 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +0000341 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +0000342 continue;
George Burgess IV3887a412016-03-21 21:25:39 +0000343 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000344
George Burgess IVe1100f52016-02-02 22:46:49 +0000345 if (!Accesses)
346 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +0000347 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +0000348 }
Daniel Berlin7898ca62016-02-07 01:52:15 +0000349 if (InsertIntoDef)
350 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +0000351 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +0000352 DefUseBlocks.insert(&B);
353 }
354
355 // Compute live-in.
356 // Live in is normally defined as "all the blocks on the path from each def to
357 // each of it's uses".
358 // MemoryDef's are implicit uses of previous state, so they are also uses.
359 // This means we don't really have def-only instructions. The only
360 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
361 // variable (because LiveOnEntry can reach anywhere, and every def is a
362 // must-kill of LiveOnEntry).
363 // In theory, you could precisely compute live-in by using alias-analysis to
364 // disambiguate defs and uses to see which really pair up with which.
365 // In practice, this would be really expensive and difficult. So we simply
366 // assume all defs are also uses that need to be kept live.
367 // Because of this, the end result of this live-in computation will be "the
368 // entire set of basic blocks that reach any use".
369
370 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
371 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
372 DefUseBlocks.end());
373 // Now that we have a set of blocks where a value is live-in, recursively add
374 // predecessors until we find the full region the value is live.
375 while (!LiveInBlockWorklist.empty()) {
376 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
377
378 // The block really is live in here, insert it into the set. If already in
379 // the set, then it has already been processed.
380 if (!LiveInBlocks.insert(BB).second)
381 continue;
382
383 // Since the value is live into BB, it is either defined in a predecessor or
384 // live into it to.
385 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +0000386 }
387
388 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +0000389 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000390 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000391 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +0000392 SmallVector<BasicBlock *, 32> IDFBlocks;
393 IDFs.calculate(IDFBlocks);
394
395 // Now place MemoryPhi nodes.
396 for (auto &BB : IDFBlocks) {
397 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +0000398 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +0000399 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000400 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +0000401 // Phi's always are placed at the front of the block.
402 Accesses->push_front(Phi);
403 }
404
405 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
406 // filled in with all blocks.
407 SmallPtrSet<BasicBlock *, 16> Visited;
408 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
409
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000410 MemorySSAWalker *Walker = getWalker();
411
George Burgess IVe1100f52016-02-02 22:46:49 +0000412 // Now optimize the MemoryUse's defining access to point to the nearest
413 // dominating clobbering def.
414 // This ensures that MemoryUse's that are killed by the same store are
415 // immediate users of that store, one of the invariants we guarantee.
416 for (auto DomNode : depth_first(DT)) {
417 BasicBlock *BB = DomNode->getBlock();
418 auto AI = PerBlockAccesses.find(BB);
419 if (AI == PerBlockAccesses.end())
420 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000421 AccessList *Accesses = AI->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000422 for (auto &MA : *Accesses) {
423 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
424 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +0000425 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +0000426 }
427 }
428 }
429
430 // Mark the uses in unreachable blocks as live on entry, so that they go
431 // somewhere.
432 for (auto &BB : F)
433 if (!Visited.count(&BB))
434 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000435}
George Burgess IVe1100f52016-02-02 22:46:49 +0000436
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000437MemorySSAWalker *MemorySSA::getWalker() {
438 if (Walker)
439 return Walker.get();
440
441 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +0000442 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000443}
444
Daniel Berlin14300262016-06-21 18:39:20 +0000445MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
446 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
447 AccessList *Accesses = getOrCreateAccessList(BB);
448 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
449 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
450 // Phi's always are placed at the front of the block.
451 Accesses->push_front(Phi);
452 return Phi;
453}
454
455MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
456 MemoryAccess *Definition) {
457 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
458 MemoryUseOrDef *NewAccess = createNewAccess(I);
459 assert(
460 NewAccess != nullptr &&
461 "Tried to create a memory access for a non-memory touching instruction");
462 NewAccess->setDefiningAccess(Definition);
463 return NewAccess;
464}
465
466MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
467 MemoryAccess *Definition,
468 const BasicBlock *BB,
469 InsertionPlace Point) {
470 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
471 auto *Accesses = getOrCreateAccessList(BB);
472 if (Point == Beginning) {
473 // It goes after any phi nodes
474 auto AI = std::find_if(
475 Accesses->begin(), Accesses->end(),
476 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
477
478 Accesses->insert(AI, NewAccess);
479 } else {
480 Accesses->push_back(NewAccess);
481 }
482
483 return NewAccess;
484}
485MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
486 MemoryAccess *Definition,
487 MemoryAccess *InsertPt) {
488 assert(I->getParent() == InsertPt->getBlock() &&
489 "New and old access must be in the same block");
490 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
491 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
492 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
493 return NewAccess;
494}
495
496MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
497 MemoryAccess *Definition,
498 MemoryAccess *InsertPt) {
499 assert(I->getParent() == InsertPt->getBlock() &&
500 "New and old access must be in the same block");
501 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
502 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
503 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
504 return NewAccess;
505}
506
George Burgess IVe1100f52016-02-02 22:46:49 +0000507/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +0000508MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +0000509 // The assume intrinsic has a control dependency which we model by claiming
510 // that it writes arbitrarily. Ignore that fake memory dependency here.
511 // FIXME: Replace this special casing with a more accurate modelling of
512 // assume's control dependency.
513 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
514 if (II->getIntrinsicID() == Intrinsic::assume)
515 return nullptr;
516
George Burgess IVe1100f52016-02-02 22:46:49 +0000517 // Find out what affect this instruction has on memory.
518 ModRefInfo ModRef = AA->getModRefInfo(I);
519 bool Def = bool(ModRef & MRI_Mod);
520 bool Use = bool(ModRef & MRI_Ref);
521
522 // It's possible for an instruction to not modify memory at all. During
523 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +0000524 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +0000525 return nullptr;
526
527 assert((Def || Use) &&
528 "Trying to create a memory access with a non-memory instruction");
529
George Burgess IVb42b7622016-03-11 19:34:03 +0000530 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000531 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +0000532 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +0000533 else
George Burgess IVb42b7622016-03-11 19:34:03 +0000534 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
535 ValueToMemoryAccess.insert(std::make_pair(I, MUD));
536 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000537}
538
539MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
540 enum InsertionPlace Where) {
541 // Handle the initial case
542 if (Where == Beginning)
543 // The only thing that could define us at the beginning is a phi node
544 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
545 return Phi;
546
547 DomTreeNode *CurrNode = DT->getNode(UseBlock);
548 // Need to be defined by our dominator
549 if (Where == Beginning)
550 CurrNode = CurrNode->getIDom();
551 Where = End;
552 while (CurrNode) {
553 auto It = PerBlockAccesses.find(CurrNode->getBlock());
554 if (It != PerBlockAccesses.end()) {
555 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +0000556 for (MemoryAccess &RA : reverse(*Accesses)) {
557 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
558 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +0000559 }
560 }
561 CurrNode = CurrNode->getIDom();
562 }
563 return LiveOnEntryDef.get();
564}
565
566/// \brief Returns true if \p Replacer dominates \p Replacee .
567bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
568 const MemoryAccess *Replacee) const {
569 if (isa<MemoryUseOrDef>(Replacee))
570 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
571 const auto *MP = cast<MemoryPhi>(Replacee);
572 // For a phi node, the use occurs in the predecessor block of the phi node.
573 // Since we may occur multiple times in the phi node, we have to check each
574 // operand to ensure Replacer dominates each operand where Replacee occurs.
575 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000576 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000577 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
578 return false;
579 }
580 return true;
581}
582
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000583/// \brief If all arguments of a MemoryPHI are defined by the same incoming
584/// argument, return that argument.
585static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
586 MemoryAccess *MA = nullptr;
587
588 for (auto &Arg : MP->operands()) {
589 if (!MA)
590 MA = cast<MemoryAccess>(Arg);
591 else if (MA != Arg)
592 return nullptr;
593 }
594 return MA;
595}
596
597/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
598///
599/// Because of the way the intrusive list and use lists work, it is important to
600/// do removal in the right order.
601void MemorySSA::removeFromLookups(MemoryAccess *MA) {
602 assert(MA->use_empty() &&
603 "Trying to remove memory access that still has uses");
604 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
605 MUD->setDefiningAccess(nullptr);
606 // Invalidate our walker's cache if necessary
607 if (!isa<MemoryUse>(MA))
608 Walker->invalidateInfo(MA);
609 // The call below to erase will destroy MA, so we can't change the order we
610 // are doing things here
611 Value *MemoryInst;
612 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
613 MemoryInst = MUD->getMemoryInst();
614 } else {
615 MemoryInst = MA->getBlock();
616 }
617 ValueToMemoryAccess.erase(MemoryInst);
618
George Burgess IVe0e6e482016-03-02 02:35:04 +0000619 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +0000620 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000621 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +0000622 if (Accesses->empty())
623 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000624}
625
626void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
627 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
628 // We can only delete phi nodes if they have no uses, or we can replace all
629 // uses with a single definition.
630 MemoryAccess *NewDefTarget = nullptr;
631 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
632 // Note that it is sufficient to know that all edges of the phi node have
633 // the same argument. If they do, by the definition of dominance frontiers
634 // (which we used to place this phi), that argument must dominate this phi,
635 // and thus, must dominate the phi's uses, and so we will not hit the assert
636 // below.
637 NewDefTarget = onlySingleValue(MP);
638 assert((NewDefTarget || MP->use_empty()) &&
639 "We can't delete this memory phi");
640 } else {
641 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
642 }
643
644 // Re-point the uses at our defining access
645 if (!MA->use_empty())
646 MA->replaceAllUsesWith(NewDefTarget);
647
648 // The call below to erase will destroy MA, so we can't change the order we
649 // are doing things here
650 removeFromLookups(MA);
651}
652
George Burgess IVe1100f52016-02-02 22:46:49 +0000653void MemorySSA::print(raw_ostream &OS) const {
654 MemorySSAAnnotatedWriter Writer(this);
655 F.print(OS, &Writer);
656}
657
658void MemorySSA::dump() const {
659 MemorySSAAnnotatedWriter Writer(this);
660 F.print(dbgs(), &Writer);
661}
662
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000663void MemorySSA::verifyMemorySSA() const {
664 verifyDefUses(F);
665 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +0000666 verifyOrdering(F);
667}
668
669/// \brief Verify that the order and existence of MemoryAccesses matches the
670/// order and existence of memory affecting instructions.
671void MemorySSA::verifyOrdering(Function &F) const {
672 // Walk all the blocks, comparing what the lookups think and what the access
673 // lists think, as well as the order in the blocks vs the order in the access
674 // lists.
675 SmallVector<MemoryAccess *, 32> ActualAccesses;
676 for (BasicBlock &B : F) {
677 const AccessList *AL = getBlockAccesses(&B);
678 MemoryAccess *Phi = getMemoryAccess(&B);
679 if (Phi)
680 ActualAccesses.push_back(Phi);
681 for (Instruction &I : B) {
682 MemoryAccess *MA = getMemoryAccess(&I);
683 assert((!MA || AL) && "We have memory affecting instructions "
684 "in this block but they are not in the "
685 "access list");
686 if (MA)
687 ActualAccesses.push_back(MA);
688 }
689 // Either we hit the assert, really have no accesses, or we have both
690 // accesses and an access list
691 if (!AL)
692 continue;
693 assert(AL->size() == ActualAccesses.size() &&
694 "We don't have the same number of accesses in the block as on the "
695 "access list");
696 auto ALI = AL->begin();
697 auto AAI = ActualAccesses.begin();
698 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
699 assert(&*ALI == *AAI && "Not the same accesses in the same order");
700 ++ALI;
701 ++AAI;
702 }
703 ActualAccesses.clear();
704 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000705}
706
George Burgess IVe1100f52016-02-02 22:46:49 +0000707/// \brief Verify the domination properties of MemorySSA by checking that each
708/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000709void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000710 for (BasicBlock &B : F) {
711 // Phi nodes are attached to basic blocks
712 if (MemoryPhi *MP = getMemoryAccess(&B)) {
713 for (User *U : MP->users()) {
714 BasicBlock *UseBlock;
715 // Phi operands are used on edges, we simulate the right domination by
716 // acting as if the use occurred at the end of the predecessor block.
717 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
718 for (const auto &Arg : P->operands()) {
719 if (Arg == MP) {
720 UseBlock = P->getIncomingBlock(Arg);
721 break;
722 }
723 }
724 } else {
725 UseBlock = cast<MemoryAccess>(U)->getBlock();
726 }
George Burgess IV60adac42016-02-02 23:26:01 +0000727 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000728 assert(DT->dominates(MP->getBlock(), UseBlock) &&
729 "Memory PHI does not dominate it's uses");
730 }
731 }
732
733 for (Instruction &I : B) {
734 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
735 if (!MD)
736 continue;
737
Benjamin Kramer451f54c2016-02-22 13:11:58 +0000738 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000739 BasicBlock *UseBlock;
740 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000741 // Things are allowed to flow to phi nodes over their predecessor edge.
742 if (auto *P = dyn_cast<MemoryPhi>(U)) {
743 for (const auto &Arg : P->operands()) {
744 if (Arg == MD) {
745 UseBlock = P->getIncomingBlock(Arg);
746 break;
747 }
748 }
749 } else {
750 UseBlock = cast<MemoryAccess>(U)->getBlock();
751 }
752 assert(DT->dominates(MD->getBlock(), UseBlock) &&
753 "Memory Def does not dominate it's uses");
754 }
755 }
756 }
757}
758
759/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
760/// appears in the use list of \p Def.
761///
762/// llvm_unreachable is used instead of asserts because this may be called in
763/// a build without asserts. In that case, we don't want this to turn into a
764/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000765void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000766 // The live on entry use may cause us to get a NULL def here
767 if (!Def) {
768 if (!isLiveOnEntryDef(Use))
769 llvm_unreachable("Null def but use not point to live on entry def");
770 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
771 Def->user_end()) {
772 llvm_unreachable("Did not find use in def's use list");
773 }
774}
775
776/// \brief Verify the immediate use information, by walking all the memory
777/// accesses and verifying that, for each use, it appears in the
778/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000779void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000780 for (BasicBlock &B : F) {
781 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +0000782 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +0000783 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
784 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +0000785 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +0000786 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
787 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +0000788 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000789
790 for (Instruction &I : B) {
791 if (MemoryAccess *MA = getMemoryAccess(&I)) {
792 assert(isa<MemoryUseOrDef>(MA) &&
793 "Found a phi node not attached to a bb");
794 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
795 }
796 }
797 }
798}
799
800MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000801 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +0000802}
803
804MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
805 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
806}
807
808/// \brief Determine, for two memory accesses in the same block,
809/// whether \p Dominator dominates \p Dominatee.
810/// \returns True if \p Dominator dominates \p Dominatee.
811bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
812 const MemoryAccess *Dominatee) const {
813
814 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
815 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +0000816
817 // A node dominates itself.
818 if (Dominatee == Dominator)
819 return true;
820
821 // When Dominatee is defined on function entry, it is not dominated by another
822 // memory access.
823 if (isLiveOnEntryDef(Dominatee))
824 return false;
825
826 // When Dominator is defined on function entry, it dominates the other memory
827 // access.
828 if (isLiveOnEntryDef(Dominator))
829 return true;
830
George Burgess IVe1100f52016-02-02 22:46:49 +0000831 // Get the access list for the block
Daniel Berlinada263d2016-06-20 20:21:33 +0000832 const AccessList *AccessList = getBlockAccesses(Dominator->getBlock());
833 AccessList::const_reverse_iterator It(Dominator->getIterator());
George Burgess IVe1100f52016-02-02 22:46:49 +0000834
835 // If we hit the beginning of the access list before we hit dominatee, we must
836 // dominate it
837 return std::none_of(It, AccessList->rend(),
838 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
839}
840
841const static char LiveOnEntryStr[] = "liveOnEntry";
842
843void MemoryDef::print(raw_ostream &OS) const {
844 MemoryAccess *UO = getDefiningAccess();
845
846 OS << getID() << " = MemoryDef(";
847 if (UO && UO->getID())
848 OS << UO->getID();
849 else
850 OS << LiveOnEntryStr;
851 OS << ')';
852}
853
854void MemoryPhi::print(raw_ostream &OS) const {
855 bool First = true;
856 OS << getID() << " = MemoryPhi(";
857 for (const auto &Op : operands()) {
858 BasicBlock *BB = getIncomingBlock(Op);
859 MemoryAccess *MA = cast<MemoryAccess>(Op);
860 if (!First)
861 OS << ',';
862 else
863 First = false;
864
865 OS << '{';
866 if (BB->hasName())
867 OS << BB->getName();
868 else
869 BB->printAsOperand(OS, false);
870 OS << ',';
871 if (unsigned ID = MA->getID())
872 OS << ID;
873 else
874 OS << LiveOnEntryStr;
875 OS << '}';
876 }
877 OS << ')';
878}
879
880MemoryAccess::~MemoryAccess() {}
881
882void MemoryUse::print(raw_ostream &OS) const {
883 MemoryAccess *UO = getDefiningAccess();
884 OS << "MemoryUse(";
885 if (UO && UO->getID())
886 OS << UO->getID();
887 else
888 OS << LiveOnEntryStr;
889 OS << ')';
890}
891
892void MemoryAccess::dump() const {
893 print(dbgs());
894 dbgs() << "\n";
895}
896
Geoff Berryb96d3b22016-06-01 21:30:40 +0000897char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +0000898
Geoff Berryb96d3b22016-06-01 21:30:40 +0000899MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
900 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
901 auto &AA = AM.getResult<AAManager>(F);
902 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000903}
904
Geoff Berryb96d3b22016-06-01 21:30:40 +0000905PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
906 FunctionAnalysisManager &AM) {
907 OS << "MemorySSA for function: " << F.getName() << "\n";
908 AM.getResult<MemorySSAAnalysis>(F).print(OS);
909
910 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +0000911}
912
Geoff Berryb96d3b22016-06-01 21:30:40 +0000913PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
914 FunctionAnalysisManager &AM) {
915 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
916
917 return PreservedAnalyses::all();
918}
919
920char MemorySSAWrapperPass::ID = 0;
921
922MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
923 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
924}
925
926void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
927
928void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000929 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +0000930 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
931 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000932}
933
Geoff Berryb96d3b22016-06-01 21:30:40 +0000934bool MemorySSAWrapperPass::runOnFunction(Function &F) {
935 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
936 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
937 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +0000938 return false;
939}
940
Geoff Berryb96d3b22016-06-01 21:30:40 +0000941void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +0000942
Geoff Berryb96d3b22016-06-01 21:30:40 +0000943void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000944 MSSA->print(OS);
945}
946
George Burgess IVe1100f52016-02-02 22:46:49 +0000947MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
948
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000949MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
950 DominatorTree *D)
George Burgess IVe1100f52016-02-02 22:46:49 +0000951 : MemorySSAWalker(M), AA(A), DT(D) {}
952
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000953MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +0000954
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000955struct MemorySSA::CachingWalker::UpwardsMemoryQuery {
George Burgess IVe1100f52016-02-02 22:46:49 +0000956 // True if we saw a phi whose predecessor was a backedge
957 bool SawBackedgePhi;
958 // True if our original query started off as a call
959 bool IsCall;
960 // The pointer location we started the query with. This will be empty if
961 // IsCall is true.
962 MemoryLocation StartingLoc;
963 // This is the instruction we were querying about.
964 const Instruction *Inst;
965 // Set of visited Instructions for this query.
966 DenseSet<MemoryAccessPair> Visited;
George Burgess IV49cad7d2016-03-30 03:12:08 +0000967 // Vector of visited call accesses for this query. This is separated out
968 // because you can always cache and lookup the result of call queries (IE when
969 // IsCall == true) for every call in the chain. The calls have no AA location
George Burgess IVe1100f52016-02-02 22:46:49 +0000970 // associated with them with them, and thus, no context dependence.
George Burgess IV49cad7d2016-03-30 03:12:08 +0000971 SmallVector<const MemoryAccess *, 32> VisitedCalls;
George Burgess IVe1100f52016-02-02 22:46:49 +0000972 // The MemoryAccess we actually got called with, used to test local domination
973 const MemoryAccess *OriginalAccess;
George Burgess IVe1100f52016-02-02 22:46:49 +0000974
975 UpwardsMemoryQuery()
976 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000977 OriginalAccess(nullptr) {}
978
979 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
980 : SawBackedgePhi(false), IsCall(ImmutableCallSite(Inst)), Inst(Inst),
981 OriginalAccess(Access) {}
George Burgess IVe1100f52016-02-02 22:46:49 +0000982};
983
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000984void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000985
986 // TODO: We can do much better cache invalidation with differently stored
987 // caches. For now, for MemoryUses, we simply remove them
988 // from the cache, and kill the entire call/non-call cache for everything
989 // else. The problem is for phis or defs, currently we'd need to follow use
990 // chains down and invalidate anything below us in the chain that currently
991 // terminates at this access.
992
993 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
994 // is by definition never a barrier, so nothing in the cache could point to
995 // this use. In that case, we only need invalidate the info for the use
996 // itself.
997
998 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
999 UpwardsMemoryQuery Q;
1000 Instruction *I = MU->getMemoryInst();
1001 Q.IsCall = bool(ImmutableCallSite(I));
1002 Q.Inst = I;
1003 if (!Q.IsCall)
1004 Q.StartingLoc = MemoryLocation::get(I);
1005 doCacheRemove(MA, Q, Q.StartingLoc);
Geoff Berry9fe26e62016-04-22 14:44:10 +00001006 } else {
1007 // If it is not a use, the best we can do right now is destroy the cache.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001008 CachedUpwardsClobberingCall.clear();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001009 CachedUpwardsClobberingAccess.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00001010 }
1011
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00001012#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00001013 // Run this only when expensive checks are enabled.
1014 verifyRemoved(MA);
1015#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001016}
1017
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001018void MemorySSA::CachingWalker::doCacheRemove(const MemoryAccess *M,
1019 const UpwardsMemoryQuery &Q,
1020 const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001021 if (Q.IsCall)
1022 CachedUpwardsClobberingCall.erase(M);
1023 else
1024 CachedUpwardsClobberingAccess.erase({M, Loc});
1025}
1026
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001027void MemorySSA::CachingWalker::doCacheInsert(const MemoryAccess *M,
1028 MemoryAccess *Result,
1029 const UpwardsMemoryQuery &Q,
1030 const MemoryLocation &Loc) {
George Burgess IV1b1fef32016-04-29 18:42:55 +00001031 // This is fine for Phis, since there are times where we can't optimize them.
1032 // Making a def its own clobber is never correct, though.
1033 assert((Result != M || isa<MemoryPhi>(M)) &&
1034 "Something can't clobber itself!");
George Burgess IVe1100f52016-02-02 22:46:49 +00001035 ++NumClobberCacheInserts;
1036 if (Q.IsCall)
1037 CachedUpwardsClobberingCall[M] = Result;
1038 else
1039 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
1040}
1041
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001042MemoryAccess *
1043MemorySSA::CachingWalker::doCacheLookup(const MemoryAccess *M,
1044 const UpwardsMemoryQuery &Q,
1045 const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001046 ++NumClobberCacheLookups;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001047 MemoryAccess *Result;
George Burgess IVe1100f52016-02-02 22:46:49 +00001048
1049 if (Q.IsCall)
1050 Result = CachedUpwardsClobberingCall.lookup(M);
1051 else
1052 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
1053
1054 if (Result)
1055 ++NumClobberCacheHits;
1056 return Result;
1057}
1058
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001059bool MemorySSA::CachingWalker::instructionClobbersQuery(
George Burgess IVe1100f52016-02-02 22:46:49 +00001060 const MemoryDef *MD, UpwardsMemoryQuery &Q,
1061 const MemoryLocation &Loc) const {
1062 Instruction *DefMemoryInst = MD->getMemoryInst();
1063 assert(DefMemoryInst && "Defining instruction not actually an instruction");
1064
1065 if (!Q.IsCall)
1066 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
1067
1068 // If this is a call, mark it for caching
1069 if (ImmutableCallSite(DefMemoryInst))
George Burgess IV49cad7d2016-03-30 03:12:08 +00001070 Q.VisitedCalls.push_back(MD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001071 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
1072 return I != MRI_NoModRef;
1073}
1074
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001075MemoryAccessPair MemorySSA::CachingWalker::UpwardsDFSWalk(
George Burgess IVe1100f52016-02-02 22:46:49 +00001076 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
1077 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
1078 MemoryAccess *ModifyingAccess = nullptr;
1079
1080 auto DFI = df_begin(StartingAccess);
1081 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
1082 MemoryAccess *CurrAccess = *DFI;
1083 if (MSSA->isLiveOnEntryDef(CurrAccess))
1084 return {CurrAccess, Loc};
George Burgess IV1b1fef32016-04-29 18:42:55 +00001085 // If this is a MemoryDef, check whether it clobbers our current query. This
1086 // needs to be done before consulting the cache, because the cache reports
1087 // the clobber for CurrAccess. If CurrAccess is a clobber for this query,
1088 // and we ask the cache for information first, then we might skip this
1089 // clobber, which is bad.
George Burgess IVe1100f52016-02-02 22:46:49 +00001090 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
1091 // If we hit the top, stop following this path.
1092 // While we can do lookups, we can't sanely do inserts here unless we were
1093 // to track everything we saw along the way, since we don't know where we
1094 // will stop.
1095 if (instructionClobbersQuery(MD, Q, Loc)) {
1096 ModifyingAccess = CurrAccess;
1097 break;
1098 }
1099 }
George Burgess IV1b1fef32016-04-29 18:42:55 +00001100 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
1101 return {CacheResult, Loc};
George Burgess IVe1100f52016-02-02 22:46:49 +00001102
1103 // We need to know whether it is a phi so we can track backedges.
1104 // Otherwise, walk all upward defs.
1105 if (!isa<MemoryPhi>(CurrAccess)) {
1106 ++DFI;
1107 continue;
1108 }
1109
George Burgess IV0e489862016-03-23 18:31:55 +00001110#ifndef NDEBUG
1111 // The loop below visits the phi's children for us. Because phis are the
1112 // only things with multiple edges, skipping the children should always lead
1113 // us to the end of the loop.
1114 //
1115 // Use a copy of DFI because skipChildren would kill our search stack, which
1116 // would make caching anything on the way back impossible.
1117 auto DFICopy = DFI;
1118 assert(DFICopy.skipChildren() == DFE &&
1119 "Skipping phi's children doesn't end the DFS?");
1120#endif
1121
George Burgess IV82ee9422016-03-30 00:26:26 +00001122 const MemoryAccessPair PHIPair(CurrAccess, Loc);
1123
1124 // Don't try to optimize this phi again if we've already tried to do so.
1125 if (!Q.Visited.insert(PHIPair).second) {
1126 ModifyingAccess = CurrAccess;
1127 break;
1128 }
1129
George Burgess IV49cad7d2016-03-30 03:12:08 +00001130 std::size_t InitialVisitedCallSize = Q.VisitedCalls.size();
1131
George Burgess IVe1100f52016-02-02 22:46:49 +00001132 // Recurse on PHI nodes, since we need to change locations.
1133 // TODO: Allow graphtraits on pairs, which would turn this whole function
1134 // into a normal single depth first walk.
1135 MemoryAccess *FirstDef = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001136 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
1137 MPI != MPE; ++MPI) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001138 bool Backedge =
1139 !FollowingBackedge &&
1140 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
1141
1142 MemoryAccessPair CurrentPair =
1143 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
1144 // All the phi arguments should reach the same point if we can bypass
1145 // this phi. The alternative is that they hit this phi node, which
1146 // means we can skip this argument.
1147 if (FirstDef && CurrentPair.first != PHIPair.first &&
1148 CurrentPair.first != FirstDef) {
1149 ModifyingAccess = CurrAccess;
1150 break;
1151 }
1152
1153 if (!FirstDef)
1154 FirstDef = CurrentPair.first;
George Burgess IVe1100f52016-02-02 22:46:49 +00001155 }
1156
George Burgess IV0e489862016-03-23 18:31:55 +00001157 // If we exited the loop early, go with the result it gave us.
1158 if (!ModifyingAccess) {
George Burgess IV82ee9422016-03-30 00:26:26 +00001159 assert(FirstDef && "Found a Phi with no upward defs?");
1160 ModifyingAccess = FirstDef;
George Burgess IV49cad7d2016-03-30 03:12:08 +00001161 } else {
1162 // If we can't optimize this Phi, then we can't safely cache any of the
1163 // calls we visited when trying to optimize it. Wipe them out now.
1164 Q.VisitedCalls.resize(InitialVisitedCallSize);
George Burgess IV0e489862016-03-23 18:31:55 +00001165 }
1166 break;
George Burgess IVe1100f52016-02-02 22:46:49 +00001167 }
1168
1169 if (!ModifyingAccess)
1170 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
1171
George Burgess IV0e489862016-03-23 18:31:55 +00001172 const BasicBlock *OriginalBlock = StartingAccess->getBlock();
George Burgess IV1b1fef32016-04-29 18:42:55 +00001173 assert(DFI.getPathLength() > 0 && "We dropped our path?");
George Burgess IVe1100f52016-02-02 22:46:49 +00001174 unsigned N = DFI.getPathLength();
George Burgess IV1b1fef32016-04-29 18:42:55 +00001175 // If we found a clobbering def, the last element in the path will be our
1176 // clobber, so we don't want to cache that to itself. OTOH, if we optimized a
1177 // phi, we can add the last thing in the path to the cache, since that won't
1178 // be the result.
1179 if (DFI.getPath(N - 1) == ModifyingAccess)
1180 --N;
1181 for (; N > 1; --N) {
George Burgess IV0e489862016-03-23 18:31:55 +00001182 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
1183 BasicBlock *CurrBlock = CacheAccess->getBlock();
George Burgess IVe1100f52016-02-02 22:46:49 +00001184 if (!FollowingBackedge)
George Burgess IV0e489862016-03-23 18:31:55 +00001185 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001186 if (DT->dominates(CurrBlock, OriginalBlock) &&
1187 (CurrBlock != OriginalBlock || !FollowingBackedge ||
George Burgess IV0e489862016-03-23 18:31:55 +00001188 MSSA->locallyDominates(CacheAccess, StartingAccess)))
George Burgess IVe1100f52016-02-02 22:46:49 +00001189 break;
1190 }
1191
1192 // Cache everything else on the way back. The caller should cache
George Burgess IV1b1fef32016-04-29 18:42:55 +00001193 // StartingAccess for us.
1194 for (; N > 1; --N) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001195 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
1196 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
1197 }
1198 assert(Q.Visited.size() < 1000 && "Visited too much");
1199
1200 return {ModifyingAccess, Loc};
1201}
1202
1203/// \brief Walk the use-def chains starting at \p MA and find
1204/// the MemoryAccess that actually clobbers Loc.
1205///
1206/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001207MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1208 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001209 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
1210}
1211
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001212MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1213 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001214 if (isa<MemoryPhi>(StartingAccess))
1215 return StartingAccess;
1216
1217 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1218 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1219 return StartingUseOrDef;
1220
1221 Instruction *I = StartingUseOrDef->getMemoryInst();
1222
1223 // Conservatively, fences are always clobbers, so don't perform the walk if we
1224 // hit a fence.
1225 if (isa<FenceInst>(I))
1226 return StartingUseOrDef;
1227
1228 UpwardsMemoryQuery Q;
1229 Q.OriginalAccess = StartingUseOrDef;
1230 Q.StartingLoc = Loc;
1231 Q.Inst = StartingUseOrDef->getMemoryInst();
1232 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001233
1234 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
1235 return CacheResult;
1236
1237 // Unlike the other function, do not walk to the def of a def, because we are
1238 // handed something we already believe is the clobbering access.
1239 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1240 ? StartingUseOrDef->getDefiningAccess()
1241 : StartingUseOrDef;
1242
1243 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IV1b1fef32016-04-29 18:42:55 +00001244 // Only cache this if it wouldn't make Clobber point to itself.
1245 if (Clobber != StartingAccess)
1246 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001247 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1248 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1249 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1250 DEBUG(dbgs() << *Clobber << "\n");
1251 return Clobber;
1252}
1253
1254MemoryAccess *
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001255MemorySSA::CachingWalker::getClobberingMemoryAccess(const Instruction *I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001256 // There should be no way to lookup an instruction and get a phi as the
1257 // access, since we only map BB's to PHI's. So, this must be a use or def.
1258 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
1259
1260 // We can't sanely do anything with a FenceInst, they conservatively
1261 // clobber all memory, and have no locations to get pointers from to
1262 // try to disambiguate
1263 if (isa<FenceInst>(I))
1264 return StartingAccess;
1265
1266 UpwardsMemoryQuery Q;
1267 Q.OriginalAccess = StartingAccess;
1268 Q.IsCall = bool(ImmutableCallSite(I));
1269 if (!Q.IsCall)
1270 Q.StartingLoc = MemoryLocation::get(I);
1271 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001272 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
1273 return CacheResult;
1274
1275 // Start with the thing we already think clobbers this location
1276 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1277
1278 // At this point, DefiningAccess may be the live on entry def.
1279 // If it is, we will not get a better result.
1280 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1281 return DefiningAccess;
1282
1283 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IV1b1fef32016-04-29 18:42:55 +00001284 // DFS won't cache a result for DefiningAccess. So, if DefiningAccess isn't
1285 // our clobber, be sure that it gets a cache entry, too.
1286 if (Result != DefiningAccess)
1287 doCacheInsert(DefiningAccess, Result, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001288 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
1289 // TODO: When this implementation is more mature, we may want to figure out
1290 // what this additional caching buys us. It's most likely A Good Thing.
1291 if (Q.IsCall)
1292 for (const MemoryAccess *MA : Q.VisitedCalls)
George Burgess IV1b1fef32016-04-29 18:42:55 +00001293 if (MA != Result)
1294 doCacheInsert(MA, Result, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001295
1296 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1297 DEBUG(dbgs() << *DefiningAccess << "\n");
1298 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1299 DEBUG(dbgs() << *Result << "\n");
1300
1301 return Result;
1302}
1303
Geoff Berry9fe26e62016-04-22 14:44:10 +00001304// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001305void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
Geoff Berry9fe26e62016-04-22 14:44:10 +00001306#ifndef NDEBUG
1307 for (auto &P : CachedUpwardsClobberingAccess)
1308 assert(P.first.first != MA && P.second != MA &&
1309 "Found removed MemoryAccess in cache.");
1310 for (auto &P : CachedUpwardsClobberingCall)
1311 assert(P.first != MA && P.second != MA &&
1312 "Found removed MemoryAccess in cache.");
1313#endif // !NDEBUG
1314}
1315
George Burgess IVe1100f52016-02-02 22:46:49 +00001316MemoryAccess *
1317DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1318 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1319 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1320 return Use->getDefiningAccess();
1321 return MA;
1322}
1323
1324MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1325 MemoryAccess *StartingAccess, MemoryLocation &) {
1326 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1327 return Use->getDefiningAccess();
1328 return StartingAccess;
1329}
1330}