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