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 "poison" 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 `poison` and fix all the uses later.
82 // For instance, our algorithm first converts %y to
83 //   %y' = phi float addrspace(3)* [ %input, poison ]
84 // Then, it converts %y2 to
85 //   %y2' = getelementptr %y', 1
86 // Finally, it fixes the poison 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 *> *PoisonUsesToFix) 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 *> *PoisonUsesToFix) 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 static Type *getPtrOrVecOfPtrsWithNewAS(Type *Ty, unsigned NewAddrSpace) {
260   assert(Ty->isPtrOrPtrVectorTy());
261   PointerType *NPT = PointerType::get(Ty->getContext(), NewAddrSpace);
262   return Ty->getWithNewType(NPT);
263 }
264 
265 // Check whether that's no-op pointer bicast using a pair of
266 // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
267 // different address spaces.
268 static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
269                                  const TargetTransformInfo *TTI) {
270   assert(I2P->getOpcode() == Instruction::IntToPtr);
271   auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
272   if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
273     return false;
274   // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
275   // no-op cast. Besides checking both of them are no-op casts, as the
276   // reinterpreted pointer may be used in other pointer arithmetic, we also
277   // need to double-check that through the target-specific hook. That ensures
278   // the underlying target also agrees that's a no-op address space cast and
279   // pointer bits are preserved.
280   // The current IR spec doesn't have clear rules on address space casts,
281   // especially a clear definition for pointer bits in non-default address
282   // spaces. It would be undefined if that pointer is dereferenced after an
283   // invalid reinterpret cast. Also, due to the unclearness for the meaning of
284   // bits in non-default address spaces in the current spec, the pointer
285   // arithmetic may also be undefined after invalid pointer reinterpret cast.
286   // However, as we confirm through the target hooks that it's a no-op
287   // addrspacecast, it doesn't matter since the bits should be the same.
288   unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
289   unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
290   return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
291                               I2P->getOperand(0)->getType(), I2P->getType(),
292                               DL) &&
293          CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()),
294                               P2I->getOperand(0)->getType(), P2I->getType(),
295                               DL) &&
296          (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
297 }
298 
299 // Returns true if V is an address expression.
300 // TODO: Currently, we consider only phi, bitcast, addrspacecast, and
301 // getelementptr operators.
302 static bool isAddressExpression(const Value &V, const DataLayout &DL,
303                                 const TargetTransformInfo *TTI) {
304   const Operator *Op = dyn_cast<Operator>(&V);
305   if (!Op)
306     return false;
307 
308   switch (Op->getOpcode()) {
309   case Instruction::PHI:
310     assert(Op->getType()->isPtrOrPtrVectorTy());
311     return true;
312   case Instruction::BitCast:
313   case Instruction::AddrSpaceCast:
314   case Instruction::GetElementPtr:
315     return true;
316   case Instruction::Select:
317     return Op->getType()->isPtrOrPtrVectorTy();
318   case Instruction::Call: {
319     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
320     return II && II->getIntrinsicID() == Intrinsic::ptrmask;
321   }
322   case Instruction::IntToPtr:
323     return isNoopPtrIntCastPair(Op, DL, TTI);
324   default:
325     // That value is an address expression if it has an assumed address space.
326     return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace;
327   }
328 }
329 
330 // Returns the pointer operands of V.
331 //
332 // Precondition: V is an address expression.
333 static SmallVector<Value *, 2>
334 getPointerOperands(const Value &V, const DataLayout &DL,
335                    const TargetTransformInfo *TTI) {
336   const Operator &Op = cast<Operator>(V);
337   switch (Op.getOpcode()) {
338   case Instruction::PHI: {
339     auto IncomingValues = cast<PHINode>(Op).incoming_values();
340     return {IncomingValues.begin(), IncomingValues.end()};
341   }
342   case Instruction::BitCast:
343   case Instruction::AddrSpaceCast:
344   case Instruction::GetElementPtr:
345     return {Op.getOperand(0)};
346   case Instruction::Select:
347     return {Op.getOperand(1), Op.getOperand(2)};
348   case Instruction::Call: {
349     const IntrinsicInst &II = cast<IntrinsicInst>(Op);
350     assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
351            "unexpected intrinsic call");
352     return {II.getArgOperand(0)};
353   }
354   case Instruction::IntToPtr: {
355     assert(isNoopPtrIntCastPair(&Op, DL, TTI));
356     auto *P2I = cast<Operator>(Op.getOperand(0));
357     return {P2I->getOperand(0)};
358   }
359   default:
360     llvm_unreachable("Unexpected instruction type.");
361   }
362 }
363 
364 bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
365                                                       Value *OldV,
366                                                       Value *NewV) const {
367   Module *M = II->getParent()->getParent()->getParent();
368 
369   switch (II->getIntrinsicID()) {
370   case Intrinsic::objectsize: {
371     Type *DestTy = II->getType();
372     Type *SrcTy = NewV->getType();
373     Function *NewDecl =
374         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
375     II->setArgOperand(0, NewV);
376     II->setCalledFunction(NewDecl);
377     return true;
378   }
379   case Intrinsic::ptrmask:
380     // This is handled as an address expression, not as a use memory operation.
381     return false;
382   case Intrinsic::masked_gather: {
383     Type *RetTy = II->getType();
384     Type *NewPtrTy = NewV->getType();
385     Function *NewDecl =
386         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {RetTy, NewPtrTy});
387     II->setArgOperand(0, NewV);
388     II->setCalledFunction(NewDecl);
389     return true;
390   }
391   case Intrinsic::masked_scatter: {
392     Type *ValueTy = II->getOperand(0)->getType();
393     Type *NewPtrTy = NewV->getType();
394     Function *NewDecl =
395         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {ValueTy, NewPtrTy});
396     II->setArgOperand(1, NewV);
397     II->setCalledFunction(NewDecl);
398     return true;
399   }
400   default: {
401     Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
402     if (!Rewrite)
403       return false;
404     if (Rewrite != II)
405       II->replaceAllUsesWith(Rewrite);
406     return true;
407   }
408   }
409 }
410 
411 void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
412     IntrinsicInst *II, PostorderStackTy &PostorderStack,
413     DenseSet<Value *> &Visited) const {
414   auto IID = II->getIntrinsicID();
415   switch (IID) {
416   case Intrinsic::ptrmask:
417   case Intrinsic::objectsize:
418     appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
419                                                  PostorderStack, Visited);
420     break;
421   case Intrinsic::masked_gather:
422     appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
423                                                  PostorderStack, Visited);
424     break;
425   case Intrinsic::masked_scatter:
426     appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(1),
427                                                  PostorderStack, Visited);
428     break;
429   default:
430     SmallVector<int, 2> OpIndexes;
431     if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
432       for (int Idx : OpIndexes) {
433         appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
434                                                      PostorderStack, Visited);
435       }
436     }
437     break;
438   }
439 }
440 
441 // Returns all flat address expressions in function F. The elements are
442 // If V is an unvisited flat address expression, appends V to PostorderStack
443 // and marks it as visited.
444 void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
445     Value *V, PostorderStackTy &PostorderStack,
446     DenseSet<Value *> &Visited) const {
447   assert(V->getType()->isPtrOrPtrVectorTy());
448 
449   // Generic addressing expressions may be hidden in nested constant
450   // expressions.
451   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
452     // TODO: Look in non-address parts, like icmp operands.
453     if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
454       PostorderStack.emplace_back(CE, false);
455 
456     return;
457   }
458 
459   if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
460       isAddressExpression(*V, *DL, TTI)) {
461     if (Visited.insert(V).second) {
462       PostorderStack.emplace_back(V, false);
463 
464       Operator *Op = cast<Operator>(V);
465       for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
466         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
467           if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
468             PostorderStack.emplace_back(CE, false);
469         }
470       }
471     }
472   }
473 }
474 
475 // Returns all flat address expressions in function F. The elements are ordered
476 // ordered in postorder.
477 std::vector<WeakTrackingVH>
478 InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
479   // This function implements a non-recursive postorder traversal of a partial
480   // use-def graph of function F.
481   PostorderStackTy PostorderStack;
482   // The set of visited expressions.
483   DenseSet<Value *> Visited;
484 
485   auto PushPtrOperand = [&](Value *Ptr) {
486     appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
487                                                  Visited);
488   };
489 
490   // Look at operations that may be interesting accelerate by moving to a known
491   // address space. We aim at generating after loads and stores, but pure
492   // addressing calculations may also be faster.
493   for (Instruction &I : instructions(F)) {
494     if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
495       PushPtrOperand(GEP->getPointerOperand());
496     } else if (auto *LI = dyn_cast<LoadInst>(&I))
497       PushPtrOperand(LI->getPointerOperand());
498     else if (auto *SI = dyn_cast<StoreInst>(&I))
499       PushPtrOperand(SI->getPointerOperand());
500     else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
501       PushPtrOperand(RMW->getPointerOperand());
502     else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
503       PushPtrOperand(CmpX->getPointerOperand());
504     else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
505       // For memset/memcpy/memmove, any pointer operand can be replaced.
506       PushPtrOperand(MI->getRawDest());
507 
508       // Handle 2nd operand for memcpy/memmove.
509       if (auto *MTI = dyn_cast<MemTransferInst>(MI))
510         PushPtrOperand(MTI->getRawSource());
511     } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
512       collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
513     else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
514       if (Cmp->getOperand(0)->getType()->isPtrOrPtrVectorTy()) {
515         PushPtrOperand(Cmp->getOperand(0));
516         PushPtrOperand(Cmp->getOperand(1));
517       }
518     } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
519       PushPtrOperand(ASC->getPointerOperand());
520     } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
521       if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
522         PushPtrOperand(
523             cast<Operator>(I2P->getOperand(0))->getOperand(0));
524     }
525   }
526 
527   std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
528   while (!PostorderStack.empty()) {
529     Value *TopVal = PostorderStack.back().getPointer();
530     // If the operands of the expression on the top are already explored,
531     // adds that expression to the resultant postorder.
532     if (PostorderStack.back().getInt()) {
533       if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
534         Postorder.push_back(TopVal);
535       PostorderStack.pop_back();
536       continue;
537     }
538     // Otherwise, adds its operands to the stack and explores them.
539     PostorderStack.back().setInt(true);
540     // Skip values with an assumed address space.
541     if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) {
542       for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
543         appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
544                                                      Visited);
545       }
546     }
547   }
548   return Postorder;
549 }
550 
551 // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
552 // of OperandUse.get() in the new address space. If the clone is not ready yet,
553 // returns poison in the new address space as a placeholder.
554 static Value *operandWithNewAddressSpaceOrCreatePoison(
555     const Use &OperandUse, unsigned NewAddrSpace,
556     const ValueToValueMapTy &ValueWithNewAddrSpace,
557     const PredicatedAddrSpaceMapTy &PredicatedAS,
558     SmallVectorImpl<const Use *> *PoisonUsesToFix) {
559   Value *Operand = OperandUse.get();
560 
561   Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(Operand->getType(), NewAddrSpace);
562 
563   if (Constant *C = dyn_cast<Constant>(Operand))
564     return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
565 
566   if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
567     return NewOperand;
568 
569   Instruction *Inst = cast<Instruction>(OperandUse.getUser());
570   auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
571   if (I != PredicatedAS.end()) {
572     // Insert an addrspacecast on that operand before the user.
573     unsigned NewAS = I->second;
574     Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(Operand->getType(), NewAS);
575     auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
576     NewI->insertBefore(Inst);
577     NewI->setDebugLoc(Inst->getDebugLoc());
578     return NewI;
579   }
580 
581   PoisonUsesToFix->push_back(&OperandUse);
582   return PoisonValue::get(NewPtrTy);
583 }
584 
585 // Returns a clone of `I` with its operands converted to those specified in
586 // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
587 // operand whose address space needs to be modified might not exist in
588 // ValueWithNewAddrSpace. In that case, uses poison as a placeholder operand and
589 // adds that operand use to PoisonUsesToFix so that caller can fix them later.
590 //
591 // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
592 // from a pointer whose type already matches. Therefore, this function returns a
593 // Value* instead of an Instruction*.
594 //
595 // This may also return nullptr in the case the instruction could not be
596 // rewritten.
597 Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
598     Instruction *I, unsigned NewAddrSpace,
599     const ValueToValueMapTy &ValueWithNewAddrSpace,
600     const PredicatedAddrSpaceMapTy &PredicatedAS,
601     SmallVectorImpl<const Use *> *PoisonUsesToFix) const {
602   Type *NewPtrType = getPtrOrVecOfPtrsWithNewAS(I->getType(), NewAddrSpace);
603 
604   if (I->getOpcode() == Instruction::AddrSpaceCast) {
605     Value *Src = I->getOperand(0);
606     // Because `I` is flat, the source address space must be specific.
607     // Therefore, the inferred address space must be the source space, according
608     // to our algorithm.
609     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
610     if (Src->getType() != NewPtrType)
611       return new BitCastInst(Src, NewPtrType);
612     return Src;
613   }
614 
615   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
616     // Technically the intrinsic ID is a pointer typed argument, so specially
617     // handle calls early.
618     assert(II->getIntrinsicID() == Intrinsic::ptrmask);
619     Value *NewPtr = operandWithNewAddressSpaceOrCreatePoison(
620         II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
621         PredicatedAS, PoisonUsesToFix);
622     Value *Rewrite =
623         TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr);
624     if (Rewrite) {
625       assert(Rewrite != II && "cannot modify this pointer operation in place");
626       return Rewrite;
627     }
628 
629     return nullptr;
630   }
631 
632   unsigned AS = TTI->getAssumedAddrSpace(I);
633   if (AS != UninitializedAddressSpace) {
634     // For the assumed address space, insert an `addrspacecast` to make that
635     // explicit.
636     Type *NewPtrTy = getPtrOrVecOfPtrsWithNewAS(I->getType(), AS);
637     auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
638     NewI->insertAfter(I);
639     return NewI;
640   }
641 
642   // Computes the converted pointer operands.
643   SmallVector<Value *, 4> NewPointerOperands;
644   for (const Use &OperandUse : I->operands()) {
645     if (!OperandUse.get()->getType()->isPtrOrPtrVectorTy())
646       NewPointerOperands.push_back(nullptr);
647     else
648       NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreatePoison(
649           OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
650           PoisonUsesToFix));
651   }
652 
653   switch (I->getOpcode()) {
654   case Instruction::BitCast:
655     return new BitCastInst(NewPointerOperands[0], NewPtrType);
656   case Instruction::PHI: {
657     assert(I->getType()->isPtrOrPtrVectorTy());
658     PHINode *PHI = cast<PHINode>(I);
659     PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
660     for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
661       unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
662       NewPHI->addIncoming(NewPointerOperands[OperandNo],
663                           PHI->getIncomingBlock(Index));
664     }
665     return NewPHI;
666   }
667   case Instruction::GetElementPtr: {
668     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
669     GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
670         GEP->getSourceElementType(), NewPointerOperands[0],
671         SmallVector<Value *, 4>(GEP->indices()));
672     NewGEP->setIsInBounds(GEP->isInBounds());
673     return NewGEP;
674   }
675   case Instruction::Select:
676     assert(I->getType()->isPtrOrPtrVectorTy());
677     return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
678                               NewPointerOperands[2], "", nullptr, I);
679   case Instruction::IntToPtr: {
680     assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
681     Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
682     if (Src->getType() == NewPtrType)
683       return Src;
684 
685     // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a
686     // source address space from a generic pointer source need to insert a cast
687     // back.
688     return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType);
689   }
690   default:
691     llvm_unreachable("Unexpected opcode");
692   }
693 }
694 
695 // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
696 // constant expression `CE` with its operands replaced as specified in
697 // ValueWithNewAddrSpace.
698 static Value *cloneConstantExprWithNewAddressSpace(
699     ConstantExpr *CE, unsigned NewAddrSpace,
700     const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
701     const TargetTransformInfo *TTI) {
702   Type *TargetType =
703       CE->getType()->isPtrOrPtrVectorTy()
704           ? getPtrOrVecOfPtrsWithNewAS(CE->getType(), NewAddrSpace)
705           : CE->getType();
706 
707   if (CE->getOpcode() == Instruction::AddrSpaceCast) {
708     // Because CE is flat, the source address space must be specific.
709     // Therefore, the inferred address space must be the source space according
710     // to our algorithm.
711     assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
712            NewAddrSpace);
713     return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
714   }
715 
716   if (CE->getOpcode() == Instruction::BitCast) {
717     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
718       return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
719     return ConstantExpr::getAddrSpaceCast(CE, TargetType);
720   }
721 
722   if (CE->getOpcode() == Instruction::IntToPtr) {
723     assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
724     Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
725     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
726     return ConstantExpr::getBitCast(Src, TargetType);
727   }
728 
729   // Computes the operands of the new constant expression.
730   bool IsNew = false;
731   SmallVector<Constant *, 4> NewOperands;
732   for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
733     Constant *Operand = CE->getOperand(Index);
734     // If the address space of `Operand` needs to be modified, the new operand
735     // with the new address space should already be in ValueWithNewAddrSpace
736     // because (1) the constant expressions we consider (i.e. addrspacecast,
737     // bitcast, and getelementptr) do not incur cycles in the data flow graph
738     // and (2) this function is called on constant expressions in postorder.
739     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
740       IsNew = true;
741       NewOperands.push_back(cast<Constant>(NewOperand));
742       continue;
743     }
744     if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
745       if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
746               CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
747         IsNew = true;
748         NewOperands.push_back(cast<Constant>(NewOperand));
749         continue;
750       }
751     // Otherwise, reuses the old operand.
752     NewOperands.push_back(Operand);
753   }
754 
755   // If !IsNew, we will replace the Value with itself. However, replaced values
756   // are assumed to wrapped in an addrspacecast cast later so drop it now.
757   if (!IsNew)
758     return nullptr;
759 
760   if (CE->getOpcode() == Instruction::GetElementPtr) {
761     // Needs to specify the source type while constructing a getelementptr
762     // constant expression.
763     return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false,
764                                cast<GEPOperator>(CE)->getSourceElementType());
765   }
766 
767   return CE->getWithOperands(NewOperands, TargetType);
768 }
769 
770 // Returns a clone of the value `V`, with its operands replaced as specified in
771 // ValueWithNewAddrSpace. This function is called on every flat address
772 // expression whose address space needs to be modified, in postorder.
773 //
774 // See cloneInstructionWithNewAddressSpace for the meaning of PoisonUsesToFix.
775 Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
776     Value *V, unsigned NewAddrSpace,
777     const ValueToValueMapTy &ValueWithNewAddrSpace,
778     const PredicatedAddrSpaceMapTy &PredicatedAS,
779     SmallVectorImpl<const Use *> *PoisonUsesToFix) const {
780   // All values in Postorder are flat address expressions.
781   assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
782          isAddressExpression(*V, *DL, TTI));
783 
784   if (Instruction *I = dyn_cast<Instruction>(V)) {
785     Value *NewV = cloneInstructionWithNewAddressSpace(
786         I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, PoisonUsesToFix);
787     if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
788       if (NewI->getParent() == nullptr) {
789         NewI->insertBefore(I);
790         NewI->takeName(I);
791         NewI->setDebugLoc(I->getDebugLoc());
792       }
793     }
794     return NewV;
795   }
796 
797   return cloneConstantExprWithNewAddressSpace(
798       cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
799 }
800 
801 // Defines the join operation on the address space lattice (see the file header
802 // comments).
803 unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
804                                                    unsigned AS2) const {
805   if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
806     return FlatAddrSpace;
807 
808   if (AS1 == UninitializedAddressSpace)
809     return AS2;
810   if (AS2 == UninitializedAddressSpace)
811     return AS1;
812 
813   // The join of two different specific address spaces is flat.
814   return (AS1 == AS2) ? AS1 : FlatAddrSpace;
815 }
816 
817 bool InferAddressSpacesImpl::run(Function &F) {
818   DL = &F.getParent()->getDataLayout();
819 
820   if (AssumeDefaultIsFlatAddressSpace)
821     FlatAddrSpace = 0;
822 
823   if (FlatAddrSpace == UninitializedAddressSpace) {
824     FlatAddrSpace = TTI->getFlatAddressSpace();
825     if (FlatAddrSpace == UninitializedAddressSpace)
826       return false;
827   }
828 
829   // Collects all flat address expressions in postorder.
830   std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
831 
832   // Runs a data-flow analysis to refine the address spaces of every expression
833   // in Postorder.
834   ValueToAddrSpaceMapTy InferredAddrSpace;
835   PredicatedAddrSpaceMapTy PredicatedAS;
836   inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
837 
838   // Changes the address spaces of the flat address expressions who are inferred
839   // to point to a specific address space.
840   return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS,
841                                      &F);
842 }
843 
844 // Constants need to be tracked through RAUW to handle cases with nested
845 // constant expressions, so wrap values in WeakTrackingVH.
846 void InferAddressSpacesImpl::inferAddressSpaces(
847     ArrayRef<WeakTrackingVH> Postorder,
848     ValueToAddrSpaceMapTy &InferredAddrSpace,
849     PredicatedAddrSpaceMapTy &PredicatedAS) const {
850   SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
851   // Initially, all expressions are in the uninitialized address space.
852   for (Value *V : Postorder)
853     InferredAddrSpace[V] = UninitializedAddressSpace;
854 
855   while (!Worklist.empty()) {
856     Value *V = Worklist.pop_back_val();
857 
858     // Try to update the address space of the stack top according to the
859     // address spaces of its operands.
860     if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
861       continue;
862 
863     for (Value *User : V->users()) {
864       // Skip if User is already in the worklist.
865       if (Worklist.count(User))
866         continue;
867 
868       auto Pos = InferredAddrSpace.find(User);
869       // Our algorithm only updates the address spaces of flat address
870       // expressions, which are those in InferredAddrSpace.
871       if (Pos == InferredAddrSpace.end())
872         continue;
873 
874       // Function updateAddressSpace moves the address space down a lattice
875       // path. Therefore, nothing to do if User is already inferred as flat (the
876       // bottom element in the lattice).
877       if (Pos->second == FlatAddrSpace)
878         continue;
879 
880       Worklist.insert(User);
881     }
882   }
883 }
884 
885 unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V,
886                                                         Value *Opnd) const {
887   const Instruction *I = dyn_cast<Instruction>(&V);
888   if (!I)
889     return UninitializedAddressSpace;
890 
891   Opnd = Opnd->stripInBoundsOffsets();
892   for (auto &AssumeVH : AC.assumptionsFor(Opnd)) {
893     if (!AssumeVH)
894       continue;
895     CallInst *CI = cast<CallInst>(AssumeVH);
896     if (!isValidAssumeForContext(CI, I, DT))
897       continue;
898 
899     const Value *Ptr;
900     unsigned AS;
901     std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
902     if (Ptr)
903       return AS;
904   }
905 
906   return UninitializedAddressSpace;
907 }
908 
909 bool InferAddressSpacesImpl::updateAddressSpace(
910     const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
911     PredicatedAddrSpaceMapTy &PredicatedAS) const {
912   assert(InferredAddrSpace.count(&V));
913 
914   LLVM_DEBUG(dbgs() << "Updating the address space of\n  " << V << '\n');
915 
916   // The new inferred address space equals the join of the address spaces
917   // of all its pointer operands.
918   unsigned NewAS = UninitializedAddressSpace;
919 
920   const Operator &Op = cast<Operator>(V);
921   if (Op.getOpcode() == Instruction::Select) {
922     Value *Src0 = Op.getOperand(1);
923     Value *Src1 = Op.getOperand(2);
924 
925     auto I = InferredAddrSpace.find(Src0);
926     unsigned Src0AS = (I != InferredAddrSpace.end()) ?
927       I->second : Src0->getType()->getPointerAddressSpace();
928 
929     auto J = InferredAddrSpace.find(Src1);
930     unsigned Src1AS = (J != InferredAddrSpace.end()) ?
931       J->second : Src1->getType()->getPointerAddressSpace();
932 
933     auto *C0 = dyn_cast<Constant>(Src0);
934     auto *C1 = dyn_cast<Constant>(Src1);
935 
936     // If one of the inputs is a constant, we may be able to do a constant
937     // addrspacecast of it. Defer inferring the address space until the input
938     // address space is known.
939     if ((C1 && Src0AS == UninitializedAddressSpace) ||
940         (C0 && Src1AS == UninitializedAddressSpace))
941       return false;
942 
943     if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
944       NewAS = Src1AS;
945     else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
946       NewAS = Src0AS;
947     else
948       NewAS = joinAddressSpaces(Src0AS, Src1AS);
949   } else {
950     unsigned AS = TTI->getAssumedAddrSpace(&V);
951     if (AS != UninitializedAddressSpace) {
952       // Use the assumed address space directly.
953       NewAS = AS;
954     } else {
955       // Otherwise, infer the address space from its pointer operands.
956       for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
957         auto I = InferredAddrSpace.find(PtrOperand);
958         unsigned OperandAS;
959         if (I == InferredAddrSpace.end()) {
960           OperandAS = PtrOperand->getType()->getPointerAddressSpace();
961           if (OperandAS == FlatAddrSpace) {
962             // Check AC for assumption dominating V.
963             unsigned AS = getPredicatedAddrSpace(V, PtrOperand);
964             if (AS != UninitializedAddressSpace) {
965               LLVM_DEBUG(dbgs()
966                          << "  deduce operand AS from the predicate addrspace "
967                          << AS << '\n');
968               OperandAS = AS;
969               // Record this use with the predicated AS.
970               PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
971             }
972           }
973         } else
974           OperandAS = I->second;
975 
976         // join(flat, *) = flat. So we can break if NewAS is already flat.
977         NewAS = joinAddressSpaces(NewAS, OperandAS);
978         if (NewAS == FlatAddrSpace)
979           break;
980       }
981     }
982   }
983 
984   unsigned OldAS = InferredAddrSpace.lookup(&V);
985   assert(OldAS != FlatAddrSpace);
986   if (OldAS == NewAS)
987     return false;
988 
989   // If any updates are made, grabs its users to the worklist because
990   // their address spaces can also be possibly updated.
991   LLVM_DEBUG(dbgs() << "  to " << NewAS << '\n');
992   InferredAddrSpace[&V] = NewAS;
993   return true;
994 }
995 
996 /// \p returns true if \p U is the pointer operand of a memory instruction with
997 /// a single pointer operand that can have its address space changed by simply
998 /// mutating the use to a new value. If the memory instruction is volatile,
999 /// return true only if the target allows the memory instruction to be volatile
1000 /// in the new address space.
1001 static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
1002                                              Use &U, unsigned AddrSpace) {
1003   User *Inst = U.getUser();
1004   unsigned OpNo = U.getOperandNo();
1005   bool VolatileIsAllowed = false;
1006   if (auto *I = dyn_cast<Instruction>(Inst))
1007     VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
1008 
1009   if (auto *LI = dyn_cast<LoadInst>(Inst))
1010     return OpNo == LoadInst::getPointerOperandIndex() &&
1011            (VolatileIsAllowed || !LI->isVolatile());
1012 
1013   if (auto *SI = dyn_cast<StoreInst>(Inst))
1014     return OpNo == StoreInst::getPointerOperandIndex() &&
1015            (VolatileIsAllowed || !SI->isVolatile());
1016 
1017   if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
1018     return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
1019            (VolatileIsAllowed || !RMW->isVolatile());
1020 
1021   if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
1022     return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
1023            (VolatileIsAllowed || !CmpX->isVolatile());
1024 
1025   return false;
1026 }
1027 
1028 /// Update memory intrinsic uses that require more complex processing than
1029 /// simple memory instructions. These require re-mangling and may have multiple
1030 /// pointer operands.
1031 static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
1032                                      Value *NewV) {
1033   IRBuilder<> B(MI);
1034   MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
1035   MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
1036   MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
1037 
1038   if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
1039     B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
1040                    false, // isVolatile
1041                    TBAA, ScopeMD, NoAliasMD);
1042   } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
1043     Value *Src = MTI->getRawSource();
1044     Value *Dest = MTI->getRawDest();
1045 
1046     // Be careful in case this is a self-to-self copy.
1047     if (Src == OldV)
1048       Src = NewV;
1049 
1050     if (Dest == OldV)
1051       Dest = NewV;
1052 
1053     if (isa<MemCpyInlineInst>(MTI)) {
1054       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
1055       B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
1056                            MTI->getSourceAlign(), MTI->getLength(),
1057                            false, // isVolatile
1058                            TBAA, TBAAStruct, ScopeMD, NoAliasMD);
1059     } else if (isa<MemCpyInst>(MTI)) {
1060       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
1061       B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1062                      MTI->getLength(),
1063                      false, // isVolatile
1064                      TBAA, TBAAStruct, ScopeMD, NoAliasMD);
1065     } else {
1066       assert(isa<MemMoveInst>(MTI));
1067       B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
1068                       MTI->getLength(),
1069                       false, // isVolatile
1070                       TBAA, ScopeMD, NoAliasMD);
1071     }
1072   } else
1073     llvm_unreachable("unhandled MemIntrinsic");
1074 
1075   MI->eraseFromParent();
1076   return true;
1077 }
1078 
1079 // \p returns true if it is OK to change the address space of constant \p C with
1080 // a ConstantExpr addrspacecast.
1081 bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
1082                                                         unsigned NewAS) const {
1083   assert(NewAS != UninitializedAddressSpace);
1084 
1085   unsigned SrcAS = C->getType()->getPointerAddressSpace();
1086   if (SrcAS == NewAS || isa<UndefValue>(C))
1087     return true;
1088 
1089   // Prevent illegal casts between different non-flat address spaces.
1090   if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
1091     return false;
1092 
1093   if (isa<ConstantPointerNull>(C))
1094     return true;
1095 
1096   if (auto *Op = dyn_cast<Operator>(C)) {
1097     // If we already have a constant addrspacecast, it should be safe to cast it
1098     // off.
1099     if (Op->getOpcode() == Instruction::AddrSpaceCast)
1100       return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
1101 
1102     if (Op->getOpcode() == Instruction::IntToPtr &&
1103         Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
1104       return true;
1105   }
1106 
1107   return false;
1108 }
1109 
1110 static Value::use_iterator skipToNextUser(Value::use_iterator I,
1111                                           Value::use_iterator End) {
1112   User *CurUser = I->getUser();
1113   ++I;
1114 
1115   while (I != End && I->getUser() == CurUser)
1116     ++I;
1117 
1118   return I;
1119 }
1120 
1121 bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
1122     ArrayRef<WeakTrackingVH> Postorder,
1123     const ValueToAddrSpaceMapTy &InferredAddrSpace,
1124     const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const {
1125   // For each address expression to be modified, creates a clone of it with its
1126   // pointer operands converted to the new address space. Since the pointer
1127   // operands are converted, the clone is naturally in the new address space by
1128   // construction.
1129   ValueToValueMapTy ValueWithNewAddrSpace;
1130   SmallVector<const Use *, 32> PoisonUsesToFix;
1131   for (Value* V : Postorder) {
1132     unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
1133 
1134     // In some degenerate cases (e.g. invalid IR in unreachable code), we may
1135     // not even infer the value to have its original address space.
1136     if (NewAddrSpace == UninitializedAddressSpace)
1137       continue;
1138 
1139     if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
1140       Value *New =
1141           cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
1142                                         PredicatedAS, &PoisonUsesToFix);
1143       if (New)
1144         ValueWithNewAddrSpace[V] = New;
1145     }
1146   }
1147 
1148   if (ValueWithNewAddrSpace.empty())
1149     return false;
1150 
1151   // Fixes all the poison uses generated by cloneInstructionWithNewAddressSpace.
1152   for (const Use *PoisonUse : PoisonUsesToFix) {
1153     User *V = PoisonUse->getUser();
1154     User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
1155     if (!NewV)
1156       continue;
1157 
1158     unsigned OperandNo = PoisonUse->getOperandNo();
1159     assert(isa<PoisonValue>(NewV->getOperand(OperandNo)));
1160     NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(PoisonUse->get()));
1161   }
1162 
1163   SmallVector<Instruction *, 16> DeadInstructions;
1164 
1165   // Replaces the uses of the old address expressions with the new ones.
1166   for (const WeakTrackingVH &WVH : Postorder) {
1167     assert(WVH && "value was unexpectedly deleted");
1168     Value *V = WVH;
1169     Value *NewV = ValueWithNewAddrSpace.lookup(V);
1170     if (NewV == nullptr)
1171       continue;
1172 
1173     LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n  with\n  "
1174                       << *NewV << '\n');
1175 
1176     if (Constant *C = dyn_cast<Constant>(V)) {
1177       Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1178                                                          C->getType());
1179       if (C != Replace) {
1180         LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
1181                           << ": " << *Replace << '\n');
1182         C->replaceAllUsesWith(Replace);
1183         V = Replace;
1184       }
1185     }
1186 
1187     Value::use_iterator I, E, Next;
1188     for (I = V->use_begin(), E = V->use_end(); I != E; ) {
1189       Use &U = *I;
1190 
1191       // Some users may see the same pointer operand in multiple operands. Skip
1192       // to the next instruction.
1193       I = skipToNextUser(I, E);
1194 
1195       if (isSimplePointerUseValidToReplace(
1196               *TTI, U, V->getType()->getPointerAddressSpace())) {
1197         // If V is used as the pointer operand of a compatible memory operation,
1198         // sets the pointer operand to NewV. This replacement does not change
1199         // the element type, so the resultant load/store is still valid.
1200         U.set(NewV);
1201         continue;
1202       }
1203 
1204       User *CurUser = U.getUser();
1205       // Skip if the current user is the new value itself.
1206       if (CurUser == NewV)
1207         continue;
1208       // Handle more complex cases like intrinsic that need to be remangled.
1209       if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
1210         if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
1211           continue;
1212       }
1213 
1214       if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
1215         if (rewriteIntrinsicOperands(II, V, NewV))
1216           continue;
1217       }
1218 
1219       if (isa<Instruction>(CurUser)) {
1220         if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
1221           // If we can infer that both pointers are in the same addrspace,
1222           // transform e.g.
1223           //   %cmp = icmp eq float* %p, %q
1224           // into
1225           //   %cmp = icmp eq float addrspace(3)* %new_p, %new_q
1226 
1227           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1228           int SrcIdx = U.getOperandNo();
1229           int OtherIdx = (SrcIdx == 0) ? 1 : 0;
1230           Value *OtherSrc = Cmp->getOperand(OtherIdx);
1231 
1232           if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
1233             if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
1234               Cmp->setOperand(OtherIdx, OtherNewV);
1235               Cmp->setOperand(SrcIdx, NewV);
1236               continue;
1237             }
1238           }
1239 
1240           // Even if the type mismatches, we can cast the constant.
1241           if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
1242             if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
1243               Cmp->setOperand(SrcIdx, NewV);
1244               Cmp->setOperand(OtherIdx,
1245                 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
1246               continue;
1247             }
1248           }
1249         }
1250 
1251         if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
1252           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1253           if (ASC->getDestAddressSpace() == NewAS) {
1254             ASC->replaceAllUsesWith(NewV);
1255             DeadInstructions.push_back(ASC);
1256             continue;
1257           }
1258         }
1259 
1260         // Otherwise, replaces the use with flat(NewV).
1261         if (Instruction *VInst = dyn_cast<Instruction>(V)) {
1262           // Don't create a copy of the original addrspacecast.
1263           if (U == V && isa<AddrSpaceCastInst>(V))
1264             continue;
1265 
1266           // Insert the addrspacecast after NewV.
1267           BasicBlock::iterator InsertPos;
1268           if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1269             InsertPos = std::next(NewVInst->getIterator());
1270           else
1271             InsertPos = std::next(VInst->getIterator());
1272 
1273           while (isa<PHINode>(InsertPos))
1274             ++InsertPos;
1275           U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
1276         } else {
1277           U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
1278                                                V->getType()));
1279         }
1280       }
1281     }
1282 
1283     if (V->use_empty()) {
1284       if (Instruction *I = dyn_cast<Instruction>(V))
1285         DeadInstructions.push_back(I);
1286     }
1287   }
1288 
1289   for (Instruction *I : DeadInstructions)
1290     RecursivelyDeleteTriviallyDeadInstructions(I);
1291 
1292   return true;
1293 }
1294 
1295 bool InferAddressSpaces::runOnFunction(Function &F) {
1296   if (skipFunction(F))
1297     return false;
1298 
1299   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1300   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1301   return InferAddressSpacesImpl(
1302              getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
1303              &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
1304              FlatAddrSpace)
1305       .run(F);
1306 }
1307 
1308 FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
1309   return new InferAddressSpaces(AddressSpace);
1310 }
1311 
1312 InferAddressSpacesPass::InferAddressSpacesPass()
1313     : FlatAddrSpace(UninitializedAddressSpace) {}
1314 InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace)
1315     : FlatAddrSpace(AddressSpace) {}
1316 
1317 PreservedAnalyses InferAddressSpacesPass::run(Function &F,
1318                                               FunctionAnalysisManager &AM) {
1319   bool Changed =
1320       InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
1321                              AM.getCachedResult<DominatorTreeAnalysis>(F),
1322                              &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
1323           .run(F);
1324   if (Changed) {
1325     PreservedAnalyses PA;
1326     PA.preserveSet<CFGAnalyses>();
1327     PA.preserve<DominatorTreeAnalysis>();
1328     return PA;
1329   }
1330   return PreservedAnalyses::all();
1331 }
1332