blob: faa25b5ade89118b2488e24bc02e6c299c6841e1 [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
234 auto *Result = new CachingMemorySSAWalker(this, AA, DT);
235 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 Berlin1b51a292016-02-07 01:52:19 +0000256 bool InsertIntoDefUse = false;
Daniel Berlin7898ca62016-02-07 01:52:15 +0000257 bool InsertIntoDef = false;
George Burgess IVe1100f52016-02-02 22:46:49 +0000258 AccessListType *Accesses = nullptr;
259 for (Instruction &I : B) {
260 MemoryAccess *MA = createNewAccess(&I, true);
261 if (!MA)
262 continue;
263 if (isa<MemoryDef>(MA))
Daniel Berlin7898ca62016-02-07 01:52:15 +0000264 InsertIntoDef = true;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000265 else if (isa<MemoryUse>(MA))
266 InsertIntoDefUse = true;
267
George Burgess IVe1100f52016-02-02 22:46:49 +0000268 if (!Accesses)
269 Accesses = getOrCreateAccessList(&B);
270 Accesses->push_back(MA);
271 }
Daniel Berlin7898ca62016-02-07 01:52:15 +0000272 if (InsertIntoDef)
273 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000274 if (InsertIntoDefUse)
275 DefUseBlocks.insert(&B);
276 }
277
278 // Compute live-in.
279 // Live in is normally defined as "all the blocks on the path from each def to
280 // each of it's uses".
281 // MemoryDef's are implicit uses of previous state, so they are also uses.
282 // This means we don't really have def-only instructions. The only
283 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
284 // variable (because LiveOnEntry can reach anywhere, and every def is a
285 // must-kill of LiveOnEntry).
286 // In theory, you could precisely compute live-in by using alias-analysis to
287 // disambiguate defs and uses to see which really pair up with which.
288 // In practice, this would be really expensive and difficult. So we simply
289 // assume all defs are also uses that need to be kept live.
290 // Because of this, the end result of this live-in computation will be "the
291 // entire set of basic blocks that reach any use".
292
293 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
294 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
295 DefUseBlocks.end());
296 // Now that we have a set of blocks where a value is live-in, recursively add
297 // predecessors until we find the full region the value is live.
298 while (!LiveInBlockWorklist.empty()) {
299 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
300
301 // The block really is live in here, insert it into the set. If already in
302 // the set, then it has already been processed.
303 if (!LiveInBlocks.insert(BB).second)
304 continue;
305
306 // Since the value is live into BB, it is either defined in a predecessor or
307 // live into it to.
308 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +0000309 }
310
311 // Determine where our MemoryPhi's should go
312 IDFCalculator IDFs(*DT);
313 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000314 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +0000315 SmallVector<BasicBlock *, 32> IDFBlocks;
316 IDFs.calculate(IDFBlocks);
317
318 // Now place MemoryPhi nodes.
319 for (auto &BB : IDFBlocks) {
320 // Insert phi node
321 AccessListType *Accesses = getOrCreateAccessList(BB);
322 MemoryPhi *Phi = new MemoryPhi(F.getContext(), BB, NextID++);
323 InstructionToMemoryAccess.insert(std::make_pair(BB, Phi));
324 // Phi's always are placed at the front of the block.
325 Accesses->push_front(Phi);
326 }
327
328 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
329 // filled in with all blocks.
330 SmallPtrSet<BasicBlock *, 16> Visited;
331 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
332
333 // Now optimize the MemoryUse's defining access to point to the nearest
334 // dominating clobbering def.
335 // This ensures that MemoryUse's that are killed by the same store are
336 // immediate users of that store, one of the invariants we guarantee.
337 for (auto DomNode : depth_first(DT)) {
338 BasicBlock *BB = DomNode->getBlock();
339 auto AI = PerBlockAccesses.find(BB);
340 if (AI == PerBlockAccesses.end())
341 continue;
342 AccessListType *Accesses = AI->second.get();
343 for (auto &MA : *Accesses) {
344 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
345 Instruction *Inst = MU->getMemoryInst();
346 MU->setDefiningAccess(Result->getClobberingMemoryAccess(Inst));
347 }
348 }
349 }
350
351 // Mark the uses in unreachable blocks as live on entry, so that they go
352 // somewhere.
353 for (auto &BB : F)
354 if (!Visited.count(&BB))
355 markUnreachableAsLiveOnEntry(&BB);
356
357 Walker = Result;
358 return Walker;
359}
360
361/// \brief Helper function to create new memory accesses
362MemoryAccess *MemorySSA::createNewAccess(Instruction *I, bool IgnoreNonMemory) {
363 // Find out what affect this instruction has on memory.
364 ModRefInfo ModRef = AA->getModRefInfo(I);
365 bool Def = bool(ModRef & MRI_Mod);
366 bool Use = bool(ModRef & MRI_Ref);
367
368 // It's possible for an instruction to not modify memory at all. During
369 // construction, we ignore them.
370 if (IgnoreNonMemory && !Def && !Use)
371 return nullptr;
372
373 assert((Def || Use) &&
374 "Trying to create a memory access with a non-memory instruction");
375
376 MemoryUseOrDef *MA;
377 if (Def)
Daniel Berlin905a6462016-02-07 02:03:39 +0000378 MA = new MemoryDef(I->getContext(), nullptr, I, I->getParent(),
George Burgess IVe1100f52016-02-02 22:46:49 +0000379 NextID++);
380 else
381 MA =
Daniel Berlin905a6462016-02-07 02:03:39 +0000382 new MemoryUse(I->getContext(), nullptr, I, I->getParent());
George Burgess IVe1100f52016-02-02 22:46:49 +0000383 InstructionToMemoryAccess.insert(std::make_pair(I, MA));
384 return MA;
385}
386
387MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
388 enum InsertionPlace Where) {
389 // Handle the initial case
390 if (Where == Beginning)
391 // The only thing that could define us at the beginning is a phi node
392 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
393 return Phi;
394
395 DomTreeNode *CurrNode = DT->getNode(UseBlock);
396 // Need to be defined by our dominator
397 if (Where == Beginning)
398 CurrNode = CurrNode->getIDom();
399 Where = End;
400 while (CurrNode) {
401 auto It = PerBlockAccesses.find(CurrNode->getBlock());
402 if (It != PerBlockAccesses.end()) {
403 auto &Accesses = It->second;
404 for (auto RAI = Accesses->rbegin(), RAE = Accesses->rend(); RAI != RAE;
405 ++RAI) {
406 if (isa<MemoryDef>(*RAI) || isa<MemoryPhi>(*RAI))
407 return &*RAI;
408 }
409 }
410 CurrNode = CurrNode->getIDom();
411 }
412 return LiveOnEntryDef.get();
413}
414
415/// \brief Returns true if \p Replacer dominates \p Replacee .
416bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
417 const MemoryAccess *Replacee) const {
418 if (isa<MemoryUseOrDef>(Replacee))
419 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
420 const auto *MP = cast<MemoryPhi>(Replacee);
421 // For a phi node, the use occurs in the predecessor block of the phi node.
422 // Since we may occur multiple times in the phi node, we have to check each
423 // operand to ensure Replacer dominates each operand where Replacee occurs.
424 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000425 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000426 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
427 return false;
428 }
429 return true;
430}
431
432void MemorySSA::print(raw_ostream &OS) const {
433 MemorySSAAnnotatedWriter Writer(this);
434 F.print(OS, &Writer);
435}
436
437void MemorySSA::dump() const {
438 MemorySSAAnnotatedWriter Writer(this);
439 F.print(dbgs(), &Writer);
440}
441
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000442void MemorySSA::verifyMemorySSA() const {
443 verifyDefUses(F);
444 verifyDomination(F);
445}
446
George Burgess IVe1100f52016-02-02 22:46:49 +0000447/// \brief Verify the domination properties of MemorySSA by checking that each
448/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000449void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000450 for (BasicBlock &B : F) {
451 // Phi nodes are attached to basic blocks
452 if (MemoryPhi *MP = getMemoryAccess(&B)) {
453 for (User *U : MP->users()) {
454 BasicBlock *UseBlock;
455 // Phi operands are used on edges, we simulate the right domination by
456 // acting as if the use occurred at the end of the predecessor block.
457 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
458 for (const auto &Arg : P->operands()) {
459 if (Arg == MP) {
460 UseBlock = P->getIncomingBlock(Arg);
461 break;
462 }
463 }
464 } else {
465 UseBlock = cast<MemoryAccess>(U)->getBlock();
466 }
George Burgess IV60adac42016-02-02 23:26:01 +0000467 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000468 assert(DT->dominates(MP->getBlock(), UseBlock) &&
469 "Memory PHI does not dominate it's uses");
470 }
471 }
472
473 for (Instruction &I : B) {
474 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
475 if (!MD)
476 continue;
477
478 for (const auto &U : MD->users()) {
479 BasicBlock *UseBlock;
480 // Things are allowed to flow to phi nodes over their predecessor edge.
481 if (auto *P = dyn_cast<MemoryPhi>(U)) {
482 for (const auto &Arg : P->operands()) {
483 if (Arg == MD) {
484 UseBlock = P->getIncomingBlock(Arg);
485 break;
486 }
487 }
488 } else {
489 UseBlock = cast<MemoryAccess>(U)->getBlock();
490 }
491 assert(DT->dominates(MD->getBlock(), UseBlock) &&
492 "Memory Def does not dominate it's uses");
493 }
494 }
495 }
496}
497
498/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
499/// appears in the use list of \p Def.
500///
501/// llvm_unreachable is used instead of asserts because this may be called in
502/// a build without asserts. In that case, we don't want this to turn into a
503/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000504void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000505 // The live on entry use may cause us to get a NULL def here
506 if (!Def) {
507 if (!isLiveOnEntryDef(Use))
508 llvm_unreachable("Null def but use not point to live on entry def");
509 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
510 Def->user_end()) {
511 llvm_unreachable("Did not find use in def's use list");
512 }
513}
514
515/// \brief Verify the immediate use information, by walking all the memory
516/// accesses and verifying that, for each use, it appears in the
517/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000518void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000519 for (BasicBlock &B : F) {
520 // Phi nodes are attached to basic blocks
521 if (MemoryPhi *Phi = getMemoryAccess(&B))
522 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
523 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
524
525 for (Instruction &I : B) {
526 if (MemoryAccess *MA = getMemoryAccess(&I)) {
527 assert(isa<MemoryUseOrDef>(MA) &&
528 "Found a phi node not attached to a bb");
529 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
530 }
531 }
532 }
533}
534
535MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
536 return InstructionToMemoryAccess.lookup(I);
537}
538
539MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
540 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
541}
542
543/// \brief Determine, for two memory accesses in the same block,
544/// whether \p Dominator dominates \p Dominatee.
545/// \returns True if \p Dominator dominates \p Dominatee.
546bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
547 const MemoryAccess *Dominatee) const {
548
549 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
550 "Asking for local domination when accesses are in different blocks!");
551 // Get the access list for the block
552 const AccessListType *AccessList = getBlockAccesses(Dominator->getBlock());
553 AccessListType::const_reverse_iterator It(Dominator->getIterator());
554
555 // If we hit the beginning of the access list before we hit dominatee, we must
556 // dominate it
557 return std::none_of(It, AccessList->rend(),
558 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
559}
560
561const static char LiveOnEntryStr[] = "liveOnEntry";
562
563void MemoryDef::print(raw_ostream &OS) const {
564 MemoryAccess *UO = getDefiningAccess();
565
566 OS << getID() << " = MemoryDef(";
567 if (UO && UO->getID())
568 OS << UO->getID();
569 else
570 OS << LiveOnEntryStr;
571 OS << ')';
572}
573
574void MemoryPhi::print(raw_ostream &OS) const {
575 bool First = true;
576 OS << getID() << " = MemoryPhi(";
577 for (const auto &Op : operands()) {
578 BasicBlock *BB = getIncomingBlock(Op);
579 MemoryAccess *MA = cast<MemoryAccess>(Op);
580 if (!First)
581 OS << ',';
582 else
583 First = false;
584
585 OS << '{';
586 if (BB->hasName())
587 OS << BB->getName();
588 else
589 BB->printAsOperand(OS, false);
590 OS << ',';
591 if (unsigned ID = MA->getID())
592 OS << ID;
593 else
594 OS << LiveOnEntryStr;
595 OS << '}';
596 }
597 OS << ')';
598}
599
600MemoryAccess::~MemoryAccess() {}
601
602void MemoryUse::print(raw_ostream &OS) const {
603 MemoryAccess *UO = getDefiningAccess();
604 OS << "MemoryUse(";
605 if (UO && UO->getID())
606 OS << UO->getID();
607 else
608 OS << LiveOnEntryStr;
609 OS << ')';
610}
611
612void MemoryAccess::dump() const {
613 print(dbgs());
614 dbgs() << "\n";
615}
616
617char MemorySSAPrinterPass::ID = 0;
618
619MemorySSAPrinterPass::MemorySSAPrinterPass() : FunctionPass(ID) {
620 initializeMemorySSAPrinterPassPass(*PassRegistry::getPassRegistry());
621}
622
623void MemorySSAPrinterPass::releaseMemory() {
624 // Subtlety: Be sure to delete the walker before MSSA, because the walker's
625 // dtor may try to access MemorySSA.
626 Walker.reset();
627 MSSA.reset();
628}
629
630void MemorySSAPrinterPass::getAnalysisUsage(AnalysisUsage &AU) const {
631 AU.setPreservesAll();
632 AU.addRequired<AAResultsWrapperPass>();
633 AU.addRequired<DominatorTreeWrapperPass>();
634 AU.addPreserved<DominatorTreeWrapperPass>();
635 AU.addPreserved<GlobalsAAWrapperPass>();
636}
637
638bool MemorySSAPrinterPass::doInitialization(Module &M) {
George Burgess IV60adac42016-02-02 23:26:01 +0000639 VerifyMemorySSA = M.getContext()
640 .getOption<bool, MemorySSAPrinterPass,
641 &MemorySSAPrinterPass::VerifyMemorySSA>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000642 return false;
643}
644
645void MemorySSAPrinterPass::registerOptions() {
646 OptionRegistry::registerOption<bool, MemorySSAPrinterPass,
647 &MemorySSAPrinterPass::VerifyMemorySSA>(
648 "verify-memoryssa", "Run the Memory SSA verifier", false);
649}
650
651void MemorySSAPrinterPass::print(raw_ostream &OS, const Module *M) const {
652 MSSA->print(OS);
653}
654
655bool MemorySSAPrinterPass::runOnFunction(Function &F) {
656 this->F = &F;
657 MSSA.reset(new MemorySSA(F));
658 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
659 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
660 Walker.reset(MSSA->buildMemorySSA(AA, DT));
661
662 if (VerifyMemorySSA) {
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000663 MSSA->verifyMemorySSA();
George Burgess IVe1100f52016-02-02 22:46:49 +0000664 }
665
666 return false;
667}
668
669char MemorySSALazy::ID = 0;
670
671MemorySSALazy::MemorySSALazy() : FunctionPass(ID) {
672 initializeMemorySSALazyPass(*PassRegistry::getPassRegistry());
673}
674
675void MemorySSALazy::releaseMemory() { MSSA.reset(); }
676
677bool MemorySSALazy::runOnFunction(Function &F) {
678 MSSA.reset(new MemorySSA(F));
679 return false;
680}
681
682MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
683
684CachingMemorySSAWalker::CachingMemorySSAWalker(MemorySSA *M, AliasAnalysis *A,
685 DominatorTree *D)
686 : MemorySSAWalker(M), AA(A), DT(D) {}
687
688CachingMemorySSAWalker::~CachingMemorySSAWalker() {}
689
690struct CachingMemorySSAWalker::UpwardsMemoryQuery {
691 // True if we saw a phi whose predecessor was a backedge
692 bool SawBackedgePhi;
693 // True if our original query started off as a call
694 bool IsCall;
695 // The pointer location we started the query with. This will be empty if
696 // IsCall is true.
697 MemoryLocation StartingLoc;
698 // This is the instruction we were querying about.
699 const Instruction *Inst;
700 // Set of visited Instructions for this query.
701 DenseSet<MemoryAccessPair> Visited;
702 // Set of visited call accesses for this query. This is separated out because
703 // you can always cache and lookup the result of call queries (IE when IsCall
704 // == true) for every call in the chain. The calls have no AA location
705 // associated with them with them, and thus, no context dependence.
706 SmallPtrSet<const MemoryAccess *, 32> VisitedCalls;
707 // The MemoryAccess we actually got called with, used to test local domination
708 const MemoryAccess *OriginalAccess;
709 // The Datalayout for the module we started in
710 const DataLayout *DL;
711
712 UpwardsMemoryQuery()
713 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
714 OriginalAccess(nullptr), DL(nullptr) {}
715};
716
717void CachingMemorySSAWalker::doCacheRemove(const MemoryAccess *M,
718 const UpwardsMemoryQuery &Q,
719 const MemoryLocation &Loc) {
720 if (Q.IsCall)
721 CachedUpwardsClobberingCall.erase(M);
722 else
723 CachedUpwardsClobberingAccess.erase({M, Loc});
724}
725
726void CachingMemorySSAWalker::doCacheInsert(const MemoryAccess *M,
727 MemoryAccess *Result,
728 const UpwardsMemoryQuery &Q,
729 const MemoryLocation &Loc) {
730 ++NumClobberCacheInserts;
731 if (Q.IsCall)
732 CachedUpwardsClobberingCall[M] = Result;
733 else
734 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
735}
736
737MemoryAccess *CachingMemorySSAWalker::doCacheLookup(const MemoryAccess *M,
738 const UpwardsMemoryQuery &Q,
739 const MemoryLocation &Loc) {
740 ++NumClobberCacheLookups;
741 MemoryAccess *Result = nullptr;
742
743 if (Q.IsCall)
744 Result = CachedUpwardsClobberingCall.lookup(M);
745 else
746 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
747
748 if (Result)
749 ++NumClobberCacheHits;
750 return Result;
751}
752
753bool CachingMemorySSAWalker::instructionClobbersQuery(
754 const MemoryDef *MD, UpwardsMemoryQuery &Q,
755 const MemoryLocation &Loc) const {
756 Instruction *DefMemoryInst = MD->getMemoryInst();
757 assert(DefMemoryInst && "Defining instruction not actually an instruction");
758
759 if (!Q.IsCall)
760 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
761
762 // If this is a call, mark it for caching
763 if (ImmutableCallSite(DefMemoryInst))
764 Q.VisitedCalls.insert(MD);
765 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
766 return I != MRI_NoModRef;
767}
768
769MemoryAccessPair CachingMemorySSAWalker::UpwardsDFSWalk(
770 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
771 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
772 MemoryAccess *ModifyingAccess = nullptr;
773
774 auto DFI = df_begin(StartingAccess);
775 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
776 MemoryAccess *CurrAccess = *DFI;
777 if (MSSA->isLiveOnEntryDef(CurrAccess))
778 return {CurrAccess, Loc};
779 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
780 return {CacheResult, Loc};
781 // If this is a MemoryDef, check whether it clobbers our current query.
782 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
783 // If we hit the top, stop following this path.
784 // While we can do lookups, we can't sanely do inserts here unless we were
785 // to track everything we saw along the way, since we don't know where we
786 // will stop.
787 if (instructionClobbersQuery(MD, Q, Loc)) {
788 ModifyingAccess = CurrAccess;
789 break;
790 }
791 }
792
793 // We need to know whether it is a phi so we can track backedges.
794 // Otherwise, walk all upward defs.
795 if (!isa<MemoryPhi>(CurrAccess)) {
796 ++DFI;
797 continue;
798 }
799
800 // Recurse on PHI nodes, since we need to change locations.
801 // TODO: Allow graphtraits on pairs, which would turn this whole function
802 // into a normal single depth first walk.
803 MemoryAccess *FirstDef = nullptr;
804 DFI = DFI.skipChildren();
805 const MemoryAccessPair PHIPair(CurrAccess, Loc);
806 bool VisitedOnlyOne = true;
807 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
808 MPI != MPE; ++MPI) {
809 // Don't follow this path again if we've followed it once
810 if (!Q.Visited.insert(*MPI).second)
811 continue;
812
813 bool Backedge =
814 !FollowingBackedge &&
815 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
816
817 MemoryAccessPair CurrentPair =
818 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
819 // All the phi arguments should reach the same point if we can bypass
820 // this phi. The alternative is that they hit this phi node, which
821 // means we can skip this argument.
822 if (FirstDef && CurrentPair.first != PHIPair.first &&
823 CurrentPair.first != FirstDef) {
824 ModifyingAccess = CurrAccess;
825 break;
826 }
827
828 if (!FirstDef)
829 FirstDef = CurrentPair.first;
830 else
831 VisitedOnlyOne = false;
832 }
833
834 // The above loop determines if all arguments of the phi node reach the
835 // same place. However we skip arguments that are cyclically dependent
836 // only on the value of this phi node. This means in some cases, we may
837 // only visit one argument of the phi node, and the above loop will
838 // happily say that all the arguments are the same. However, in that case,
839 // we still can't walk past the phi node, because that argument still
840 // kills the access unless we hit the top of the function when walking
841 // that argument.
842 if (VisitedOnlyOne && FirstDef && !MSSA->isLiveOnEntryDef(FirstDef))
843 ModifyingAccess = CurrAccess;
844 }
845
846 if (!ModifyingAccess)
847 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
848
849 const BasicBlock *OriginalBlock = Q.OriginalAccess->getBlock();
850 unsigned N = DFI.getPathLength();
851 MemoryAccess *FinalAccess = ModifyingAccess;
852 for (; N != 0; --N) {
853 ModifyingAccess = DFI.getPath(N - 1);
854 BasicBlock *CurrBlock = ModifyingAccess->getBlock();
855 if (!FollowingBackedge)
856 doCacheInsert(ModifyingAccess, FinalAccess, Q, Loc);
857 if (DT->dominates(CurrBlock, OriginalBlock) &&
858 (CurrBlock != OriginalBlock || !FollowingBackedge ||
859 MSSA->locallyDominates(ModifyingAccess, Q.OriginalAccess)))
860 break;
861 }
862
863 // Cache everything else on the way back. The caller should cache
864 // Q.OriginalAccess for us.
865 for (; N != 0; --N) {
866 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
867 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
868 }
869 assert(Q.Visited.size() < 1000 && "Visited too much");
870
871 return {ModifyingAccess, Loc};
872}
873
874/// \brief Walk the use-def chains starting at \p MA and find
875/// the MemoryAccess that actually clobbers Loc.
876///
877/// \returns our clobbering memory access
878MemoryAccess *
879CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
880 UpwardsMemoryQuery &Q) {
881 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
882}
883
884MemoryAccess *
885CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
886 MemoryLocation &Loc) {
887 if (isa<MemoryPhi>(StartingAccess))
888 return StartingAccess;
889
890 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
891 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
892 return StartingUseOrDef;
893
894 Instruction *I = StartingUseOrDef->getMemoryInst();
895
896 // Conservatively, fences are always clobbers, so don't perform the walk if we
897 // hit a fence.
898 if (isa<FenceInst>(I))
899 return StartingUseOrDef;
900
901 UpwardsMemoryQuery Q;
902 Q.OriginalAccess = StartingUseOrDef;
903 Q.StartingLoc = Loc;
904 Q.Inst = StartingUseOrDef->getMemoryInst();
905 Q.IsCall = false;
906 Q.DL = &Q.Inst->getModule()->getDataLayout();
907
908 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
909 return CacheResult;
910
911 // Unlike the other function, do not walk to the def of a def, because we are
912 // handed something we already believe is the clobbering access.
913 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
914 ? StartingUseOrDef->getDefiningAccess()
915 : StartingUseOrDef;
916
917 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
918 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
919 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
920 DEBUG(dbgs() << *StartingUseOrDef << "\n");
921 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
922 DEBUG(dbgs() << *Clobber << "\n");
923 return Clobber;
924}
925
926MemoryAccess *
927CachingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
928 // There should be no way to lookup an instruction and get a phi as the
929 // access, since we only map BB's to PHI's. So, this must be a use or def.
930 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
931
932 // We can't sanely do anything with a FenceInst, they conservatively
933 // clobber all memory, and have no locations to get pointers from to
934 // try to disambiguate
935 if (isa<FenceInst>(I))
936 return StartingAccess;
937
938 UpwardsMemoryQuery Q;
939 Q.OriginalAccess = StartingAccess;
940 Q.IsCall = bool(ImmutableCallSite(I));
941 if (!Q.IsCall)
942 Q.StartingLoc = MemoryLocation::get(I);
943 Q.Inst = I;
944 Q.DL = &Q.Inst->getModule()->getDataLayout();
945 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
946 return CacheResult;
947
948 // Start with the thing we already think clobbers this location
949 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
950
951 // At this point, DefiningAccess may be the live on entry def.
952 // If it is, we will not get a better result.
953 if (MSSA->isLiveOnEntryDef(DefiningAccess))
954 return DefiningAccess;
955
956 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
957 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
958 // TODO: When this implementation is more mature, we may want to figure out
959 // what this additional caching buys us. It's most likely A Good Thing.
960 if (Q.IsCall)
961 for (const MemoryAccess *MA : Q.VisitedCalls)
962 doCacheInsert(MA, Result, Q, Q.StartingLoc);
963
964 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
965 DEBUG(dbgs() << *DefiningAccess << "\n");
966 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
967 DEBUG(dbgs() << *Result << "\n");
968
969 return Result;
970}
971
972MemoryAccess *
973DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
974 MemoryAccess *MA = MSSA->getMemoryAccess(I);
975 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
976 return Use->getDefiningAccess();
977 return MA;
978}
979
980MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
981 MemoryAccess *StartingAccess, MemoryLocation &) {
982 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
983 return Use->getDefiningAccess();
984 return StartingAccess;
985}
986}