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