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 "Utils/AMDGPUBaseInfo.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/IR/User.h"
46 #include "llvm/IR/Value.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
62 #define DEBUG_TYPE "amdgpu-promote-alloca"
68 // FIXME: This can create globals so should be a module pass.
69 class AMDGPUPromoteAlloca : public FunctionPass {
71 const TargetMachine *TM;
72 Module *Mod = nullptr;
73 const DataLayout *DL = nullptr;
76 // FIXME: This should be per-kernel.
77 uint32_t LocalMemLimit = 0;
78 uint32_t CurrentLocalMemUsage = 0;
80 bool IsAMDGCN = false;
81 bool IsAMDHSA = false;
83 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
84 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
86 /// BaseAlloca is the alloca root the search started from.
87 /// Val may be that alloca or a recursive user of it.
88 bool collectUsesWithPtrTypes(Value *BaseAlloca,
90 std::vector<Value*> &WorkList) const;
92 /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
93 /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
94 /// Returns true if both operands are derived from the same alloca. Val should
95 /// be the same value as one of the input operands of UseInst.
96 bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
98 int OpIdx0, int OpIdx1) const;
100 /// Check whether we have enough local memory for promotion.
101 bool hasSufficientLocalMem(const Function &F);
106 AMDGPUPromoteAlloca() : FunctionPass(ID) {}
108 bool doInitialization(Module &M) override;
109 bool runOnFunction(Function &F) override;
111 StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
113 bool handleAlloca(AllocaInst &I, bool SufficientLDS);
115 void getAnalysisUsage(AnalysisUsage &AU) const override {
116 AU.setPreservesCFG();
117 FunctionPass::getAnalysisUsage(AU);
121 } // end anonymous namespace
123 char AMDGPUPromoteAlloca::ID = 0;
125 INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
126 "AMDGPU promote alloca to vector or LDS", false, false)
128 char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
130 bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
132 DL = &Mod->getDataLayout();
137 bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
141 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
142 TM = &TPC->getTM<TargetMachine>();
146 const Triple &TT = TM->getTargetTriple();
147 IsAMDGCN = TT.getArch() == Triple::amdgcn;
148 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
150 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
151 if (!ST.isPromoteAllocaEnabled())
154 AS = AMDGPU::getAMDGPUAS(*F.getParent());
156 bool SufficientLDS = hasSufficientLocalMem(F);
157 bool Changed = false;
158 BasicBlock &EntryBB = *F.begin();
159 for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
160 AllocaInst *AI = dyn_cast<AllocaInst>(I);
164 Changed |= handleAlloca(*AI, SufficientLDS);
170 std::pair<Value *, Value *>
171 AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
172 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(
173 *Builder.GetInsertBlock()->getParent());
176 Function *LocalSizeYFn
177 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
178 Function *LocalSizeZFn
179 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
181 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
182 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
184 ST.makeLIDRangeMetadata(LocalSizeY);
185 ST.makeLIDRangeMetadata(LocalSizeZ);
187 return std::make_pair(LocalSizeY, LocalSizeZ);
190 // We must read the size out of the dispatch pointer.
193 // We are indexing into this struct, and want to extract the workgroup_size_*
196 // typedef struct hsa_kernel_dispatch_packet_s {
199 // uint16_t workgroup_size_x ;
200 // uint16_t workgroup_size_y;
201 // uint16_t workgroup_size_z;
202 // uint16_t reserved0;
203 // uint32_t grid_size_x ;
204 // uint32_t grid_size_y ;
205 // uint32_t grid_size_z;
207 // uint32_t private_segment_size;
208 // uint32_t group_segment_size;
209 // uint64_t kernel_object;
211 // #ifdef HSA_LARGE_MODEL
212 // void *kernarg_address;
213 // #elif defined HSA_LITTLE_ENDIAN
214 // void *kernarg_address;
215 // uint32_t reserved1;
217 // uint32_t reserved1;
218 // void *kernarg_address;
220 // uint64_t reserved2;
221 // hsa_signal_t completion_signal; // uint64_t wrapper
222 // } hsa_kernel_dispatch_packet_t
224 Function *DispatchPtrFn
225 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
227 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
228 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
229 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
231 // Size of the dispatch packet struct.
232 DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
234 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
235 Value *CastDispatchPtr = Builder.CreateBitCast(
236 DispatchPtr, PointerType::get(I32Ty, AS.CONSTANT_ADDRESS));
238 // We could do a single 64-bit load here, but it's likely that the basic
239 // 32-bit and extract sequence is already present, and it is probably easier
240 // to CSE this. The loads should be mergable later anyway.
241 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
242 LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
244 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
245 LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
247 MDNode *MD = MDNode::get(Mod->getContext(), None);
248 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
249 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
250 ST.makeLIDRangeMetadata(LoadZU);
252 // Extract y component. Upper half of LoadZU should be zero already.
253 Value *Y = Builder.CreateLShr(LoadXY, 16);
255 return std::make_pair(Y, LoadZU);
258 Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
259 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(
260 *Builder.GetInsertBlock()->getParent());
261 Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
265 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
266 : Intrinsic::r600_read_tidig_x;
269 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
270 : Intrinsic::r600_read_tidig_y;
274 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
275 : Intrinsic::r600_read_tidig_z;
278 llvm_unreachable("invalid dimension");
281 Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
282 CallInst *CI = Builder.CreateCall(WorkitemIdFn);
283 ST.makeLIDRangeMetadata(CI);
288 static VectorType *arrayTypeToVecType(Type *ArrayTy) {
289 return VectorType::get(ArrayTy->getArrayElementType(),
290 ArrayTy->getArrayNumElements());
294 calculateVectorIndex(Value *Ptr,
295 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
296 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
298 auto I = GEPIdx.find(GEP);
299 return I == GEPIdx.end() ? nullptr : I->second;
302 static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
303 // FIXME we only support simple cases
304 if (GEP->getNumOperands() != 3)
307 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
308 if (!I0 || !I0->isZero())
311 return GEP->getOperand(2);
314 // Not an instruction handled below to turn into a vector.
316 // TODO: Check isTriviallyVectorizable for calls and handle other
318 static bool canVectorizeInst(Instruction *Inst, User *User) {
319 switch (Inst->getOpcode()) {
320 case Instruction::Load: {
321 LoadInst *LI = cast<LoadInst>(Inst);
322 return !LI->isVolatile();
324 case Instruction::BitCast:
325 case Instruction::AddrSpaceCast:
327 case Instruction::Store: {
328 // Must be the stored pointer operand, not a stored value.
329 StoreInst *SI = cast<StoreInst>(Inst);
330 return (SI->getPointerOperand() == User) && !SI->isVolatile();
337 static bool tryPromoteAllocaToVector(AllocaInst *Alloca, AMDGPUAS AS) {
338 ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
340 DEBUG(dbgs() << "Alloca candidate for vectorization\n");
342 // FIXME: There is no reason why we can't support larger arrays, we
343 // are just being conservative for now.
345 AllocaTy->getElementType()->isVectorTy() ||
346 AllocaTy->getNumElements() > 4 ||
347 AllocaTy->getNumElements() < 2) {
348 DEBUG(dbgs() << " Cannot convert type to vector\n");
352 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
353 std::vector<Value*> WorkList;
354 for (User *AllocaUser : Alloca->users()) {
355 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
357 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
360 WorkList.push_back(AllocaUser);
364 Value *Index = GEPToVectorIndex(GEP);
366 // If we can't compute a vector index from this GEP, then we can't
367 // promote this alloca to vector.
369 DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
373 GEPVectorIdx[GEP] = Index;
374 for (User *GEPUser : AllocaUser->users()) {
375 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
378 WorkList.push_back(GEPUser);
382 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
384 DEBUG(dbgs() << " Converting alloca to vector "
385 << *AllocaTy << " -> " << *VectorTy << '\n');
387 for (Value *V : WorkList) {
388 Instruction *Inst = cast<Instruction>(V);
389 IRBuilder<> Builder(Inst);
390 switch (Inst->getOpcode()) {
391 case Instruction::Load: {
392 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
393 Value *Ptr = Inst->getOperand(0);
394 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
396 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
397 Value *VecValue = Builder.CreateLoad(BitCast);
398 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
399 Inst->replaceAllUsesWith(ExtractElement);
400 Inst->eraseFromParent();
403 case Instruction::Store: {
404 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
406 Value *Ptr = Inst->getOperand(1);
407 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
408 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
409 Value *VecValue = Builder.CreateLoad(BitCast);
410 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
413 Builder.CreateStore(NewVecValue, BitCast);
414 Inst->eraseFromParent();
417 case Instruction::BitCast:
418 case Instruction::AddrSpaceCast:
422 llvm_unreachable("Inconsistency in instructions promotable to vector");
428 static bool isCallPromotable(CallInst *CI) {
429 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
433 switch (II->getIntrinsicID()) {
434 case Intrinsic::memcpy:
435 case Intrinsic::memmove:
436 case Intrinsic::memset:
437 case Intrinsic::lifetime_start:
438 case Intrinsic::lifetime_end:
439 case Intrinsic::invariant_start:
440 case Intrinsic::invariant_end:
441 case Intrinsic::invariant_group_barrier:
442 case Intrinsic::objectsize:
449 bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
454 // Figure out which operand is the one we might not be promoting.
455 Value *OtherOp = Inst->getOperand(OpIdx0);
457 OtherOp = Inst->getOperand(OpIdx1);
459 if (isa<ConstantPointerNull>(OtherOp))
462 Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
463 if (!isa<AllocaInst>(OtherObj))
466 // TODO: We should be able to replace undefs with the right pointer type.
468 // TODO: If we know the other base object is another promotable
469 // alloca, not necessarily this alloca, we can do this. The
470 // important part is both must have the same address space at
472 if (OtherObj != BaseAlloca) {
473 DEBUG(dbgs() << "Found a binary instruction with another alloca object\n");
480 bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
483 std::vector<Value*> &WorkList) const {
485 for (User *User : Val->users()) {
486 if (is_contained(WorkList, User))
489 if (CallInst *CI = dyn_cast<CallInst>(User)) {
490 if (!isCallPromotable(CI))
493 WorkList.push_back(User);
497 Instruction *UseInst = cast<Instruction>(User);
498 if (UseInst->getOpcode() == Instruction::PtrToInt)
501 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
502 if (LI->isVolatile())
508 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
509 if (SI->isVolatile())
512 // Reject if the stored value is not the pointer operand.
513 if (SI->getPointerOperand() != Val)
515 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
516 if (RMW->isVolatile())
518 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
519 if (CAS->isVolatile())
523 // Only promote a select if we know that the other select operand
524 // is from another pointer that will also be promoted.
525 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
526 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
529 // May need to rewrite constant operands.
530 WorkList.push_back(ICmp);
533 if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
534 // Give up if the pointer may be captured.
535 if (PointerMayBeCaptured(UseInst, true, true))
537 // Don't collect the users of this.
538 WorkList.push_back(User);
542 if (!User->getType()->isPointerTy())
545 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
546 // Be conservative if an address could be computed outside the bounds of
548 if (!GEP->isInBounds())
552 // Only promote a select if we know that the other select operand is from
553 // another pointer that will also be promoted.
554 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
555 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
560 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
561 // TODO: Handle more complex cases. We should be able to replace loops
563 switch (Phi->getNumIncomingValues()) {
567 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
575 WorkList.push_back(User);
576 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
583 bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
585 FunctionType *FTy = F.getFunctionType();
586 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
588 // If the function has any arguments in the local address space, then it's
589 // possible these arguments require the entire local memory space, so
590 // we cannot use local memory in the pass.
591 for (Type *ParamTy : FTy->params()) {
592 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
593 if (PtrTy && PtrTy->getAddressSpace() == AS.LOCAL_ADDRESS) {
595 DEBUG(dbgs() << "Function has local memory argument. Promoting to "
596 "local memory disabled.\n");
601 LocalMemLimit = ST.getLocalMemorySize();
602 if (LocalMemLimit == 0)
605 const DataLayout &DL = Mod->getDataLayout();
607 // Check how much local memory is being used by global objects
608 CurrentLocalMemUsage = 0;
609 for (GlobalVariable &GV : Mod->globals()) {
610 if (GV.getType()->getAddressSpace() != AS.LOCAL_ADDRESS)
613 for (const User *U : GV.users()) {
614 const Instruction *Use = dyn_cast<Instruction>(U);
618 if (Use->getParent()->getParent() == &F) {
619 unsigned Align = GV.getAlignment();
621 Align = DL.getABITypeAlignment(GV.getValueType());
623 // FIXME: Try to account for padding here. The padding is currently
624 // determined from the inverse order of uses in the function. I'm not
625 // sure if the use list order is in any way connected to this, so the
626 // total reported size is likely incorrect.
627 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
628 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
629 CurrentLocalMemUsage += AllocSize;
635 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
638 // Restrict local memory usage so that we don't drastically reduce occupancy,
639 // unless it is already significantly reduced.
641 // TODO: Have some sort of hint or other heuristics to guess occupancy based
642 // on other factors..
643 unsigned OccupancyHint = ST.getWavesPerEU(F).second;
644 if (OccupancyHint == 0)
647 // Clamp to max value.
648 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
650 // Check the hint but ignore it if it's obviously wrong from the existing LDS
652 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
655 // Round up to the next tier of usage.
656 unsigned MaxSizeWithWaveCount
657 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
659 // Program is possibly broken by using more local mem than available.
660 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
663 LocalMemLimit = MaxSizeWithWaveCount;
666 dbgs() << F.getName() << " uses " << CurrentLocalMemUsage << " bytes of LDS\n"
667 << " Rounding size to " << MaxSizeWithWaveCount
668 << " with a maximum occupancy of " << MaxOccupancy << '\n'
669 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
670 << " available for promotion\n"
676 // FIXME: Should try to pick the most likely to be profitable allocas first.
677 bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
678 // Array allocations are probably not worth handling, since an allocation of
679 // the array type is the canonical form.
680 if (!I.isStaticAlloca() || I.isArrayAllocation())
683 IRBuilder<> Builder(&I);
685 // First try to replace the alloca with a vector
686 Type *AllocaTy = I.getAllocatedType();
688 DEBUG(dbgs() << "Trying to promote " << I << '\n');
690 if (tryPromoteAllocaToVector(&I, AS))
691 return true; // Promoted to vector.
693 const Function &ContainingFunction = *I.getParent()->getParent();
694 CallingConv::ID CC = ContainingFunction.getCallingConv();
696 // Don't promote the alloca to LDS for shader calling conventions as the work
697 // item ID intrinsics are not supported for these calling conventions.
698 // Furthermore not all LDS is available for some of the stages.
700 case CallingConv::AMDGPU_KERNEL:
701 case CallingConv::SPIR_KERNEL:
704 DEBUG(dbgs() << " promote alloca to LDS not supported with calling convention.\n");
708 // Not likely to have sufficient local memory for promotion.
712 const AMDGPUSubtarget &ST =
713 TM->getSubtarget<AMDGPUSubtarget>(ContainingFunction);
714 unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
716 const DataLayout &DL = Mod->getDataLayout();
718 unsigned Align = I.getAlignment();
720 Align = DL.getABITypeAlignment(I.getAllocatedType());
722 // FIXME: This computed padding is likely wrong since it depends on inverse
725 // FIXME: It is also possible that if we're allowed to use all of the memory
726 // could could end up using more than the maximum due to alignment padding.
728 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
729 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
730 NewSize += AllocSize;
732 if (NewSize > LocalMemLimit) {
733 DEBUG(dbgs() << " " << AllocSize
734 << " bytes of local memory not available to promote\n");
738 CurrentLocalMemUsage = NewSize;
740 std::vector<Value*> WorkList;
742 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
743 DEBUG(dbgs() << " Do not know how to convert all uses\n");
747 DEBUG(dbgs() << "Promoting alloca to local memory\n");
749 Function *F = I.getParent()->getParent();
751 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
752 GlobalVariable *GV = new GlobalVariable(
753 *Mod, GVTy, false, GlobalValue::InternalLinkage,
754 UndefValue::get(GVTy),
755 Twine(F->getName()) + Twine('.') + I.getName(),
757 GlobalVariable::NotThreadLocal,
759 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
760 GV->setAlignment(I.getAlignment());
762 Value *TCntY, *TCntZ;
764 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
765 Value *TIdX = getWorkitemID(Builder, 0);
766 Value *TIdY = getWorkitemID(Builder, 1);
767 Value *TIdZ = getWorkitemID(Builder, 2);
769 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
770 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
771 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
772 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
773 TID = Builder.CreateAdd(TID, TIdZ);
776 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
780 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
781 I.mutateType(Offset->getType());
782 I.replaceAllUsesWith(Offset);
785 for (Value *V : WorkList) {
786 CallInst *Call = dyn_cast<CallInst>(V);
788 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
789 Value *Src0 = CI->getOperand(0);
790 Type *EltTy = Src0->getType()->getPointerElementType();
791 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
793 if (isa<ConstantPointerNull>(CI->getOperand(0)))
794 CI->setOperand(0, ConstantPointerNull::get(NewTy));
796 if (isa<ConstantPointerNull>(CI->getOperand(1)))
797 CI->setOperand(1, ConstantPointerNull::get(NewTy));
802 // The operand's value should be corrected on its own and we don't want to
804 if (isa<AddrSpaceCastInst>(V))
807 Type *EltTy = V->getType()->getPointerElementType();
808 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
810 // FIXME: It doesn't really make sense to try to do this for all
812 V->mutateType(NewTy);
814 // Adjust the types of any constant operands.
815 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
816 if (isa<ConstantPointerNull>(SI->getOperand(1)))
817 SI->setOperand(1, ConstantPointerNull::get(NewTy));
819 if (isa<ConstantPointerNull>(SI->getOperand(2)))
820 SI->setOperand(2, ConstantPointerNull::get(NewTy));
821 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
822 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
823 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
824 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
831 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
832 Builder.SetInsertPoint(Intr);
833 switch (Intr->getIntrinsicID()) {
834 case Intrinsic::lifetime_start:
835 case Intrinsic::lifetime_end:
836 // These intrinsics are for address space 0 only
837 Intr->eraseFromParent();
839 case Intrinsic::memcpy: {
840 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
841 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
842 MemCpy->getLength(), MemCpy->getAlignment(),
843 MemCpy->isVolatile());
844 Intr->eraseFromParent();
847 case Intrinsic::memmove: {
848 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
849 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getRawSource(),
850 MemMove->getLength(), MemMove->getAlignment(),
851 MemMove->isVolatile());
852 Intr->eraseFromParent();
855 case Intrinsic::memset: {
856 MemSetInst *MemSet = cast<MemSetInst>(Intr);
857 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
858 MemSet->getLength(), MemSet->getAlignment(),
859 MemSet->isVolatile());
860 Intr->eraseFromParent();
863 case Intrinsic::invariant_start:
864 case Intrinsic::invariant_end:
865 case Intrinsic::invariant_group_barrier:
866 Intr->eraseFromParent();
867 // FIXME: I think the invariant marker should still theoretically apply,
868 // but the intrinsics need to be changed to accept pointers with any
871 case Intrinsic::objectsize: {
872 Value *Src = Intr->getOperand(0);
873 Type *SrcTy = Src->getType()->getPointerElementType();
874 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
875 Intrinsic::objectsize,
876 { Intr->getType(), PointerType::get(SrcTy, AS.LOCAL_ADDRESS) }
879 CallInst *NewCall = Builder.CreateCall(
880 ObjectSize, {Src, Intr->getOperand(1), Intr->getOperand(2)});
881 Intr->replaceAllUsesWith(NewCall);
882 Intr->eraseFromParent();
887 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
893 FunctionPass *llvm::createAMDGPUPromoteAlloca() {
894 return new AMDGPUPromoteAlloca();