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