blob: fa92fd341ecbcb863f1b7a5c418af6c5aab4ae2a [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
Andrew Scullcdfcccc2018-10-05 20:58:37 +010010/// This file exposes an interface to building/using memory SSA to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010011/// walk memory instructions using a use/def graph.
12///
13/// Memory SSA class builds an SSA form that links together memory access
14/// instructions such as loads, stores, atomics, and calls. Additionally, it
15/// does a trivial form of "heap versioning" Every time the memory state changes
16/// in the program, we generate a new heap version. It generates
17/// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
18///
19/// As a trivial example,
20/// define i32 @main() #0 {
21/// entry:
22/// %call = call noalias i8* @_Znwm(i64 4) #2
23/// %0 = bitcast i8* %call to i32*
24/// %call1 = call noalias i8* @_Znwm(i64 4) #2
25/// %1 = bitcast i8* %call1 to i32*
26/// store i32 5, i32* %0, align 4
27/// store i32 7, i32* %1, align 4
28/// %2 = load i32* %0, align 4
29/// %3 = load i32* %1, align 4
30/// %add = add nsw i32 %2, %3
31/// ret i32 %add
32/// }
33///
34/// Will become
35/// define i32 @main() #0 {
36/// entry:
37/// ; 1 = MemoryDef(0)
38/// %call = call noalias i8* @_Znwm(i64 4) #3
39/// %2 = bitcast i8* %call to i32*
40/// ; 2 = MemoryDef(1)
41/// %call1 = call noalias i8* @_Znwm(i64 4) #3
42/// %4 = bitcast i8* %call1 to i32*
43/// ; 3 = MemoryDef(2)
44/// store i32 5, i32* %2, align 4
45/// ; 4 = MemoryDef(3)
46/// store i32 7, i32* %4, align 4
47/// ; MemoryUse(3)
48/// %7 = load i32* %2, align 4
49/// ; MemoryUse(4)
50/// %8 = load i32* %4, align 4
51/// %add = add nsw i32 %7, %8
52/// ret i32 %add
53/// }
54///
55/// Given this form, all the stores that could ever effect the load at %8 can be
56/// gotten by using the MemoryUse associated with it, and walking from use to
57/// def until you hit the top of the function.
58///
59/// Each def also has a list of users associated with it, so you can walk from
60/// both def to users, and users to defs. Note that we disambiguate MemoryUses,
61/// but not the RHS of MemoryDefs. You can see this above at %7, which would
62/// otherwise be a MemoryUse(4). Being disambiguated means that for a given
63/// store, all the MemoryUses on its use lists are may-aliases of that store
64/// (but the MemoryDefs on its use list may not be).
65///
66/// MemoryDefs are not disambiguated because it would require multiple reaching
67/// definitions, which would require multiple phis, and multiple memoryaccesses
68/// per instruction.
69//
70//===----------------------------------------------------------------------===//
71
72#ifndef LLVM_ANALYSIS_MEMORYSSA_H
73#define LLVM_ANALYSIS_MEMORYSSA_H
74
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/GraphTraits.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/SmallVector.h"
79#include "llvm/ADT/ilist.h"
80#include "llvm/ADT/ilist_node.h"
81#include "llvm/ADT/iterator.h"
82#include "llvm/ADT/iterator_range.h"
83#include "llvm/ADT/simple_ilist.h"
84#include "llvm/Analysis/AliasAnalysis.h"
85#include "llvm/Analysis/MemoryLocation.h"
86#include "llvm/Analysis/PHITransAddr.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/DerivedUser.h"
89#include "llvm/IR/Dominators.h"
90#include "llvm/IR/Module.h"
91#include "llvm/IR/Type.h"
92#include "llvm/IR/Use.h"
93#include "llvm/IR/User.h"
94#include "llvm/IR/Value.h"
95#include "llvm/IR/ValueHandle.h"
96#include "llvm/Pass.h"
97#include "llvm/Support/Casting.h"
98#include <algorithm>
99#include <cassert>
100#include <cstddef>
101#include <iterator>
102#include <memory>
103#include <utility>
104
105namespace llvm {
106
107class Function;
108class Instruction;
109class MemoryAccess;
110class MemorySSAWalker;
111class LLVMContext;
112class raw_ostream;
113
114namespace MSSAHelpers {
115
116struct AllAccessTag {};
117struct DefsOnlyTag {};
118
119} // end namespace MSSAHelpers
120
121enum : unsigned {
122 // Used to signify what the default invalid ID is for MemoryAccess's
123 // getID()
124 INVALID_MEMORYACCESS_ID = -1U
125};
126
127template <class T> class memoryaccess_def_iterator_base;
128using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
129using const_memoryaccess_def_iterator =
130 memoryaccess_def_iterator_base<const MemoryAccess>;
131
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100132// The base for all memory accesses. All memory accesses in a block are
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100133// linked together using an intrusive list.
134class MemoryAccess
135 : public DerivedUser,
136 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
137 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
138public:
139 using AllAccessType =
140 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
141 using DefsOnlyType =
142 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
143
144 MemoryAccess(const MemoryAccess &) = delete;
145 MemoryAccess &operator=(const MemoryAccess &) = delete;
146
147 void *operator new(size_t) = delete;
148
149 // Methods for support type inquiry through isa, cast, and
150 // dyn_cast
151 static bool classof(const Value *V) {
152 unsigned ID = V->getValueID();
153 return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
154 }
155
156 BasicBlock *getBlock() const { return Block; }
157
158 void print(raw_ostream &OS) const;
159 void dump() const;
160
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100161 /// The user iterators for a memory access
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100162 using iterator = user_iterator;
163 using const_iterator = const_user_iterator;
164
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100165 /// This iterator walks over all of the defs in a given
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100166 /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
167 /// MemoryUse/MemoryDef, this walks the defining access.
168 memoryaccess_def_iterator defs_begin();
169 const_memoryaccess_def_iterator defs_begin() const;
170 memoryaccess_def_iterator defs_end();
171 const_memoryaccess_def_iterator defs_end() const;
172
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100173 /// Get the iterators for the all access list and the defs only list
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100174 /// We default to the all access list.
175 AllAccessType::self_iterator getIterator() {
176 return this->AllAccessType::getIterator();
177 }
178 AllAccessType::const_self_iterator getIterator() const {
179 return this->AllAccessType::getIterator();
180 }
181 AllAccessType::reverse_self_iterator getReverseIterator() {
182 return this->AllAccessType::getReverseIterator();
183 }
184 AllAccessType::const_reverse_self_iterator getReverseIterator() const {
185 return this->AllAccessType::getReverseIterator();
186 }
187 DefsOnlyType::self_iterator getDefsIterator() {
188 return this->DefsOnlyType::getIterator();
189 }
190 DefsOnlyType::const_self_iterator getDefsIterator() const {
191 return this->DefsOnlyType::getIterator();
192 }
193 DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
194 return this->DefsOnlyType::getReverseIterator();
195 }
196 DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
197 return this->DefsOnlyType::getReverseIterator();
198 }
199
200protected:
201 friend class MemoryDef;
202 friend class MemoryPhi;
203 friend class MemorySSA;
204 friend class MemoryUse;
205 friend class MemoryUseOrDef;
206
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100207 /// Used by MemorySSA to change the block of a MemoryAccess when it is
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100208 /// moved.
209 void setBlock(BasicBlock *BB) { Block = BB; }
210
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100211 /// Used for debugging and tracking things about MemoryAccesses.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100212 /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
213 inline unsigned getID() const;
214
215 MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
216 BasicBlock *BB, unsigned NumOperands)
217 : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
218 Block(BB) {}
219
220 // Use deleteValue() to delete a generic MemoryAccess.
221 ~MemoryAccess() = default;
222
223private:
224 BasicBlock *Block;
225};
226
227template <>
228struct ilist_alloc_traits<MemoryAccess> {
229 static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
230};
231
232inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
233 MA.print(OS);
234 return OS;
235}
236
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100237/// Class that has the common methods + fields of memory uses/defs. It's
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100238/// a little awkward to have, but there are many cases where we want either a
239/// use or def, and there are many cases where uses are needed (defs aren't
240/// acceptable), and vice-versa.
241///
242/// This class should never be instantiated directly; make a MemoryUse or
243/// MemoryDef instead.
244class MemoryUseOrDef : public MemoryAccess {
245public:
246 void *operator new(size_t) = delete;
247
248 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
249
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100250 /// Get the instruction that this MemoryUse represents.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100251 Instruction *getMemoryInst() const { return MemoryInstruction; }
252
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100253 /// Get the access that produces the memory state used by this Use.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100254 MemoryAccess *getDefiningAccess() const { return getOperand(0); }
255
256 static bool classof(const Value *MA) {
257 return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
258 }
259
260 // Sadly, these have to be public because they are needed in some of the
261 // iterators.
262 inline bool isOptimized() const;
263 inline MemoryAccess *getOptimized() const;
264 inline void setOptimized(MemoryAccess *);
265
266 // Retrieve AliasResult type of the optimized access. Ideally this would be
267 // returned by the caching walker and may go away in the future.
268 Optional<AliasResult> getOptimizedAccessType() const {
269 return OptimizedAccessAlias;
270 }
271
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100272 /// Reset the ID of what this MemoryUse was optimized to, causing it to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100273 /// be rewalked by the walker if necessary.
274 /// This really should only be called by tests.
275 inline void resetOptimized();
276
277protected:
278 friend class MemorySSA;
279 friend class MemorySSAUpdater;
280
281 MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
Andrew Scull0372a572018-11-16 15:47:06 +0000282 DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
283 unsigned NumOperands)
284 : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
285 MemoryInstruction(MI), OptimizedAccessAlias(MayAlias) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100286 setDefiningAccess(DMA);
287 }
288
289 // Use deleteValue() to delete a generic MemoryUseOrDef.
290 ~MemoryUseOrDef() = default;
291
292 void setOptimizedAccessType(Optional<AliasResult> AR) {
293 OptimizedAccessAlias = AR;
294 }
295
296 void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false,
297 Optional<AliasResult> AR = MayAlias) {
298 if (!Optimized) {
299 setOperand(0, DMA);
300 return;
301 }
302 setOptimized(DMA);
303 setOptimizedAccessType(AR);
304 }
305
306private:
307 Instruction *MemoryInstruction;
308 Optional<AliasResult> OptimizedAccessAlias;
309};
310
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100311/// Represents read-only accesses to memory
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100312///
313/// In particular, the set of Instructions that will be represented by
314/// MemoryUse's is exactly the set of Instructions for which
315/// AliasAnalysis::getModRefInfo returns "Ref".
316class MemoryUse final : public MemoryUseOrDef {
317public:
318 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
319
320 MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
Andrew Scull0372a572018-11-16 15:47:06 +0000321 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
322 /*NumOperands=*/1) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100323
324 // allocate space for exactly one operand
325 void *operator new(size_t s) { return User::operator new(s, 1); }
326
327 static bool classof(const Value *MA) {
328 return MA->getValueID() == MemoryUseVal;
329 }
330
331 void print(raw_ostream &OS) const;
332
333 void setOptimized(MemoryAccess *DMA) {
334 OptimizedID = DMA->getID();
335 setOperand(0, DMA);
336 }
337
338 bool isOptimized() const {
339 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
340 }
341
342 MemoryAccess *getOptimized() const {
343 return getDefiningAccess();
344 }
345
346 void resetOptimized() {
347 OptimizedID = INVALID_MEMORYACCESS_ID;
348 }
349
350protected:
351 friend class MemorySSA;
352
353private:
354 static void deleteMe(DerivedUser *Self);
355
356 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
357};
358
359template <>
360struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
361DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
362
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100363/// Represents a read-write access to memory, whether it is a must-alias,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100364/// or a may-alias.
365///
366/// In particular, the set of Instructions that will be represented by
367/// MemoryDef's is exactly the set of Instructions for which
368/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
369/// Note that, in order to provide def-def chains, all defs also have a use
370/// associated with them. This use points to the nearest reaching
371/// MemoryDef/MemoryPhi.
372class MemoryDef final : public MemoryUseOrDef {
373public:
374 friend class MemorySSA;
375
376 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
377
378 MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
379 unsigned Ver)
Andrew Scull0372a572018-11-16 15:47:06 +0000380 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
381 /*NumOperands=*/2),
382 ID(Ver) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100383
Andrew Scull0372a572018-11-16 15:47:06 +0000384 // allocate space for exactly two operands
385 void *operator new(size_t s) { return User::operator new(s, 2); }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100386
387 static bool classof(const Value *MA) {
388 return MA->getValueID() == MemoryDefVal;
389 }
390
391 void setOptimized(MemoryAccess *MA) {
Andrew Scull0372a572018-11-16 15:47:06 +0000392 setOperand(1, MA);
393 OptimizedID = MA->getID();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100394 }
395
396 MemoryAccess *getOptimized() const {
Andrew Scull0372a572018-11-16 15:47:06 +0000397 return cast_or_null<MemoryAccess>(getOperand(1));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100398 }
399
400 bool isOptimized() const {
Andrew Scull0372a572018-11-16 15:47:06 +0000401 return getOptimized() && OptimizedID == getOptimized()->getID();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100402 }
403
404 void resetOptimized() {
405 OptimizedID = INVALID_MEMORYACCESS_ID;
Andrew Walbran16937d02019-10-22 13:54:20 +0100406 setOperand(1, nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100407 }
408
409 void print(raw_ostream &OS) const;
410
411 unsigned getID() const { return ID; }
412
413private:
414 static void deleteMe(DerivedUser *Self);
415
416 const unsigned ID;
417 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100418};
419
420template <>
Andrew Scull0372a572018-11-16 15:47:06 +0000421struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100422DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
423
Andrew Scull0372a572018-11-16 15:47:06 +0000424template <>
425struct OperandTraits<MemoryUseOrDef> {
426 static Use *op_begin(MemoryUseOrDef *MUD) {
427 if (auto *MU = dyn_cast<MemoryUse>(MUD))
428 return OperandTraits<MemoryUse>::op_begin(MU);
429 return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
430 }
431
432 static Use *op_end(MemoryUseOrDef *MUD) {
433 if (auto *MU = dyn_cast<MemoryUse>(MUD))
434 return OperandTraits<MemoryUse>::op_end(MU);
435 return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
436 }
437
438 static unsigned operands(const MemoryUseOrDef *MUD) {
439 if (const auto *MU = dyn_cast<MemoryUse>(MUD))
440 return OperandTraits<MemoryUse>::operands(MU);
441 return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
442 }
443};
444DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
445
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100446/// Represents phi nodes for memory accesses.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100447///
448/// These have the same semantic as regular phi nodes, with the exception that
449/// only one phi will ever exist in a given basic block.
450/// Guaranteeing one phi per block means guaranteeing there is only ever one
451/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
452/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
453/// a MemoryPhi's operands.
454/// That is, given
455/// if (a) {
456/// store %a
457/// store %b
458/// }
459/// it *must* be transformed into
460/// if (a) {
461/// 1 = MemoryDef(liveOnEntry)
462/// store %a
463/// 2 = MemoryDef(1)
464/// store %b
465/// }
466/// and *not*
467/// if (a) {
468/// 1 = MemoryDef(liveOnEntry)
469/// store %a
470/// 2 = MemoryDef(liveOnEntry)
471/// store %b
472/// }
473/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
474/// end of the branch, and if there are not two phi nodes, one will be
475/// disconnected completely from the SSA graph below that point.
476/// Because MemoryUse's do not generate new definitions, they do not have this
477/// issue.
478class MemoryPhi final : public MemoryAccess {
479 // allocate space for exactly zero operands
480 void *operator new(size_t s) { return User::operator new(s); }
481
482public:
483 /// Provide fast operand accessors
484 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
485
486 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
487 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
488 ReservedSpace(NumPreds) {
489 allocHungoffUses(ReservedSpace);
490 }
491
492 // Block iterator interface. This provides access to the list of incoming
493 // basic blocks, which parallels the list of incoming values.
494 using block_iterator = BasicBlock **;
495 using const_block_iterator = BasicBlock *const *;
496
497 block_iterator block_begin() {
498 auto *Ref = reinterpret_cast<Use::UserRef *>(op_begin() + ReservedSpace);
499 return reinterpret_cast<block_iterator>(Ref + 1);
500 }
501
502 const_block_iterator block_begin() const {
503 const auto *Ref =
504 reinterpret_cast<const Use::UserRef *>(op_begin() + ReservedSpace);
505 return reinterpret_cast<const_block_iterator>(Ref + 1);
506 }
507
508 block_iterator block_end() { return block_begin() + getNumOperands(); }
509
510 const_block_iterator block_end() const {
511 return block_begin() + getNumOperands();
512 }
513
514 iterator_range<block_iterator> blocks() {
515 return make_range(block_begin(), block_end());
516 }
517
518 iterator_range<const_block_iterator> blocks() const {
519 return make_range(block_begin(), block_end());
520 }
521
522 op_range incoming_values() { return operands(); }
523
524 const_op_range incoming_values() const { return operands(); }
525
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100526 /// Return the number of incoming edges
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100527 unsigned getNumIncomingValues() const { return getNumOperands(); }
528
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100529 /// Return incoming value number x
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100530 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
531 void setIncomingValue(unsigned I, MemoryAccess *V) {
532 assert(V && "PHI node got a null value!");
533 setOperand(I, V);
534 }
535
536 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
537 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
538
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100539 /// Return incoming basic block number @p i.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100540 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
541
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100542 /// Return incoming basic block corresponding
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100543 /// to an operand of the PHI.
544 BasicBlock *getIncomingBlock(const Use &U) const {
545 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
546 return getIncomingBlock(unsigned(&U - op_begin()));
547 }
548
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100549 /// Return incoming basic block corresponding
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100550 /// to value use iterator.
551 BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
552 return getIncomingBlock(I.getUse());
553 }
554
555 void setIncomingBlock(unsigned I, BasicBlock *BB) {
556 assert(BB && "PHI node got a null basic block!");
557 block_begin()[I] = BB;
558 }
559
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100560 /// Add an incoming value to the end of the PHI list
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100561 void addIncoming(MemoryAccess *V, BasicBlock *BB) {
562 if (getNumOperands() == ReservedSpace)
563 growOperands(); // Get more space!
564 // Initialize some new operands.
565 setNumHungOffUseOperands(getNumOperands() + 1);
566 setIncomingValue(getNumOperands() - 1, V);
567 setIncomingBlock(getNumOperands() - 1, BB);
568 }
569
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100570 /// Return the first index of the specified basic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100571 /// block in the value list for this PHI. Returns -1 if no instance.
572 int getBasicBlockIndex(const BasicBlock *BB) const {
573 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
574 if (block_begin()[I] == BB)
575 return I;
576 return -1;
577 }
578
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100579 MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100580 int Idx = getBasicBlockIndex(BB);
581 assert(Idx >= 0 && "Invalid basic block argument!");
582 return getIncomingValue(Idx);
583 }
584
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100585 // After deleting incoming position I, the order of incoming may be changed.
586 void unorderedDeleteIncoming(unsigned I) {
587 unsigned E = getNumOperands();
588 assert(I < E && "Cannot remove out of bounds Phi entry.");
589 // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
590 // itself should be deleted.
591 assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
592 "at least 2 values.");
593 setIncomingValue(I, getIncomingValue(E - 1));
594 setIncomingBlock(I, block_begin()[E - 1]);
595 setOperand(E - 1, nullptr);
596 block_begin()[E - 1] = nullptr;
597 setNumHungOffUseOperands(getNumOperands() - 1);
598 }
599
600 // After deleting entries that satisfy Pred, remaining entries may have
601 // changed order.
602 template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
603 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
604 if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
605 unorderedDeleteIncoming(I);
606 E = getNumOperands();
607 --I;
608 }
609 assert(getNumOperands() >= 1 &&
610 "Cannot remove all incoming blocks in a MemoryPhi.");
611 }
612
613 // After deleting incoming block BB, the incoming blocks order may be changed.
614 void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
615 unorderedDeleteIncomingIf(
616 [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
617 }
618
619 // After deleting incoming memory access MA, the incoming accesses order may
620 // be changed.
621 void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
622 unorderedDeleteIncomingIf(
623 [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
624 }
625
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100626 static bool classof(const Value *V) {
627 return V->getValueID() == MemoryPhiVal;
628 }
629
630 void print(raw_ostream &OS) const;
631
632 unsigned getID() const { return ID; }
633
634protected:
635 friend class MemorySSA;
636
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100637 /// this is more complicated than the generic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100638 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
639 /// values and pointers to the incoming blocks, all in one allocation.
640 void allocHungoffUses(unsigned N) {
641 User::allocHungoffUses(N, /* IsPhi */ true);
642 }
643
644private:
645 // For debugging only
646 const unsigned ID;
647 unsigned ReservedSpace;
648
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100649 /// This grows the operand list in response to a push_back style of
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100650 /// operation. This grows the number of ops by 1.5 times.
651 void growOperands() {
652 unsigned E = getNumOperands();
653 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
654 ReservedSpace = std::max(E + E / 2, 2u);
655 growHungoffUses(ReservedSpace, /* IsPhi */ true);
656 }
657
658 static void deleteMe(DerivedUser *Self);
659};
660
661inline unsigned MemoryAccess::getID() const {
662 assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
663 "only memory defs and phis have ids");
664 if (const auto *MD = dyn_cast<MemoryDef>(this))
665 return MD->getID();
666 return cast<MemoryPhi>(this)->getID();
667}
668
669inline bool MemoryUseOrDef::isOptimized() const {
670 if (const auto *MD = dyn_cast<MemoryDef>(this))
671 return MD->isOptimized();
672 return cast<MemoryUse>(this)->isOptimized();
673}
674
675inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
676 if (const auto *MD = dyn_cast<MemoryDef>(this))
677 return MD->getOptimized();
678 return cast<MemoryUse>(this)->getOptimized();
679}
680
681inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
682 if (auto *MD = dyn_cast<MemoryDef>(this))
683 MD->setOptimized(MA);
684 else
685 cast<MemoryUse>(this)->setOptimized(MA);
686}
687
688inline void MemoryUseOrDef::resetOptimized() {
689 if (auto *MD = dyn_cast<MemoryDef>(this))
690 MD->resetOptimized();
691 else
692 cast<MemoryUse>(this)->resetOptimized();
693}
694
695template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
696DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
697
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100698/// Encapsulates MemorySSA, including all data associated with memory
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100699/// accesses.
700class MemorySSA {
701public:
702 MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
703 ~MemorySSA();
704
705 MemorySSAWalker *getWalker();
Andrew Walbran16937d02019-10-22 13:54:20 +0100706 MemorySSAWalker *getSkipSelfWalker();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100707
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100708 /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100709 /// access associated with it. If passed a basic block gets the memory phi
710 /// node that exists for that block, if there is one. Otherwise, this will get
711 /// a MemoryUseOrDef.
Andrew Scull0372a572018-11-16 15:47:06 +0000712 MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
713 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
714 }
715
716 MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
717 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
718 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100719
720 void dump() const;
721 void print(raw_ostream &) const;
722
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100723 /// Return true if \p MA represents the live on entry value
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100724 ///
725 /// Loads and stores from pointer arguments and other global values may be
726 /// defined by memory operations that do not occur in the current function, so
727 /// they may be live on entry to the function. MemorySSA represents such
728 /// memory state by the live on entry definition, which is guaranteed to occur
729 /// before any other memory access in the function.
730 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
731 return MA == LiveOnEntryDef.get();
732 }
733
734 inline MemoryAccess *getLiveOnEntryDef() const {
735 return LiveOnEntryDef.get();
736 }
737
738 // Sadly, iplists, by default, owns and deletes pointers added to the
739 // list. It's not currently possible to have two iplists for the same type,
740 // where one owns the pointers, and one does not. This is because the traits
741 // are per-type, not per-tag. If this ever changes, we should make the
742 // DefList an iplist.
743 using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
744 using DefsList =
745 simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
746
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100747 /// Return the list of MemoryAccess's for a given basic block.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100748 ///
749 /// This list is not modifiable by the user.
750 const AccessList *getBlockAccesses(const BasicBlock *BB) const {
751 return getWritableBlockAccesses(BB);
752 }
753
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100754 /// Return the list of MemoryDef's and MemoryPhi's for a given basic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100755 /// block.
756 ///
757 /// This list is not modifiable by the user.
758 const DefsList *getBlockDefs(const BasicBlock *BB) const {
759 return getWritableBlockDefs(BB);
760 }
761
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100762 /// Given two memory accesses in the same basic block, determine
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100763 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
764 bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
765
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100766 /// Given two memory accesses in potentially different blocks,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100767 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
768 bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
769
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100770 /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100771 /// dominates Use \p B.
772 bool dominates(const MemoryAccess *A, const Use &B) const;
773
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100774 /// Verify that MemorySSA is self consistent (IE definitions dominate
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100775 /// all uses, uses appear in the right places). This is used by unit tests.
776 void verifyMemorySSA() const;
777
778 /// Used in various insertion functions to specify whether we are talking
779 /// about the beginning or end of a block.
780 enum InsertionPlace { Beginning, End };
781
782protected:
783 // Used by Memory SSA annotater, dumpers, and wrapper pass
784 friend class MemorySSAAnnotatedWriter;
785 friend class MemorySSAPrinterLegacyPass;
786 friend class MemorySSAUpdater;
787
788 void verifyDefUses(Function &F) const;
789 void verifyDomination(Function &F) const;
790 void verifyOrdering(Function &F) const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100791 void verifyDominationNumbers(const Function &F) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100792
793 // This is used by the use optimizer and updater.
794 AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
795 auto It = PerBlockAccesses.find(BB);
796 return It == PerBlockAccesses.end() ? nullptr : It->second.get();
797 }
798
799 // This is used by the use optimizer and updater.
800 DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
801 auto It = PerBlockDefs.find(BB);
802 return It == PerBlockDefs.end() ? nullptr : It->second.get();
803 }
804
805 // These is used by the updater to perform various internal MemorySSA
806 // machinsations. They do not always leave the IR in a correct state, and
807 // relies on the updater to fixup what it breaks, so it is not public.
808
809 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100810 void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100811
812 // Rename the dominator tree branch rooted at BB.
813 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
814 SmallPtrSetImpl<BasicBlock *> &Visited) {
815 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
816 }
817
818 void removeFromLookups(MemoryAccess *);
819 void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
820 void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
821 InsertionPlace);
822 void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
823 AccessList::iterator);
Andrew Scull0372a572018-11-16 15:47:06 +0000824 MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
825 const MemoryUseOrDef *Template = nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100826
827private:
Andrew Walbran16937d02019-10-22 13:54:20 +0100828 class ClobberWalkerBase;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100829 class CachingWalker;
Andrew Walbran16937d02019-10-22 13:54:20 +0100830 class SkipSelfWalker;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100831 class OptimizeUses;
832
833 CachingWalker *getWalkerImpl();
834 void buildMemorySSA();
835 void optimizeUses();
836
Andrew Scull0372a572018-11-16 15:47:06 +0000837 void prepareForMoveTo(MemoryAccess *, BasicBlock *);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100838 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
839
840 using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
841 using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
842
843 void
844 determineInsertionPoint(const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks);
845 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
846 bool dominatesUse(const MemoryAccess *, const MemoryAccess *) const;
847 MemoryPhi *createMemoryPhi(BasicBlock *BB);
Andrew Scull0372a572018-11-16 15:47:06 +0000848 MemoryUseOrDef *createNewAccess(Instruction *,
849 const MemoryUseOrDef *Template = nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100850 MemoryAccess *findDominatingDef(BasicBlock *, enum InsertionPlace);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100851 void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100852 MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
853 void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
854 void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
855 SmallPtrSetImpl<BasicBlock *> &Visited,
856 bool SkipVisited = false, bool RenameAllUses = false);
857 AccessList *getOrCreateAccessList(const BasicBlock *);
858 DefsList *getOrCreateDefsList(const BasicBlock *);
859 void renumberBlock(const BasicBlock *) const;
860 AliasAnalysis *AA;
861 DominatorTree *DT;
862 Function &F;
863
864 // Memory SSA mappings
865 DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
866
867 // These two mappings contain the main block to access/def mappings for
868 // MemorySSA. The list contained in PerBlockAccesses really owns all the
869 // MemoryAccesses.
870 // Both maps maintain the invariant that if a block is found in them, the
871 // corresponding list is not empty, and if a block is not found in them, the
872 // corresponding list is empty.
873 AccessMap PerBlockAccesses;
874 DefsMap PerBlockDefs;
875 std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
876
877 // Domination mappings
878 // Note that the numbering is local to a block, even though the map is
879 // global.
880 mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
881 mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
882
883 // Memory SSA building info
Andrew Walbran16937d02019-10-22 13:54:20 +0100884 std::unique_ptr<ClobberWalkerBase> WalkerBase;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100885 std::unique_ptr<CachingWalker> Walker;
Andrew Walbran16937d02019-10-22 13:54:20 +0100886 std::unique_ptr<SkipSelfWalker> SkipWalker;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100887 unsigned NextID;
888};
889
890// Internal MemorySSA utils, for use by MemorySSA classes and walkers
891class MemorySSAUtil {
892protected:
893 friend class GVNHoist;
894 friend class MemorySSAWalker;
895
896 // This function should not be used by new passes.
897 static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
898 AliasAnalysis &AA);
899};
900
901// This pass does eager building and then printing of MemorySSA. It is used by
902// the tests to be able to build, dump, and verify Memory SSA.
903class MemorySSAPrinterLegacyPass : public FunctionPass {
904public:
905 MemorySSAPrinterLegacyPass();
906
907 bool runOnFunction(Function &) override;
908 void getAnalysisUsage(AnalysisUsage &AU) const override;
909
910 static char ID;
911};
912
913/// An analysis that produces \c MemorySSA for a function.
914///
915class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
916 friend AnalysisInfoMixin<MemorySSAAnalysis>;
917
918 static AnalysisKey Key;
919
920public:
921 // Wrap MemorySSA result to ensure address stability of internal MemorySSA
922 // pointers after construction. Use a wrapper class instead of plain
923 // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
924 struct Result {
925 Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
926
927 MemorySSA &getMSSA() { return *MSSA.get(); }
928
929 std::unique_ptr<MemorySSA> MSSA;
930 };
931
932 Result run(Function &F, FunctionAnalysisManager &AM);
933};
934
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100935/// Printer pass for \c MemorySSA.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100936class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
937 raw_ostream &OS;
938
939public:
940 explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
941
942 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
943};
944
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100945/// Verifier pass for \c MemorySSA.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100946struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
947 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
948};
949
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100950/// Legacy analysis pass which computes \c MemorySSA.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100951class MemorySSAWrapperPass : public FunctionPass {
952public:
953 MemorySSAWrapperPass();
954
955 static char ID;
956
957 bool runOnFunction(Function &) override;
958 void releaseMemory() override;
959 MemorySSA &getMSSA() { return *MSSA; }
960 const MemorySSA &getMSSA() const { return *MSSA; }
961
962 void getAnalysisUsage(AnalysisUsage &AU) const override;
963
964 void verifyAnalysis() const override;
965 void print(raw_ostream &OS, const Module *M = nullptr) const override;
966
967private:
968 std::unique_ptr<MemorySSA> MSSA;
969};
970
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100971/// This is the generic walker interface for walkers of MemorySSA.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100972/// Walkers are used to be able to further disambiguate the def-use chains
973/// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
974/// you.
975/// In particular, while the def-use chains provide basic information, and are
976/// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
977/// MemoryUse as AliasAnalysis considers it, a user mant want better or other
978/// information. In particular, they may want to use SCEV info to further
979/// disambiguate memory accesses, or they may want the nearest dominating
980/// may-aliasing MemoryDef for a call or a store. This API enables a
981/// standardized interface to getting and using that info.
982class MemorySSAWalker {
983public:
984 MemorySSAWalker(MemorySSA *);
985 virtual ~MemorySSAWalker() = default;
986
987 using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
988
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100989 /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100990 /// will give you the nearest dominating MemoryAccess that Mod's the location
991 /// the instruction accesses (by skipping any def which AA can prove does not
992 /// alias the location(s) accessed by the instruction given).
993 ///
994 /// Note that this will return a single access, and it must dominate the
995 /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
996 /// this will return the MemoryPhi, not the operand. This means that
997 /// given:
998 /// if (a) {
999 /// 1 = MemoryDef(liveOnEntry)
1000 /// store %a
1001 /// } else {
1002 /// 2 = MemoryDef(liveOnEntry)
1003 /// store %b
1004 /// }
1005 /// 3 = MemoryPhi(2, 1)
1006 /// MemoryUse(3)
1007 /// load %a
1008 ///
1009 /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
1010 /// in the if (a) branch.
1011 MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
1012 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1013 assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
1014 return getClobberingMemoryAccess(MA);
1015 }
1016
1017 /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
1018 /// but takes a MemoryAccess instead of an Instruction.
1019 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
1020
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001021 /// Given a potentially clobbering memory access and a new location,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001022 /// calling this will give you the nearest dominating clobbering MemoryAccess
1023 /// (by skipping non-aliasing def links).
1024 ///
1025 /// This version of the function is mainly used to disambiguate phi translated
1026 /// pointers, where the value of a pointer may have changed from the initial
1027 /// memory access. Note that this expects to be handed either a MemoryUse,
1028 /// or an already potentially clobbering access. Unlike the above API, if
1029 /// given a MemoryDef that clobbers the pointer as the starting access, it
1030 /// will return that MemoryDef, whereas the above would return the clobber
1031 /// starting from the use side of the memory def.
1032 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1033 const MemoryLocation &) = 0;
1034
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001035 /// Given a memory access, invalidate anything this walker knows about
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001036 /// that access.
1037 /// This API is used by walkers that store information to perform basic cache
1038 /// invalidation. This will be called by MemorySSA at appropriate times for
1039 /// the walker it uses or returns.
1040 virtual void invalidateInfo(MemoryAccess *) {}
1041
1042 virtual void verify(const MemorySSA *MSSA) { assert(MSSA == this->MSSA); }
1043
1044protected:
1045 friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
1046 // constructor.
1047 MemorySSA *MSSA;
1048};
1049
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001050/// A MemorySSAWalker that does no alias queries, or anything else. It
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001051/// simply returns the links as they were constructed by the builder.
1052class DoNothingMemorySSAWalker final : public MemorySSAWalker {
1053public:
1054 // Keep the overrides below from hiding the Instruction overload of
1055 // getClobberingMemoryAccess.
1056 using MemorySSAWalker::getClobberingMemoryAccess;
1057
1058 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
1059 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1060 const MemoryLocation &) override;
1061};
1062
1063using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
1064using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
1065
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001066/// Iterator base class used to implement const and non-const iterators
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001067/// over the defining accesses of a MemoryAccess.
1068template <class T>
1069class memoryaccess_def_iterator_base
1070 : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
1071 std::forward_iterator_tag, T, ptrdiff_t, T *,
1072 T *> {
1073 using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1074
1075public:
1076 memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1077 memoryaccess_def_iterator_base() = default;
1078
1079 bool operator==(const memoryaccess_def_iterator_base &Other) const {
1080 return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1081 }
1082
1083 // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1084 // block from the operand in constant time (In a PHINode, the uselist has
1085 // both, so it's just subtraction). We provide it as part of the
1086 // iterator to avoid callers having to linear walk to get the block.
1087 // If the operation becomes constant time on MemoryPHI's, this bit of
1088 // abstraction breaking should be removed.
1089 BasicBlock *getPhiArgBlock() const {
1090 MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1091 assert(MP && "Tried to get phi arg block when not iterating over a PHI");
1092 return MP->getIncomingBlock(ArgNo);
1093 }
1094
1095 typename BaseT::iterator::pointer operator*() const {
1096 assert(Access && "Tried to access past the end of our iterator");
1097 // Go to the first argument for phis, and the defining access for everything
1098 // else.
1099 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1100 return MP->getIncomingValue(ArgNo);
1101 return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1102 }
1103
1104 using BaseT::operator++;
1105 memoryaccess_def_iterator &operator++() {
1106 assert(Access && "Hit end of iterator");
1107 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1108 if (++ArgNo >= MP->getNumIncomingValues()) {
1109 ArgNo = 0;
1110 Access = nullptr;
1111 }
1112 } else {
1113 Access = nullptr;
1114 }
1115 return *this;
1116 }
1117
1118private:
1119 T *Access = nullptr;
1120 unsigned ArgNo = 0;
1121};
1122
1123inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
1124 return memoryaccess_def_iterator(this);
1125}
1126
1127inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
1128 return const_memoryaccess_def_iterator(this);
1129}
1130
1131inline memoryaccess_def_iterator MemoryAccess::defs_end() {
1132 return memoryaccess_def_iterator();
1133}
1134
1135inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
1136 return const_memoryaccess_def_iterator();
1137}
1138
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001139/// GraphTraits for a MemoryAccess, which walks defs in the normal case,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001140/// and uses in the inverse case.
1141template <> struct GraphTraits<MemoryAccess *> {
1142 using NodeRef = MemoryAccess *;
1143 using ChildIteratorType = memoryaccess_def_iterator;
1144
1145 static NodeRef getEntryNode(NodeRef N) { return N; }
1146 static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1147 static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1148};
1149
1150template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1151 using NodeRef = MemoryAccess *;
1152 using ChildIteratorType = MemoryAccess::iterator;
1153
1154 static NodeRef getEntryNode(NodeRef N) { return N; }
1155 static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1156 static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1157};
1158
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001159/// Provide an iterator that walks defs, giving both the memory access,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001160/// and the current pointer location, updating the pointer location as it
1161/// changes due to phi node translation.
1162///
1163/// This iterator, while somewhat specialized, is what most clients actually
1164/// want when walking upwards through MemorySSA def chains. It takes a pair of
1165/// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1166/// memory location through phi nodes for the user.
1167class upward_defs_iterator
1168 : public iterator_facade_base<upward_defs_iterator,
1169 std::forward_iterator_tag,
1170 const MemoryAccessPair> {
1171 using BaseT = upward_defs_iterator::iterator_facade_base;
1172
1173public:
1174 upward_defs_iterator(const MemoryAccessPair &Info)
1175 : DefIterator(Info.first), Location(Info.second),
1176 OriginalAccess(Info.first) {
1177 CurrentPair.first = nullptr;
1178
1179 WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
1180 fillInCurrentPair();
1181 }
1182
1183 upward_defs_iterator() { CurrentPair.first = nullptr; }
1184
1185 bool operator==(const upward_defs_iterator &Other) const {
1186 return DefIterator == Other.DefIterator;
1187 }
1188
1189 BaseT::iterator::reference operator*() const {
1190 assert(DefIterator != OriginalAccess->defs_end() &&
1191 "Tried to access past the end of our iterator");
1192 return CurrentPair;
1193 }
1194
1195 using BaseT::operator++;
1196 upward_defs_iterator &operator++() {
1197 assert(DefIterator != OriginalAccess->defs_end() &&
1198 "Tried to access past the end of the iterator");
1199 ++DefIterator;
1200 if (DefIterator != OriginalAccess->defs_end())
1201 fillInCurrentPair();
1202 return *this;
1203 }
1204
1205 BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1206
1207private:
1208 void fillInCurrentPair() {
1209 CurrentPair.first = *DefIterator;
1210 if (WalkingPhi && Location.Ptr) {
1211 PHITransAddr Translator(
1212 const_cast<Value *>(Location.Ptr),
1213 OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
1214 if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
1215 DefIterator.getPhiArgBlock(), nullptr,
1216 false))
1217 if (Translator.getAddr() != Location.Ptr) {
1218 CurrentPair.second = Location.getWithNewPtr(Translator.getAddr());
1219 return;
1220 }
1221 }
1222 CurrentPair.second = Location;
1223 }
1224
1225 MemoryAccessPair CurrentPair;
1226 memoryaccess_def_iterator DefIterator;
1227 MemoryLocation Location;
1228 MemoryAccess *OriginalAccess = nullptr;
1229 bool WalkingPhi = false;
1230};
1231
1232inline upward_defs_iterator upward_defs_begin(const MemoryAccessPair &Pair) {
1233 return upward_defs_iterator(Pair);
1234}
1235
1236inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
1237
1238inline iterator_range<upward_defs_iterator>
1239upward_defs(const MemoryAccessPair &Pair) {
1240 return make_range(upward_defs_begin(Pair), upward_defs_end());
1241}
1242
1243/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1244/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1245/// comparing against a null def_chain_iterator, this will compare equal only
1246/// after walking said Phi/liveOnEntry.
1247///
1248/// The UseOptimizedChain flag specifies whether to walk the clobbering
1249/// access chain, or all the accesses.
1250///
1251/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1252/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1253/// a phi node. The optimized chain walks the clobbering access of a store.
1254/// So if you are just trying to find, given a store, what the next
1255/// thing that would clobber the same memory is, you want the optimized chain.
1256template <class T, bool UseOptimizedChain = false>
1257struct def_chain_iterator
1258 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1259 std::forward_iterator_tag, MemoryAccess *> {
1260 def_chain_iterator() : MA(nullptr) {}
1261 def_chain_iterator(T MA) : MA(MA) {}
1262
1263 T operator*() const { return MA; }
1264
1265 def_chain_iterator &operator++() {
1266 // N.B. liveOnEntry has a null defining access.
1267 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1268 if (UseOptimizedChain && MUD->isOptimized())
1269 MA = MUD->getOptimized();
1270 else
1271 MA = MUD->getDefiningAccess();
1272 } else {
1273 MA = nullptr;
1274 }
1275
1276 return *this;
1277 }
1278
1279 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1280
1281private:
1282 T MA;
1283};
1284
1285template <class T>
1286inline iterator_range<def_chain_iterator<T>>
1287def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1288#ifdef EXPENSIVE_CHECKS
1289 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
1290 "UpTo isn't in the def chain!");
1291#endif
1292 return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
1293}
1294
1295template <class T>
1296inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
1297 return make_range(def_chain_iterator<T, true>(MA),
1298 def_chain_iterator<T, true>(nullptr));
1299}
1300
1301} // end namespace llvm
1302
1303#endif // LLVM_ANALYSIS_MEMORYSSA_H