blob: 16f2fc0a302b229bf5fd5f1df35bd1baa90c841d [file] [log] [blame]
Jingyue Wu13755602016-03-20 20:59:20 +00001//===-- 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//
Jingyue Wu13755602016-03-20 20:59:20 +000090//===----------------------------------------------------------------------===//
91
Matt Arsenault850657a2017-01-31 01:10:58 +000092#include "llvm/Transforms/Scalar.h"
Jingyue Wu13755602016-03-20 20:59:20 +000093#include "llvm/ADT/DenseSet.h"
94#include "llvm/ADT/Optional.h"
95#include "llvm/ADT/SetVector.h"
Matt Arsenault42b64782017-01-30 23:02:12 +000096#include "llvm/Analysis/TargetTransformInfo.h"
Jingyue Wu13755602016-03-20 20:59:20 +000097#include "llvm/IR/Function.h"
98#include "llvm/IR/InstIterator.h"
99#include "llvm/IR/Instructions.h"
100#include "llvm/IR/Operator.h"
Jingyue Wu13755602016-03-20 20:59:20 +0000101#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
Matt Arsenault850657a2017-01-31 01:10:58 +0000106#define DEBUG_TYPE "infer-address-spaces"
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000107
Jingyue Wu13755602016-03-20 20:59:20 +0000108using namespace llvm;
109
110namespace {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000111static const unsigned UnknownAddressSpace = ~0u;
Jingyue Wu13755602016-03-20 20:59:20 +0000112
113using ValueToAddrSpaceMapTy = DenseMap<const Value *, unsigned>;
114
Matt Arsenault850657a2017-01-31 01:10:58 +0000115/// \brief InferAddressSpaces
116class InferAddressSpaces: public FunctionPass {
Matt Arsenault42b64782017-01-30 23:02:12 +0000117 /// Target specific address space which uses of should be replaced if
118 /// possible.
119 unsigned FlatAddrSpace;
120
Jingyue Wu13755602016-03-20 20:59:20 +0000121public:
122 static char ID;
123
Matt Arsenault850657a2017-01-31 01:10:58 +0000124 InferAddressSpaces() : FunctionPass(ID) {}
Jingyue Wu13755602016-03-20 20:59:20 +0000125
Matt Arsenault32b96002017-01-27 17:30:39 +0000126 void getAnalysisUsage(AnalysisUsage &AU) const override {
127 AU.setPreservesCFG();
Matt Arsenault42b64782017-01-30 23:02:12 +0000128 AU.addRequired<TargetTransformInfoWrapperPass>();
Matt Arsenault32b96002017-01-27 17:30:39 +0000129 }
130
Jingyue Wu13755602016-03-20 20:59:20 +0000131 bool runOnFunction(Function &F) override;
132
133private:
134 // Returns the new address space of V if updated; otherwise, returns None.
135 Optional<unsigned>
136 updateAddressSpace(const Value &V,
Matt Arsenault42b64782017-01-30 23:02:12 +0000137 const ValueToAddrSpaceMapTy &InferredAddrSpace) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000138
139 // Tries to infer the specific address space of each address expression in
140 // Postorder.
141 void inferAddressSpaces(const std::vector<Value *> &Postorder,
Matt Arsenault42b64782017-01-30 23:02:12 +0000142 ValueToAddrSpaceMapTy *InferredAddrSpace) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000143
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000144 // Changes the flat address expressions in function F to point to specific
Jingyue Wu13755602016-03-20 20:59:20 +0000145 // address spaces if InferredAddrSpace says so. Postorder is the postorder of
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000146 // all flat expressions in the use-def graph of function F.
Jingyue Wu13755602016-03-20 20:59:20 +0000147 bool
148 rewriteWithNewAddressSpaces(const std::vector<Value *> &Postorder,
149 const ValueToAddrSpaceMapTy &InferredAddrSpace,
Matt Arsenault42b64782017-01-30 23:02:12 +0000150 Function *F) const;
151
152 void appendsFlatAddressExpressionToPostorderStack(
153 Value *V, std::vector<std::pair<Value *, bool>> *PostorderStack,
154 DenseSet<Value *> *Visited) const;
155
156 std::vector<Value *> collectFlatAddressExpressions(Function &F) const;
157 Value *cloneValueWithNewAddressSpace(
158 Value *V, unsigned NewAddrSpace,
159 const ValueToValueMapTy &ValueWithNewAddrSpace,
160 SmallVectorImpl<const Use *> *UndefUsesToFix) const;
161 unsigned joinAddressSpaces(unsigned AS1, unsigned AS2) const;
Jingyue Wu13755602016-03-20 20:59:20 +0000162};
163} // end anonymous namespace
164
Matt Arsenault850657a2017-01-31 01:10:58 +0000165char InferAddressSpaces::ID = 0;
Jingyue Wu13755602016-03-20 20:59:20 +0000166
167namespace llvm {
Matt Arsenault850657a2017-01-31 01:10:58 +0000168void initializeInferAddressSpacesPass(PassRegistry &);
Jingyue Wu13755602016-03-20 20:59:20 +0000169}
Matt Arsenault850657a2017-01-31 01:10:58 +0000170
171INITIALIZE_PASS(InferAddressSpaces, DEBUG_TYPE, "Infer address spaces",
Jingyue Wu13755602016-03-20 20:59:20 +0000172 false, false)
173
174// Returns true if V is an address expression.
175// TODO: Currently, we consider only phi, bitcast, addrspacecast, and
176// getelementptr operators.
177static bool isAddressExpression(const Value &V) {
178 if (!isa<Operator>(V))
179 return false;
180
181 switch (cast<Operator>(V).getOpcode()) {
182 case Instruction::PHI:
183 case Instruction::BitCast:
184 case Instruction::AddrSpaceCast:
185 case Instruction::GetElementPtr:
186 return true;
187 default:
188 return false;
189 }
190}
191
192// Returns the pointer operands of V.
193//
194// Precondition: V is an address expression.
195static SmallVector<Value *, 2> getPointerOperands(const Value &V) {
196 assert(isAddressExpression(V));
197 const Operator& Op = cast<Operator>(V);
198 switch (Op.getOpcode()) {
199 case Instruction::PHI: {
200 auto IncomingValues = cast<PHINode>(Op).incoming_values();
201 return SmallVector<Value *, 2>(IncomingValues.begin(),
202 IncomingValues.end());
203 }
204 case Instruction::BitCast:
205 case Instruction::AddrSpaceCast:
206 case Instruction::GetElementPtr:
207 return {Op.getOperand(0)};
208 default:
209 llvm_unreachable("Unexpected instruction type.");
210 }
211}
212
Matt Arsenault42b64782017-01-30 23:02:12 +0000213// If V is an unvisited flat address expression, appends V to PostorderStack
Jingyue Wu13755602016-03-20 20:59:20 +0000214// and marks it as visited.
Matt Arsenault850657a2017-01-31 01:10:58 +0000215void InferAddressSpaces::appendsFlatAddressExpressionToPostorderStack(
216 Value *V, std::vector<std::pair<Value *, bool>> *PostorderStack,
217 DenseSet<Value *> *Visited) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000218 assert(V->getType()->isPointerTy());
219 if (isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000220 V->getType()->getPointerAddressSpace() == FlatAddrSpace) {
Jingyue Wu13755602016-03-20 20:59:20 +0000221 if (Visited->insert(V).second)
222 PostorderStack->push_back(std::make_pair(V, false));
223 }
224}
225
Matt Arsenault42b64782017-01-30 23:02:12 +0000226// Returns all flat address expressions in function F. The elements are ordered
227// in postorder.
228std::vector<Value *>
Matt Arsenault850657a2017-01-31 01:10:58 +0000229InferAddressSpaces::collectFlatAddressExpressions(Function &F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000230 // This function implements a non-recursive postorder traversal of a partial
231 // use-def graph of function F.
232 std::vector<std::pair<Value*, bool>> PostorderStack;
233 // The set of visited expressions.
234 DenseSet<Value*> Visited;
Matt Arsenault6c907a92017-01-31 01:40:38 +0000235
236 auto PushPtrOperand = [&](Value *Ptr) {
237 appendsFlatAddressExpressionToPostorderStack(
238 Ptr, &PostorderStack, &Visited);
239 };
240
Jingyue Wu13755602016-03-20 20:59:20 +0000241 // We only explore address expressions that are reachable from loads and
242 // stores for now because we aim at generating faster loads and stores.
243 for (Instruction &I : instructions(F)) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000244 if (auto *LI = dyn_cast<LoadInst>(&I))
245 PushPtrOperand(LI->getPointerOperand());
246 else if (auto *SI = dyn_cast<StoreInst>(&I))
247 PushPtrOperand(SI->getPointerOperand());
248 else if (auto *RMW = dyn_cast<AtomicRMWInst>(&I))
249 PushPtrOperand(RMW->getPointerOperand());
250 else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(&I))
251 PushPtrOperand(CmpX->getPointerOperand());
252
253 // TODO: Support intrinsics
Jingyue Wu13755602016-03-20 20:59:20 +0000254 }
255
256 std::vector<Value *> Postorder; // The resultant postorder.
257 while (!PostorderStack.empty()) {
258 // If the operands of the expression on the top are already explored,
259 // adds that expression to the resultant postorder.
260 if (PostorderStack.back().second) {
261 Postorder.push_back(PostorderStack.back().first);
262 PostorderStack.pop_back();
263 continue;
264 }
265 // Otherwise, adds its operands to the stack and explores them.
266 PostorderStack.back().second = true;
267 for (Value *PtrOperand : getPointerOperands(*PostorderStack.back().first)) {
Matt Arsenault42b64782017-01-30 23:02:12 +0000268 appendsFlatAddressExpressionToPostorderStack(
Matt Arsenault850657a2017-01-31 01:10:58 +0000269 PtrOperand, &PostorderStack, &Visited);
Jingyue Wu13755602016-03-20 20:59:20 +0000270 }
271 }
272 return Postorder;
273}
274
275// A helper function for cloneInstructionWithNewAddressSpace. Returns the clone
276// of OperandUse.get() in the new address space. If the clone is not ready yet,
277// returns an undef in the new address space as a placeholder.
278static Value *operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenault850657a2017-01-31 01:10:58 +0000279 const Use &OperandUse, unsigned NewAddrSpace,
280 const ValueToValueMapTy &ValueWithNewAddrSpace,
281 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000282 Value *Operand = OperandUse.get();
283 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand))
284 return NewOperand;
285
286 UndefUsesToFix->push_back(&OperandUse);
287 return UndefValue::get(
Matt Arsenault850657a2017-01-31 01:10:58 +0000288 Operand->getType()->getPointerElementType()->getPointerTo(NewAddrSpace));
Jingyue Wu13755602016-03-20 20:59:20 +0000289}
290
291// Returns a clone of `I` with its operands converted to those specified in
292// ValueWithNewAddrSpace. Due to potential cycles in the data flow graph, an
293// operand whose address space needs to be modified might not exist in
294// ValueWithNewAddrSpace. In that case, uses undef as a placeholder operand and
295// adds that operand use to UndefUsesToFix so that caller can fix them later.
296//
297// Note that we do not necessarily clone `I`, e.g., if it is an addrspacecast
298// from a pointer whose type already matches. Therefore, this function returns a
299// Value* instead of an Instruction*.
300static Value *cloneInstructionWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000301 Instruction *I, unsigned NewAddrSpace,
302 const ValueToValueMapTy &ValueWithNewAddrSpace,
303 SmallVectorImpl<const Use *> *UndefUsesToFix) {
Jingyue Wu13755602016-03-20 20:59:20 +0000304 Type *NewPtrType =
Matt Arsenault850657a2017-01-31 01:10:58 +0000305 I->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000306
307 if (I->getOpcode() == Instruction::AddrSpaceCast) {
308 Value *Src = I->getOperand(0);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000309 // Because `I` is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000310 // Therefore, the inferred address space must be the source space, according
311 // to our algorithm.
312 assert(Src->getType()->getPointerAddressSpace() == NewAddrSpace);
313 if (Src->getType() != NewPtrType)
314 return new BitCastInst(Src, NewPtrType);
315 return Src;
316 }
317
318 // Computes the converted pointer operands.
319 SmallVector<Value *, 4> NewPointerOperands;
320 for (const Use &OperandUse : I->operands()) {
321 if (!OperandUse.get()->getType()->isPointerTy())
322 NewPointerOperands.push_back(nullptr);
323 else
324 NewPointerOperands.push_back(operandWithNewAddressSpaceOrCreateUndef(
Matt Arsenault850657a2017-01-31 01:10:58 +0000325 OperandUse, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix));
Jingyue Wu13755602016-03-20 20:59:20 +0000326 }
327
328 switch (I->getOpcode()) {
329 case Instruction::BitCast:
330 return new BitCastInst(NewPointerOperands[0], NewPtrType);
331 case Instruction::PHI: {
332 assert(I->getType()->isPointerTy());
333 PHINode *PHI = cast<PHINode>(I);
334 PHINode *NewPHI = PHINode::Create(NewPtrType, PHI->getNumIncomingValues());
335 for (unsigned Index = 0; Index < PHI->getNumIncomingValues(); ++Index) {
336 unsigned OperandNo = PHINode::getOperandNumForIncomingValue(Index);
337 NewPHI->addIncoming(NewPointerOperands[OperandNo],
338 PHI->getIncomingBlock(Index));
339 }
340 return NewPHI;
341 }
342 case Instruction::GetElementPtr: {
343 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
344 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
Matt Arsenault850657a2017-01-31 01:10:58 +0000345 GEP->getSourceElementType(), NewPointerOperands[0],
346 SmallVector<Value *, 4>(GEP->idx_begin(), GEP->idx_end()));
Jingyue Wu13755602016-03-20 20:59:20 +0000347 NewGEP->setIsInBounds(GEP->isInBounds());
348 return NewGEP;
349 }
350 default:
351 llvm_unreachable("Unexpected opcode");
352 }
353}
354
355// Similar to cloneInstructionWithNewAddressSpace, returns a clone of the
356// constant expression `CE` with its operands replaced as specified in
357// ValueWithNewAddrSpace.
358static Value *cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000359 ConstantExpr *CE, unsigned NewAddrSpace,
360 const ValueToValueMapTy &ValueWithNewAddrSpace) {
Jingyue Wu13755602016-03-20 20:59:20 +0000361 Type *TargetType =
Matt Arsenault850657a2017-01-31 01:10:58 +0000362 CE->getType()->getPointerElementType()->getPointerTo(NewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000363
364 if (CE->getOpcode() == Instruction::AddrSpaceCast) {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000365 // Because CE is flat, the source address space must be specific.
Jingyue Wu13755602016-03-20 20:59:20 +0000366 // Therefore, the inferred address space must be the source space according
367 // to our algorithm.
368 assert(CE->getOperand(0)->getType()->getPointerAddressSpace() ==
369 NewAddrSpace);
370 return ConstantExpr::getBitCast(CE->getOperand(0), TargetType);
371 }
372
373 // Computes the operands of the new constant expression.
374 SmallVector<Constant *, 4> NewOperands;
375 for (unsigned Index = 0; Index < CE->getNumOperands(); ++Index) {
376 Constant *Operand = CE->getOperand(Index);
377 // If the address space of `Operand` needs to be modified, the new operand
378 // with the new address space should already be in ValueWithNewAddrSpace
379 // because (1) the constant expressions we consider (i.e. addrspacecast,
380 // bitcast, and getelementptr) do not incur cycles in the data flow graph
381 // and (2) this function is called on constant expressions in postorder.
382 if (Value *NewOperand = ValueWithNewAddrSpace.lookup(Operand)) {
383 NewOperands.push_back(cast<Constant>(NewOperand));
384 } else {
385 // Otherwise, reuses the old operand.
386 NewOperands.push_back(Operand);
387 }
388 }
389
390 if (CE->getOpcode() == Instruction::GetElementPtr) {
391 // Needs to specify the source type while constructing a getelementptr
392 // constant expression.
393 return CE->getWithOperands(
Matt Arsenault850657a2017-01-31 01:10:58 +0000394 NewOperands, TargetType, /*OnlyIfReduced=*/false,
395 NewOperands[0]->getType()->getPointerElementType());
Jingyue Wu13755602016-03-20 20:59:20 +0000396 }
397
398 return CE->getWithOperands(NewOperands, TargetType);
399}
400
401// Returns a clone of the value `V`, with its operands replaced as specified in
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000402// ValueWithNewAddrSpace. This function is called on every flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000403// expression whose address space needs to be modified, in postorder.
404//
405// See cloneInstructionWithNewAddressSpace for the meaning of UndefUsesToFix.
Matt Arsenault850657a2017-01-31 01:10:58 +0000406Value *InferAddressSpaces::cloneValueWithNewAddressSpace(
Matt Arsenault42b64782017-01-30 23:02:12 +0000407 Value *V, unsigned NewAddrSpace,
408 const ValueToValueMapTy &ValueWithNewAddrSpace,
409 SmallVectorImpl<const Use *> *UndefUsesToFix) const {
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000410 // All values in Postorder are flat address expressions.
Jingyue Wu13755602016-03-20 20:59:20 +0000411 assert(isAddressExpression(*V) &&
Matt Arsenault42b64782017-01-30 23:02:12 +0000412 V->getType()->getPointerAddressSpace() == FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000413
414 if (Instruction *I = dyn_cast<Instruction>(V)) {
415 Value *NewV = cloneInstructionWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000416 I, NewAddrSpace, ValueWithNewAddrSpace, UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000417 if (Instruction *NewI = dyn_cast<Instruction>(NewV)) {
418 if (NewI->getParent() == nullptr) {
419 NewI->insertBefore(I);
420 NewI->takeName(I);
421 }
422 }
423 return NewV;
424 }
425
426 return cloneConstantExprWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000427 cast<ConstantExpr>(V), NewAddrSpace, ValueWithNewAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000428}
429
430// Defines the join operation on the address space lattice (see the file header
431// comments).
Matt Arsenault850657a2017-01-31 01:10:58 +0000432unsigned InferAddressSpaces::joinAddressSpaces(unsigned AS1,
433 unsigned AS2) const {
Matt Arsenault42b64782017-01-30 23:02:12 +0000434 if (AS1 == FlatAddrSpace || AS2 == FlatAddrSpace)
435 return FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000436
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000437 if (AS1 == UnknownAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000438 return AS2;
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000439 if (AS2 == UnknownAddressSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000440 return AS1;
441
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000442 // The join of two different specific address spaces is flat.
Matt Arsenault42b64782017-01-30 23:02:12 +0000443 return (AS1 == AS2) ? AS1 : FlatAddrSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000444}
445
Matt Arsenault850657a2017-01-31 01:10:58 +0000446bool InferAddressSpaces::runOnFunction(Function &F) {
Andrew Kaylor87b10dd2016-04-26 23:44:31 +0000447 if (skipFunction(F))
448 return false;
449
Matt Arsenault42b64782017-01-30 23:02:12 +0000450 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
451 FlatAddrSpace = TTI.getFlatAddressSpace();
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000452 if (FlatAddrSpace == UnknownAddressSpace)
Matt Arsenault42b64782017-01-30 23:02:12 +0000453 return false;
454
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000455 // Collects all flat address expressions in postorder.
Matt Arsenault42b64782017-01-30 23:02:12 +0000456 std::vector<Value *> Postorder = collectFlatAddressExpressions(F);
Jingyue Wu13755602016-03-20 20:59:20 +0000457
458 // Runs a data-flow analysis to refine the address spaces of every expression
459 // in Postorder.
460 ValueToAddrSpaceMapTy InferredAddrSpace;
461 inferAddressSpaces(Postorder, &InferredAddrSpace);
462
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000463 // Changes the address spaces of the flat address expressions who are inferred
464 // to point to a specific address space.
Jingyue Wu13755602016-03-20 20:59:20 +0000465 return rewriteWithNewAddressSpaces(Postorder, InferredAddrSpace, &F);
466}
467
Matt Arsenault850657a2017-01-31 01:10:58 +0000468void InferAddressSpaces::inferAddressSpaces(
469 const std::vector<Value *> &Postorder,
470 ValueToAddrSpaceMapTy *InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000471 SetVector<Value *> Worklist(Postorder.begin(), Postorder.end());
472 // Initially, all expressions are in the uninitialized address space.
473 for (Value *V : Postorder)
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000474 (*InferredAddrSpace)[V] = UnknownAddressSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000475
476 while (!Worklist.empty()) {
477 Value* V = Worklist.pop_back_val();
478
479 // Tries to update the address space of the stack top according to the
480 // address spaces of its operands.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000481 DEBUG(dbgs() << "Updating the address space of\n " << *V << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000482 Optional<unsigned> NewAS = updateAddressSpace(*V, *InferredAddrSpace);
483 if (!NewAS.hasValue())
484 continue;
485 // If any updates are made, grabs its users to the worklist because
486 // their address spaces can also be possibly updated.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000487 DEBUG(dbgs() << " to " << NewAS.getValue() << '\n');
Jingyue Wu13755602016-03-20 20:59:20 +0000488 (*InferredAddrSpace)[V] = NewAS.getValue();
489
490 for (Value *User : V->users()) {
491 // Skip if User is already in the worklist.
492 if (Worklist.count(User))
493 continue;
494
495 auto Pos = InferredAddrSpace->find(User);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000496 // Our algorithm only updates the address spaces of flat address
Jingyue Wu13755602016-03-20 20:59:20 +0000497 // expressions, which are those in InferredAddrSpace.
498 if (Pos == InferredAddrSpace->end())
499 continue;
500
501 // Function updateAddressSpace moves the address space down a lattice
Matt Arsenault850657a2017-01-31 01:10:58 +0000502 // path. Therefore, nothing to do if User is already inferred as flat (the
503 // bottom element in the lattice).
Matt Arsenault42b64782017-01-30 23:02:12 +0000504 if (Pos->second == FlatAddrSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000505 continue;
506
507 Worklist.insert(User);
508 }
509 }
510}
511
Matt Arsenault850657a2017-01-31 01:10:58 +0000512Optional<unsigned> InferAddressSpaces::updateAddressSpace(
513 const Value &V, const ValueToAddrSpaceMapTy &InferredAddrSpace) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000514 assert(InferredAddrSpace.count(&V));
515
516 // The new inferred address space equals the join of the address spaces
517 // of all its pointer operands.
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000518 unsigned NewAS = UnknownAddressSpace;
Jingyue Wu13755602016-03-20 20:59:20 +0000519 for (Value *PtrOperand : getPointerOperands(V)) {
520 unsigned OperandAS;
521 if (InferredAddrSpace.count(PtrOperand))
522 OperandAS = InferredAddrSpace.lookup(PtrOperand);
523 else
524 OperandAS = PtrOperand->getType()->getPointerAddressSpace();
525 NewAS = joinAddressSpaces(NewAS, OperandAS);
Matt Arsenault850657a2017-01-31 01:10:58 +0000526
527 // join(flat, *) = flat. So we can break if NewAS is already flat.
Matt Arsenault42b64782017-01-30 23:02:12 +0000528 if (NewAS == FlatAddrSpace)
Jingyue Wu13755602016-03-20 20:59:20 +0000529 break;
530 }
531
532 unsigned OldAS = InferredAddrSpace.lookup(&V);
Matt Arsenault42b64782017-01-30 23:02:12 +0000533 assert(OldAS != FlatAddrSpace);
Jingyue Wu13755602016-03-20 20:59:20 +0000534 if (OldAS == NewAS)
535 return None;
536 return NewAS;
537}
538
Matt Arsenault6c907a92017-01-31 01:40:38 +0000539/// \p returns true if \p U is the pointer operand of a memory instruction with
540/// a single pointer operand that can have its address space changed by simply
541/// mutating the use to a new value.
542static bool isSimplePointerUseValidToReplace(Use &U) {
543 User *Inst = U.getUser();
544 unsigned OpNo = U.getOperandNo();
545
546 if (auto *LI = dyn_cast<LoadInst>(Inst))
547 return OpNo == LoadInst::getPointerOperandIndex() && !LI->isVolatile();
548
549 if (auto *SI = dyn_cast<StoreInst>(Inst))
550 return OpNo == StoreInst::getPointerOperandIndex() && !SI->isVolatile();
551
552 if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst))
553 return OpNo == AtomicRMWInst::getPointerOperandIndex() && !RMW->isVolatile();
554
555 if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
556 return OpNo == AtomicCmpXchgInst::getPointerOperandIndex() &&
557 !CmpX->isVolatile();
558 }
559
560 return false;
561}
562
Matt Arsenault850657a2017-01-31 01:10:58 +0000563bool InferAddressSpaces::rewriteWithNewAddressSpaces(
564 const std::vector<Value *> &Postorder,
565 const ValueToAddrSpaceMapTy &InferredAddrSpace, Function *F) const {
Jingyue Wu13755602016-03-20 20:59:20 +0000566 // For each address expression to be modified, creates a clone of it with its
567 // pointer operands converted to the new address space. Since the pointer
568 // operands are converted, the clone is naturally in the new address space by
569 // construction.
570 ValueToValueMapTy ValueWithNewAddrSpace;
571 SmallVector<const Use *, 32> UndefUsesToFix;
572 for (Value* V : Postorder) {
573 unsigned NewAddrSpace = InferredAddrSpace.lookup(V);
574 if (V->getType()->getPointerAddressSpace() != NewAddrSpace) {
575 ValueWithNewAddrSpace[V] = cloneValueWithNewAddressSpace(
Matt Arsenault850657a2017-01-31 01:10:58 +0000576 V, NewAddrSpace, ValueWithNewAddrSpace, &UndefUsesToFix);
Jingyue Wu13755602016-03-20 20:59:20 +0000577 }
578 }
579
580 if (ValueWithNewAddrSpace.empty())
581 return false;
582
583 // Fixes all the undef uses generated by cloneInstructionWithNewAddressSpace.
584 for (const Use* UndefUse : UndefUsesToFix) {
585 User *V = UndefUse->getUser();
586 User *NewV = cast<User>(ValueWithNewAddrSpace.lookup(V));
587 unsigned OperandNo = UndefUse->getOperandNo();
588 assert(isa<UndefValue>(NewV->getOperand(OperandNo)));
589 NewV->setOperand(OperandNo, ValueWithNewAddrSpace.lookup(UndefUse->get()));
590 }
591
592 // Replaces the uses of the old address expressions with the new ones.
593 for (Value *V : Postorder) {
594 Value *NewV = ValueWithNewAddrSpace.lookup(V);
595 if (NewV == nullptr)
596 continue;
597
598 SmallVector<Use *, 4> Uses;
599 for (Use &U : V->uses())
600 Uses.push_back(&U);
Matt Arsenault9f432ec2017-01-30 23:27:11 +0000601
602 DEBUG(dbgs() << "Replacing the uses of " << *V
603 << "\n with\n " << *NewV << '\n');
604
Jingyue Wu13755602016-03-20 20:59:20 +0000605 for (Use *U : Uses) {
Matt Arsenault6c907a92017-01-31 01:40:38 +0000606 if (isSimplePointerUseValidToReplace(*U)) {
607 // If V is used as the pointer operand of a compatible memory operation,
608 // sets the pointer operand to NewV. This replacement does not change
609 // the element type, so the resultant load/store is still valid.
Jingyue Wu13755602016-03-20 20:59:20 +0000610 U->set(NewV);
611 } else if (isa<Instruction>(U->getUser())) {
Matt Arsenault850657a2017-01-31 01:10:58 +0000612 // Otherwise, replaces the use with flat(NewV).
Jingyue Wu13755602016-03-20 20:59:20 +0000613 // TODO: Some optimization opportunities are missed. For example, in
614 // %0 = icmp eq float* %p, %q
615 // if both p and q are inferred to be shared, we can rewrite %0 as
616 // %0 = icmp eq float addrspace(3)* %new_p, %new_q
617 // instead of currently
Matt Arsenault850657a2017-01-31 01:10:58 +0000618 // %flat_p = addrspacecast float addrspace(3)* %new_p to float*
619 // %flat_q = addrspacecast float addrspace(3)* %new_q to float*
620 // %0 = icmp eq float* %flat_p, %flat_q
Jingyue Wu13755602016-03-20 20:59:20 +0000621 if (Instruction *I = dyn_cast<Instruction>(V)) {
622 BasicBlock::iterator InsertPos = std::next(I->getIterator());
623 while (isa<PHINode>(InsertPos))
624 ++InsertPos;
625 U->set(new AddrSpaceCastInst(NewV, V->getType(), "", &*InsertPos));
626 } else {
627 U->set(ConstantExpr::getAddrSpaceCast(cast<Constant>(NewV),
628 V->getType()));
629 }
630 }
631 }
632 if (V->use_empty())
633 RecursivelyDeleteTriviallyDeadInstructions(V);
634 }
635
636 return true;
637}
638
Matt Arsenault850657a2017-01-31 01:10:58 +0000639FunctionPass *llvm::createInferAddressSpacesPass() {
640 return new InferAddressSpaces();
Jingyue Wu13755602016-03-20 20:59:20 +0000641}