xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/Scalar/InferAddressSpaces.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- InferAddressSpace.cpp - --------------------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // CUDA C/C++ includes memory space designation as variable type qualifers (such
1009467b48Spatrick // as __global__ and __shared__). Knowing the space of a memory access allows
1109467b48Spatrick // CUDA compilers to emit faster PTX loads and stores. For example, a load from
1209467b48Spatrick // shared memory can be translated to `ld.shared` which is roughly 10% faster
1309467b48Spatrick // than a generic `ld` on an NVIDIA Tesla K40c.
1409467b48Spatrick //
1509467b48Spatrick // Unfortunately, type qualifiers only apply to variable declarations, so CUDA
1609467b48Spatrick // compilers must infer the memory space of an address expression from
1709467b48Spatrick // type-qualified variables.
1809467b48Spatrick //
1909467b48Spatrick // LLVM IR uses non-zero (so-called) specific address spaces to represent memory
2009467b48Spatrick // spaces (e.g. addrspace(3) means shared memory). The Clang frontend
2109467b48Spatrick // places only type-qualified variables in specific address spaces, and then
2209467b48Spatrick // conservatively `addrspacecast`s each type-qualified variable to addrspace(0)
2309467b48Spatrick // (so-called the generic address space) for other instructions to use.
2409467b48Spatrick //
2509467b48Spatrick // For example, the Clang translates the following CUDA code
2609467b48Spatrick //   __shared__ float a[10];
2709467b48Spatrick //   float v = a[i];
2809467b48Spatrick // to
2909467b48Spatrick //   %0 = addrspacecast [10 x float] addrspace(3)* @a to [10 x float]*
3009467b48Spatrick //   %1 = gep [10 x float], [10 x float]* %0, i64 0, i64 %i
3109467b48Spatrick //   %v = load float, float* %1 ; emits ld.f32
3209467b48Spatrick // @a is in addrspace(3) since it's type-qualified, but its use from %1 is
3309467b48Spatrick // redirected to %0 (the generic version of @a).
3409467b48Spatrick //
3509467b48Spatrick // The optimization implemented in this file propagates specific address spaces
3609467b48Spatrick // from type-qualified variable declarations to its users. For example, it
3709467b48Spatrick // optimizes the above IR to
3809467b48Spatrick //   %1 = gep [10 x float] addrspace(3)* @a, i64 0, i64 %i
3909467b48Spatrick //   %v = load float addrspace(3)* %1 ; emits ld.shared.f32
4009467b48Spatrick // propagating the addrspace(3) from @a to %1. As the result, the NVPTX
4109467b48Spatrick // codegen is able to emit ld.shared.f32 for %v.
4209467b48Spatrick //
4309467b48Spatrick // Address space inference works in two steps. First, it uses a data-flow
4409467b48Spatrick // analysis to infer as many generic pointers as possible to point to only one
4509467b48Spatrick // specific address space. In the above example, it can prove that %1 only
4609467b48Spatrick // points to addrspace(3). This algorithm was published in
4709467b48Spatrick //   CUDA: Compiling and optimizing for a GPU platform
4809467b48Spatrick //   Chakrabarti, Grover, Aarts, Kong, Kudlur, Lin, Marathe, Murphy, Wang
4909467b48Spatrick //   ICCS 2012
5009467b48Spatrick //
5109467b48Spatrick // Then, address space inference replaces all refinable generic pointers with
5209467b48Spatrick // equivalent specific pointers.
5309467b48Spatrick //
5409467b48Spatrick // The major challenge of implementing this optimization is handling PHINodes,
5509467b48Spatrick // which may create loops in the data flow graph. This brings two complications.
5609467b48Spatrick //
5709467b48Spatrick // First, the data flow analysis in Step 1 needs to be circular. For example,
5809467b48Spatrick //     %generic.input = addrspacecast float addrspace(3)* %input to float*
5909467b48Spatrick //   loop:
6009467b48Spatrick //     %y = phi [ %generic.input, %y2 ]
6109467b48Spatrick //     %y2 = getelementptr %y, 1
6209467b48Spatrick //     %v = load %y2
6309467b48Spatrick //     br ..., label %loop, ...
6409467b48Spatrick // proving %y specific requires proving both %generic.input and %y2 specific,
6509467b48Spatrick // but proving %y2 specific circles back to %y. To address this complication,
6609467b48Spatrick // the data flow analysis operates on a lattice:
6709467b48Spatrick //   uninitialized > specific address spaces > generic.
6809467b48Spatrick // All address expressions (our implementation only considers phi, bitcast,
6909467b48Spatrick // addrspacecast, and getelementptr) start with the uninitialized address space.
7009467b48Spatrick // The monotone transfer function moves the address space of a pointer down a
7109467b48Spatrick // lattice path from uninitialized to specific and then to generic. A join
7209467b48Spatrick // operation of two different specific address spaces pushes the expression down
7309467b48Spatrick // to the generic address space. The analysis completes once it reaches a fixed
7409467b48Spatrick // point.
7509467b48Spatrick //
7609467b48Spatrick // Second, IR rewriting in Step 2 also needs to be circular. For example,
7709467b48Spatrick // converting %y to addrspace(3) requires the compiler to know the converted
7809467b48Spatrick // %y2, but converting %y2 needs the converted %y. To address this complication,
7909467b48Spatrick // we break these cycles using "undef" placeholders. When converting an
8009467b48Spatrick // instruction `I` to a new address space, if its operand `Op` is not converted
8109467b48Spatrick // yet, we let `I` temporarily use `undef` and fix all the uses of undef later.
8209467b48Spatrick // For instance, our algorithm first converts %y to
8309467b48Spatrick //   %y' = phi float addrspace(3)* [ %input, undef ]
8409467b48Spatrick // Then, it converts %y2 to
8509467b48Spatrick //   %y2' = getelementptr %y', 1
8609467b48Spatrick // Finally, it fixes the undef in %y' so that
8709467b48Spatrick //   %y' = phi float addrspace(3)* [ %input, %y2' ]
8809467b48Spatrick //
8909467b48Spatrick //===----------------------------------------------------------------------===//
9009467b48Spatrick 
9173471bf0Spatrick #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
9209467b48Spatrick #include "llvm/ADT/ArrayRef.h"
9309467b48Spatrick #include "llvm/ADT/DenseMap.h"
9409467b48Spatrick #include "llvm/ADT/DenseSet.h"
9509467b48Spatrick #include "llvm/ADT/SetVector.h"
9609467b48Spatrick #include "llvm/ADT/SmallVector.h"
97*d415bd75Srobert #include "llvm/Analysis/AssumptionCache.h"
9809467b48Spatrick #include "llvm/Analysis/TargetTransformInfo.h"
99*d415bd75Srobert #include "llvm/Analysis/ValueTracking.h"
10009467b48Spatrick #include "llvm/IR/BasicBlock.h"
10109467b48Spatrick #include "llvm/IR/Constant.h"
10209467b48Spatrick #include "llvm/IR/Constants.h"
103*d415bd75Srobert #include "llvm/IR/Dominators.h"
10409467b48Spatrick #include "llvm/IR/Function.h"
10509467b48Spatrick #include "llvm/IR/IRBuilder.h"
10609467b48Spatrick #include "llvm/IR/InstIterator.h"
10709467b48Spatrick #include "llvm/IR/Instruction.h"
10809467b48Spatrick #include "llvm/IR/Instructions.h"
10909467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
11009467b48Spatrick #include "llvm/IR/Intrinsics.h"
11109467b48Spatrick #include "llvm/IR/LLVMContext.h"
11209467b48Spatrick #include "llvm/IR/Operator.h"
11373471bf0Spatrick #include "llvm/IR/PassManager.h"
11409467b48Spatrick #include "llvm/IR/Type.h"
11509467b48Spatrick #include "llvm/IR/Use.h"
11609467b48Spatrick #include "llvm/IR/User.h"
11709467b48Spatrick #include "llvm/IR/Value.h"
11809467b48Spatrick #include "llvm/IR/ValueHandle.h"
119*d415bd75Srobert #include "llvm/InitializePasses.h"
12009467b48Spatrick #include "llvm/Pass.h"
12109467b48Spatrick #include "llvm/Support/Casting.h"
122097a140dSpatrick #include "llvm/Support/CommandLine.h"
12309467b48Spatrick #include "llvm/Support/Compiler.h"
12409467b48Spatrick #include "llvm/Support/Debug.h"
12509467b48Spatrick #include "llvm/Support/ErrorHandling.h"
12609467b48Spatrick #include "llvm/Support/raw_ostream.h"
12709467b48Spatrick #include "llvm/Transforms/Scalar.h"
128097a140dSpatrick #include "llvm/Transforms/Utils/Local.h"
12909467b48Spatrick #include "llvm/Transforms/Utils/ValueMapper.h"
13009467b48Spatrick #include <cassert>
13109467b48Spatrick #include <iterator>
13209467b48Spatrick #include <limits>
13309467b48Spatrick #include <utility>
13409467b48Spatrick #include <vector>
13509467b48Spatrick 
13609467b48Spatrick #define DEBUG_TYPE "infer-address-spaces"
13709467b48Spatrick 
13809467b48Spatrick using namespace llvm;
13909467b48Spatrick 
140097a140dSpatrick static cl::opt<bool> AssumeDefaultIsFlatAddressSpace(
141097a140dSpatrick     "assume-default-is-flat-addrspace", cl::init(false), cl::ReallyHidden,
142097a140dSpatrick     cl::desc("The default address space is assumed as the flat address space. "
143097a140dSpatrick              "This is mainly for test purpose."));
144097a140dSpatrick 
14509467b48Spatrick static const unsigned UninitializedAddressSpace =
14609467b48Spatrick     std::numeric_limits<unsigned>::max();
14709467b48Spatrick 
14809467b48Spatrick namespace {
14909467b48Spatrick 
15009467b48Spatrick using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
151*d415bd75Srobert // Different from ValueToAddrSpaceMapTy, where a new addrspace is inferred on
152*d415bd75Srobert // the *def* of a value, PredicatedAddrSpaceMapTy is map where a new
153*d415bd75Srobert // addrspace is inferred on the *use* of a pointer. This map is introduced to
154*d415bd75Srobert // infer addrspace from the addrspace predicate assumption built from assume
155*d415bd75Srobert // intrinsic. In that scenario, only specific uses (under valid assumption
156*d415bd75Srobert // context) could be inferred with a new addrspace.
157*d415bd75Srobert using PredicatedAddrSpaceMapTy =
158*d415bd75Srobert     DenseMap<std::pair<const Value *, const Value *>, unsigned>;
159097a140dSpatrick using PostorderStackTy = llvm::SmallVector<PointerIntPair<Value *, 1, bool>, 4>;
16009467b48Spatrick 
16109467b48Spatrick class InferAddressSpaces : public FunctionPass {
16209467b48Spatrick   unsigned FlatAddrSpace = 0;
16309467b48Spatrick 
16409467b48Spatrick public:
16509467b48Spatrick   static char ID;
16609467b48Spatrick 
InferAddressSpaces()16709467b48Spatrick   InferAddressSpaces() :
16809467b48Spatrick     FunctionPass(ID), FlatAddrSpace(UninitializedAddressSpace) {}
InferAddressSpaces(unsigned AS)16909467b48Spatrick   InferAddressSpaces(unsigned AS) : FunctionPass(ID), FlatAddrSpace(AS) {}
17009467b48Spatrick 
getAnalysisUsage(AnalysisUsage & AU) const17109467b48Spatrick   void getAnalysisUsage(AnalysisUsage &AU) const override {
17209467b48Spatrick     AU.setPreservesCFG();
173*d415bd75Srobert     AU.addPreserved<DominatorTreeWrapperPass>();
174*d415bd75Srobert     AU.addRequired<AssumptionCacheTracker>();
17509467b48Spatrick     AU.addRequired<TargetTransformInfoWrapperPass>();
17609467b48Spatrick   }
17709467b48Spatrick 
17809467b48Spatrick   bool runOnFunction(Function &F) override;
17973471bf0Spatrick };
18009467b48Spatrick 
18173471bf0Spatrick class InferAddressSpacesImpl {
182*d415bd75Srobert   AssumptionCache &AC;
183*d415bd75Srobert   const DominatorTree *DT = nullptr;
18473471bf0Spatrick   const TargetTransformInfo *TTI = nullptr;
18573471bf0Spatrick   const DataLayout *DL = nullptr;
18673471bf0Spatrick 
18773471bf0Spatrick   /// Target specific address space which uses of should be replaced if
18873471bf0Spatrick   /// possible.
18973471bf0Spatrick   unsigned FlatAddrSpace = 0;
19073471bf0Spatrick 
191*d415bd75Srobert   // Try to update the address space of V. If V is updated, returns true and
192*d415bd75Srobert   // false otherwise.
193*d415bd75Srobert   bool updateAddressSpace(const Value &V,
194*d415bd75Srobert                           ValueToAddrSpaceMapTy &InferredAddrSpace,
195*d415bd75Srobert                           PredicatedAddrSpaceMapTy &PredicatedAS) const;
19609467b48Spatrick 
19709467b48Spatrick   // Tries to infer the specific address space of each address expression in
19809467b48Spatrick   // Postorder.
19909467b48Spatrick   void inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
200*d415bd75Srobert                           ValueToAddrSpaceMapTy &InferredAddrSpace,
201*d415bd75Srobert                           PredicatedAddrSpaceMapTy &PredicatedAS) const;
20209467b48Spatrick 
20309467b48Spatrick   bool isSafeToCastConstAddrSpace(Constant *C, unsigned NewAS) const;
20409467b48Spatrick 
205097a140dSpatrick   Value *cloneInstructionWithNewAddressSpace(
206097a140dSpatrick       Instruction *I, unsigned NewAddrSpace,
207097a140dSpatrick       const ValueToValueMapTy &ValueWithNewAddrSpace,
208*d415bd75Srobert       const PredicatedAddrSpaceMapTy &PredicatedAS,
209097a140dSpatrick       SmallVectorImpl<const Use *> *UndefUsesToFix) const;
210097a140dSpatrick 
21109467b48Spatrick   // Changes the flat address expressions in function F to point to specific
21209467b48Spatrick   // address spaces if InferredAddrSpace says so. Postorder is the postorder of
21309467b48Spatrick   // all flat expressions in the use-def graph of function F.
214*d415bd75Srobert   bool
215*d415bd75Srobert   rewriteWithNewAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,
216*d415bd75Srobert                               const ValueToAddrSpaceMapTy &InferredAddrSpace,
217*d415bd75Srobert                               const PredicatedAddrSpaceMapTy &PredicatedAS,
218*d415bd75Srobert                               Function *F) const;
21909467b48Spatrick 
22009467b48Spatrick   void appendsFlatAddressExpressionToPostorderStack(
221097a140dSpatrick       Value *V, PostorderStackTy &PostorderStack,
22209467b48Spatrick       DenseSet<Value *> &Visited) const;
22309467b48Spatrick 
22409467b48Spatrick   bool rewriteIntrinsicOperands(IntrinsicInst *II,
22509467b48Spatrick                                 Value *OldV, Value *NewV) const;
226097a140dSpatrick   void collectRewritableIntrinsicOperands(IntrinsicInst *II,
227097a140dSpatrick                                           PostorderStackTy &PostorderStack,
22809467b48Spatrick                                           DenseSet<Value *> &Visited) const;
22909467b48Spatrick 
23009467b48Spatrick   std::vector<WeakTrackingVH> collectFlatAddressExpressions(Function &F) const;
23109467b48Spatrick 
23209467b48Spatrick   Value *cloneValueWithNewAddressSpace(
23309467b48Spatrick       Value *V, unsigned NewAddrSpace,
23409467b48Spatrick       const ValueToValueMapTy &ValueWithNewAddrSpace,
235*d415bd75Srobert       const PredicatedAddrSpaceMapTy &PredicatedAS,
23609467b48Spatrick       SmallVectorImpl<const Use *> *UndefUsesToFix) const;
23709467b48Spatrick   unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
23873471bf0Spatrick 
239*d415bd75Srobert   unsigned getPredicatedAddrSpace(const Value &V, Value *Opnd) const;
240*d415bd75Srobert 
24173471bf0Spatrick public:
InferAddressSpacesImpl(AssumptionCache & AC,const DominatorTree * DT,const TargetTransformInfo * TTI,unsigned FlatAddrSpace)242*d415bd75Srobert   InferAddressSpacesImpl(AssumptionCache &AC, const DominatorTree *DT,
243*d415bd75Srobert                          const TargetTransformInfo *TTI, unsigned FlatAddrSpace)
244*d415bd75Srobert       : AC(AC), DT(DT), TTI(TTI), FlatAddrSpace(FlatAddrSpace) {}
24573471bf0Spatrick   bool run(Function &F);
24609467b48Spatrick };
24709467b48Spatrick 
24809467b48Spatrick } // end anonymous namespace
24909467b48Spatrick 
25009467b48Spatrick char InferAddressSpaces::ID = 0;
25109467b48Spatrick 
252*d415bd75Srobert INITIALIZE_PASS_BEGIN(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
253*d415bd75Srobert                       false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)254*d415bd75Srobert INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
255*d415bd75Srobert INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
256*d415bd75Srobert INITIALIZE_PASS_END(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
25709467b48Spatrick                     false, false)
25809467b48Spatrick 
259097a140dSpatrick // Check whether that's no-op pointer bicast using a pair of
260097a140dSpatrick // `ptrtoint`/`inttoptr` due to the missing no-op pointer bitcast over
261097a140dSpatrick // different address spaces.
262097a140dSpatrick static bool isNoopPtrIntCastPair(const Operator *I2P, const DataLayout &DL,
263097a140dSpatrick                                  const TargetTransformInfo *TTI) {
264097a140dSpatrick   assert(I2P->getOpcode() == Instruction::IntToPtr);
265097a140dSpatrick   auto *P2I = dyn_cast<Operator>(I2P->getOperand(0));
266097a140dSpatrick   if (!P2I || P2I->getOpcode() != Instruction::PtrToInt)
267097a140dSpatrick     return false;
268097a140dSpatrick   // Check it's really safe to treat that pair of `ptrtoint`/`inttoptr` as a
269097a140dSpatrick   // no-op cast. Besides checking both of them are no-op casts, as the
270097a140dSpatrick   // reinterpreted pointer may be used in other pointer arithmetic, we also
271097a140dSpatrick   // need to double-check that through the target-specific hook. That ensures
272097a140dSpatrick   // the underlying target also agrees that's a no-op address space cast and
273097a140dSpatrick   // pointer bits are preserved.
274097a140dSpatrick   // The current IR spec doesn't have clear rules on address space casts,
275097a140dSpatrick   // especially a clear definition for pointer bits in non-default address
276097a140dSpatrick   // spaces. It would be undefined if that pointer is dereferenced after an
277097a140dSpatrick   // invalid reinterpret cast. Also, due to the unclearness for the meaning of
278097a140dSpatrick   // bits in non-default address spaces in the current spec, the pointer
279097a140dSpatrick   // arithmetic may also be undefined after invalid pointer reinterpret cast.
280097a140dSpatrick   // However, as we confirm through the target hooks that it's a no-op
281097a140dSpatrick   // addrspacecast, it doesn't matter since the bits should be the same.
282*d415bd75Srobert   unsigned P2IOp0AS = P2I->getOperand(0)->getType()->getPointerAddressSpace();
283*d415bd75Srobert   unsigned I2PAS = I2P->getType()->getPointerAddressSpace();
284097a140dSpatrick   return CastInst::isNoopCast(Instruction::CastOps(I2P->getOpcode()),
285097a140dSpatrick                               I2P->getOperand(0)->getType(), I2P->getType(),
286097a140dSpatrick                               DL) &&
287097a140dSpatrick          CastInst::isNoopCast(Instruction::CastOps(P2I->getOpcode()),
288097a140dSpatrick                               P2I->getOperand(0)->getType(), P2I->getType(),
289097a140dSpatrick                               DL) &&
290*d415bd75Srobert          (P2IOp0AS == I2PAS || TTI->isNoopAddrSpaceCast(P2IOp0AS, I2PAS));
291097a140dSpatrick }
292097a140dSpatrick 
29309467b48Spatrick // Returns true if V is an address expression.
29409467b48Spatrick // TODO: Currently, we consider only phi, bitcast, addrspacecast, and
29509467b48Spatrick // getelementptr operators.
isAddressExpression(const Value & V,const DataLayout & DL,const TargetTransformInfo * TTI)296097a140dSpatrick static bool isAddressExpression(const Value &V, const DataLayout &DL,
297097a140dSpatrick                                 const TargetTransformInfo *TTI) {
298097a140dSpatrick   const Operator *Op = dyn_cast<Operator>(&V);
299097a140dSpatrick   if (!Op)
30009467b48Spatrick     return false;
30109467b48Spatrick 
302097a140dSpatrick   switch (Op->getOpcode()) {
30309467b48Spatrick   case Instruction::PHI:
304097a140dSpatrick     assert(Op->getType()->isPointerTy());
30509467b48Spatrick     return true;
30609467b48Spatrick   case Instruction::BitCast:
30709467b48Spatrick   case Instruction::AddrSpaceCast:
30809467b48Spatrick   case Instruction::GetElementPtr:
30909467b48Spatrick     return true;
31009467b48Spatrick   case Instruction::Select:
311097a140dSpatrick     return Op->getType()->isPointerTy();
312097a140dSpatrick   case Instruction::Call: {
313097a140dSpatrick     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&V);
314097a140dSpatrick     return II && II->getIntrinsicID() == Intrinsic::ptrmask;
315097a140dSpatrick   }
316097a140dSpatrick   case Instruction::IntToPtr:
317097a140dSpatrick     return isNoopPtrIntCastPair(Op, DL, TTI);
31809467b48Spatrick   default:
31973471bf0Spatrick     // That value is an address expression if it has an assumed address space.
32073471bf0Spatrick     return TTI->getAssumedAddrSpace(&V) != UninitializedAddressSpace;
32109467b48Spatrick   }
32209467b48Spatrick }
32309467b48Spatrick 
32409467b48Spatrick // Returns the pointer operands of V.
32509467b48Spatrick //
32609467b48Spatrick // Precondition: V is an address expression.
327097a140dSpatrick static SmallVector<Value *, 2>
getPointerOperands(const Value & V,const DataLayout & DL,const TargetTransformInfo * TTI)328097a140dSpatrick getPointerOperands(const Value &V, const DataLayout &DL,
329097a140dSpatrick                    const TargetTransformInfo *TTI) {
33009467b48Spatrick   const Operator &Op = cast<Operator>(V);
33109467b48Spatrick   switch (Op.getOpcode()) {
33209467b48Spatrick   case Instruction::PHI: {
33309467b48Spatrick     auto IncomingValues = cast<PHINode>(Op).incoming_values();
334*d415bd75Srobert     return {IncomingValues.begin(), IncomingValues.end()};
33509467b48Spatrick   }
33609467b48Spatrick   case Instruction::BitCast:
33709467b48Spatrick   case Instruction::AddrSpaceCast:
33809467b48Spatrick   case Instruction::GetElementPtr:
33909467b48Spatrick     return {Op.getOperand(0)};
34009467b48Spatrick   case Instruction::Select:
34109467b48Spatrick     return {Op.getOperand(1), Op.getOperand(2)};
342097a140dSpatrick   case Instruction::Call: {
343097a140dSpatrick     const IntrinsicInst &II = cast<IntrinsicInst>(Op);
344097a140dSpatrick     assert(II.getIntrinsicID() == Intrinsic::ptrmask &&
345097a140dSpatrick            "unexpected intrinsic call");
346097a140dSpatrick     return {II.getArgOperand(0)};
347097a140dSpatrick   }
348097a140dSpatrick   case Instruction::IntToPtr: {
349097a140dSpatrick     assert(isNoopPtrIntCastPair(&Op, DL, TTI));
350097a140dSpatrick     auto *P2I = cast<Operator>(Op.getOperand(0));
351097a140dSpatrick     return {P2I->getOperand(0)};
352097a140dSpatrick   }
35309467b48Spatrick   default:
35409467b48Spatrick     llvm_unreachable("Unexpected instruction type.");
35509467b48Spatrick   }
35609467b48Spatrick }
35709467b48Spatrick 
rewriteIntrinsicOperands(IntrinsicInst * II,Value * OldV,Value * NewV) const35873471bf0Spatrick bool InferAddressSpacesImpl::rewriteIntrinsicOperands(IntrinsicInst *II,
35909467b48Spatrick                                                       Value *OldV,
36009467b48Spatrick                                                       Value *NewV) const {
36109467b48Spatrick   Module *M = II->getParent()->getParent()->getParent();
36209467b48Spatrick 
36309467b48Spatrick   switch (II->getIntrinsicID()) {
36409467b48Spatrick   case Intrinsic::objectsize: {
36509467b48Spatrick     Type *DestTy = II->getType();
36609467b48Spatrick     Type *SrcTy = NewV->getType();
36709467b48Spatrick     Function *NewDecl =
36809467b48Spatrick         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
36909467b48Spatrick     II->setArgOperand(0, NewV);
37009467b48Spatrick     II->setCalledFunction(NewDecl);
37109467b48Spatrick     return true;
37209467b48Spatrick   }
373097a140dSpatrick   case Intrinsic::ptrmask:
374097a140dSpatrick     // This is handled as an address expression, not as a use memory operation.
375097a140dSpatrick     return false;
376097a140dSpatrick   default: {
377097a140dSpatrick     Value *Rewrite = TTI->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
378097a140dSpatrick     if (!Rewrite)
379097a140dSpatrick       return false;
380097a140dSpatrick     if (Rewrite != II)
381097a140dSpatrick       II->replaceAllUsesWith(Rewrite);
382097a140dSpatrick     return true;
383097a140dSpatrick   }
38409467b48Spatrick   }
38509467b48Spatrick }
38609467b48Spatrick 
collectRewritableIntrinsicOperands(IntrinsicInst * II,PostorderStackTy & PostorderStack,DenseSet<Value * > & Visited) const38773471bf0Spatrick void InferAddressSpacesImpl::collectRewritableIntrinsicOperands(
388097a140dSpatrick     IntrinsicInst *II, PostorderStackTy &PostorderStack,
38909467b48Spatrick     DenseSet<Value *> &Visited) const {
39009467b48Spatrick   auto IID = II->getIntrinsicID();
39109467b48Spatrick   switch (IID) {
392097a140dSpatrick   case Intrinsic::ptrmask:
39309467b48Spatrick   case Intrinsic::objectsize:
39409467b48Spatrick     appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(0),
39509467b48Spatrick                                                  PostorderStack, Visited);
39609467b48Spatrick     break;
39709467b48Spatrick   default:
39809467b48Spatrick     SmallVector<int, 2> OpIndexes;
39909467b48Spatrick     if (TTI->collectFlatAddressOperands(OpIndexes, IID)) {
40009467b48Spatrick       for (int Idx : OpIndexes) {
40109467b48Spatrick         appendsFlatAddressExpressionToPostorderStack(II->getArgOperand(Idx),
40209467b48Spatrick                                                      PostorderStack, Visited);
40309467b48Spatrick       }
40409467b48Spatrick     }
40509467b48Spatrick     break;
40609467b48Spatrick   }
40709467b48Spatrick }
40809467b48Spatrick 
40909467b48Spatrick // Returns all flat address expressions in function F. The elements are
41009467b48Spatrick // If V is an unvisited flat address expression, appends V to PostorderStack
41109467b48Spatrick // and marks it as visited.
appendsFlatAddressExpressionToPostorderStack(Value * V,PostorderStackTy & PostorderStack,DenseSet<Value * > & Visited) const41273471bf0Spatrick void InferAddressSpacesImpl::appendsFlatAddressExpressionToPostorderStack(
413097a140dSpatrick     Value *V, PostorderStackTy &PostorderStack,
41409467b48Spatrick     DenseSet<Value *> &Visited) const {
41509467b48Spatrick   assert(V->getType()->isPointerTy());
41609467b48Spatrick 
41709467b48Spatrick   // Generic addressing expressions may be hidden in nested constant
41809467b48Spatrick   // expressions.
41909467b48Spatrick   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
42009467b48Spatrick     // TODO: Look in non-address parts, like icmp operands.
421097a140dSpatrick     if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
422097a140dSpatrick       PostorderStack.emplace_back(CE, false);
42309467b48Spatrick 
42409467b48Spatrick     return;
42509467b48Spatrick   }
42609467b48Spatrick 
42773471bf0Spatrick   if (V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
42873471bf0Spatrick       isAddressExpression(*V, *DL, TTI)) {
42909467b48Spatrick     if (Visited.insert(V).second) {
430097a140dSpatrick       PostorderStack.emplace_back(V, false);
43109467b48Spatrick 
43209467b48Spatrick       Operator *Op = cast<Operator>(V);
43309467b48Spatrick       for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I) {
43409467b48Spatrick         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op->getOperand(I))) {
435097a140dSpatrick           if (isAddressExpression(*CE, *DL, TTI) && Visited.insert(CE).second)
43609467b48Spatrick             PostorderStack.emplace_back(CE, false);
43709467b48Spatrick         }
43809467b48Spatrick       }
43909467b48Spatrick     }
44009467b48Spatrick   }
44109467b48Spatrick }
44209467b48Spatrick 
44309467b48Spatrick // Returns all flat address expressions in function F. The elements are ordered
44409467b48Spatrick // ordered in postorder.
44509467b48Spatrick std::vector<WeakTrackingVH>
collectFlatAddressExpressions(Function & F) const44673471bf0Spatrick InferAddressSpacesImpl::collectFlatAddressExpressions(Function &F) const {
44709467b48Spatrick   // This function implements a non-recursive postorder traversal of a partial
44809467b48Spatrick   // use-def graph of function F.
449097a140dSpatrick   PostorderStackTy PostorderStack;
45009467b48Spatrick   // The set of visited expressions.
45109467b48Spatrick   DenseSet<Value *> Visited;
45209467b48Spatrick 
45309467b48Spatrick   auto PushPtrOperand = [&](Value *Ptr) {
45409467b48Spatrick     appendsFlatAddressExpressionToPostorderStack(Ptr, PostorderStack,
45509467b48Spatrick                                                  Visited);
45609467b48Spatrick   };
45709467b48Spatrick 
45809467b48Spatrick   // Look at operations that may be interesting accelerate by moving to a known
45909467b48Spatrick   // address space. We aim at generating after loads and stores, but pure
46009467b48Spatrick   // addressing calculations may also be faster.
46109467b48Spatrick   for (Instruction &I : instructions(F)) {
46209467b48Spatrick     if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
46309467b48Spatrick       if (!GEP->getType()->isVectorTy())
46409467b48Spatrick         PushPtrOperand(GEP->getPointerOperand());
46509467b48Spatrick     } else if (auto *LI = dyn_cast<LoadInst>(&I))
46609467b48Spatrick       PushPtrOperand(LI->getPointerOperand());
46709467b48Spatrick     else if (auto *SI = dyn_cast<StoreInst>(&I))
46809467b48Spatrick       PushPtrOperand(SI->getPointerOperand());
46909467b48Spatrick     else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
47009467b48Spatrick       PushPtrOperand(RMW->getPointerOperand());
47109467b48Spatrick     else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
47209467b48Spatrick       PushPtrOperand(CmpX->getPointerOperand());
47309467b48Spatrick     else if (auto *MI = dyn_cast<MemIntrinsic>(&I)) {
47409467b48Spatrick       // For memset/memcpy/memmove, any pointer operand can be replaced.
47509467b48Spatrick       PushPtrOperand(MI->getRawDest());
47609467b48Spatrick 
47709467b48Spatrick       // Handle 2nd operand for memcpy/memmove.
47809467b48Spatrick       if (auto *MTI = dyn_cast<MemTransferInst>(MI))
47909467b48Spatrick         PushPtrOperand(MTI->getRawSource());
48009467b48Spatrick     } else if (auto *II = dyn_cast<IntrinsicInst>(&I))
48109467b48Spatrick       collectRewritableIntrinsicOperands(II, PostorderStack, Visited);
48209467b48Spatrick     else if (ICmpInst *Cmp = dyn_cast<ICmpInst>(&I)) {
48309467b48Spatrick       // FIXME: Handle vectors of pointers
48409467b48Spatrick       if (Cmp->getOperand(0)->getType()->isPointerTy()) {
48509467b48Spatrick         PushPtrOperand(Cmp->getOperand(0));
48609467b48Spatrick         PushPtrOperand(Cmp->getOperand(1));
48709467b48Spatrick       }
48809467b48Spatrick     } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I)) {
48909467b48Spatrick       if (!ASC->getType()->isVectorTy())
49009467b48Spatrick         PushPtrOperand(ASC->getPointerOperand());
491097a140dSpatrick     } else if (auto *I2P = dyn_cast<IntToPtrInst>(&I)) {
492097a140dSpatrick       if (isNoopPtrIntCastPair(cast<Operator>(I2P), *DL, TTI))
493097a140dSpatrick         PushPtrOperand(
49473471bf0Spatrick             cast<Operator>(I2P->getOperand(0))->getOperand(0));
49509467b48Spatrick     }
49609467b48Spatrick   }
49709467b48Spatrick 
49809467b48Spatrick   std::vector<WeakTrackingVH> Postorder; // The resultant postorder.
49909467b48Spatrick   while (!PostorderStack.empty()) {
500097a140dSpatrick     Value *TopVal = PostorderStack.back().getPointer();
50109467b48Spatrick     // If the operands of the expression on the top are already explored,
50209467b48Spatrick     // adds that expression to the resultant postorder.
503097a140dSpatrick     if (PostorderStack.back().getInt()) {
50409467b48Spatrick       if (TopVal->getType()->getPointerAddressSpace() == FlatAddrSpace)
50509467b48Spatrick         Postorder.push_back(TopVal);
50609467b48Spatrick       PostorderStack.pop_back();
50709467b48Spatrick       continue;
50809467b48Spatrick     }
50909467b48Spatrick     // Otherwise, adds its operands to the stack and explores them.
510097a140dSpatrick     PostorderStack.back().setInt(true);
51173471bf0Spatrick     // Skip values with an assumed address space.
51273471bf0Spatrick     if (TTI->getAssumedAddrSpace(TopVal) == UninitializedAddressSpace) {
513097a140dSpatrick       for (Value *PtrOperand : getPointerOperands(*TopVal, *DL, TTI)) {
51409467b48Spatrick         appendsFlatAddressExpressionToPostorderStack(PtrOperand, PostorderStack,
51509467b48Spatrick                                                      Visited);
51609467b48Spatrick       }
51709467b48Spatrick     }
51873471bf0Spatrick   }
51909467b48Spatrick   return Postorder;
52009467b48Spatrick }
52109467b48Spatrick 
52209467b48Spatrick // A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
52309467b48Spatrick // of OperandUse.get() in the new address space. If the clone is not ready yet,
52409467b48Spatrick // returns an undef in the new address space as a placeholder.
operandWithNewAddressSpaceOrCreateUndef(const Use & OperandUse,unsigned NewAddrSpace,const ValueToValueMapTy & ValueWithNewAddrSpace,const PredicatedAddrSpaceMapTy & PredicatedAS,SmallVectorImpl<const Use * > * UndefUsesToFix)52509467b48Spatrick static Value *operandWithNewAddressSpaceOrCreateUndef(
52609467b48Spatrick     const Use &OperandUse, unsigned NewAddrSpace,
52709467b48Spatrick     const ValueToValueMapTy &ValueWithNewAddrSpace,
528*d415bd75Srobert     const PredicatedAddrSpaceMapTy &PredicatedAS,
52909467b48Spatrick     SmallVectorImpl<const Use *> *UndefUsesToFix) {
53009467b48Spatrick   Value *Operand = OperandUse.get();
53109467b48Spatrick 
53273471bf0Spatrick   Type *NewPtrTy = PointerType::getWithSamePointeeType(
53373471bf0Spatrick       cast<PointerType>(Operand->getType()), NewAddrSpace);
53409467b48Spatrick 
53509467b48Spatrick   if (Constant *C = dyn_cast<Constant>(Operand))
53609467b48Spatrick     return ConstantExpr::getAddrSpaceCast(C, NewPtrTy);
53709467b48Spatrick 
53809467b48Spatrick   if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
53909467b48Spatrick     return NewOperand;
54009467b48Spatrick 
541*d415bd75Srobert   Instruction *Inst = cast<Instruction>(OperandUse.getUser());
542*d415bd75Srobert   auto I = PredicatedAS.find(std::make_pair(Inst, Operand));
543*d415bd75Srobert   if (I != PredicatedAS.end()) {
544*d415bd75Srobert     // Insert an addrspacecast on that operand before the user.
545*d415bd75Srobert     unsigned NewAS = I->second;
546*d415bd75Srobert     Type *NewPtrTy = PointerType::getWithSamePointeeType(
547*d415bd75Srobert         cast<PointerType>(Operand->getType()), NewAS);
548*d415bd75Srobert     auto *NewI = new AddrSpaceCastInst(Operand, NewPtrTy);
549*d415bd75Srobert     NewI->insertBefore(Inst);
550*d415bd75Srobert     NewI->setDebugLoc(Inst->getDebugLoc());
551*d415bd75Srobert     return NewI;
552*d415bd75Srobert   }
553*d415bd75Srobert 
55409467b48Spatrick   UndefUsesToFix->push_back(&OperandUse);
55509467b48Spatrick   return UndefValue::get(NewPtrTy);
55609467b48Spatrick }
55709467b48Spatrick 
55809467b48Spatrick // Returns a clone of `I` with its operands converted to those specified in
55909467b48Spatrick // ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
56009467b48Spatrick // operand whose address space needs to be modified might not exist in
56109467b48Spatrick // ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
56209467b48Spatrick // adds that operand use to UndefUsesToFix so that caller can fix them later.
56309467b48Spatrick //
56409467b48Spatrick // Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
56509467b48Spatrick // from a pointer whose type already matches. Therefore, this function returns a
56609467b48Spatrick // Value* instead of an Instruction*.
567097a140dSpatrick //
568097a140dSpatrick // This may also return nullptr in the case the instruction could not be
569097a140dSpatrick // rewritten.
cloneInstructionWithNewAddressSpace(Instruction * I,unsigned NewAddrSpace,const ValueToValueMapTy & ValueWithNewAddrSpace,const PredicatedAddrSpaceMapTy & PredicatedAS,SmallVectorImpl<const Use * > * UndefUsesToFix) const57073471bf0Spatrick Value *InferAddressSpacesImpl::cloneInstructionWithNewAddressSpace(
57109467b48Spatrick     Instruction *I, unsigned NewAddrSpace,
57209467b48Spatrick     const ValueToValueMapTy &ValueWithNewAddrSpace,
573*d415bd75Srobert     const PredicatedAddrSpaceMapTy &PredicatedAS,
574097a140dSpatrick     SmallVectorImpl<const Use *> *UndefUsesToFix) const {
57573471bf0Spatrick   Type *NewPtrType = PointerType::getWithSamePointeeType(
57673471bf0Spatrick       cast<PointerType>(I->getType()), NewAddrSpace);
57709467b48Spatrick 
57809467b48Spatrick   if (I->getOpcode() == Instruction::AddrSpaceCast) {
57909467b48Spatrick     Value *Src = I->getOperand(0);
58009467b48Spatrick     // Because `I` is flat, the source address space must be specific.
58109467b48Spatrick     // Therefore, the inferred address space must be the source space, according
58209467b48Spatrick     // to our algorithm.
58309467b48Spatrick     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
58409467b48Spatrick     if (Src->getType() != NewPtrType)
58509467b48Spatrick       return new BitCastInst(Src, NewPtrType);
58609467b48Spatrick     return Src;
58709467b48Spatrick   }
58809467b48Spatrick 
589097a140dSpatrick   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
590097a140dSpatrick     // Technically the intrinsic ID is a pointer typed argument, so specially
591097a140dSpatrick     // handle calls early.
592097a140dSpatrick     assert(II->getIntrinsicID() == Intrinsic::ptrmask);
593097a140dSpatrick     Value *NewPtr = operandWithNewAddressSpaceOrCreateUndef(
594097a140dSpatrick         II->getArgOperandUse(0), NewAddrSpace, ValueWithNewAddrSpace,
595*d415bd75Srobert         PredicatedAS, UndefUsesToFix);
596097a140dSpatrick     Value *Rewrite =
597097a140dSpatrick         TTI->rewriteIntrinsicWithAddressSpace(II, II->getArgOperand(0), NewPtr);
598097a140dSpatrick     if (Rewrite) {
599097a140dSpatrick       assert(Rewrite != II && "cannot modify this pointer operation in place");
600097a140dSpatrick       return Rewrite;
601097a140dSpatrick     }
602097a140dSpatrick 
603097a140dSpatrick     return nullptr;
604097a140dSpatrick   }
605097a140dSpatrick 
60673471bf0Spatrick   unsigned AS = TTI->getAssumedAddrSpace(I);
60773471bf0Spatrick   if (AS != UninitializedAddressSpace) {
60873471bf0Spatrick     // For the assumed address space, insert an `addrspacecast` to make that
60973471bf0Spatrick     // explicit.
61073471bf0Spatrick     Type *NewPtrTy = PointerType::getWithSamePointeeType(
61173471bf0Spatrick         cast<PointerType>(I->getType()), AS);
61273471bf0Spatrick     auto *NewI = new AddrSpaceCastInst(I, NewPtrTy);
61373471bf0Spatrick     NewI->insertAfter(I);
61473471bf0Spatrick     return NewI;
61573471bf0Spatrick   }
61673471bf0Spatrick 
61709467b48Spatrick   // Computes the converted pointer operands.
61809467b48Spatrick   SmallVector<Value *, 4> NewPointerOperands;
61909467b48Spatrick   for (const Use &OperandUse : I->operands()) {
62009467b48Spatrick     if (!OperandUse.get()->getType()->isPointerTy())
62109467b48Spatrick       NewPointerOperands.push_back(nullptr);
62209467b48Spatrick     else
62309467b48Spatrick       NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
624*d415bd75Srobert           OperandUse, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS,
625*d415bd75Srobert           UndefUsesToFix));
62609467b48Spatrick   }
62709467b48Spatrick 
62809467b48Spatrick   switch (I->getOpcode()) {
62909467b48Spatrick   case Instruction::BitCast:
63009467b48Spatrick     return new BitCastInst(NewPointerOperands[0], NewPtrType);
63109467b48Spatrick   case Instruction::PHI: {
63209467b48Spatrick     assert(I->getType()->isPointerTy());
63309467b48Spatrick     PHINode *PHI = cast<PHINode>(I);
63409467b48Spatrick     PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
63509467b48Spatrick     for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
63609467b48Spatrick       unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
63709467b48Spatrick       NewPHI->addIncoming(NewPointerOperands[OperandNo],
63809467b48Spatrick                           PHI->getIncomingBlock(Index));
63909467b48Spatrick     }
64009467b48Spatrick     return NewPHI;
64109467b48Spatrick   }
64209467b48Spatrick   case Instruction::GetElementPtr: {
64309467b48Spatrick     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
64409467b48Spatrick     GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
64509467b48Spatrick         GEP->getSourceElementType(), NewPointerOperands[0],
64673471bf0Spatrick         SmallVector<Value *, 4>(GEP->indices()));
64709467b48Spatrick     NewGEP->setIsInBounds(GEP->isInBounds());
64809467b48Spatrick     return NewGEP;
64909467b48Spatrick   }
65009467b48Spatrick   case Instruction::Select:
65109467b48Spatrick     assert(I->getType()->isPointerTy());
65209467b48Spatrick     return SelectInst::Create(I->getOperand(0), NewPointerOperands[1],
65309467b48Spatrick                               NewPointerOperands[2], "", nullptr, I);
654097a140dSpatrick   case Instruction::IntToPtr: {
655097a140dSpatrick     assert(isNoopPtrIntCastPair(cast<Operator>(I), *DL, TTI));
656097a140dSpatrick     Value *Src = cast<Operator>(I->getOperand(0))->getOperand(0);
657*d415bd75Srobert     if (Src->getType() == NewPtrType)
658097a140dSpatrick       return Src;
659*d415bd75Srobert 
660*d415bd75Srobert     // If we had a no-op inttoptr/ptrtoint pair, we may still have inferred a
661*d415bd75Srobert     // source address space from a generic pointer source need to insert a cast
662*d415bd75Srobert     // back.
663*d415bd75Srobert     return CastInst::CreatePointerBitCastOrAddrSpaceCast(Src, NewPtrType);
664097a140dSpatrick   }
66509467b48Spatrick   default:
66609467b48Spatrick     llvm_unreachable("Unexpected opcode");
66709467b48Spatrick   }
66809467b48Spatrick }
66909467b48Spatrick 
67009467b48Spatrick // Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
67109467b48Spatrick // constant expression `CE` with its operands replaced as specified in
67209467b48Spatrick // ValueWithNewAddrSpace.
cloneConstantExprWithNewAddressSpace(ConstantExpr * CE,unsigned NewAddrSpace,const ValueToValueMapTy & ValueWithNewAddrSpace,const DataLayout * DL,const TargetTransformInfo * TTI)67309467b48Spatrick static Value *cloneConstantExprWithNewAddressSpace(
67409467b48Spatrick     ConstantExpr *CE, unsigned NewAddrSpace,
675097a140dSpatrick     const ValueToValueMapTy &ValueWithNewAddrSpace, const DataLayout *DL,
676097a140dSpatrick     const TargetTransformInfo *TTI) {
67773471bf0Spatrick   Type *TargetType = CE->getType()->isPointerTy()
67873471bf0Spatrick                          ? PointerType::getWithSamePointeeType(
67973471bf0Spatrick                                cast<PointerType>(CE->getType()), NewAddrSpace)
68073471bf0Spatrick                          : CE->getType();
68109467b48Spatrick 
68209467b48Spatrick   if (CE->getOpcode() == Instruction::AddrSpaceCast) {
68309467b48Spatrick     // Because CE is flat, the source address space must be specific.
68409467b48Spatrick     // Therefore, the inferred address space must be the source space according
68509467b48Spatrick     // to our algorithm.
68609467b48Spatrick     assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
68709467b48Spatrick            NewAddrSpace);
68809467b48Spatrick     return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
68909467b48Spatrick   }
69009467b48Spatrick 
69109467b48Spatrick   if (CE->getOpcode() == Instruction::BitCast) {
69209467b48Spatrick     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(CE->getOperand(0)))
69309467b48Spatrick       return ConstantExpr::getBitCast(cast<Constant>(NewOperand), TargetType);
69409467b48Spatrick     return ConstantExpr::getAddrSpaceCast(CE, TargetType);
69509467b48Spatrick   }
69609467b48Spatrick 
69709467b48Spatrick   if (CE->getOpcode() == Instruction::Select) {
69809467b48Spatrick     Constant *Src0 = CE->getOperand(1);
69909467b48Spatrick     Constant *Src1 = CE->getOperand(2);
70009467b48Spatrick     if (Src0->getType()->getPointerAddressSpace() ==
70109467b48Spatrick         Src1->getType()->getPointerAddressSpace()) {
70209467b48Spatrick 
70309467b48Spatrick       return ConstantExpr::getSelect(
70409467b48Spatrick           CE->getOperand(0), ConstantExpr::getAddrSpaceCast(Src0, TargetType),
70509467b48Spatrick           ConstantExpr::getAddrSpaceCast(Src1, TargetType));
70609467b48Spatrick     }
70709467b48Spatrick   }
70809467b48Spatrick 
709097a140dSpatrick   if (CE->getOpcode() == Instruction::IntToPtr) {
710097a140dSpatrick     assert(isNoopPtrIntCastPair(cast<Operator>(CE), *DL, TTI));
711097a140dSpatrick     Constant *Src = cast<ConstantExpr>(CE->getOperand(0))->getOperand(0);
712097a140dSpatrick     assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
713097a140dSpatrick     return ConstantExpr::getBitCast(Src, TargetType);
714097a140dSpatrick   }
715097a140dSpatrick 
71609467b48Spatrick   // Computes the operands of the new constant expression.
71709467b48Spatrick   bool IsNew = false;
71809467b48Spatrick   SmallVector<Constant *, 4> NewOperands;
71909467b48Spatrick   for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
72009467b48Spatrick     Constant *Operand = CE->getOperand(Index);
72109467b48Spatrick     // If the address space of `Operand` needs to be modified, the new operand
72209467b48Spatrick     // with the new address space should already be in ValueWithNewAddrSpace
72309467b48Spatrick     // because (1) the constant expressions we consider (i.e. addrspacecast,
72409467b48Spatrick     // bitcast, and getelementptr) do not incur cycles in the data flow graph
72509467b48Spatrick     // and (2) this function is called on constant expressions in postorder.
72609467b48Spatrick     if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
72709467b48Spatrick       IsNew = true;
72809467b48Spatrick       NewOperands.push_back(cast<Constant>(NewOperand));
72909467b48Spatrick       continue;
73009467b48Spatrick     }
731*d415bd75Srobert     if (auto *CExpr = dyn_cast<ConstantExpr>(Operand))
73209467b48Spatrick       if (Value *NewOperand = cloneConstantExprWithNewAddressSpace(
733097a140dSpatrick               CExpr, NewAddrSpace, ValueWithNewAddrSpace, DL, TTI)) {
73409467b48Spatrick         IsNew = true;
73509467b48Spatrick         NewOperands.push_back(cast<Constant>(NewOperand));
73609467b48Spatrick         continue;
73709467b48Spatrick       }
73809467b48Spatrick     // Otherwise, reuses the old operand.
73909467b48Spatrick     NewOperands.push_back(Operand);
74009467b48Spatrick   }
74109467b48Spatrick 
74209467b48Spatrick   // If !IsNew, we will replace the Value with itself. However, replaced values
743*d415bd75Srobert   // are assumed to wrapped in an addrspacecast cast later so drop it now.
74409467b48Spatrick   if (!IsNew)
74509467b48Spatrick     return nullptr;
74609467b48Spatrick 
74709467b48Spatrick   if (CE->getOpcode() == Instruction::GetElementPtr) {
74809467b48Spatrick     // Needs to specify the source type while constructing a getelementptr
74909467b48Spatrick     // constant expression.
750*d415bd75Srobert     return CE->getWithOperands(NewOperands, TargetType, /*OnlyIfReduced=*/false,
751*d415bd75Srobert                                cast<GEPOperator>(CE)->getSourceElementType());
75209467b48Spatrick   }
75309467b48Spatrick 
75409467b48Spatrick   return CE->getWithOperands(NewOperands, TargetType);
75509467b48Spatrick }
75609467b48Spatrick 
75709467b48Spatrick // Returns a clone of the value `V`, with its operands replaced as specified in
75809467b48Spatrick // ValueWithNewAddrSpace. This function is called on every flat address
75909467b48Spatrick // expression whose address space needs to be modified, in postorder.
76009467b48Spatrick //
76109467b48Spatrick // See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
cloneValueWithNewAddressSpace(Value * V,unsigned NewAddrSpace,const ValueToValueMapTy & ValueWithNewAddrSpace,const PredicatedAddrSpaceMapTy & PredicatedAS,SmallVectorImpl<const Use * > * UndefUsesToFix) const76273471bf0Spatrick Value *InferAddressSpacesImpl::cloneValueWithNewAddressSpace(
76309467b48Spatrick     Value *V, unsigned NewAddrSpace,
76409467b48Spatrick     const ValueToValueMapTy &ValueWithNewAddrSpace,
765*d415bd75Srobert     const PredicatedAddrSpaceMapTy &PredicatedAS,
76609467b48Spatrick     SmallVectorImpl<const Use *> *UndefUsesToFix) const {
76709467b48Spatrick   // All values in Postorder are flat address expressions.
76873471bf0Spatrick   assert(V->getType()->getPointerAddressSpace() == FlatAddrSpace &&
76973471bf0Spatrick          isAddressExpression(*V, *DL, TTI));
77009467b48Spatrick 
77109467b48Spatrick   if (Instruction *I = dyn_cast<Instruction>(V)) {
77209467b48Spatrick     Value *NewV = cloneInstructionWithNewAddressSpace(
773*d415bd75Srobert         I, NewAddrSpace, ValueWithNewAddrSpace, PredicatedAS, UndefUsesToFix);
774097a140dSpatrick     if (Instruction *NewI = dyn_cast_or_null<Instruction>(NewV)) {
77509467b48Spatrick       if (NewI->getParent() == nullptr) {
77609467b48Spatrick         NewI->insertBefore(I);
77709467b48Spatrick         NewI->takeName(I);
778*d415bd75Srobert         NewI->setDebugLoc(I->getDebugLoc());
77909467b48Spatrick       }
78009467b48Spatrick     }
78109467b48Spatrick     return NewV;
78209467b48Spatrick   }
78309467b48Spatrick 
78409467b48Spatrick   return cloneConstantExprWithNewAddressSpace(
785097a140dSpatrick       cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace, DL, TTI);
78609467b48Spatrick }
78709467b48Spatrick 
78809467b48Spatrick // Defines the join operation on the address space lattice (see the file header
78909467b48Spatrick // comments).
joinAddressSpaces(unsigned AS1,unsigned AS2) const79073471bf0Spatrick unsigned InferAddressSpacesImpl::joinAddressSpaces(unsigned AS1,
79109467b48Spatrick                                                    unsigned AS2) const {
79209467b48Spatrick   if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
79309467b48Spatrick     return FlatAddrSpace;
79409467b48Spatrick 
79509467b48Spatrick   if (AS1 == UninitializedAddressSpace)
79609467b48Spatrick     return AS2;
79709467b48Spatrick   if (AS2 == UninitializedAddressSpace)
79809467b48Spatrick     return AS1;
79909467b48Spatrick 
80009467b48Spatrick   // The join of two different specific address spaces is flat.
80109467b48Spatrick   return (AS1 == AS2) ? AS1 : FlatAddrSpace;
80209467b48Spatrick }
80309467b48Spatrick 
run(Function & F)80473471bf0Spatrick bool InferAddressSpacesImpl::run(Function &F) {
805097a140dSpatrick   DL = &F.getParent()->getDataLayout();
806097a140dSpatrick 
807097a140dSpatrick   if (AssumeDefaultIsFlatAddressSpace)
808097a140dSpatrick     FlatAddrSpace = 0;
80909467b48Spatrick 
81009467b48Spatrick   if (FlatAddrSpace == UninitializedAddressSpace) {
81109467b48Spatrick     FlatAddrSpace = TTI->getFlatAddressSpace();
81209467b48Spatrick     if (FlatAddrSpace == UninitializedAddressSpace)
81309467b48Spatrick       return false;
81409467b48Spatrick   }
81509467b48Spatrick 
81609467b48Spatrick   // Collects all flat address expressions in postorder.
81709467b48Spatrick   std::vector<WeakTrackingVH> Postorder = collectFlatAddressExpressions(F);
81809467b48Spatrick 
81909467b48Spatrick   // Runs a data-flow analysis to refine the address spaces of every expression
82009467b48Spatrick   // in Postorder.
82109467b48Spatrick   ValueToAddrSpaceMapTy InferredAddrSpace;
822*d415bd75Srobert   PredicatedAddrSpaceMapTy PredicatedAS;
823*d415bd75Srobert   inferAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS);
82409467b48Spatrick 
82509467b48Spatrick   // Changes the address spaces of the flat address expressions who are inferred
82609467b48Spatrick   // to point to a specific address space.
827*d415bd75Srobert   return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, PredicatedAS,
828*d415bd75Srobert                                      &F);
82909467b48Spatrick }
83009467b48Spatrick 
83109467b48Spatrick // Constants need to be tracked through RAUW to handle cases with nested
83209467b48Spatrick // constant expressions, so wrap values in WeakTrackingVH.
inferAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,ValueToAddrSpaceMapTy & InferredAddrSpace,PredicatedAddrSpaceMapTy & PredicatedAS) const83373471bf0Spatrick void InferAddressSpacesImpl::inferAddressSpaces(
83409467b48Spatrick     ArrayRef<WeakTrackingVH> Postorder,
835*d415bd75Srobert     ValueToAddrSpaceMapTy &InferredAddrSpace,
836*d415bd75Srobert     PredicatedAddrSpaceMapTy &PredicatedAS) const {
83709467b48Spatrick   SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
83809467b48Spatrick   // Initially, all expressions are in the uninitialized address space.
83909467b48Spatrick   for (Value *V : Postorder)
840*d415bd75Srobert     InferredAddrSpace[V] = UninitializedAddressSpace;
84109467b48Spatrick 
84209467b48Spatrick   while (!Worklist.empty()) {
84309467b48Spatrick     Value *V = Worklist.pop_back_val();
84409467b48Spatrick 
845*d415bd75Srobert     // Try to update the address space of the stack top according to the
84609467b48Spatrick     // address spaces of its operands.
847*d415bd75Srobert     if (!updateAddressSpace(*V, InferredAddrSpace, PredicatedAS))
84809467b48Spatrick       continue;
84909467b48Spatrick 
85009467b48Spatrick     for (Value *User : V->users()) {
85109467b48Spatrick       // Skip if User is already in the worklist.
85209467b48Spatrick       if (Worklist.count(User))
85309467b48Spatrick         continue;
85409467b48Spatrick 
855*d415bd75Srobert       auto Pos = InferredAddrSpace.find(User);
85609467b48Spatrick       // Our algorithm only updates the address spaces of flat address
85709467b48Spatrick       // expressions, which are those in InferredAddrSpace.
858*d415bd75Srobert       if (Pos == InferredAddrSpace.end())
85909467b48Spatrick         continue;
86009467b48Spatrick 
86109467b48Spatrick       // Function updateAddressSpace moves the address space down a lattice
86209467b48Spatrick       // path. Therefore, nothing to do if User is already inferred as flat (the
86309467b48Spatrick       // bottom element in the lattice).
86409467b48Spatrick       if (Pos->second == FlatAddrSpace)
86509467b48Spatrick         continue;
86609467b48Spatrick 
86709467b48Spatrick       Worklist.insert(User);
86809467b48Spatrick     }
86909467b48Spatrick   }
87009467b48Spatrick }
87109467b48Spatrick 
getPredicatedAddrSpace(const Value & V,Value * Opnd) const872*d415bd75Srobert unsigned InferAddressSpacesImpl::getPredicatedAddrSpace(const Value &V,
873*d415bd75Srobert                                                         Value *Opnd) const {
874*d415bd75Srobert   const Instruction *I = dyn_cast<Instruction>(&V);
875*d415bd75Srobert   if (!I)
876*d415bd75Srobert     return UninitializedAddressSpace;
877*d415bd75Srobert 
878*d415bd75Srobert   Opnd = Opnd->stripInBoundsOffsets();
879*d415bd75Srobert   for (auto &AssumeVH : AC.assumptionsFor(Opnd)) {
880*d415bd75Srobert     if (!AssumeVH)
881*d415bd75Srobert       continue;
882*d415bd75Srobert     CallInst *CI = cast<CallInst>(AssumeVH);
883*d415bd75Srobert     if (!isValidAssumeForContext(CI, I, DT))
884*d415bd75Srobert       continue;
885*d415bd75Srobert 
886*d415bd75Srobert     const Value *Ptr;
887*d415bd75Srobert     unsigned AS;
888*d415bd75Srobert     std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(CI->getArgOperand(0));
889*d415bd75Srobert     if (Ptr)
890*d415bd75Srobert       return AS;
891*d415bd75Srobert   }
892*d415bd75Srobert 
893*d415bd75Srobert   return UninitializedAddressSpace;
894*d415bd75Srobert }
895*d415bd75Srobert 
updateAddressSpace(const Value & V,ValueToAddrSpaceMapTy & InferredAddrSpace,PredicatedAddrSpaceMapTy & PredicatedAS) const896*d415bd75Srobert bool InferAddressSpacesImpl::updateAddressSpace(
897*d415bd75Srobert     const Value &V, ValueToAddrSpaceMapTy &InferredAddrSpace,
898*d415bd75Srobert     PredicatedAddrSpaceMapTy &PredicatedAS) const {
89909467b48Spatrick   assert(InferredAddrSpace.count(&V));
90009467b48Spatrick 
901*d415bd75Srobert   LLVM_DEBUG(dbgs() << "Updating the address space of\n  " << V << '\n');
902*d415bd75Srobert 
90309467b48Spatrick   // The new inferred address space equals the join of the address spaces
90409467b48Spatrick   // of all its pointer operands.
90509467b48Spatrick   unsigned NewAS = UninitializedAddressSpace;
90609467b48Spatrick 
90709467b48Spatrick   const Operator &Op = cast<Operator>(V);
90809467b48Spatrick   if (Op.getOpcode() == Instruction::Select) {
90909467b48Spatrick     Value *Src0 = Op.getOperand(1);
91009467b48Spatrick     Value *Src1 = Op.getOperand(2);
91109467b48Spatrick 
91209467b48Spatrick     auto I = InferredAddrSpace.find(Src0);
91309467b48Spatrick     unsigned Src0AS = (I != InferredAddrSpace.end()) ?
91409467b48Spatrick       I->second : Src0->getType()->getPointerAddressSpace();
91509467b48Spatrick 
91609467b48Spatrick     auto J = InferredAddrSpace.find(Src1);
91709467b48Spatrick     unsigned Src1AS = (J != InferredAddrSpace.end()) ?
91809467b48Spatrick       J->second : Src1->getType()->getPointerAddressSpace();
91909467b48Spatrick 
92009467b48Spatrick     auto *C0 = dyn_cast<Constant>(Src0);
92109467b48Spatrick     auto *C1 = dyn_cast<Constant>(Src1);
92209467b48Spatrick 
92309467b48Spatrick     // If one of the inputs is a constant, we may be able to do a constant
92409467b48Spatrick     // addrspacecast of it. Defer inferring the address space until the input
92509467b48Spatrick     // address space is known.
92609467b48Spatrick     if ((C1 && Src0AS == UninitializedAddressSpace) ||
92709467b48Spatrick         (C0 && Src1AS == UninitializedAddressSpace))
928*d415bd75Srobert       return false;
92909467b48Spatrick 
93009467b48Spatrick     if (C0 && isSafeToCastConstAddrSpace(C0, Src1AS))
93109467b48Spatrick       NewAS = Src1AS;
93209467b48Spatrick     else if (C1 && isSafeToCastConstAddrSpace(C1, Src0AS))
93309467b48Spatrick       NewAS = Src0AS;
93409467b48Spatrick     else
93509467b48Spatrick       NewAS = joinAddressSpaces(Src0AS, Src1AS);
93609467b48Spatrick   } else {
93773471bf0Spatrick     unsigned AS = TTI->getAssumedAddrSpace(&V);
93873471bf0Spatrick     if (AS != UninitializedAddressSpace) {
93973471bf0Spatrick       // Use the assumed address space directly.
94073471bf0Spatrick       NewAS = AS;
94173471bf0Spatrick     } else {
94273471bf0Spatrick       // Otherwise, infer the address space from its pointer operands.
943097a140dSpatrick       for (Value *PtrOperand : getPointerOperands(V, *DL, TTI)) {
94409467b48Spatrick         auto I = InferredAddrSpace.find(PtrOperand);
945*d415bd75Srobert         unsigned OperandAS;
946*d415bd75Srobert         if (I == InferredAddrSpace.end()) {
947*d415bd75Srobert           OperandAS = PtrOperand->getType()->getPointerAddressSpace();
948*d415bd75Srobert           if (OperandAS == FlatAddrSpace) {
949*d415bd75Srobert             // Check AC for assumption dominating V.
950*d415bd75Srobert             unsigned AS = getPredicatedAddrSpace(V, PtrOperand);
951*d415bd75Srobert             if (AS != UninitializedAddressSpace) {
952*d415bd75Srobert               LLVM_DEBUG(dbgs()
953*d415bd75Srobert                          << "  deduce operand AS from the predicate addrspace "
954*d415bd75Srobert                          << AS << '\n');
955*d415bd75Srobert               OperandAS = AS;
956*d415bd75Srobert               // Record this use with the predicated AS.
957*d415bd75Srobert               PredicatedAS[std::make_pair(&V, PtrOperand)] = OperandAS;
958*d415bd75Srobert             }
959*d415bd75Srobert           }
960*d415bd75Srobert         } else
961*d415bd75Srobert           OperandAS = I->second;
96209467b48Spatrick 
96309467b48Spatrick         // join(flat, *) = flat. So we can break if NewAS is already flat.
96409467b48Spatrick         NewAS = joinAddressSpaces(NewAS, OperandAS);
96509467b48Spatrick         if (NewAS == FlatAddrSpace)
96609467b48Spatrick           break;
96709467b48Spatrick       }
96809467b48Spatrick     }
96973471bf0Spatrick   }
97009467b48Spatrick 
97109467b48Spatrick   unsigned OldAS = InferredAddrSpace.lookup(&V);
97209467b48Spatrick   assert(OldAS != FlatAddrSpace);
97309467b48Spatrick   if (OldAS == NewAS)
974*d415bd75Srobert     return false;
975*d415bd75Srobert 
976*d415bd75Srobert   // If any updates are made, grabs its users to the worklist because
977*d415bd75Srobert   // their address spaces can also be possibly updated.
978*d415bd75Srobert   LLVM_DEBUG(dbgs() << "  to " << NewAS << '\n');
979*d415bd75Srobert   InferredAddrSpace[&V] = NewAS;
980*d415bd75Srobert   return true;
98109467b48Spatrick }
98209467b48Spatrick 
98309467b48Spatrick /// \p returns true if \p U is the pointer operand of a memory instruction with
98409467b48Spatrick /// a single pointer operand that can have its address space changed by simply
98509467b48Spatrick /// mutating the use to a new value. If the memory instruction is volatile,
98609467b48Spatrick /// return true only if the target allows the memory instruction to be volatile
98709467b48Spatrick /// in the new address space.
isSimplePointerUseValidToReplace(const TargetTransformInfo & TTI,Use & U,unsigned AddrSpace)98809467b48Spatrick static bool isSimplePointerUseValidToReplace(const TargetTransformInfo &TTI,
98909467b48Spatrick                                              Use &U, unsigned AddrSpace) {
99009467b48Spatrick   User *Inst = U.getUser();
99109467b48Spatrick   unsigned OpNo = U.getOperandNo();
99209467b48Spatrick   bool VolatileIsAllowed = false;
99309467b48Spatrick   if (auto *I = dyn_cast<Instruction>(Inst))
99409467b48Spatrick     VolatileIsAllowed = TTI.hasVolatileVariant(I, AddrSpace);
99509467b48Spatrick 
99609467b48Spatrick   if (auto *LI = dyn_cast<LoadInst>(Inst))
99709467b48Spatrick     return OpNo == LoadInst::getPointerOperandIndex() &&
99809467b48Spatrick            (VolatileIsAllowed || !LI->isVolatile());
99909467b48Spatrick 
100009467b48Spatrick   if (auto *SI = dyn_cast<StoreInst>(Inst))
100109467b48Spatrick     return OpNo == StoreInst::getPointerOperandIndex() &&
100209467b48Spatrick            (VolatileIsAllowed || !SI->isVolatile());
100309467b48Spatrick 
100409467b48Spatrick   if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
100509467b48Spatrick     return OpNo == AtomicRMWInst::getPointerOperandIndex() &&
100609467b48Spatrick            (VolatileIsAllowed || !RMW->isVolatile());
100709467b48Spatrick 
100809467b48Spatrick   if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst))
100909467b48Spatrick     return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
101009467b48Spatrick            (VolatileIsAllowed || !CmpX->isVolatile());
101109467b48Spatrick 
101209467b48Spatrick   return false;
101309467b48Spatrick }
101409467b48Spatrick 
101509467b48Spatrick /// Update memory intrinsic uses that require more complex processing than
1016*d415bd75Srobert /// simple memory instructions. These require re-mangling and may have multiple
101709467b48Spatrick /// pointer operands.
handleMemIntrinsicPtrUse(MemIntrinsic * MI,Value * OldV,Value * NewV)101809467b48Spatrick static bool handleMemIntrinsicPtrUse(MemIntrinsic *MI, Value *OldV,
101909467b48Spatrick                                      Value *NewV) {
102009467b48Spatrick   IRBuilder<> B(MI);
102109467b48Spatrick   MDNode *TBAA = MI->getMetadata(LLVMContext::MD_tbaa);
102209467b48Spatrick   MDNode *ScopeMD = MI->getMetadata(LLVMContext::MD_alias_scope);
102309467b48Spatrick   MDNode *NoAliasMD = MI->getMetadata(LLVMContext::MD_noalias);
102409467b48Spatrick 
102509467b48Spatrick   if (auto *MSI = dyn_cast<MemSetInst>(MI)) {
1026*d415bd75Srobert     B.CreateMemSet(NewV, MSI->getValue(), MSI->getLength(), MSI->getDestAlign(),
102709467b48Spatrick                    false, // isVolatile
102809467b48Spatrick                    TBAA, ScopeMD, NoAliasMD);
102909467b48Spatrick   } else if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
103009467b48Spatrick     Value *Src = MTI->getRawSource();
103109467b48Spatrick     Value *Dest = MTI->getRawDest();
103209467b48Spatrick 
103309467b48Spatrick     // Be careful in case this is a self-to-self copy.
103409467b48Spatrick     if (Src == OldV)
103509467b48Spatrick       Src = NewV;
103609467b48Spatrick 
103709467b48Spatrick     if (Dest == OldV)
103809467b48Spatrick       Dest = NewV;
103909467b48Spatrick 
104073471bf0Spatrick     if (isa<MemCpyInlineInst>(MTI)) {
104173471bf0Spatrick       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
104273471bf0Spatrick       B.CreateMemCpyInline(Dest, MTI->getDestAlign(), Src,
104373471bf0Spatrick                            MTI->getSourceAlign(), MTI->getLength(),
104473471bf0Spatrick                            false, // isVolatile
104573471bf0Spatrick                            TBAA, TBAAStruct, ScopeMD, NoAliasMD);
104673471bf0Spatrick     } else if (isa<MemCpyInst>(MTI)) {
104709467b48Spatrick       MDNode *TBAAStruct = MTI->getMetadata(LLVMContext::MD_tbaa_struct);
104809467b48Spatrick       B.CreateMemCpy(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
104909467b48Spatrick                      MTI->getLength(),
105009467b48Spatrick                      false, // isVolatile
105109467b48Spatrick                      TBAA, TBAAStruct, ScopeMD, NoAliasMD);
105209467b48Spatrick     } else {
105309467b48Spatrick       assert(isa<MemMoveInst>(MTI));
105409467b48Spatrick       B.CreateMemMove(Dest, MTI->getDestAlign(), Src, MTI->getSourceAlign(),
105509467b48Spatrick                       MTI->getLength(),
105609467b48Spatrick                       false, // isVolatile
105709467b48Spatrick                       TBAA, ScopeMD, NoAliasMD);
105809467b48Spatrick     }
105909467b48Spatrick   } else
106009467b48Spatrick     llvm_unreachable("unhandled MemIntrinsic");
106109467b48Spatrick 
106209467b48Spatrick   MI->eraseFromParent();
106309467b48Spatrick   return true;
106409467b48Spatrick }
106509467b48Spatrick 
106609467b48Spatrick // \p returns true if it is OK to change the address space of constant \p C with
106709467b48Spatrick // a ConstantExpr addrspacecast.
isSafeToCastConstAddrSpace(Constant * C,unsigned NewAS) const106873471bf0Spatrick bool InferAddressSpacesImpl::isSafeToCastConstAddrSpace(Constant *C,
106973471bf0Spatrick                                                         unsigned NewAS) const {
107009467b48Spatrick   assert(NewAS != UninitializedAddressSpace);
107109467b48Spatrick 
107209467b48Spatrick   unsigned SrcAS = C->getType()->getPointerAddressSpace();
107309467b48Spatrick   if (SrcAS == NewAS || isa<UndefValue>(C))
107409467b48Spatrick     return true;
107509467b48Spatrick 
107609467b48Spatrick   // Prevent illegal casts between different non-flat address spaces.
107709467b48Spatrick   if (SrcAS != FlatAddrSpace && NewAS != FlatAddrSpace)
107809467b48Spatrick     return false;
107909467b48Spatrick 
108009467b48Spatrick   if (isa<ConstantPointerNull>(C))
108109467b48Spatrick     return true;
108209467b48Spatrick 
108309467b48Spatrick   if (auto *Op = dyn_cast<Operator>(C)) {
108409467b48Spatrick     // If we already have a constant addrspacecast, it should be safe to cast it
108509467b48Spatrick     // off.
108609467b48Spatrick     if (Op->getOpcode() == Instruction::AddrSpaceCast)
108709467b48Spatrick       return isSafeToCastConstAddrSpace(cast<Constant>(Op->getOperand(0)), NewAS);
108809467b48Spatrick 
108909467b48Spatrick     if (Op->getOpcode() == Instruction::IntToPtr &&
109009467b48Spatrick         Op->getType()->getPointerAddressSpace() == FlatAddrSpace)
109109467b48Spatrick       return true;
109209467b48Spatrick   }
109309467b48Spatrick 
109409467b48Spatrick   return false;
109509467b48Spatrick }
109609467b48Spatrick 
skipToNextUser(Value::use_iterator I,Value::use_iterator End)109709467b48Spatrick static Value::use_iterator skipToNextUser(Value::use_iterator I,
109809467b48Spatrick                                           Value::use_iterator End) {
109909467b48Spatrick   User *CurUser = I->getUser();
110009467b48Spatrick   ++I;
110109467b48Spatrick 
110209467b48Spatrick   while (I != End && I->getUser() == CurUser)
110309467b48Spatrick     ++I;
110409467b48Spatrick 
110509467b48Spatrick   return I;
110609467b48Spatrick }
110709467b48Spatrick 
rewriteWithNewAddressSpaces(ArrayRef<WeakTrackingVH> Postorder,const ValueToAddrSpaceMapTy & InferredAddrSpace,const PredicatedAddrSpaceMapTy & PredicatedAS,Function * F) const110873471bf0Spatrick bool InferAddressSpacesImpl::rewriteWithNewAddressSpaces(
1109*d415bd75Srobert     ArrayRef<WeakTrackingVH> Postorder,
1110*d415bd75Srobert     const ValueToAddrSpaceMapTy &InferredAddrSpace,
1111*d415bd75Srobert     const PredicatedAddrSpaceMapTy &PredicatedAS, Function *F) const {
111209467b48Spatrick   // For each address expression to be modified, creates a clone of it with its
111309467b48Spatrick   // pointer operands converted to the new address space. Since the pointer
111409467b48Spatrick   // operands are converted, the clone is naturally in the new address space by
111509467b48Spatrick   // construction.
111609467b48Spatrick   ValueToValueMapTy ValueWithNewAddrSpace;
111709467b48Spatrick   SmallVector<const Use *, 32> UndefUsesToFix;
111809467b48Spatrick   for (Value* V : Postorder) {
111909467b48Spatrick     unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
112073471bf0Spatrick 
112173471bf0Spatrick     // In some degenerate cases (e.g. invalid IR in unreachable code), we may
112273471bf0Spatrick     // not even infer the value to have its original address space.
112373471bf0Spatrick     if (NewAddrSpace == UninitializedAddressSpace)
112473471bf0Spatrick       continue;
112573471bf0Spatrick 
112609467b48Spatrick     if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
1127*d415bd75Srobert       Value *New =
1128*d415bd75Srobert           cloneValueWithNewAddressSpace(V, NewAddrSpace, ValueWithNewAddrSpace,
1129*d415bd75Srobert                                         PredicatedAS, &UndefUsesToFix);
1130097a140dSpatrick       if (New)
1131097a140dSpatrick         ValueWithNewAddrSpace[V] = New;
113209467b48Spatrick     }
113309467b48Spatrick   }
113409467b48Spatrick 
113509467b48Spatrick   if (ValueWithNewAddrSpace.empty())
113609467b48Spatrick     return false;
113709467b48Spatrick 
113809467b48Spatrick   // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
113909467b48Spatrick   for (const Use *UndefUse : UndefUsesToFix) {
114009467b48Spatrick     User *V = UndefUse->getUser();
1141097a140dSpatrick     User *NewV = cast_or_null<User>(ValueWithNewAddrSpace.lookup(V));
1142097a140dSpatrick     if (!NewV)
1143097a140dSpatrick       continue;
1144097a140dSpatrick 
114509467b48Spatrick     unsigned OperandNo = UndefUse->getOperandNo();
114609467b48Spatrick     assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
114709467b48Spatrick     NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
114809467b48Spatrick   }
114909467b48Spatrick 
115009467b48Spatrick   SmallVector<Instruction *, 16> DeadInstructions;
115109467b48Spatrick 
115209467b48Spatrick   // Replaces the uses of the old address expressions with the new ones.
115309467b48Spatrick   for (const WeakTrackingVH &WVH : Postorder) {
115409467b48Spatrick     assert(WVH && "value was unexpectedly deleted");
115509467b48Spatrick     Value *V = WVH;
115609467b48Spatrick     Value *NewV = ValueWithNewAddrSpace.lookup(V);
115709467b48Spatrick     if (NewV == nullptr)
115809467b48Spatrick       continue;
115909467b48Spatrick 
116009467b48Spatrick     LLVM_DEBUG(dbgs() << "Replacing the uses of " << *V << "\n  with\n  "
116109467b48Spatrick                       << *NewV << '\n');
116209467b48Spatrick 
116309467b48Spatrick     if (Constant *C = dyn_cast<Constant>(V)) {
116409467b48Spatrick       Constant *Replace = ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
116509467b48Spatrick                                                          C->getType());
116609467b48Spatrick       if (C != Replace) {
116709467b48Spatrick         LLVM_DEBUG(dbgs() << "Inserting replacement const cast: " << Replace
116809467b48Spatrick                           << ": " << *Replace << '\n');
116909467b48Spatrick         C->replaceAllUsesWith(Replace);
117009467b48Spatrick         V = Replace;
117109467b48Spatrick       }
117209467b48Spatrick     }
117309467b48Spatrick 
117409467b48Spatrick     Value::use_iterator I, E, Next;
117509467b48Spatrick     for (I = V->use_begin(), E = V->use_end(); I != E; ) {
117609467b48Spatrick       Use &U = *I;
117709467b48Spatrick 
117809467b48Spatrick       // Some users may see the same pointer operand in multiple operands. Skip
117909467b48Spatrick       // to the next instruction.
118009467b48Spatrick       I = skipToNextUser(I, E);
118109467b48Spatrick 
118209467b48Spatrick       if (isSimplePointerUseValidToReplace(
1183*d415bd75Srobert               *TTI, U, V->getType()->getPointerAddressSpace())) {
118409467b48Spatrick         // If V is used as the pointer operand of a compatible memory operation,
118509467b48Spatrick         // sets the pointer operand to NewV. This replacement does not change
118609467b48Spatrick         // the element type, so the resultant load/store is still valid.
118709467b48Spatrick         U.set(NewV);
118809467b48Spatrick         continue;
118909467b48Spatrick       }
119009467b48Spatrick 
119109467b48Spatrick       User *CurUser = U.getUser();
119273471bf0Spatrick       // Skip if the current user is the new value itself.
119373471bf0Spatrick       if (CurUser == NewV)
119473471bf0Spatrick         continue;
119509467b48Spatrick       // Handle more complex cases like intrinsic that need to be remangled.
119609467b48Spatrick       if (auto *MI = dyn_cast<MemIntrinsic>(CurUser)) {
119709467b48Spatrick         if (!MI->isVolatile() && handleMemIntrinsicPtrUse(MI, V, NewV))
119809467b48Spatrick           continue;
119909467b48Spatrick       }
120009467b48Spatrick 
120109467b48Spatrick       if (auto *II = dyn_cast<IntrinsicInst>(CurUser)) {
120209467b48Spatrick         if (rewriteIntrinsicOperands(II, V, NewV))
120309467b48Spatrick           continue;
120409467b48Spatrick       }
120509467b48Spatrick 
120609467b48Spatrick       if (isa<Instruction>(CurUser)) {
120709467b48Spatrick         if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CurUser)) {
120809467b48Spatrick           // If we can infer that both pointers are in the same addrspace,
120909467b48Spatrick           // transform e.g.
121009467b48Spatrick           //   %cmp = icmp eq float* %p, %q
121109467b48Spatrick           // into
121209467b48Spatrick           //   %cmp = icmp eq float addrspace(3)* %new_p, %new_q
121309467b48Spatrick 
121409467b48Spatrick           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
121509467b48Spatrick           int SrcIdx = U.getOperandNo();
121609467b48Spatrick           int OtherIdx = (SrcIdx == 0) ? 1 : 0;
121709467b48Spatrick           Value *OtherSrc = Cmp->getOperand(OtherIdx);
121809467b48Spatrick 
121909467b48Spatrick           if (Value *OtherNewV = ValueWithNewAddrSpace.lookup(OtherSrc)) {
122009467b48Spatrick             if (OtherNewV->getType()->getPointerAddressSpace() == NewAS) {
122109467b48Spatrick               Cmp->setOperand(OtherIdx, OtherNewV);
122209467b48Spatrick               Cmp->setOperand(SrcIdx, NewV);
122309467b48Spatrick               continue;
122409467b48Spatrick             }
122509467b48Spatrick           }
122609467b48Spatrick 
122709467b48Spatrick           // Even if the type mismatches, we can cast the constant.
122809467b48Spatrick           if (auto *KOtherSrc = dyn_cast<Constant>(OtherSrc)) {
122909467b48Spatrick             if (isSafeToCastConstAddrSpace(KOtherSrc, NewAS)) {
123009467b48Spatrick               Cmp->setOperand(SrcIdx, NewV);
123109467b48Spatrick               Cmp->setOperand(OtherIdx,
123209467b48Spatrick                 ConstantExpr::getAddrSpaceCast(KOtherSrc, NewV->getType()));
123309467b48Spatrick               continue;
123409467b48Spatrick             }
123509467b48Spatrick           }
123609467b48Spatrick         }
123709467b48Spatrick 
123809467b48Spatrick         if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(CurUser)) {
123909467b48Spatrick           unsigned NewAS = NewV->getType()->getPointerAddressSpace();
124009467b48Spatrick           if (ASC->getDestAddressSpace() == NewAS) {
1241*d415bd75Srobert             if (!cast<PointerType>(ASC->getType())
1242*d415bd75Srobert                     ->hasSameElementTypeAs(
1243*d415bd75Srobert                         cast<PointerType>(NewV->getType()))) {
1244*d415bd75Srobert               BasicBlock::iterator InsertPos;
1245*d415bd75Srobert               if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1246*d415bd75Srobert                 InsertPos = std::next(NewVInst->getIterator());
1247*d415bd75Srobert               else if (Instruction *VInst = dyn_cast<Instruction>(V))
1248*d415bd75Srobert                 InsertPos = std::next(VInst->getIterator());
1249*d415bd75Srobert               else
1250*d415bd75Srobert                 InsertPos = ASC->getIterator();
1251*d415bd75Srobert 
125209467b48Spatrick               NewV = CastInst::Create(Instruction::BitCast, NewV,
1253*d415bd75Srobert                                       ASC->getType(), "", &*InsertPos);
125409467b48Spatrick             }
125509467b48Spatrick             ASC->replaceAllUsesWith(NewV);
125609467b48Spatrick             DeadInstructions.push_back(ASC);
125709467b48Spatrick             continue;
125809467b48Spatrick           }
125909467b48Spatrick         }
126009467b48Spatrick 
126109467b48Spatrick         // Otherwise, replaces the use with flat(NewV).
1262*d415bd75Srobert         if (Instruction *VInst = dyn_cast<Instruction>(V)) {
126309467b48Spatrick           // Don't create a copy of the original addrspacecast.
126409467b48Spatrick           if (U == V && isa<AddrSpaceCastInst>(V))
126509467b48Spatrick             continue;
126609467b48Spatrick 
1267*d415bd75Srobert           // Insert the addrspacecast after NewV.
1268*d415bd75Srobert           BasicBlock::iterator InsertPos;
1269*d415bd75Srobert           if (Instruction *NewVInst = dyn_cast<Instruction>(NewV))
1270*d415bd75Srobert             InsertPos = std::next(NewVInst->getIterator());
1271*d415bd75Srobert           else
1272*d415bd75Srobert             InsertPos = std::next(VInst->getIterator());
1273*d415bd75Srobert 
127409467b48Spatrick           while (isa<PHINode>(InsertPos))
127509467b48Spatrick             ++InsertPos;
127609467b48Spatrick           U.set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
127709467b48Spatrick         } else {
127809467b48Spatrick           U.set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
127909467b48Spatrick                                                V->getType()));
128009467b48Spatrick         }
128109467b48Spatrick       }
128209467b48Spatrick     }
128309467b48Spatrick 
128409467b48Spatrick     if (V->use_empty()) {
128509467b48Spatrick       if (Instruction *I = dyn_cast<Instruction>(V))
128609467b48Spatrick         DeadInstructions.push_back(I);
128709467b48Spatrick     }
128809467b48Spatrick   }
128909467b48Spatrick 
129009467b48Spatrick   for (Instruction *I : DeadInstructions)
129109467b48Spatrick     RecursivelyDeleteTriviallyDeadInstructions(I);
129209467b48Spatrick 
129309467b48Spatrick   return true;
129409467b48Spatrick }
129509467b48Spatrick 
runOnFunction(Function & F)129673471bf0Spatrick bool InferAddressSpaces::runOnFunction(Function &F) {
129773471bf0Spatrick   if (skipFunction(F))
129873471bf0Spatrick     return false;
129973471bf0Spatrick 
1300*d415bd75Srobert   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1301*d415bd75Srobert   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
130273471bf0Spatrick   return InferAddressSpacesImpl(
1303*d415bd75Srobert              getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), DT,
130473471bf0Spatrick              &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
130573471bf0Spatrick              FlatAddrSpace)
130673471bf0Spatrick       .run(F);
130773471bf0Spatrick }
130873471bf0Spatrick 
createInferAddressSpacesPass(unsigned AddressSpace)130909467b48Spatrick FunctionPass *llvm::createInferAddressSpacesPass(unsigned AddressSpace) {
131009467b48Spatrick   return new InferAddressSpaces(AddressSpace);
131109467b48Spatrick }
131273471bf0Spatrick 
InferAddressSpacesPass()131373471bf0Spatrick InferAddressSpacesPass::InferAddressSpacesPass()
131473471bf0Spatrick     : FlatAddrSpace(UninitializedAddressSpace) {}
InferAddressSpacesPass(unsigned AddressSpace)131573471bf0Spatrick InferAddressSpacesPass::InferAddressSpacesPass(unsigned AddressSpace)
131673471bf0Spatrick     : FlatAddrSpace(AddressSpace) {}
131773471bf0Spatrick 
run(Function & F,FunctionAnalysisManager & AM)131873471bf0Spatrick PreservedAnalyses InferAddressSpacesPass::run(Function &F,
131973471bf0Spatrick                                               FunctionAnalysisManager &AM) {
132073471bf0Spatrick   bool Changed =
1321*d415bd75Srobert       InferAddressSpacesImpl(AM.getResult<AssumptionAnalysis>(F),
1322*d415bd75Srobert                              AM.getCachedResult<DominatorTreeAnalysis>(F),
1323*d415bd75Srobert                              &AM.getResult<TargetIRAnalysis>(F), FlatAddrSpace)
132473471bf0Spatrick           .run(F);
132573471bf0Spatrick   if (Changed) {
132673471bf0Spatrick     PreservedAnalyses PA;
132773471bf0Spatrick     PA.preserveSet<CFGAnalyses>();
1328*d415bd75Srobert     PA.preserve<DominatorTreeAnalysis>();
132973471bf0Spatrick     return PA;
133073471bf0Spatrick   }
133173471bf0Spatrick   return PreservedAnalyses::all();
133273471bf0Spatrick }
1333