1 //===- InferAddressSpace.cpp - --------------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // CUDA C/C++ includes memory space designation as variable type qualifers (such
10 // as __global__ and __shared__). Knowing the space of a memory access allows
11 // CUDA compilers to emit faster PTX loads and stores. For example, a load from
12 // shared memory can be translated to `ld.shared` which is roughly 10% faster
13 // than a generic `ld` on an NVIDIA Tesla K40c.
14 //
15 // Unfortunately, type qualifiers only apply to variable declarations, so CUDA
16 // compilers must infer the memory space of an address expression from
17 // type-qualified variables.
18 //
19 // LLVM IR uses non-zero (so-called) specific address spaces to represent memory
20 // spaces (e.g. addrspace(3) means shared memory). The Clang frontend
21 // places only type-qualified variables in specific address spaces, and then
22 // conservatively `addrspacecast`s each type-qualified variable to addrspace(0)
23 // (so-called the generic address space) for other instructions to use.
24 //
25 // For example, the Clang translates the following CUDA code
26 //   __shared__ float a[10];
27 //   float v = a[i];
28 // to
29 //   %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]*
30 //   %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i
31 //   %v = load float, float* %1 ; emits ld.f32
32 // @a is in addrspace(3) since it's type-qualified, but its use from %1 is
33 // redirected to %0 (the generic version of @a).
34 //
35 // The optimization implemented in this file propagates specific address spaces
36 // from type-qualified variable declarations to its users. For example, it
37 // optimizes the above IR to
38 //   %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i
39 //   %v = load float addrspace(3)* %1 ; emits ld.shared.f32
40 // propagating the addrspace(3) from @a to %1. As the result, the NVPTX
41 // codegen is able to emit ld.shared.f32 for %v.
42 //
43 // Address space inference works in two steps. First, it uses a data-flow
44 // analysis to infer as many generic pointers as possible to point to only one
45 // specific address space. In the above example, it can prove that %1 only
46 // points to addrspace(3). This algorithm was published in
47 //   CUDA: Compiling and optimizing for a GPU platform
48 //   Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang
49 //   ICCS 2012
50 //
51 // Then, address space inference replaces all refinable generic pointers with
52 // equivalent specific pointers.
53 //
54 // The major challenge of implementing this optimization is handling PHINodes,
55 // which may create loops in the data flow graph. This brings two complications.
56 //
57 // First, the data flow analysis in Step 1 needs to be circular. For example,
58 //     %generic.input = addrspacecast float addrspace(3)* %input to float*
59 //   loop:
60 //     %y = phi [ %generic.input, %y2 ]
61 //     %y2 = getelementptr %y, 1
62 //     %v = load %y2
63 //     br ..., label %loop, ...
64 // proving %y specific requires proving both %generic.input and %y2 specific,
65 // but proving %y2 specific circles back to %y. To address this complication,
66 // the data flow analysis operates on a lattice:
67 //   uninitialized > specific address spaces > generic.
68 // All address expressions (our implementation only considers phi, bitcast,
69 // addrspacecast, and getelementptr) start with the uninitialized address space.
70 // The monotone transfer function moves the address space of a pointer down a
71 // lattice path from uninitialized to specific and then to generic. A join
72 // operation of two different specific address spaces pushes the expression down
73 // to the generic address space. The analysis completes once it reaches a fixed
74 // point.
75 //
76 // Second, IR rewriting in Step 2 also needs to be circular. For example,
77 // converting %y to addrspace(3) requires the compiler to know the converted
78 // %y2, but converting %y2 needs the converted %y. To address this complication,
79 // we break these cycles using "undef" placeholders. When converting an
80 // instruction `I` to a new address space, if its operand `Op` is not converted
81 // yet, we let `I` temporarily use `undef` and fix all the uses of undef later.
82 // For instance, our algorithm first converts %y to
83 //   %y' = phi float addrspace(3)* [ %input, undef ]
84 // Then, it converts %y2 to
85 //   %y2' = getelementptr %y', 1
86 // Finally, it fixes the undef in %y' so that
87 //   %y' = phi float addrspace(3)* [ %input, %y2' ]
88 //
89 //===----------------------------------------------------------------------===//
90 
91 #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
92 #include "llvm/ADT/ArrayRef.h"
93 #include "llvm/ADT/DenseMap.h"
94 #include "llvm/ADT/DenseSet.h"
95 #include "llvm/ADT/SetVector.h"
96 #include "llvm/ADT/SmallVector.h"
97 #include "llvm/Analysis/AssumptionCache.h"
98 #include "llvm/Analysis/TargetTransformInfo.h"
99 #include "llvm/Analysis/ValueTracking.h"
100 #include "llvm/IR/BasicBlock.h"
101 #include "llvm/IR/Constant.h"
102 #include "llvm/IR/Constants.h"
103 #include "llvm/IR/Dominators.h"
104 #include "llvm/IR/Function.h"
105 #include "llvm/IR/IRBuilder.h"
106 #include "llvm/IR/InstIterator.h"
107 #include "llvm/IR/Instruction.h"
108 #include "llvm/IR/Instructions.h"
109 #include "llvm/IR/IntrinsicInst.h"
110 #include "llvm/IR/Intrinsics.h"
111 #include "llvm/IR/LLVMContext.h"
112 #include "llvm/IR/Operator.h"
113 #include "llvm/IR/PassManager.h"
114 #include "llvm/IR/Type.h"
115 #include "llvm/IR/Use.h"
116 #include "llvm/IR/User.h"
117 #include "llvm/IR/Value.h"
118 #include "llvm/IR/ValueHandle.h"
119 #include "llvm/InitializePasses.h"
120 #include "llvm/Pass.h"
121 #include "llvm/Support/Casting.h"
122 #include "llvm/Support/CommandLine.h"
123 #include "llvm/Support/Compiler.h"
124 #include "llvm/Support/Debug.h"
125 #include "llvm/Support/ErrorHandling.h"
126 #include "llvm/Support/raw_ostream.h"
127 #include "llvm/Transforms/Scalar.h"
128 #include "llvm/Transforms/Utils/Local.h"
129 #include "llvm/Transforms/Utils/ValueMapper.h"
130 #include <cassert>
131 #include <iterator>
132 #include <limits>
133 #include <utility>
134 #include <vector>
135 
136 #define DEBUG_TYPE "infer-address-spaces"
137 
138 using namespace llvm;
139 
140 static cl::opt<bool> AssumeDefaultIsFlatAddressSpace(
141     "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
142     cl::desc("The default address space is assumed as the flat address space. "
143              "This is mainly for test purpose."));
144 
145 static const unsigned UninitializedAddressSpace =
146     std::numeric_limits<unsigned>::max();
147 
148 namespace {
149 
150 using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
151 // Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on
152 // the *def* of a value, PredicatedAddrSpaceMapTy is map where a new
153 // addrspace is inferred on the *use* of a pointer. This map is introduced to
154 // infer addrspace from the addrspace predicate assumption built from assume
155 // intrinsic. In that scenario, only specific uses (under valid assumption
156 // context) could be inferred with a new addrspace.
157 using PredicatedAddrSpaceMapTy =
158     DenseMap<std::pair<const Value *, const Value *>, unsigned>;
159 using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
160 
161 class InferAddressSpaces : public FunctionPass {
162   unsigned FlatAddrSpace = 0;
163 
164 public:
165   static char ID;
166 
167   InferAddressSpaces() :
168     FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
169   InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
170 
171   void getAnalysisUsage(AnalysisUsage &AU) const override {
172     AU.setPreservesCFG();
173     AU.addPreserved<DominatorTreeWrapperPass>();
174     AU.addRequired<AssumptionCacheTracker>();
175     AU.addRequired<TargetTransformInfoWrapperPass>();
176   }
177 
178   bool runOnFunction(Function &F) override;
179 };
180 
181 class InferAddressSpacesImpl {
182   AssumptionCache &AC;
183   const DominatorTree *DT = nullptr;
184   const TargetTransformInfo *TTI = nullptr;
185   const DataLayout *DL = nullptr;
186 
187   /// Target specific address space which uses of should be replaced if
188   /// possible.
189   unsigned FlatAddrSpace = 0;
190 
191   // Try to update the address space of V. If V is updated, returns true and
192   // false otherwise.
193   bool updateAddressSpace(const Value &V,
194                           ValueToAddrSpaceMapTy &InferredAddrSpace,
195                           PredicatedAddrSpaceMapTy &PredicatedAS) const;
196 
197   // Tries to infer the specific address space of each address expression in
198   // Postorder.
199   void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
200                           ValueToAddrSpaceMapTy &InferredAddrSpace,
201                           PredicatedAddrSpaceMapTy &PredicatedAS) const;
202 
203   bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
204 
205   Value *cloneInstructionWithNewAddressSpace(
206       Instruction *I, unsigned NewAddrSpace,
207       const ValueToValueMapTy &ValueWithNewAddrSpace,
208       const PredicatedAddrSpaceMapTy &PredicatedAS,
209       SmallVectorImpl<const Use *> *UndefUsesToFix) const;
210 
211   // Changes the flat address expressions in function F to point to specific
212   // address spaces if InferredAddrSpace says so. Postorder is the postorder of
213   // all flat expressions in the use-def graph of function F.
214   bool
215   rewriteWithNewAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
216                               const ValueToAddrSpaceMapTy &InferredAddrSpace,
217                               const PredicatedAddrSpaceMapTy &PredicatedAS,
218                               Function *F) const;
219 
220   void appendsFlatAddressExpressionToPostorderStack(
221       Value *V, PostorderStackTy &PostorderStack,
222       DenseSet<Value *> &Visited) const;
223 
224   bool rewriteIntrinsicOperands(IntrinsicInst *II,
225                                 Value *OldV, Value *NewV) const;
226   void collectRewritableIntrinsicOperands(IntrinsicInst *II,
227                                           PostorderStackTy &PostorderStack,
228                                           DenseSet<Value *> &Visited) const;
229 
230   std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
231 
232   Value *cloneValueWithNewAddressSpace(
233       Value *V, unsigned NewAddrSpace,
234       const ValueToValueMapTy &ValueWithNewAddrSpace,
235       const PredicatedAddrSpaceMapTy &PredicatedAS,
236       SmallVectorImpl<const Use *> *UndefUsesToFix) const;
237   unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
238 
239   unsigned getPredicatedAddrSpace(const Value &V, Value *Opnd) const;
240 
241 public:
242   InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT,
243                          const TargetTransformInfo *TTI, unsigned FlatAddrSpace)
244       : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {}
245   bool run(Function &F);
246 };
247 
248 } // end anonymous namespace
249 
250 char InferAddressSpaces::ID = 0;
251 
252 INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
253                       false, false)
254 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
255 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
256 INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
257                     false, false)
258 
259 // Check whether that's no-op pointer bicast using a pair of
260 // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
261 // different address spaces.
262 static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
263                                  const TargetTransformInfo *TTI) {
264   assert(I2P->getOpcode() == Instruction::IntToPtr);
265   auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
266   if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
267     return false;
268   // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
269   // no-op cast. Besides checking both of them are no-op casts, as the
270   // reinterpreted pointer may be used in other pointer arithmetic, we also
271   // need to double-check that through the target-specific hook. That ensures
272   // the underlying target also agrees that's a no-op address space cast and
273   // pointer bits are preserved.
274   // The current IR spec doesn't have clear rules on address space casts,
275   // especially a clear definition for pointer bits in non-default address
276   // spaces. It would be undefined if that pointer is dereferenced after an
277   // invalid reinterpret cast. Also, due to the unclearness for the meaning of
278   // bits in non-default address spaces in the current spec, the pointer
279   // arithmetic may also be undefined after invalid pointer reinterpret cast.
280   // However, as we confirm through the target hooks that it's a no-op
281   // addrspacecast, it doesn't matter since the bits should be the same.
282   unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
283   unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
284   return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
285                               I2P->getOperand(0)->getType(), I2P->getType(),
286                               DL) &&
287          CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()),
288                               P2I->getOperand(0)->getType(), P2I->getType(),
289                               DL) &&
290          (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
291 }
292 
293 // Returns true if V is an address expression.
294 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and
295 // getelementptr operators.
296 static bool isAddressExpression(const Value &V, const DataLayout &DL,
297                                 const TargetTransformInfo *TTI) {
298   const Operator *Op = dyn_cast<Operator>(&V);
299   if (!Op)
300     return false;
301 
302   switch (Op->getOpcode()) {
303   case Instruction::PHI:
304     assert(Op->getType()->isPointerTy());
305     return true;
306   case Instruction::BitCast:
307   case Instruction::AddrSpaceCast:
308   case Instruction::GetElementPtr:
309     return true;
310   case Instruction::Select:
311     return Op->getType()->isPointerTy();
312   case Instruction::Call: {
313     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
314     return II && II->getIntrinsicID() == Intrinsic::ptrmask;
315   }
316   case Instruction::IntToPtr:
317     return isNoopPtrIntCastPair(Op, DL, TTI);
318   default:
319     // That value is an address expression if it has an assumed address space.
320     return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace;
321   }
322 }
323 
324 // Returns the pointer operands of V.
325 //
326 // Precondition: V is an address expression.
327 static SmallVector<Value *, 2>
328 getPointerOperands(const Value &V, const DataLayout &DL,
329                    const TargetTransformInfo *TTI) {
330   const Operator &Op = cast<Operator>(V);
331   switch (Op.getOpcode()) {
332   case Instruction::PHI: {
333     auto IncomingValues = cast<PHINode>(Op).incoming_values();
334     return {IncomingValues.begin(), IncomingValues.end()};
335   }
336   case Instruction::BitCast:
337   case Instruction::AddrSpaceCast:
338   case Instruction::GetElementPtr:
339     return {Op.getOperand(0)};
340   case Instruction::Select:
341     return {Op.getOperand(1), Op.getOperand(2)};
342   case Instruction::Call: {
343     const IntrinsicInst &II = cast<IntrinsicInst>(Op);
344     assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
345            "unexpected intrinsic call");
346     return {II.getArgOperand(0)};
347   }
348   case Instruction::IntToPtr: {
349     assert(isNoopPtrIntCastPair(&Op, DL, TTI));
350     auto *P2I = cast<Operator>(Op.getOperand(0));
351     return {P2I->getOperand(0)};
352   }
353   default:
354     llvm_unreachable("Unexpected instruction type.");
355   }
356 }
357 
358 bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
359                                                       Value *OldV,
360                                                       Value *NewV) const {
361   Module *M = II->getParent()->getParent()->getParent();
362 
363   switch (II->getIntrinsicID()) {
364   case Intrinsic::objectsize: {
365     Type *DestTy = II->getType();
366     Type *SrcTy = NewV->getType();
367     Function *NewDecl =
368         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
369     II->setArgOperand(0, NewV);
370     II->setCalledFunction(NewDecl);
371     return true;
372   }
373   case Intrinsic::ptrmask:
374     // This is handled as an address expression, not as a use memory operation.
375     return false;
376   default: {
377     Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
378     if (!Rewrite)
379       return false;
380     if (Rewrite != II)
381       II->replaceAllUsesWith(Rewrite);
382     return true;
383   }
384   }
385 }
386 
387 void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
388     IntrinsicInst *II, PostorderStackTy &PostorderStack,
389     DenseSet<Value *> &Visited) const {
390   auto IID = II->getIntrinsicID();
391   switch (IID) {
392   case Intrinsic::ptrmask:
393   case Intrinsic::objectsize:
394     appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
395                                                  PostorderStack, Visited);
396     break;
397   default:
398     SmallVector<int, 2> OpIndexes;
399     if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
400       for (int Idx : OpIndexes) {
401         appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
402                                                      PostorderStack, Visited);
403       }
404     }
405     break;
406   }
407 }
408 
409 // Returns all flat address expressions in function F. The elements are
410 // If V is an unvisited flat address expression, appends V to PostorderStack
411 // and marks it as visited.
412 void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
413     Value *V, PostorderStackTy &PostorderStack,
414     DenseSet<Value *> &Visited) const {
415   assert(V->getType()->isPointerTy());
416 
417   // Generic addressing expressions may be hidden in nested constant
418   // expressions.
419   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
420     // TODO: Look in non-address parts, like icmp operands.
421     if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
422       PostorderStack.emplace_back(CE, false);
423 
424     return;
425   }
426 
427   if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
428       isAddressExpression(*V, *DL, TTI)) {
429     if (Visited.insert(V).second) {
430       PostorderStack.emplace_back(V, false);
431 
432       Operator *Op = cast<Operator>(V);
433       for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
434         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
435           if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
436             PostorderStack.emplace_back(CE, false);
437         }
438       }
439     }
440   }
441 }
442 
443 // Returns all flat address expressions in function F. The elements are ordered
444 // ordered in postorder.
445 std::vector<WeakTrackingVH>
446 InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
447   // This function implements a non-recursive postorder traversal of a partial
448   // use-def graph of function F.
449   PostorderStackTy PostorderStack;
450   // The set of visited expressions.
451   DenseSet<Value *> Visited;
452 
453   auto PushPtrOperand = [&](Value *Ptr) {
454     appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
455                                                  Visited);
456   };
457 
458   // Look at operations that may be interesting accelerate by moving to a known
459   // address space. We aim at generating after loads and stores, but pure
460   // addressing calculations may also be faster.
461   for (Instruction &I : instructions(F)) {
462     if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
463       if (!GEP->getType()->isVectorTy())
464         PushPtrOperand(GEP->getPointerOperand());
465     } else if (auto *LI = dyn_cast<LoadInst>(&I))
466       PushPtrOperand(LI->getPointerOperand());
467     else if (auto *SI = dyn_cast<StoreInst>(&I))
468       PushPtrOperand(SI->getPointerOperand());
469     else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
470       PushPtrOperand(RMW->getPointerOperand());
471     else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
472       PushPtrOperand(CmpX->getPointerOperand());
473     else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
474       // For memset/memcpy/memmove, any pointer operand can be replaced.
475       PushPtrOperand(MI->getRawDest());
476 
477       // Handle 2nd operand for memcpy/memmove.
478       if (auto *MTI = dyn_cast<MemTransferInst>(MI))
479         PushPtrOperand(MTI->getRawSource());
480     } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
481       collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
482     else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
483       // FIXME: Handle vectors of pointers
484       if (Cmp->getOperand(0)->getType()->isPointerTy()) {
485         PushPtrOperand(Cmp->getOperand(0));
486         PushPtrOperand(Cmp->getOperand(1));
487       }
488     } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
489       if (!ASC->getType()->isVectorTy())
490         PushPtrOperand(ASC->getPointerOperand());
491     } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
492       if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
493         PushPtrOperand(
494             cast<Operator>(I2P->getOperand(0))->getOperand(0));
495     }
496   }
497 
498   std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
499   while (!PostorderStack.empty()) {
500     Value *TopVal = PostorderStack.back().getPointer();
501     // If the operands of the expression on the top are already explored,
502     // adds that expression to the resultant postorder.
503     if (PostorderStack.back().getInt()) {
504       if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
505         Postorder.push_back(TopVal);
506       PostorderStack.pop_back();
507       continue;
508     }
509     // Otherwise, adds its operands to the stack and explores them.
510     PostorderStack.back().setInt(true);
511     // Skip values with an assumed address space.
512     if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) {
513       for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
514         appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
515                                                      Visited);
516       }
517     }
518   }
519   return Postorder;
520 }
521 
522 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
523 // of OperandUse.get() in the new address space. If the clone is not ready yet,
524 // returns an undef in the new address space as a placeholder.
525 static Value *operandWithNewAddressSpaceOrCreateUndef(
526     const Use &OperandUse, unsigned NewAddrSpace,
527     const ValueToValueMapTy &ValueWithNewAddrSpace,
528     const PredicatedAddrSpaceMapTy &PredicatedAS,
529     SmallVectorImpl<const Use *> *UndefUsesToFix) {
530   Value *Operand = OperandUse.get();
531 
532   Type *NewPtrTy = PointerType::getWithSamePointeeType(
533       cast<PointerType>(Operand->getType()), NewAddrSpace);
534 
535   if (Constant *C = dyn_cast<Constant>(Operand))
536     return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
537 
538   if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
539     return NewOperand;
540 
541   Instruction *Inst = cast<Instruction>(OperandUse.getUser());
542   auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
543   if (I != PredicatedAS.end()) {
544     // Insert an addrspacecast on that operand before the user.
545     unsigned NewAS = I->second;
546     Type *NewPtrTy = PointerType::getWithSamePointeeType(
547         cast<PointerType>(Operand->getType()), NewAS);
548     auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
549     NewI->insertBefore(Inst);
550     return NewI;
551   }
552 
553   UndefUsesToFix->push_back(&OperandUse);
554   return UndefValue::get(NewPtrTy);
555 }
556 
557 // Returns a clone of `I` with its operands converted to those specified in
558 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
559 // operand whose address space needs to be modified might not exist in
560 // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
561 // adds that operand use to UndefUsesToFix so that caller can fix them later.
562 //
563 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
564 // from a pointer whose type already matches. Therefore, this function returns a
565 // Value* instead of an Instruction*.
566 //
567 // This may also return nullptr in the case the instruction could not be
568 // rewritten.
569 Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
570     Instruction *I, unsigned NewAddrSpace,
571     const ValueToValueMapTy &ValueWithNewAddrSpace,
572     const PredicatedAddrSpaceMapTy &PredicatedAS,
573     SmallVectorImpl<const Use *> *UndefUsesToFix) const {
574   Type *NewPtrType = PointerType::getWithSamePointeeType(
575       cast<PointerType>(I->getType()), NewAddrSpace);
576 
577   if (I->getOpcode() == Instruction::AddrSpaceCast) {
578     Value *Src = I->getOperand(0);
579     // Because `I` is flat, the source address space must be specific.
580     // Therefore, the inferred address space must be the source space, according
581     // to our algorithm.
582     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
583     if (Src->getType() != NewPtrType)
584       return new BitCastInst(Src, NewPtrType);
585     return Src;
586   }
587 
588   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
589     // Technically the intrinsic ID is a pointer typed argument, so specially
590     // handle calls early.
591     assert(II->getIntrinsicID() == Intrinsic::ptrmask);
592     Value *NewPtr = operandWithNewAddressSpaceOrCreateUndef(
593         II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
594         PredicatedAS, UndefUsesToFix);
595     Value *Rewrite =
596         TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr);
597     if (Rewrite) {
598       assert(Rewrite != II && "cannot modify this pointer operation in place");
599       return Rewrite;
600     }
601 
602     return nullptr;
603   }
604 
605   unsigned AS = TTI->getAssumedAddrSpace(I);
606   if (AS != UninitializedAddressSpace) {
607     // For the assumed address space, insert an `addrspacecast` to make that
608     // explicit.
609     Type *NewPtrTy = PointerType::getWithSamePointeeType(
610         cast<PointerType>(I->getType()), AS);
611     auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
612     NewI->insertAfter(I);
613     return NewI;
614   }
615 
616   // Computes the converted pointer operands.
617   SmallVector<Value *, 4> NewPointerOperands;
618   for (const Use &OperandUse : I->operands()) {
619     if (!OperandUse.get()->getType()->isPointerTy())
620       NewPointerOperands.push_back(nullptr);
621     else
622       NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
623           OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
624           UndefUsesToFix));
625   }
626 
627   switch (I->getOpcode()) {
628   case Instruction::BitCast:
629     return new BitCastInst(NewPointerOperands[0], NewPtrType);
630   case Instruction::PHI: {
631     assert(I->getType()->isPointerTy());
632     PHINode *PHI = cast<PHINode>(I);
633     PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
634     for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
635       unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
636       NewPHI->addIncoming(NewPointerOperands[OperandNo],
637                           PHI->getIncomingBlock(Index));
638     }
639     return NewPHI;
640   }
641   case Instruction::GetElementPtr: {
642     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
643     GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
644         GEP->getSourceElementType(), NewPointerOperands[0],
645         SmallVector<Value *, 4>(GEP->indices()));
646     NewGEP->setIsInBounds(GEP->isInBounds());
647     return NewGEP;
648   }
649   case Instruction::Select:
650     assert(I->getType()->isPointerTy());
651     return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
652                               NewPointerOperands[2], "", nullptr, I);
653   case Instruction::IntToPtr: {
654     assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
655     Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
656     if (Src->getType() == NewPtrType)
657       return Src;
658 
659     // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a
660     // source address space from a generic pointer source need to insert a cast
661     // back.
662     return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType);
663   }
664   default:
665     llvm_unreachable("Unexpected opcode");
666   }
667 }
668 
669 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
670 // constant expression `CE` with its operands replaced as specified in
671 // ValueWithNewAddrSpace.
672 static Value *cloneConstantExprWithNewAddressSpace(
673     ConstantExpr *CE, unsigned NewAddrSpace,
674     const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
675     const TargetTransformInfo *TTI) {
676   Type *TargetType = CE->getType()->isPointerTy()
677                          ? PointerType::getWithSamePointeeType(
678                                cast<PointerType>(CE->getType()), NewAddrSpace)
679                          : CE->getType();
680 
681   if (CE->getOpcode() == Instruction::AddrSpaceCast) {
682     // Because CE is flat, the source address space must be specific.
683     // Therefore, the inferred address space must be the source space according
684     // to our algorithm.
685     assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
686            NewAddrSpace);
687     return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
688   }
689 
690   if (CE->getOpcode() == Instruction::BitCast) {
691     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
692       return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
693     return ConstantExpr::getAddrSpaceCast(CE, TargetType);
694   }
695 
696   if (CE->getOpcode() == Instruction::Select) {
697     Constant *Src0 = CE->getOperand(1);
698     Constant *Src1 = CE->getOperand(2);
699     if (Src0->getType()->getPointerAddressSpace() ==
700         Src1->getType()->getPointerAddressSpace()) {
701 
702       return ConstantExpr::getSelect(
703           CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
704           ConstantExpr::getAddrSpaceCast(Src1, TargetType));
705     }
706   }
707 
708   if (CE->getOpcode() == Instruction::IntToPtr) {
709     assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
710     Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
711     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
712     return ConstantExpr::getBitCast(Src, TargetType);
713   }
714 
715   // Computes the operands of the new constant expression.
716   bool IsNew = false;
717   SmallVector<Constant *, 4> NewOperands;
718   for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
719     Constant *Operand = CE->getOperand(Index);
720     // If the address space of `Operand` needs to be modified, the new operand
721     // with the new address space should already be in ValueWithNewAddrSpace
722     // because (1) the constant expressions we consider (i.e. addrspacecast,
723     // bitcast, and getelementptr) do not incur cycles in the data flow graph
724     // and (2) this function is called on constant expressions in postorder.
725     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
726       IsNew = true;
727       NewOperands.push_back(cast<Constant>(NewOperand));
728       continue;
729     }
730     if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
731       if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
732               CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
733         IsNew = true;
734         NewOperands.push_back(cast<Constant>(NewOperand));
735         continue;
736       }
737     // Otherwise, reuses the old operand.
738     NewOperands.push_back(Operand);
739   }
740 
741   // If !IsNew, we will replace the Value with itself. However, replaced values
742   // are assumed to wrapped in an addrspacecast cast later so drop it now.
743   if (!IsNew)
744     return nullptr;
745 
746   if (CE->getOpcode() == Instruction::GetElementPtr) {
747     // Needs to specify the source type while constructing a getelementptr
748     // constant expression.
749     return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false,
750                                cast<GEPOperator>(CE)->getSourceElementType());
751   }
752 
753   return CE->getWithOperands(NewOperands, TargetType);
754 }
755 
756 // Returns a clone of the value `V`, with its operands replaced as specified in
757 // ValueWithNewAddrSpace. This function is called on every flat address
758 // expression whose address space needs to be modified, in postorder.
759 //
760 // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
761 Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
762     Value *V, unsigned NewAddrSpace,
763     const ValueToValueMapTy &ValueWithNewAddrSpace,
764     const PredicatedAddrSpaceMapTy &PredicatedAS,
765     SmallVectorImpl<const Use *> *UndefUsesToFix) const {
766   // All values in Postorder are flat address expressions.
767   assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
768          isAddressExpression(*V, *DL, TTI));
769 
770   if (Instruction *I = dyn_cast<Instruction>(V)) {
771     Value *NewV = cloneInstructionWithNewAddressSpace(
772         I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, UndefUsesToFix);
773     if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
774       if (NewI->getParent() == nullptr) {
775         NewI->insertBefore(I);
776         NewI->takeName(I);
777       }
778     }
779     return NewV;
780   }
781 
782   return cloneConstantExprWithNewAddressSpace(
783       cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
784 }
785 
786 // Defines the join operation on the address space lattice (see the file header
787 // comments).
788 unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
789                                                    unsigned AS2) const {
790   if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
791     return FlatAddrSpace;
792 
793   if (AS1 == UninitializedAddressSpace)
794     return AS2;
795   if (AS2 == UninitializedAddressSpace)
796     return AS1;
797 
798   // The join of two different specific address spaces is flat.
799   return (AS1 == AS2) ? AS1 : FlatAddrSpace;
800 }
801 
802 bool InferAddressSpacesImpl::run(Function &F) {
803   DL = &F.getParent()->getDataLayout();
804 
805   if (AssumeDefaultIsFlatAddressSpace)
806     FlatAddrSpace = 0;
807 
808   if (FlatAddrSpace == UninitializedAddressSpace) {
809     FlatAddrSpace = TTI->getFlatAddressSpace();
810     if (FlatAddrSpace == UninitializedAddressSpace)
811       return false;
812   }
813 
814   // Collects all flat address expressions in postorder.
815   std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
816 
817   // Runs a data-flow analysis to refine the address spaces of every expression
818   // in Postorder.
819   ValueToAddrSpaceMapTy InferredAddrSpace;
820   PredicatedAddrSpaceMapTy PredicatedAS;
821   inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
822 
823   // Changes the address spaces of the flat address expressions who are inferred
824   // to point to a specific address space.
825   return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS,
826                                      &F);
827 }
828 
829 // Constants need to be tracked through RAUW to handle cases with nested
830 // constant expressions, so wrap values in WeakTrackingVH.
831 void InferAddressSpacesImpl::inferAddressSpaces(
832     ArrayRef<WeakTrackingVH> Postorder,
833     ValueToAddrSpaceMapTy &InferredAddrSpace,
834     PredicatedAddrSpaceMapTy &PredicatedAS) const {
835   SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
836   // Initially, all expressions are in the uninitialized address space.
837   for (Value *V : Postorder)
838     InferredAddrSpace[V] = UninitializedAddressSpace;
839 
840   while (!Worklist.empty()) {
841     Value *V = Worklist.pop_back_val();
842 
843     // Try to update the address space of the stack top according to the
844     // address spaces of its operands.
845     if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
846       continue;
847 
848     for (Value *User : V->users()) {
849       // Skip if User is already in the worklist.
850       if (Worklist.count(User))
851         continue;
852 
853       auto Pos = InferredAddrSpace.find(User);
854       // Our algorithm only updates the address spaces of flat address
855       // expressions, which are those in InferredAddrSpace.
856       if (Pos == InferredAddrSpace.end())
857         continue;
858 
859       // Function updateAddressSpace moves the address space down a lattice
860       // path. Therefore, nothing to do if User is already inferred as flat (the
861       // bottom element in the lattice).
862       if (Pos->second == FlatAddrSpace)
863         continue;
864 
865       Worklist.insert(User);
866     }
867   }
868 }
869 
870 unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V,
871                                                         Value *Opnd) const {
872   const Instruction *I = dyn_cast<Instruction>(&V);
873   if (!I)
874     return UninitializedAddressSpace;
875 
876   Opnd = Opnd->stripInBoundsOffsets();
877   for (auto &AssumeVH : AC.assumptionsFor(Opnd)) {
878     if (!AssumeVH)
879       continue;
880     CallInst *CI = cast<CallInst>(AssumeVH);
881     if (!isValidAssumeForContext(CI, I, DT))
882       continue;
883 
884     const Value *Ptr;
885     unsigned AS;
886     std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
887     if (Ptr)
888       return AS;
889   }
890 
891   return UninitializedAddressSpace;
892 }
893 
894 bool InferAddressSpacesImpl::updateAddressSpace(
895     const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
896     PredicatedAddrSpaceMapTy &PredicatedAS) const {
897   assert(InferredAddrSpace.count(&V));
898 
899   LLVM_DEBUG(dbgs() << "Updating the address space of\n  " << V << '\n');
900 
901   // The new inferred address space equals the join of the address spaces
902   // of all its pointer operands.
903   unsigned NewAS = UninitializedAddressSpace;
904 
905   const Operator &Op = cast<Operator>(V);
906   if (Op.getOpcode() == Instruction::Select) {
907     Value *Src0 = Op.getOperand(1);
908     Value *Src1 = Op.getOperand(2);
909 
910     auto I = InferredAddrSpace.find(Src0);
911     unsigned Src0AS = (I != InferredAddrSpace.end()) ?
912       I->second : Src0->getType()->getPointerAddressSpace();
913 
914     auto J = InferredAddrSpace.find(Src1);
915     unsigned Src1AS = (J != InferredAddrSpace.end()) ?
916       J->second : Src1->getType()->getPointerAddressSpace();
917 
918     auto *C0 = dyn_cast<Constant>(Src0);
919     auto *C1 = dyn_cast<Constant>(Src1);
920 
921     // If one of the inputs is a constant, we may be able to do a constant
922     // addrspacecast of it. Defer inferring the address space until the input
923     // address space is known.
924     if ((C1 && Src0AS == UninitializedAddressSpace) ||
925         (C0 && Src1AS == UninitializedAddressSpace))
926       return false;
927 
928     if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
929       NewAS = Src1AS;
930     else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
931       NewAS = Src0AS;
932     else
933       NewAS = joinAddressSpaces(Src0AS, Src1AS);
934   } else {
935     unsigned AS = TTI->getAssumedAddrSpace(&V);
936     if (AS != UninitializedAddressSpace) {
937       // Use the assumed address space directly.
938       NewAS = AS;
939     } else {
940       // Otherwise, infer the address space from its pointer operands.
941       for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
942         auto I = InferredAddrSpace.find(PtrOperand);
943         unsigned OperandAS;
944         if (I == InferredAddrSpace.end()) {
945           OperandAS = PtrOperand->getType()->getPointerAddressSpace();
946           if (OperandAS == FlatAddrSpace) {
947             // Check AC for assumption dominating V.
948             unsigned AS = getPredicatedAddrSpace(V, PtrOperand);
949             if (AS != UninitializedAddressSpace) {
950               LLVM_DEBUG(dbgs()
951                          << "  deduce operand AS from the predicate addrspace "
952                          << AS << '\n');
953               OperandAS = AS;
954               // Record this use with the predicated AS.
955               PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
956             }
957           }
958         } else
959           OperandAS = I->second;
960 
961         // join(flat, *) = flat. So we can break if NewAS is already flat.
962         NewAS = joinAddressSpaces(NewAS, OperandAS);
963         if (NewAS == FlatAddrSpace)
964           break;
965       }
966     }
967   }
968 
969   unsigned OldAS = InferredAddrSpace.lookup(&V);
970   assert(OldAS != FlatAddrSpace);
971   if (OldAS == NewAS)
972     return false;
973 
974   // If any updates are made, grabs its users to the worklist because
975   // their address spaces can also be possibly updated.
976   LLVM_DEBUG(dbgs() << "  to " << NewAS << '\n');
977   InferredAddrSpace[&V] = NewAS;
978   return true;
979 }
980 
981 /// \p returns true if \p U is the pointer operand of a memory instruction with
982 /// a single pointer operand that can have its address space changed by simply
983 /// mutating the use to a new value. If the memory instruction is volatile,
984 /// return true only if the target allows the memory instruction to be volatile
985 /// in the new address space.
986 static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
987                                              Use &U, unsigned AddrSpace) {
988   User *Inst = U.getUser();
989   unsigned OpNo = U.getOperandNo();
990   bool VolatileIsAllowed = false;
991   if (auto *I = dyn_cast<Instruction>(Inst))
992     VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
993 
994   if (auto *LI = dyn_cast<LoadInst>(Inst))
995     return OpNo == LoadInst::getPointerOperandIndex() &&
996            (VolatileIsAllowed || !LI->isVolatile());
997 
998   if (auto *SI = dyn_cast<StoreInst>(Inst))
999     return OpNo == StoreInst::getPointerOperandIndex() &&
1000            (VolatileIsAllowed || !SI->isVolatile());
1001 
1002   if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
1003     return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
1004            (VolatileIsAllowed || !RMW->isVolatile());
1005 
1006   if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
1007     return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
1008            (VolatileIsAllowed || !CmpX->isVolatile());
1009 
1010   return false;
1011 }
1012 
1013 /// Update memory intrinsic uses that require more complex processing than
1014 /// simple memory instructions. These require re-mangling and may have multiple
1015 /// pointer operands.
1016 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
1017                                      Value *NewV) {
1018   IRBuilder<> B(MI);
1019   MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
1020   MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
1021   MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
1022 
1023   if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
1024     B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
1025                    false, // isVolatile
1026                    TBAA, ScopeMD, NoAliasMD);
1027   } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
1028     Value *Src = MTI->getRawSource();
1029     Value *Dest = MTI->getRawDest();
1030 
1031     // Be careful in case this is a self-to-self copy.
1032     if (Src == OldV)
1033       Src = NewV;
1034 
1035     if (Dest == OldV)
1036       Dest = NewV;
1037 
1038     if (isa<MemCpyInlineInst>(MTI)) {
1039       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
1040       B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
1041                            MTI->getSourceAlign(), MTI->getLength(),
1042                            false, // isVolatile
1043                            TBAA, TBAAStruct, ScopeMD, NoAliasMD);
1044     } else if (isa<MemCpyInst>(MTI)) {
1045       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
1046       B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1047                      MTI->getLength(),
1048                      false, // isVolatile
1049                      TBAA, TBAAStruct, ScopeMD, NoAliasMD);
1050     } else {
1051       assert(isa<MemMoveInst>(MTI));
1052       B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1053                       MTI->getLength(),
1054                       false, // isVolatile
1055                       TBAA, ScopeMD, NoAliasMD);
1056     }
1057   } else
1058     llvm_unreachable("unhandled MemIntrinsic");
1059 
1060   MI->eraseFromParent();
1061   return true;
1062 }
1063 
1064 // \p returns true if it is OK to change the address space of constant \p C with
1065 // a ConstantExpr addrspacecast.
1066 bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
1067                                                         unsigned NewAS) const {
1068   assert(NewAS != UninitializedAddressSpace);
1069 
1070   unsigned SrcAS = C->getType()->getPointerAddressSpace();
1071   if (SrcAS == NewAS || isa<UndefValue>(C))
1072     return true;
1073 
1074   // Prevent illegal casts between different non-flat address spaces.
1075   if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
1076     return false;
1077 
1078   if (isa<ConstantPointerNull>(C))
1079     return true;
1080 
1081   if (auto *Op = dyn_cast<Operator>(C)) {
1082     // If we already have a constant addrspacecast, it should be safe to cast it
1083     // off.
1084     if (Op->getOpcode() == Instruction::AddrSpaceCast)
1085       return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
1086 
1087     if (Op->getOpcode() == Instruction::IntToPtr &&
1088         Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
1089       return true;
1090   }
1091 
1092   return false;
1093 }
1094 
1095 static Value::use_iterator skipToNextUser(Value::use_iterator I,
1096                                           Value::use_iterator End) {
1097   User *CurUser = I->getUser();
1098   ++I;
1099 
1100   while (I != End && I->getUser() == CurUser)
1101     ++I;
1102 
1103   return I;
1104 }
1105 
1106 bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
1107     ArrayRef<WeakTrackingVH> Postorder,
1108     const ValueToAddrSpaceMapTy &InferredAddrSpace,
1109     const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const {
1110   // For each address expression to be modified, creates a clone of it with its
1111   // pointer operands converted to the new address space. Since the pointer
1112   // operands are converted, the clone is naturally in the new address space by
1113   // construction.
1114   ValueToValueMapTy ValueWithNewAddrSpace;
1115   SmallVector<const Use *, 32> UndefUsesToFix;
1116   for (Value* V : Postorder) {
1117     unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
1118 
1119     // In some degenerate cases (e.g. invalid IR in unreachable code), we may
1120     // not even infer the value to have its original address space.
1121     if (NewAddrSpace == UninitializedAddressSpace)
1122       continue;
1123 
1124     if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
1125       Value *New =
1126           cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
1127                                         PredicatedAS, &UndefUsesToFix);
1128       if (New)
1129         ValueWithNewAddrSpace[V] = New;
1130     }
1131   }
1132 
1133   if (ValueWithNewAddrSpace.empty())
1134     return false;
1135 
1136   // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
1137   for (const Use *UndefUse : UndefUsesToFix) {
1138     User *V = UndefUse->getUser();
1139     User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
1140     if (!NewV)
1141       continue;
1142 
1143     unsigned OperandNo = UndefUse->getOperandNo();
1144     assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
1145     NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
1146   }
1147 
1148   SmallVector<Instruction *, 16> DeadInstructions;
1149 
1150   // Replaces the uses of the old address expressions with the new ones.
1151   for (const WeakTrackingVH &WVH : Postorder) {
1152     assert(WVH && "value was unexpectedly deleted");
1153     Value *V = WVH;
1154     Value *NewV = ValueWithNewAddrSpace.lookup(V);
1155     if (NewV == nullptr)
1156       continue;
1157 
1158     LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n  with\n  "
1159                       << *NewV << '\n');
1160 
1161     if (Constant *C = dyn_cast<Constant>(V)) {
1162       Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1163                                                          C->getType());
1164       if (C != Replace) {
1165         LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
1166                           << ": " << *Replace << '\n');
1167         C->replaceAllUsesWith(Replace);
1168         V = Replace;
1169       }
1170     }
1171 
1172     Value::use_iterator I, E, Next;
1173     for (I = V->use_begin(), E = V->use_end(); I != E; ) {
1174       Use &U = *I;
1175 
1176       // Some users may see the same pointer operand in multiple operands. Skip
1177       // to the next instruction.
1178       I = skipToNextUser(I, E);
1179 
1180       if (isSimplePointerUseValidToReplace(
1181               *TTI, U, V->getType()->getPointerAddressSpace())) {
1182         // If V is used as the pointer operand of a compatible memory operation,
1183         // sets the pointer operand to NewV. This replacement does not change
1184         // the element type, so the resultant load/store is still valid.
1185         U.set(NewV);
1186         continue;
1187       }
1188 
1189       User *CurUser = U.getUser();
1190       // Skip if the current user is the new value itself.
1191       if (CurUser == NewV)
1192         continue;
1193       // Handle more complex cases like intrinsic that need to be remangled.
1194       if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
1195         if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
1196           continue;
1197       }
1198 
1199       if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
1200         if (rewriteIntrinsicOperands(II, V, NewV))
1201           continue;
1202       }
1203 
1204       if (isa<Instruction>(CurUser)) {
1205         if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
1206           // If we can infer that both pointers are in the same addrspace,
1207           // transform e.g.
1208           //   %cmp = icmp eq float* %p, %q
1209           // into
1210           //   %cmp = icmp eq float addrspace(3)* %new_p, %new_q
1211 
1212           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1213           int SrcIdx = U.getOperandNo();
1214           int OtherIdx = (SrcIdx == 0) ? 1 : 0;
1215           Value *OtherSrc = Cmp->getOperand(OtherIdx);
1216 
1217           if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
1218             if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
1219               Cmp->setOperand(OtherIdx, OtherNewV);
1220               Cmp->setOperand(SrcIdx, NewV);
1221               continue;
1222             }
1223           }
1224 
1225           // Even if the type mismatches, we can cast the constant.
1226           if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
1227             if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
1228               Cmp->setOperand(SrcIdx, NewV);
1229               Cmp->setOperand(OtherIdx,
1230                 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
1231               continue;
1232             }
1233           }
1234         }
1235 
1236         if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
1237           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1238           if (ASC->getDestAddressSpace() == NewAS) {
1239             if (!cast<PointerType>(ASC->getType())
1240                     ->hasSameElementTypeAs(
1241                         cast<PointerType>(NewV->getType()))) {
1242               BasicBlock::iterator InsertPos;
1243               if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1244                 InsertPos = std::next(NewVInst->getIterator());
1245               else if (Instruction *VInst = dyn_cast<Instruction>(V))
1246                 InsertPos = std::next(VInst->getIterator());
1247               else
1248                 InsertPos = ASC->getIterator();
1249 
1250               NewV = CastInst::Create(Instruction::BitCast, NewV,
1251                                       ASC->getType(), "", &*InsertPos);
1252             }
1253             ASC->replaceAllUsesWith(NewV);
1254             DeadInstructions.push_back(ASC);
1255             continue;
1256           }
1257         }
1258 
1259         // Otherwise, replaces the use with flat(NewV).
1260         if (Instruction *VInst = dyn_cast<Instruction>(V)) {
1261           // Don't create a copy of the original addrspacecast.
1262           if (U == V && isa<AddrSpaceCastInst>(V))
1263             continue;
1264 
1265           // Insert the addrspacecast after NewV.
1266           BasicBlock::iterator InsertPos;
1267           if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1268             InsertPos = std::next(NewVInst->getIterator());
1269           else
1270             InsertPos = std::next(VInst->getIterator());
1271 
1272           while (isa<PHINode>(InsertPos))
1273             ++InsertPos;
1274           U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
1275         } else {
1276           U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1277                                                V->getType()));
1278         }
1279       }
1280     }
1281 
1282     if (V->use_empty()) {
1283       if (Instruction *I = dyn_cast<Instruction>(V))
1284         DeadInstructions.push_back(I);
1285     }
1286   }
1287 
1288   for (Instruction *I : DeadInstructions)
1289     RecursivelyDeleteTriviallyDeadInstructions(I);
1290 
1291   return true;
1292 }
1293 
1294 bool InferAddressSpaces::runOnFunction(Function &F) {
1295   if (skipFunction(F))
1296     return false;
1297 
1298   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1299   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1300   return InferAddressSpacesImpl(
1301              getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
1302              &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
1303              FlatAddrSpace)
1304       .run(F);
1305 }
1306 
1307 FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
1308   return new InferAddressSpaces(AddressSpace);
1309 }
1310 
1311 InferAddressSpacesPass::InferAddressSpacesPass()
1312     : FlatAddrSpace(UninitializedAddressSpace) {}
1313 InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace)
1314     : FlatAddrSpace(AddressSpace) {}
1315 
1316 PreservedAnalyses InferAddressSpacesPass::run(Function &F,
1317                                               FunctionAnalysisManager &AM) {
1318   bool Changed =
1319       InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
1320                              AM.getCachedResult<DominatorTreeAnalysis>(F),
1321                              &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
1322           .run(F);
1323   if (Changed) {
1324     PreservedAnalyses PA;
1325     PA.preserveSet<CFGAnalyses>();
1326     PA.preserve<DominatorTreeAnalysis>();
1327     return PA;
1328   }
1329   return PreservedAnalyses::all();
1330 }
1331