1 //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass eliminates allocas by either converting them into vectors or
11 // by migrating them to local address space.
13 //===----------------------------------------------------------------------===//
16 #include "AMDGPUSubtarget.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/InstVisitor.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
23 #define DEBUG_TYPE "amdgpu-promote-alloca"
29 class AMDGPUPromoteAlloca : public FunctionPass,
30 public InstVisitor<AMDGPUPromoteAlloca> {
34 const AMDGPUSubtarget &ST;
35 int LocalMemAvailable;
38 AMDGPUPromoteAlloca(const AMDGPUSubtarget &st) : FunctionPass(ID), ST(st),
39 LocalMemAvailable(0) { }
40 bool doInitialization(Module &M) override;
41 bool runOnFunction(Function &F) override;
42 const char *getPassName() const override { return "AMDGPU Promote Alloca"; }
43 void visitAlloca(AllocaInst &I);
46 } // End anonymous namespace
48 char AMDGPUPromoteAlloca::ID = 0;
50 bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
55 bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
57 const FunctionType *FTy = F.getFunctionType();
59 LocalMemAvailable = ST.getLocalMemorySize();
62 // If the function has any arguments in the local address space, then it's
63 // possible these arguments require the entire local memory space, so
64 // we cannot use local memory in the pass.
65 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
66 const Type *ParamTy = FTy->getParamType(i);
67 if (ParamTy->isPointerTy() &&
68 ParamTy->getPointerAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
69 LocalMemAvailable = 0;
70 DEBUG(dbgs() << "Function has local memory argument. Promoting to "
71 "local memory disabled.\n");
76 if (LocalMemAvailable > 0) {
77 // Check how much local memory is being used by global objects
78 for (Module::global_iterator I = Mod->global_begin(),
79 E = Mod->global_end(); I != E; ++I) {
80 GlobalVariable *GV = I;
81 PointerType *GVTy = GV->getType();
82 if (GVTy->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
84 for (Value::use_iterator U = GV->use_begin(),
85 UE = GV->use_end(); U != UE; ++U) {
86 Instruction *Use = dyn_cast<Instruction>(*U);
89 if (Use->getParent()->getParent() == &F)
91 Mod->getDataLayout().getTypeAllocSize(GVTy->getElementType());
96 LocalMemAvailable = std::max(0, LocalMemAvailable);
97 DEBUG(dbgs() << LocalMemAvailable << "bytes free in local memory.\n");
104 static VectorType *arrayTypeToVecType(const Type *ArrayTy) {
105 return VectorType::get(ArrayTy->getArrayElementType(),
106 ArrayTy->getArrayNumElements());
110 calculateVectorIndex(Value *Ptr,
111 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
112 if (isa<AllocaInst>(Ptr))
113 return Constant::getNullValue(Type::getInt32Ty(Ptr->getContext()));
115 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
117 auto I = GEPIdx.find(GEP);
118 return I == GEPIdx.end() ? nullptr : I->second;
121 static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
122 // FIXME we only support simple cases
123 if (GEP->getNumOperands() != 3)
126 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
127 if (!I0 || !I0->isZero())
130 return GEP->getOperand(2);
133 // Not an instruction handled below to turn into a vector.
135 // TODO: Check isTriviallyVectorizable for calls and handle other
137 static bool canVectorizeInst(Instruction *Inst) {
138 switch (Inst->getOpcode()) {
139 case Instruction::Load:
140 case Instruction::Store:
141 case Instruction::BitCast:
142 case Instruction::AddrSpaceCast:
149 static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
150 Type *AllocaTy = Alloca->getAllocatedType();
152 DEBUG(dbgs() << "Alloca Candidate for vectorization \n");
154 // FIXME: There is no reason why we can't support larger arrays, we
155 // are just being conservative for now.
156 if (!AllocaTy->isArrayTy() ||
157 AllocaTy->getArrayElementType()->isVectorTy() ||
158 AllocaTy->getArrayNumElements() > 4) {
160 DEBUG(dbgs() << " Cannot convert type to vector");
164 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
165 std::vector<Value*> WorkList;
166 for (User *AllocaUser : Alloca->users()) {
167 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
169 if (!canVectorizeInst(cast<Instruction>(AllocaUser)))
172 WorkList.push_back(AllocaUser);
176 Value *Index = GEPToVectorIndex(GEP);
178 // If we can't compute a vector index from this GEP, then we can't
179 // promote this alloca to vector.
181 DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
185 GEPVectorIdx[GEP] = Index;
186 for (User *GEPUser : AllocaUser->users()) {
187 if (!canVectorizeInst(cast<Instruction>(GEPUser)))
190 WorkList.push_back(GEPUser);
194 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
196 DEBUG(dbgs() << " Converting alloca to vector "
197 << *AllocaTy << " -> " << *VectorTy << '\n');
199 for (std::vector<Value*>::iterator I = WorkList.begin(),
200 E = WorkList.end(); I != E; ++I) {
201 Instruction *Inst = cast<Instruction>(*I);
202 IRBuilder<> Builder(Inst);
203 switch (Inst->getOpcode()) {
204 case Instruction::Load: {
205 Value *Ptr = Inst->getOperand(0);
206 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
207 Value *BitCast = Builder.CreateBitCast(Alloca, VectorTy->getPointerTo(0));
208 Value *VecValue = Builder.CreateLoad(BitCast);
209 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
210 Inst->replaceAllUsesWith(ExtractElement);
211 Inst->eraseFromParent();
214 case Instruction::Store: {
215 Value *Ptr = Inst->getOperand(1);
216 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
217 Value *BitCast = Builder.CreateBitCast(Alloca, VectorTy->getPointerTo(0));
218 Value *VecValue = Builder.CreateLoad(BitCast);
219 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
222 Builder.CreateStore(NewVecValue, BitCast);
223 Inst->eraseFromParent();
226 case Instruction::BitCast:
227 case Instruction::AddrSpaceCast:
232 llvm_unreachable("Inconsistency in instructions promotable to vector");
238 static bool collectUsesWithPtrTypes(Value *Val, std::vector<Value*> &WorkList) {
240 for (User *User : Val->users()) {
241 if(std::find(WorkList.begin(), WorkList.end(), User) != WorkList.end())
243 if (CallInst *CI = dyn_cast<CallInst>(User)) {
244 // TODO: We might be able to handle some cases where the callee is a
245 // constantexpr bitcast of a function.
246 if (!CI->getCalledFunction())
249 WorkList.push_back(User);
253 // FIXME: Correctly handle ptrtoint instructions.
254 Instruction *UseInst = dyn_cast<Instruction>(User);
255 if (UseInst && UseInst->getOpcode() == Instruction::PtrToInt)
258 if (!User->getType()->isPointerTy())
261 WorkList.push_back(User);
263 Success &= collectUsesWithPtrTypes(User, WorkList);
268 void AMDGPUPromoteAlloca::visitAlloca(AllocaInst &I) {
269 IRBuilder<> Builder(&I);
271 // First try to replace the alloca with a vector
272 Type *AllocaTy = I.getAllocatedType();
274 DEBUG(dbgs() << "Trying to promote " << I << '\n');
276 if (tryPromoteAllocaToVector(&I))
279 DEBUG(dbgs() << " alloca is not a candidate for vectorization.\n");
281 // FIXME: This is the maximum work group size. We should try to get
282 // value from the reqd_work_group_size function attribute if it is
284 unsigned WorkGroupSize = 256;
286 WorkGroupSize * Mod->getDataLayout().getTypeAllocSize(AllocaTy);
288 if (AllocaSize > LocalMemAvailable) {
289 DEBUG(dbgs() << " Not enough local memory to promote alloca.\n");
293 std::vector<Value*> WorkList;
295 if (!collectUsesWithPtrTypes(&I, WorkList)) {
296 DEBUG(dbgs() << " Do not know how to convert all uses\n");
300 DEBUG(dbgs() << "Promoting alloca to local memory\n");
301 LocalMemAvailable -= AllocaSize;
303 Type *GVTy = ArrayType::get(I.getAllocatedType(), 256);
304 GlobalVariable *GV = new GlobalVariable(
305 *Mod, GVTy, false, GlobalValue::ExternalLinkage, 0, I.getName(), 0,
306 GlobalVariable::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS);
308 FunctionType *FTy = FunctionType::get(
309 Type::getInt32Ty(Mod->getContext()), false);
310 AttributeSet AttrSet;
311 AttrSet.addAttribute(Mod->getContext(), 0, Attribute::ReadNone);
313 Value *ReadLocalSizeY = Mod->getOrInsertFunction(
314 "llvm.r600.read.local.size.y", FTy, AttrSet);
315 Value *ReadLocalSizeZ = Mod->getOrInsertFunction(
316 "llvm.r600.read.local.size.z", FTy, AttrSet);
317 Value *ReadTIDIGX = Mod->getOrInsertFunction(
318 "llvm.r600.read.tidig.x", FTy, AttrSet);
319 Value *ReadTIDIGY = Mod->getOrInsertFunction(
320 "llvm.r600.read.tidig.y", FTy, AttrSet);
321 Value *ReadTIDIGZ = Mod->getOrInsertFunction(
322 "llvm.r600.read.tidig.z", FTy, AttrSet);
324 Value *TCntY = Builder.CreateCall(ReadLocalSizeY, {});
325 Value *TCntZ = Builder.CreateCall(ReadLocalSizeZ, {});
326 Value *TIdX = Builder.CreateCall(ReadTIDIGX, {});
327 Value *TIdY = Builder.CreateCall(ReadTIDIGY, {});
328 Value *TIdZ = Builder.CreateCall(ReadTIDIGZ, {});
330 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ);
331 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
332 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ);
333 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
334 TID = Builder.CreateAdd(TID, TIdZ);
336 std::vector<Value*> Indices;
337 Indices.push_back(Constant::getNullValue(Type::getInt32Ty(Mod->getContext())));
338 Indices.push_back(TID);
340 Value *Offset = Builder.CreateGEP(GVTy, GV, Indices);
341 I.mutateType(Offset->getType());
342 I.replaceAllUsesWith(Offset);
345 for (std::vector<Value*>::iterator i = WorkList.begin(),
346 e = WorkList.end(); i != e; ++i) {
348 CallInst *Call = dyn_cast<CallInst>(V);
350 Type *EltTy = V->getType()->getPointerElementType();
351 PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
353 // The operand's value should be corrected on its own.
354 if (isa<AddrSpaceCastInst>(V))
357 // FIXME: It doesn't really make sense to try to do this for all
359 V->mutateType(NewTy);
363 IntrinsicInst *Intr = dyn_cast<IntrinsicInst>(Call);
365 std::vector<Type*> ArgTypes;
366 for (unsigned ArgIdx = 0, ArgEnd = Call->getNumArgOperands();
367 ArgIdx != ArgEnd; ++ArgIdx) {
368 ArgTypes.push_back(Call->getArgOperand(ArgIdx)->getType());
370 Function *F = Call->getCalledFunction();
371 FunctionType *NewType = FunctionType::get(Call->getType(), ArgTypes,
373 Constant *C = Mod->getOrInsertFunction((F->getName() + ".local").str(),
374 NewType, F->getAttributes());
375 Function *NewF = cast<Function>(C);
376 Call->setCalledFunction(NewF);
380 Builder.SetInsertPoint(Intr);
381 switch (Intr->getIntrinsicID()) {
382 case Intrinsic::lifetime_start:
383 case Intrinsic::lifetime_end:
384 // These intrinsics are for address space 0 only
385 Intr->eraseFromParent();
387 case Intrinsic::memcpy: {
388 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
389 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
390 MemCpy->getLength(), MemCpy->getAlignment(),
391 MemCpy->isVolatile());
392 Intr->eraseFromParent();
395 case Intrinsic::memset: {
396 MemSetInst *MemSet = cast<MemSetInst>(Intr);
397 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
398 MemSet->getLength(), MemSet->getAlignment(),
399 MemSet->isVolatile());
400 Intr->eraseFromParent();
405 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
410 FunctionPass *llvm::createAMDGPUPromoteAlloca(const AMDGPUSubtarget &ST) {
411 return new AMDGPUPromoteAlloca(ST);