blob: b71c1945a0e85edc38bdb9cdc7032f8c8f3f5821 [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//===----------------------------------------------------------------===//
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/DepthFirstIterator.h"
16#include "llvm/ADT/GraphTraits.h"
17#include "llvm/ADT/PostOrderIterator.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/CFG.h"
24#include "llvm/Analysis/GlobalsModRef.h"
25#include "llvm/Analysis/IteratedDominanceFrontier.h"
26#include "llvm/Analysis/MemoryLocation.h"
27#include "llvm/Analysis/PHITransAddr.h"
28#include "llvm/IR/AssemblyAnnotationWriter.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/PatternMatch.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/FormattedStream.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/MemorySSA.h"
43#include <algorithm>
44
45#define DEBUG_TYPE "memoryssa"
46using namespace llvm;
47STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
48STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
49STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
50INITIALIZE_PASS_WITH_OPTIONS_BEGIN(MemorySSAPrinterPass, "print-memoryssa",
51 "Memory SSA", true, true)
52INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
53INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
54INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
55INITIALIZE_PASS_END(MemorySSAPrinterPass, "print-memoryssa", "Memory SSA", true,
56 true)
57INITIALIZE_PASS(MemorySSALazy, "memoryssalazy", "Memory SSA", true, true)
58
59namespace llvm {
60
61/// \brief An assembly annotator class to print Memory SSA information in
62/// comments.
63class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
64 friend class MemorySSA;
65 const MemorySSA *MSSA;
66
67public:
68 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
69
70 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
71 formatted_raw_ostream &OS) {
72 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
73 OS << "; " << *MA << "\n";
74 }
75
76 virtual void emitInstructionAnnot(const Instruction *I,
77 formatted_raw_ostream &OS) {
78 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
79 OS << "; " << *MA << "\n";
80 }
81};
82}
83
84namespace {
85struct RenamePassData {
86 DomTreeNode *DTN;
87 DomTreeNode::const_iterator ChildIt;
88 MemoryAccess *IncomingVal;
89
90 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
91 MemoryAccess *M)
92 : DTN(D), ChildIt(It), IncomingVal(M) {}
93 void swap(RenamePassData &RHS) {
94 std::swap(DTN, RHS.DTN);
95 std::swap(ChildIt, RHS.ChildIt);
96 std::swap(IncomingVal, RHS.IncomingVal);
97 }
98};
99}
100
101namespace llvm {
102/// \brief Rename a single basic block into MemorySSA form.
103/// Uses the standard SSA renaming algorithm.
104/// \returns The new incoming value.
105MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
106 MemoryAccess *IncomingVal) {
107 auto It = PerBlockAccesses.find(BB);
108 // Skip most processing if the list is empty.
109 if (It != PerBlockAccesses.end()) {
110 AccessListType *Accesses = It->second.get();
111 for (MemoryAccess &L : *Accesses) {
112 switch (L.getValueID()) {
113 case Value::MemoryUseVal:
114 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
115 break;
116 case Value::MemoryDefVal:
117 // We can't legally optimize defs, because we only allow single
118 // memory phis/uses on operations, and if we optimize these, we can
119 // end up with multiple reaching defs. Uses do not have this
120 // problem, since they do not produce a value
121 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
122 IncomingVal = &L;
123 break;
124 case Value::MemoryPhiVal:
125 IncomingVal = &L;
126 break;
127 }
128 }
129 }
130
131 // Pass through values to our successors
132 for (const BasicBlock *S : successors(BB)) {
133 auto It = PerBlockAccesses.find(S);
134 // Rename the phi nodes in our successor block
135 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
136 continue;
137 AccessListType *Accesses = It->second.get();
138 auto *Phi = cast<MemoryPhi>(&Accesses->front());
139 assert(std::find(succ_begin(BB), succ_end(BB), S) != succ_end(BB) &&
140 "Must be at least one edge from Succ to BB!");
141 Phi->addIncoming(IncomingVal, BB);
142 }
143
144 return IncomingVal;
145}
146
147/// \brief This is the standard SSA renaming algorithm.
148///
149/// We walk the dominator tree in preorder, renaming accesses, and then filling
150/// in phi nodes in our successors.
151void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
152 SmallPtrSet<BasicBlock *, 16> &Visited) {
153 SmallVector<RenamePassData, 32> WorkStack;
154 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
155 WorkStack.push_back({Root, Root->begin(), IncomingVal});
156 Visited.insert(Root->getBlock());
157
158 while (!WorkStack.empty()) {
159 DomTreeNode *Node = WorkStack.back().DTN;
160 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
161 IncomingVal = WorkStack.back().IncomingVal;
162
163 if (ChildIt == Node->end()) {
164 WorkStack.pop_back();
165 } else {
166 DomTreeNode *Child = *ChildIt;
167 ++WorkStack.back().ChildIt;
168 BasicBlock *BB = Child->getBlock();
169 Visited.insert(BB);
170 IncomingVal = renameBlock(BB, IncomingVal);
171 WorkStack.push_back({Child, Child->begin(), IncomingVal});
172 }
173 }
174}
175
176/// \brief Compute dominator levels, used by the phi insertion algorithm above.
177void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
178 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
179 DFI != DFE; ++DFI)
180 DomLevels[*DFI] = DFI.getPathLength() - 1;
181}
182
183/// \brief This handles unreachable block acccesses by deleting phi nodes in
184/// unreachable blocks, and marking all other unreachable MemoryAccess's as
185/// being uses of the live on entry definition.
186void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
187 assert(!DT->isReachableFromEntry(BB) &&
188 "Reachable block found while handling unreachable blocks");
189
190 auto It = PerBlockAccesses.find(BB);
191 if (It == PerBlockAccesses.end())
192 return;
193
194 auto &Accesses = It->second;
195 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
196 auto Next = std::next(AI);
197 // If we have a phi, just remove it. We are going to replace all
198 // users with live on entry.
199 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
200 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
201 else
202 Accesses->erase(AI);
203 AI = Next;
204 }
205}
206
207MemorySSA::MemorySSA(Function &Func)
208 : AA(nullptr), DT(nullptr), F(Func), LiveOnEntryDef(nullptr),
209 Walker(nullptr), NextID(0) {}
210
211MemorySSA::~MemorySSA() {
212 // Drop all our references
213 for (const auto &Pair : PerBlockAccesses)
214 for (MemoryAccess &MA : *Pair.second)
215 MA.dropAllReferences();
216}
217
218MemorySSA::AccessListType *MemorySSA::getOrCreateAccessList(BasicBlock *BB) {
219 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
220
221 if (Res.second)
222 Res.first->second = make_unique<AccessListType>();
223 return Res.first->second.get();
224}
225
226MemorySSAWalker *MemorySSA::buildMemorySSA(AliasAnalysis *AA,
227 DominatorTree *DT) {
228 if (Walker)
229 return Walker;
230
231 assert(!this->AA && !this->DT &&
232 "MemorySSA without a walker already has AA or DT?");
233
Daniel Berlin64120022016-03-02 21:16:28 +0000234 Walker = new CachingMemorySSAWalker(this, AA, DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000235 this->AA = AA;
236 this->DT = DT;
237
238 // We create an access to represent "live on entry", for things like
239 // arguments or users of globals, where the memory they use is defined before
240 // the beginning of the function. We do not actually insert it into the IR.
241 // We do not define a live on exit for the immediate uses, and thus our
242 // semantics do *not* imply that something with no immediate uses can simply
243 // be removed.
244 BasicBlock &StartingPoint = F.getEntryBlock();
245 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
246 &StartingPoint, NextID++);
247
248 // We maintain lists of memory accesses per-block, trading memory for time. We
249 // could just look up the memory access for every possible instruction in the
250 // stream.
251 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000252 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +0000253 // Go through each block, figure out where defs occur, and chain together all
254 // the accesses.
255 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +0000256 bool InsertIntoDef = false;
George Burgess IVe1100f52016-02-02 22:46:49 +0000257 AccessListType *Accesses = nullptr;
258 for (Instruction &I : B) {
George Burgess IVb42b7622016-03-11 19:34:03 +0000259 MemoryUseOrDef *MUD = createNewAccess(&I, true);
260 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +0000261 continue;
George Burgess IV3887a412016-03-21 21:25:39 +0000262 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000263
George Burgess IVe1100f52016-02-02 22:46:49 +0000264 if (!Accesses)
265 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +0000266 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +0000267 }
Daniel Berlin7898ca62016-02-07 01:52:15 +0000268 if (InsertIntoDef)
269 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +0000270 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +0000271 DefUseBlocks.insert(&B);
272 }
273
274 // Compute live-in.
275 // Live in is normally defined as "all the blocks on the path from each def to
276 // each of it's uses".
277 // MemoryDef's are implicit uses of previous state, so they are also uses.
278 // This means we don't really have def-only instructions. The only
279 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
280 // variable (because LiveOnEntry can reach anywhere, and every def is a
281 // must-kill of LiveOnEntry).
282 // In theory, you could precisely compute live-in by using alias-analysis to
283 // disambiguate defs and uses to see which really pair up with which.
284 // In practice, this would be really expensive and difficult. So we simply
285 // assume all defs are also uses that need to be kept live.
286 // Because of this, the end result of this live-in computation will be "the
287 // entire set of basic blocks that reach any use".
288
289 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
290 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
291 DefUseBlocks.end());
292 // Now that we have a set of blocks where a value is live-in, recursively add
293 // predecessors until we find the full region the value is live.
294 while (!LiveInBlockWorklist.empty()) {
295 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
296
297 // The block really is live in here, insert it into the set. If already in
298 // the set, then it has already been processed.
299 if (!LiveInBlocks.insert(BB).second)
300 continue;
301
302 // Since the value is live into BB, it is either defined in a predecessor or
303 // live into it to.
304 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +0000305 }
306
307 // Determine where our MemoryPhi's should go
308 IDFCalculator IDFs(*DT);
309 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000310 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +0000311 SmallVector<BasicBlock *, 32> IDFBlocks;
312 IDFs.calculate(IDFBlocks);
313
314 // Now place MemoryPhi nodes.
315 for (auto &BB : IDFBlocks) {
316 // Insert phi node
317 AccessListType *Accesses = getOrCreateAccessList(BB);
318 MemoryPhi *Phi = new MemoryPhi(F.getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000319 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +0000320 // Phi's always are placed at the front of the block.
321 Accesses->push_front(Phi);
322 }
323
324 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
325 // filled in with all blocks.
326 SmallPtrSet<BasicBlock *, 16> Visited;
327 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
328
329 // Now optimize the MemoryUse's defining access to point to the nearest
330 // dominating clobbering def.
331 // This ensures that MemoryUse's that are killed by the same store are
332 // immediate users of that store, one of the invariants we guarantee.
333 for (auto DomNode : depth_first(DT)) {
334 BasicBlock *BB = DomNode->getBlock();
335 auto AI = PerBlockAccesses.find(BB);
336 if (AI == PerBlockAccesses.end())
337 continue;
338 AccessListType *Accesses = AI->second.get();
339 for (auto &MA : *Accesses) {
340 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
341 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +0000342 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +0000343 }
344 }
345 }
346
347 // Mark the uses in unreachable blocks as live on entry, so that they go
348 // somewhere.
349 for (auto &BB : F)
350 if (!Visited.count(&BB))
351 markUnreachableAsLiveOnEntry(&BB);
352
George Burgess IVe1100f52016-02-02 22:46:49 +0000353 return Walker;
354}
355
356/// \brief Helper function to create new memory accesses
George Burgess IVb42b7622016-03-11 19:34:03 +0000357MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
358 bool IgnoreNonMemory) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000359 // Find out what affect this instruction has on memory.
360 ModRefInfo ModRef = AA->getModRefInfo(I);
361 bool Def = bool(ModRef & MRI_Mod);
362 bool Use = bool(ModRef & MRI_Ref);
363
364 // It's possible for an instruction to not modify memory at all. During
365 // construction, we ignore them.
366 if (IgnoreNonMemory && !Def && !Use)
367 return nullptr;
368
369 assert((Def || Use) &&
370 "Trying to create a memory access with a non-memory instruction");
371
George Burgess IVb42b7622016-03-11 19:34:03 +0000372 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000373 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +0000374 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +0000375 else
George Burgess IVb42b7622016-03-11 19:34:03 +0000376 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
377 ValueToMemoryAccess.insert(std::make_pair(I, MUD));
378 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000379}
380
381MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
382 enum InsertionPlace Where) {
383 // Handle the initial case
384 if (Where == Beginning)
385 // The only thing that could define us at the beginning is a phi node
386 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
387 return Phi;
388
389 DomTreeNode *CurrNode = DT->getNode(UseBlock);
390 // Need to be defined by our dominator
391 if (Where == Beginning)
392 CurrNode = CurrNode->getIDom();
393 Where = End;
394 while (CurrNode) {
395 auto It = PerBlockAccesses.find(CurrNode->getBlock());
396 if (It != PerBlockAccesses.end()) {
397 auto &Accesses = It->second;
398 for (auto RAI = Accesses->rbegin(), RAE = Accesses->rend(); RAI != RAE;
399 ++RAI) {
400 if (isa<MemoryDef>(*RAI) || isa<MemoryPhi>(*RAI))
401 return &*RAI;
402 }
403 }
404 CurrNode = CurrNode->getIDom();
405 }
406 return LiveOnEntryDef.get();
407}
408
409/// \brief Returns true if \p Replacer dominates \p Replacee .
410bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
411 const MemoryAccess *Replacee) const {
412 if (isa<MemoryUseOrDef>(Replacee))
413 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
414 const auto *MP = cast<MemoryPhi>(Replacee);
415 // For a phi node, the use occurs in the predecessor block of the phi node.
416 // Since we may occur multiple times in the phi node, we have to check each
417 // operand to ensure Replacer dominates each operand where Replacee occurs.
418 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000419 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000420 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
421 return false;
422 }
423 return true;
424}
425
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000426/// \brief If all arguments of a MemoryPHI are defined by the same incoming
427/// argument, return that argument.
428static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
429 MemoryAccess *MA = nullptr;
430
431 for (auto &Arg : MP->operands()) {
432 if (!MA)
433 MA = cast<MemoryAccess>(Arg);
434 else if (MA != Arg)
435 return nullptr;
436 }
437 return MA;
438}
439
440/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
441///
442/// Because of the way the intrusive list and use lists work, it is important to
443/// do removal in the right order.
444void MemorySSA::removeFromLookups(MemoryAccess *MA) {
445 assert(MA->use_empty() &&
446 "Trying to remove memory access that still has uses");
447 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
448 MUD->setDefiningAccess(nullptr);
449 // Invalidate our walker's cache if necessary
450 if (!isa<MemoryUse>(MA))
451 Walker->invalidateInfo(MA);
452 // The call below to erase will destroy MA, so we can't change the order we
453 // are doing things here
454 Value *MemoryInst;
455 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
456 MemoryInst = MUD->getMemoryInst();
457 } else {
458 MemoryInst = MA->getBlock();
459 }
460 ValueToMemoryAccess.erase(MemoryInst);
461
George Burgess IVe0e6e482016-03-02 02:35:04 +0000462 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
463 std::unique_ptr<AccessListType> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000464 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +0000465 if (Accesses->empty())
466 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000467}
468
469void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
470 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
471 // We can only delete phi nodes if they have no uses, or we can replace all
472 // uses with a single definition.
473 MemoryAccess *NewDefTarget = nullptr;
474 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
475 // Note that it is sufficient to know that all edges of the phi node have
476 // the same argument. If they do, by the definition of dominance frontiers
477 // (which we used to place this phi), that argument must dominate this phi,
478 // and thus, must dominate the phi's uses, and so we will not hit the assert
479 // below.
480 NewDefTarget = onlySingleValue(MP);
481 assert((NewDefTarget || MP->use_empty()) &&
482 "We can't delete this memory phi");
483 } else {
484 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
485 }
486
487 // Re-point the uses at our defining access
488 if (!MA->use_empty())
489 MA->replaceAllUsesWith(NewDefTarget);
490
491 // The call below to erase will destroy MA, so we can't change the order we
492 // are doing things here
493 removeFromLookups(MA);
494}
495
George Burgess IVe1100f52016-02-02 22:46:49 +0000496void MemorySSA::print(raw_ostream &OS) const {
497 MemorySSAAnnotatedWriter Writer(this);
498 F.print(OS, &Writer);
499}
500
501void MemorySSA::dump() const {
502 MemorySSAAnnotatedWriter Writer(this);
503 F.print(dbgs(), &Writer);
504}
505
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000506void MemorySSA::verifyMemorySSA() const {
507 verifyDefUses(F);
508 verifyDomination(F);
509}
510
George Burgess IVe1100f52016-02-02 22:46:49 +0000511/// \brief Verify the domination properties of MemorySSA by checking that each
512/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000513void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000514 for (BasicBlock &B : F) {
515 // Phi nodes are attached to basic blocks
516 if (MemoryPhi *MP = getMemoryAccess(&B)) {
517 for (User *U : MP->users()) {
518 BasicBlock *UseBlock;
519 // Phi operands are used on edges, we simulate the right domination by
520 // acting as if the use occurred at the end of the predecessor block.
521 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
522 for (const auto &Arg : P->operands()) {
523 if (Arg == MP) {
524 UseBlock = P->getIncomingBlock(Arg);
525 break;
526 }
527 }
528 } else {
529 UseBlock = cast<MemoryAccess>(U)->getBlock();
530 }
George Burgess IV60adac42016-02-02 23:26:01 +0000531 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000532 assert(DT->dominates(MP->getBlock(), UseBlock) &&
533 "Memory PHI does not dominate it's uses");
534 }
535 }
536
537 for (Instruction &I : B) {
538 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
539 if (!MD)
540 continue;
541
Benjamin Kramer451f54c2016-02-22 13:11:58 +0000542 for (User *U : MD->users()) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000543 BasicBlock *UseBlock;
544 // Things are allowed to flow to phi nodes over their predecessor edge.
545 if (auto *P = dyn_cast<MemoryPhi>(U)) {
546 for (const auto &Arg : P->operands()) {
547 if (Arg == MD) {
548 UseBlock = P->getIncomingBlock(Arg);
549 break;
550 }
551 }
552 } else {
553 UseBlock = cast<MemoryAccess>(U)->getBlock();
554 }
555 assert(DT->dominates(MD->getBlock(), UseBlock) &&
556 "Memory Def does not dominate it's uses");
557 }
558 }
559 }
560}
561
562/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
563/// appears in the use list of \p Def.
564///
565/// llvm_unreachable is used instead of asserts because this may be called in
566/// a build without asserts. In that case, we don't want this to turn into a
567/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000568void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000569 // The live on entry use may cause us to get a NULL def here
570 if (!Def) {
571 if (!isLiveOnEntryDef(Use))
572 llvm_unreachable("Null def but use not point to live on entry def");
573 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
574 Def->user_end()) {
575 llvm_unreachable("Did not find use in def's use list");
576 }
577}
578
579/// \brief Verify the immediate use information, by walking all the memory
580/// accesses and verifying that, for each use, it appears in the
581/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000582void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000583 for (BasicBlock &B : F) {
584 // Phi nodes are attached to basic blocks
585 if (MemoryPhi *Phi = getMemoryAccess(&B))
586 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
587 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
588
589 for (Instruction &I : B) {
590 if (MemoryAccess *MA = getMemoryAccess(&I)) {
591 assert(isa<MemoryUseOrDef>(MA) &&
592 "Found a phi node not attached to a bb");
593 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
594 }
595 }
596 }
597}
598
599MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000600 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +0000601}
602
603MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
604 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
605}
606
607/// \brief Determine, for two memory accesses in the same block,
608/// whether \p Dominator dominates \p Dominatee.
609/// \returns True if \p Dominator dominates \p Dominatee.
610bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
611 const MemoryAccess *Dominatee) const {
612
613 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
614 "Asking for local domination when accesses are in different blocks!");
615 // Get the access list for the block
616 const AccessListType *AccessList = getBlockAccesses(Dominator->getBlock());
617 AccessListType::const_reverse_iterator It(Dominator->getIterator());
618
619 // If we hit the beginning of the access list before we hit dominatee, we must
620 // dominate it
621 return std::none_of(It, AccessList->rend(),
622 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
623}
624
625const static char LiveOnEntryStr[] = "liveOnEntry";
626
627void MemoryDef::print(raw_ostream &OS) const {
628 MemoryAccess *UO = getDefiningAccess();
629
630 OS << getID() << " = MemoryDef(";
631 if (UO && UO->getID())
632 OS << UO->getID();
633 else
634 OS << LiveOnEntryStr;
635 OS << ')';
636}
637
638void MemoryPhi::print(raw_ostream &OS) const {
639 bool First = true;
640 OS << getID() << " = MemoryPhi(";
641 for (const auto &Op : operands()) {
642 BasicBlock *BB = getIncomingBlock(Op);
643 MemoryAccess *MA = cast<MemoryAccess>(Op);
644 if (!First)
645 OS << ',';
646 else
647 First = false;
648
649 OS << '{';
650 if (BB->hasName())
651 OS << BB->getName();
652 else
653 BB->printAsOperand(OS, false);
654 OS << ',';
655 if (unsigned ID = MA->getID())
656 OS << ID;
657 else
658 OS << LiveOnEntryStr;
659 OS << '}';
660 }
661 OS << ')';
662}
663
664MemoryAccess::~MemoryAccess() {}
665
666void MemoryUse::print(raw_ostream &OS) const {
667 MemoryAccess *UO = getDefiningAccess();
668 OS << "MemoryUse(";
669 if (UO && UO->getID())
670 OS << UO->getID();
671 else
672 OS << LiveOnEntryStr;
673 OS << ')';
674}
675
676void MemoryAccess::dump() const {
677 print(dbgs());
678 dbgs() << "\n";
679}
680
681char MemorySSAPrinterPass::ID = 0;
682
683MemorySSAPrinterPass::MemorySSAPrinterPass() : FunctionPass(ID) {
684 initializeMemorySSAPrinterPassPass(*PassRegistry::getPassRegistry());
685}
686
687void MemorySSAPrinterPass::releaseMemory() {
688 // Subtlety: Be sure to delete the walker before MSSA, because the walker's
689 // dtor may try to access MemorySSA.
690 Walker.reset();
691 MSSA.reset();
692}
693
694void MemorySSAPrinterPass::getAnalysisUsage(AnalysisUsage &AU) const {
695 AU.setPreservesAll();
696 AU.addRequired<AAResultsWrapperPass>();
697 AU.addRequired<DominatorTreeWrapperPass>();
698 AU.addPreserved<DominatorTreeWrapperPass>();
699 AU.addPreserved<GlobalsAAWrapperPass>();
700}
701
702bool MemorySSAPrinterPass::doInitialization(Module &M) {
George Burgess IV60adac42016-02-02 23:26:01 +0000703 VerifyMemorySSA = M.getContext()
704 .getOption<bool, MemorySSAPrinterPass,
705 &MemorySSAPrinterPass::VerifyMemorySSA>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000706 return false;
707}
708
709void MemorySSAPrinterPass::registerOptions() {
710 OptionRegistry::registerOption<bool, MemorySSAPrinterPass,
711 &MemorySSAPrinterPass::VerifyMemorySSA>(
712 "verify-memoryssa", "Run the Memory SSA verifier", false);
713}
714
715void MemorySSAPrinterPass::print(raw_ostream &OS, const Module *M) const {
716 MSSA->print(OS);
717}
718
719bool MemorySSAPrinterPass::runOnFunction(Function &F) {
720 this->F = &F;
721 MSSA.reset(new MemorySSA(F));
722 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
723 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
724 Walker.reset(MSSA->buildMemorySSA(AA, DT));
725
726 if (VerifyMemorySSA) {
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000727 MSSA->verifyMemorySSA();
George Burgess IVe1100f52016-02-02 22:46:49 +0000728 }
729
730 return false;
731}
732
733char MemorySSALazy::ID = 0;
734
735MemorySSALazy::MemorySSALazy() : FunctionPass(ID) {
736 initializeMemorySSALazyPass(*PassRegistry::getPassRegistry());
737}
738
739void MemorySSALazy::releaseMemory() { MSSA.reset(); }
740
741bool MemorySSALazy::runOnFunction(Function &F) {
742 MSSA.reset(new MemorySSA(F));
743 return false;
744}
745
746MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
747
748CachingMemorySSAWalker::CachingMemorySSAWalker(MemorySSA *M, AliasAnalysis *A,
749 DominatorTree *D)
750 : MemorySSAWalker(M), AA(A), DT(D) {}
751
752CachingMemorySSAWalker::~CachingMemorySSAWalker() {}
753
754struct CachingMemorySSAWalker::UpwardsMemoryQuery {
755 // True if we saw a phi whose predecessor was a backedge
756 bool SawBackedgePhi;
757 // True if our original query started off as a call
758 bool IsCall;
759 // The pointer location we started the query with. This will be empty if
760 // IsCall is true.
761 MemoryLocation StartingLoc;
762 // This is the instruction we were querying about.
763 const Instruction *Inst;
764 // Set of visited Instructions for this query.
765 DenseSet<MemoryAccessPair> Visited;
766 // Set of visited call accesses for this query. This is separated out because
767 // you can always cache and lookup the result of call queries (IE when IsCall
768 // == true) for every call in the chain. The calls have no AA location
769 // associated with them with them, and thus, no context dependence.
770 SmallPtrSet<const MemoryAccess *, 32> VisitedCalls;
771 // The MemoryAccess we actually got called with, used to test local domination
772 const MemoryAccess *OriginalAccess;
773 // The Datalayout for the module we started in
774 const DataLayout *DL;
775
776 UpwardsMemoryQuery()
777 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
778 OriginalAccess(nullptr), DL(nullptr) {}
779};
780
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000781void CachingMemorySSAWalker::invalidateInfo(MemoryAccess *MA) {
782
783 // TODO: We can do much better cache invalidation with differently stored
784 // caches. For now, for MemoryUses, we simply remove them
785 // from the cache, and kill the entire call/non-call cache for everything
786 // else. The problem is for phis or defs, currently we'd need to follow use
787 // chains down and invalidate anything below us in the chain that currently
788 // terminates at this access.
789
790 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
791 // is by definition never a barrier, so nothing in the cache could point to
792 // this use. In that case, we only need invalidate the info for the use
793 // itself.
794
795 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
796 UpwardsMemoryQuery Q;
797 Instruction *I = MU->getMemoryInst();
798 Q.IsCall = bool(ImmutableCallSite(I));
799 Q.Inst = I;
800 if (!Q.IsCall)
801 Q.StartingLoc = MemoryLocation::get(I);
802 doCacheRemove(MA, Q, Q.StartingLoc);
803 return;
804 }
805 // If it is not a use, the best we can do right now is destroy the cache.
806 bool IsCall = false;
807
808 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
809 Instruction *I = MUD->getMemoryInst();
810 IsCall = bool(ImmutableCallSite(I));
811 }
812 if (IsCall)
813 CachedUpwardsClobberingCall.clear();
814 else
815 CachedUpwardsClobberingAccess.clear();
816}
817
George Burgess IVe1100f52016-02-02 22:46:49 +0000818void CachingMemorySSAWalker::doCacheRemove(const MemoryAccess *M,
819 const UpwardsMemoryQuery &Q,
820 const MemoryLocation &Loc) {
821 if (Q.IsCall)
822 CachedUpwardsClobberingCall.erase(M);
823 else
824 CachedUpwardsClobberingAccess.erase({M, Loc});
825}
826
827void CachingMemorySSAWalker::doCacheInsert(const MemoryAccess *M,
828 MemoryAccess *Result,
829 const UpwardsMemoryQuery &Q,
830 const MemoryLocation &Loc) {
831 ++NumClobberCacheInserts;
832 if (Q.IsCall)
833 CachedUpwardsClobberingCall[M] = Result;
834 else
835 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
836}
837
838MemoryAccess *CachingMemorySSAWalker::doCacheLookup(const MemoryAccess *M,
839 const UpwardsMemoryQuery &Q,
840 const MemoryLocation &Loc) {
841 ++NumClobberCacheLookups;
842 MemoryAccess *Result = nullptr;
843
844 if (Q.IsCall)
845 Result = CachedUpwardsClobberingCall.lookup(M);
846 else
847 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
848
849 if (Result)
850 ++NumClobberCacheHits;
851 return Result;
852}
853
854bool CachingMemorySSAWalker::instructionClobbersQuery(
855 const MemoryDef *MD, UpwardsMemoryQuery &Q,
856 const MemoryLocation &Loc) const {
857 Instruction *DefMemoryInst = MD->getMemoryInst();
858 assert(DefMemoryInst && "Defining instruction not actually an instruction");
859
860 if (!Q.IsCall)
861 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
862
863 // If this is a call, mark it for caching
864 if (ImmutableCallSite(DefMemoryInst))
865 Q.VisitedCalls.insert(MD);
866 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
867 return I != MRI_NoModRef;
868}
869
870MemoryAccessPair CachingMemorySSAWalker::UpwardsDFSWalk(
871 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
872 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
873 MemoryAccess *ModifyingAccess = nullptr;
874
875 auto DFI = df_begin(StartingAccess);
876 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
877 MemoryAccess *CurrAccess = *DFI;
878 if (MSSA->isLiveOnEntryDef(CurrAccess))
879 return {CurrAccess, Loc};
880 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
881 return {CacheResult, Loc};
882 // If this is a MemoryDef, check whether it clobbers our current query.
883 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
884 // If we hit the top, stop following this path.
885 // While we can do lookups, we can't sanely do inserts here unless we were
886 // to track everything we saw along the way, since we don't know where we
887 // will stop.
888 if (instructionClobbersQuery(MD, Q, Loc)) {
889 ModifyingAccess = CurrAccess;
890 break;
891 }
892 }
893
894 // We need to know whether it is a phi so we can track backedges.
895 // Otherwise, walk all upward defs.
896 if (!isa<MemoryPhi>(CurrAccess)) {
897 ++DFI;
898 continue;
899 }
900
George Burgess IV0e489862016-03-23 18:31:55 +0000901#ifndef NDEBUG
902 // The loop below visits the phi's children for us. Because phis are the
903 // only things with multiple edges, skipping the children should always lead
904 // us to the end of the loop.
905 //
906 // Use a copy of DFI because skipChildren would kill our search stack, which
907 // would make caching anything on the way back impossible.
908 auto DFICopy = DFI;
909 assert(DFICopy.skipChildren() == DFE &&
910 "Skipping phi's children doesn't end the DFS?");
911#endif
912
George Burgess IV82ee9422016-03-30 00:26:26 +0000913 const MemoryAccessPair PHIPair(CurrAccess, Loc);
914
915 // Don't try to optimize this phi again if we've already tried to do so.
916 if (!Q.Visited.insert(PHIPair).second) {
917 ModifyingAccess = CurrAccess;
918 break;
919 }
920
George Burgess IVe1100f52016-02-02 22:46:49 +0000921 // Recurse on PHI nodes, since we need to change locations.
922 // TODO: Allow graphtraits on pairs, which would turn this whole function
923 // into a normal single depth first walk.
924 MemoryAccess *FirstDef = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +0000925 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
926 MPI != MPE; ++MPI) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000927 bool Backedge =
928 !FollowingBackedge &&
929 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
930
931 MemoryAccessPair CurrentPair =
932 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
933 // All the phi arguments should reach the same point if we can bypass
934 // this phi. The alternative is that they hit this phi node, which
935 // means we can skip this argument.
936 if (FirstDef && CurrentPair.first != PHIPair.first &&
937 CurrentPair.first != FirstDef) {
938 ModifyingAccess = CurrAccess;
939 break;
940 }
941
942 if (!FirstDef)
943 FirstDef = CurrentPair.first;
George Burgess IVe1100f52016-02-02 22:46:49 +0000944 }
945
George Burgess IV0e489862016-03-23 18:31:55 +0000946 // If we exited the loop early, go with the result it gave us.
947 if (!ModifyingAccess) {
George Burgess IV82ee9422016-03-30 00:26:26 +0000948 assert(FirstDef && "Found a Phi with no upward defs?");
949 ModifyingAccess = FirstDef;
George Burgess IV0e489862016-03-23 18:31:55 +0000950 }
951 break;
George Burgess IVe1100f52016-02-02 22:46:49 +0000952 }
953
954 if (!ModifyingAccess)
955 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
956
George Burgess IV0e489862016-03-23 18:31:55 +0000957 const BasicBlock *OriginalBlock = StartingAccess->getBlock();
George Burgess IVe1100f52016-02-02 22:46:49 +0000958 unsigned N = DFI.getPathLength();
George Burgess IVe1100f52016-02-02 22:46:49 +0000959 for (; N != 0; --N) {
George Burgess IV0e489862016-03-23 18:31:55 +0000960 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
961 BasicBlock *CurrBlock = CacheAccess->getBlock();
George Burgess IVe1100f52016-02-02 22:46:49 +0000962 if (!FollowingBackedge)
George Burgess IV0e489862016-03-23 18:31:55 +0000963 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
George Burgess IVe1100f52016-02-02 22:46:49 +0000964 if (DT->dominates(CurrBlock, OriginalBlock) &&
965 (CurrBlock != OriginalBlock || !FollowingBackedge ||
George Burgess IV0e489862016-03-23 18:31:55 +0000966 MSSA->locallyDominates(CacheAccess, StartingAccess)))
George Burgess IVe1100f52016-02-02 22:46:49 +0000967 break;
968 }
969
970 // Cache everything else on the way back. The caller should cache
971 // Q.OriginalAccess for us.
972 for (; N != 0; --N) {
973 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
974 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
975 }
976 assert(Q.Visited.size() < 1000 && "Visited too much");
977
978 return {ModifyingAccess, Loc};
979}
980
981/// \brief Walk the use-def chains starting at \p MA and find
982/// the MemoryAccess that actually clobbers Loc.
983///
984/// \returns our clobbering memory access
985MemoryAccess *
986CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
987 UpwardsMemoryQuery &Q) {
988 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
989}
990
991MemoryAccess *
992CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
993 MemoryLocation &Loc) {
994 if (isa<MemoryPhi>(StartingAccess))
995 return StartingAccess;
996
997 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
998 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
999 return StartingUseOrDef;
1000
1001 Instruction *I = StartingUseOrDef->getMemoryInst();
1002
1003 // Conservatively, fences are always clobbers, so don't perform the walk if we
1004 // hit a fence.
1005 if (isa<FenceInst>(I))
1006 return StartingUseOrDef;
1007
1008 UpwardsMemoryQuery Q;
1009 Q.OriginalAccess = StartingUseOrDef;
1010 Q.StartingLoc = Loc;
1011 Q.Inst = StartingUseOrDef->getMemoryInst();
1012 Q.IsCall = false;
1013 Q.DL = &Q.Inst->getModule()->getDataLayout();
1014
1015 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
1016 return CacheResult;
1017
1018 // Unlike the other function, do not walk to the def of a def, because we are
1019 // handed something we already believe is the clobbering access.
1020 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1021 ? StartingUseOrDef->getDefiningAccess()
1022 : StartingUseOrDef;
1023
1024 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
1025 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
1026 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1027 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1028 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1029 DEBUG(dbgs() << *Clobber << "\n");
1030 return Clobber;
1031}
1032
1033MemoryAccess *
1034CachingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1035 // There should be no way to lookup an instruction and get a phi as the
1036 // access, since we only map BB's to PHI's. So, this must be a use or def.
1037 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
1038
1039 // We can't sanely do anything with a FenceInst, they conservatively
1040 // clobber all memory, and have no locations to get pointers from to
1041 // try to disambiguate
1042 if (isa<FenceInst>(I))
1043 return StartingAccess;
1044
1045 UpwardsMemoryQuery Q;
1046 Q.OriginalAccess = StartingAccess;
1047 Q.IsCall = bool(ImmutableCallSite(I));
1048 if (!Q.IsCall)
1049 Q.StartingLoc = MemoryLocation::get(I);
1050 Q.Inst = I;
1051 Q.DL = &Q.Inst->getModule()->getDataLayout();
1052 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
1053 return CacheResult;
1054
1055 // Start with the thing we already think clobbers this location
1056 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1057
1058 // At this point, DefiningAccess may be the live on entry def.
1059 // If it is, we will not get a better result.
1060 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1061 return DefiningAccess;
1062
1063 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
1064 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
1065 // TODO: When this implementation is more mature, we may want to figure out
1066 // what this additional caching buys us. It's most likely A Good Thing.
1067 if (Q.IsCall)
1068 for (const MemoryAccess *MA : Q.VisitedCalls)
1069 doCacheInsert(MA, Result, Q, Q.StartingLoc);
1070
1071 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1072 DEBUG(dbgs() << *DefiningAccess << "\n");
1073 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1074 DEBUG(dbgs() << *Result << "\n");
1075
1076 return Result;
1077}
1078
1079MemoryAccess *
1080DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1081 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1082 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1083 return Use->getDefiningAccess();
1084 return MA;
1085}
1086
1087MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1088 MemoryAccess *StartingAccess, MemoryLocation &) {
1089 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1090 return Use->getDefiningAccess();
1091 return StartingAccess;
1092}
1093}