xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass eliminates allocas by either converting them into vectors or
100b57cec5SDimitry Andric // by migrating them to local address space.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "AMDGPU.h"
15e8d8bef9SDimitry Andric #include "GCNSubtarget.h"
161fd87a68SDimitry Andric #include "Utils/AMDGPUBaseInfo.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
200b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
211fd87a68SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
22480093f4SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
23480093f4SDimitry Andric #include "llvm/IR/IntrinsicsR600.h"
240b57cec5SDimitry Andric #include "llvm/Pass.h"
250b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-promote-alloca"
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric using namespace llvm;
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric namespace {
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToVector(
340b57cec5SDimitry Andric   "disable-promote-alloca-to-vector",
350b57cec5SDimitry Andric   cl::desc("Disable promote alloca to vector"),
360b57cec5SDimitry Andric   cl::init(false));
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToLDS(
390b57cec5SDimitry Andric   "disable-promote-alloca-to-lds",
400b57cec5SDimitry Andric   cl::desc("Disable promote alloca to LDS"),
410b57cec5SDimitry Andric   cl::init(false));
420b57cec5SDimitry Andric 
435ffd83dbSDimitry Andric static cl::opt<unsigned> PromoteAllocaToVectorLimit(
445ffd83dbSDimitry Andric   "amdgpu-promote-alloca-to-vector-limit",
455ffd83dbSDimitry Andric   cl::desc("Maximum byte size to consider promote alloca to vector"),
465ffd83dbSDimitry Andric   cl::init(0));
475ffd83dbSDimitry Andric 
480b57cec5SDimitry Andric // FIXME: This can create globals so should be a module pass.
490b57cec5SDimitry Andric class AMDGPUPromoteAlloca : public FunctionPass {
50e8d8bef9SDimitry Andric public:
51e8d8bef9SDimitry Andric   static char ID;
52e8d8bef9SDimitry Andric 
53e8d8bef9SDimitry Andric   AMDGPUPromoteAlloca() : FunctionPass(ID) {}
54e8d8bef9SDimitry Andric 
55e8d8bef9SDimitry Andric   bool runOnFunction(Function &F) override;
56e8d8bef9SDimitry Andric 
57e8d8bef9SDimitry Andric   StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
58e8d8bef9SDimitry Andric 
59e8d8bef9SDimitry Andric   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
60e8d8bef9SDimitry Andric 
61e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
62e8d8bef9SDimitry Andric     AU.setPreservesCFG();
63e8d8bef9SDimitry Andric     FunctionPass::getAnalysisUsage(AU);
64e8d8bef9SDimitry Andric   }
65e8d8bef9SDimitry Andric };
66e8d8bef9SDimitry Andric 
67e8d8bef9SDimitry Andric class AMDGPUPromoteAllocaImpl {
680b57cec5SDimitry Andric private:
69e8d8bef9SDimitry Andric   const TargetMachine &TM;
700b57cec5SDimitry Andric   Module *Mod = nullptr;
710b57cec5SDimitry Andric   const DataLayout *DL = nullptr;
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   // FIXME: This should be per-kernel.
740b57cec5SDimitry Andric   uint32_t LocalMemLimit = 0;
750b57cec5SDimitry Andric   uint32_t CurrentLocalMemUsage = 0;
765ffd83dbSDimitry Andric   unsigned MaxVGPRs;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   bool IsAMDGCN = false;
790b57cec5SDimitry Andric   bool IsAMDHSA = false;
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric   std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
820b57cec5SDimitry Andric   Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric   /// BaseAlloca is the alloca root the search started from.
850b57cec5SDimitry Andric   /// Val may be that alloca or a recursive user of it.
860b57cec5SDimitry Andric   bool collectUsesWithPtrTypes(Value *BaseAlloca,
870b57cec5SDimitry Andric                                Value *Val,
880b57cec5SDimitry Andric                                std::vector<Value*> &WorkList) const;
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
910b57cec5SDimitry Andric   /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
920b57cec5SDimitry Andric   /// Returns true if both operands are derived from the same alloca. Val should
930b57cec5SDimitry Andric   /// be the same value as one of the input operands of UseInst.
940b57cec5SDimitry Andric   bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
950b57cec5SDimitry Andric                                        Instruction *UseInst,
960b57cec5SDimitry Andric                                        int OpIdx0, int OpIdx1) const;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   /// Check whether we have enough local memory for promotion.
990b57cec5SDimitry Andric   bool hasSufficientLocalMem(const Function &F);
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
1020b57cec5SDimitry Andric 
103e8d8bef9SDimitry Andric public:
104e8d8bef9SDimitry Andric   AMDGPUPromoteAllocaImpl(TargetMachine &TM) : TM(TM) {}
105e8d8bef9SDimitry Andric   bool run(Function &F);
1060b57cec5SDimitry Andric };
1070b57cec5SDimitry Andric 
1085ffd83dbSDimitry Andric class AMDGPUPromoteAllocaToVector : public FunctionPass {
1095ffd83dbSDimitry Andric public:
1105ffd83dbSDimitry Andric   static char ID;
1115ffd83dbSDimitry Andric 
1125ffd83dbSDimitry Andric   AMDGPUPromoteAllocaToVector() : FunctionPass(ID) {}
1135ffd83dbSDimitry Andric 
1145ffd83dbSDimitry Andric   bool runOnFunction(Function &F) override;
1155ffd83dbSDimitry Andric 
1165ffd83dbSDimitry Andric   StringRef getPassName() const override {
1175ffd83dbSDimitry Andric     return "AMDGPU Promote Alloca to vector";
1185ffd83dbSDimitry Andric   }
1195ffd83dbSDimitry Andric 
1205ffd83dbSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1215ffd83dbSDimitry Andric     AU.setPreservesCFG();
1225ffd83dbSDimitry Andric     FunctionPass::getAnalysisUsage(AU);
1235ffd83dbSDimitry Andric   }
1245ffd83dbSDimitry Andric };
1255ffd83dbSDimitry Andric 
1260b57cec5SDimitry Andric } // end anonymous namespace
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric char AMDGPUPromoteAlloca::ID = 0;
1295ffd83dbSDimitry Andric char AMDGPUPromoteAllocaToVector::ID = 0;
1300b57cec5SDimitry Andric 
131fe6060f1SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUPromoteAlloca, DEBUG_TYPE,
132fe6060f1SDimitry Andric                       "AMDGPU promote alloca to vector or LDS", false, false)
133fe6060f1SDimitry Andric // Move LDS uses from functions to kernels before promote alloca for accurate
134fe6060f1SDimitry Andric // estimation of LDS available
135fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AMDGPULowerModuleLDS)
136fe6060f1SDimitry Andric INITIALIZE_PASS_END(AMDGPUPromoteAlloca, DEBUG_TYPE,
1370b57cec5SDimitry Andric                     "AMDGPU promote alloca to vector or LDS", false, false)
1380b57cec5SDimitry Andric 
1395ffd83dbSDimitry Andric INITIALIZE_PASS(AMDGPUPromoteAllocaToVector, DEBUG_TYPE "-to-vector",
1405ffd83dbSDimitry Andric                 "AMDGPU promote alloca to vector", false, false)
1415ffd83dbSDimitry Andric 
1420b57cec5SDimitry Andric char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
1435ffd83dbSDimitry Andric char &llvm::AMDGPUPromoteAllocaToVectorID = AMDGPUPromoteAllocaToVector::ID;
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
1460b57cec5SDimitry Andric   if (skipFunction(F))
1470b57cec5SDimitry Andric     return false;
1480b57cec5SDimitry Andric 
149e8d8bef9SDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
150e8d8bef9SDimitry Andric     return AMDGPUPromoteAllocaImpl(TPC->getTM<TargetMachine>()).run(F);
151e8d8bef9SDimitry Andric   }
1520b57cec5SDimitry Andric   return false;
153e8d8bef9SDimitry Andric }
1540b57cec5SDimitry Andric 
155e8d8bef9SDimitry Andric PreservedAnalyses AMDGPUPromoteAllocaPass::run(Function &F,
156e8d8bef9SDimitry Andric                                                FunctionAnalysisManager &AM) {
157e8d8bef9SDimitry Andric   bool Changed = AMDGPUPromoteAllocaImpl(TM).run(F);
158e8d8bef9SDimitry Andric   if (Changed) {
159e8d8bef9SDimitry Andric     PreservedAnalyses PA;
160e8d8bef9SDimitry Andric     PA.preserveSet<CFGAnalyses>();
161e8d8bef9SDimitry Andric     return PA;
162e8d8bef9SDimitry Andric   }
163e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
164e8d8bef9SDimitry Andric }
165e8d8bef9SDimitry Andric 
166e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::run(Function &F) {
167e8d8bef9SDimitry Andric   Mod = F.getParent();
168e8d8bef9SDimitry Andric   DL = &Mod->getDataLayout();
169e8d8bef9SDimitry Andric 
170e8d8bef9SDimitry Andric   const Triple &TT = TM.getTargetTriple();
1710b57cec5SDimitry Andric   IsAMDGCN = TT.getArch() == Triple::amdgcn;
1720b57cec5SDimitry Andric   IsAMDHSA = TT.getOS() == Triple::AMDHSA;
1730b57cec5SDimitry Andric 
174e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
1750b57cec5SDimitry Andric   if (!ST.isPromoteAllocaEnabled())
1760b57cec5SDimitry Andric     return false;
1770b57cec5SDimitry Andric 
1785ffd83dbSDimitry Andric   if (IsAMDGCN) {
179e8d8bef9SDimitry Andric     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
1805ffd83dbSDimitry Andric     MaxVGPRs = ST.getMaxNumVGPRs(ST.getWavesPerEU(F).first);
181349cc55cSDimitry Andric     // A non-entry function has only 32 caller preserved registers.
182349cc55cSDimitry Andric     // Do not promote alloca which will force spilling.
183349cc55cSDimitry Andric     if (!AMDGPU::isEntryFunctionCC(F.getCallingConv()))
184349cc55cSDimitry Andric       MaxVGPRs = std::min(MaxVGPRs, 32u);
1855ffd83dbSDimitry Andric   } else {
1865ffd83dbSDimitry Andric     MaxVGPRs = 128;
1875ffd83dbSDimitry Andric   }
1885ffd83dbSDimitry Andric 
1890b57cec5SDimitry Andric   bool SufficientLDS = hasSufficientLocalMem(F);
1900b57cec5SDimitry Andric   bool Changed = false;
1910b57cec5SDimitry Andric   BasicBlock &EntryBB = *F.begin();
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
1940b57cec5SDimitry Andric   for (Instruction &I : EntryBB) {
1950b57cec5SDimitry Andric     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
1960b57cec5SDimitry Andric       Allocas.push_back(AI);
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   for (AllocaInst *AI : Allocas) {
2000b57cec5SDimitry Andric     if (handleAlloca(*AI, SufficientLDS))
2010b57cec5SDimitry Andric       Changed = true;
2020b57cec5SDimitry Andric   }
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   return Changed;
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric std::pair<Value *, Value *>
208e8d8bef9SDimitry Andric AMDGPUPromoteAllocaImpl::getLocalSizeYZ(IRBuilder<> &Builder) {
209349cc55cSDimitry Andric   Function &F = *Builder.GetInsertBlock()->getParent();
210e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   if (!IsAMDHSA) {
2130b57cec5SDimitry Andric     Function *LocalSizeYFn
2140b57cec5SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
2150b57cec5SDimitry Andric     Function *LocalSizeZFn
2160b57cec5SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric     CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
2190b57cec5SDimitry Andric     CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeY);
2220b57cec5SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeZ);
2230b57cec5SDimitry Andric 
224*bdd1243dSDimitry Andric     return std::pair(LocalSizeY, LocalSizeZ);
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   // We must read the size out of the dispatch pointer.
2280b57cec5SDimitry Andric   assert(IsAMDGCN);
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   // We are indexing into this struct, and want to extract the workgroup_size_*
2310b57cec5SDimitry Andric   // fields.
2320b57cec5SDimitry Andric   //
2330b57cec5SDimitry Andric   //   typedef struct hsa_kernel_dispatch_packet_s {
2340b57cec5SDimitry Andric   //     uint16_t header;
2350b57cec5SDimitry Andric   //     uint16_t setup;
2360b57cec5SDimitry Andric   //     uint16_t workgroup_size_x ;
2370b57cec5SDimitry Andric   //     uint16_t workgroup_size_y;
2380b57cec5SDimitry Andric   //     uint16_t workgroup_size_z;
2390b57cec5SDimitry Andric   //     uint16_t reserved0;
2400b57cec5SDimitry Andric   //     uint32_t grid_size_x ;
2410b57cec5SDimitry Andric   //     uint32_t grid_size_y ;
2420b57cec5SDimitry Andric   //     uint32_t grid_size_z;
2430b57cec5SDimitry Andric   //
2440b57cec5SDimitry Andric   //     uint32_t private_segment_size;
2450b57cec5SDimitry Andric   //     uint32_t group_segment_size;
2460b57cec5SDimitry Andric   //     uint64_t kernel_object;
2470b57cec5SDimitry Andric   //
2480b57cec5SDimitry Andric   // #ifdef HSA_LARGE_MODEL
2490b57cec5SDimitry Andric   //     void *kernarg_address;
2500b57cec5SDimitry Andric   // #elif defined HSA_LITTLE_ENDIAN
2510b57cec5SDimitry Andric   //     void *kernarg_address;
2520b57cec5SDimitry Andric   //     uint32_t reserved1;
2530b57cec5SDimitry Andric   // #else
2540b57cec5SDimitry Andric   //     uint32_t reserved1;
2550b57cec5SDimitry Andric   //     void *kernarg_address;
2560b57cec5SDimitry Andric   // #endif
2570b57cec5SDimitry Andric   //     uint64_t reserved2;
2580b57cec5SDimitry Andric   //     hsa_signal_t completion_signal; // uint64_t wrapper
2590b57cec5SDimitry Andric   //   } hsa_kernel_dispatch_packet_t
2600b57cec5SDimitry Andric   //
2610b57cec5SDimitry Andric   Function *DispatchPtrFn
2620b57cec5SDimitry Andric     = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
265349cc55cSDimitry Andric   DispatchPtr->addRetAttr(Attribute::NoAlias);
266349cc55cSDimitry Andric   DispatchPtr->addRetAttr(Attribute::NonNull);
267349cc55cSDimitry Andric   F.removeFnAttr("amdgpu-no-dispatch-ptr");
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric   // Size of the dispatch packet struct.
270349cc55cSDimitry Andric   DispatchPtr->addDereferenceableRetAttr(64);
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   Type *I32Ty = Type::getInt32Ty(Mod->getContext());
2730b57cec5SDimitry Andric   Value *CastDispatchPtr = Builder.CreateBitCast(
2740b57cec5SDimitry Andric     DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   // We could do a single 64-bit load here, but it's likely that the basic
2770b57cec5SDimitry Andric   // 32-bit and extract sequence is already present, and it is probably easier
278349cc55cSDimitry Andric   // to CSE this. The loads should be mergeable later anyway.
2790b57cec5SDimitry Andric   Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 1);
2805ffd83dbSDimitry Andric   LoadInst *LoadXY = Builder.CreateAlignedLoad(I32Ty, GEPXY, Align(4));
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 2);
2835ffd83dbSDimitry Andric   LoadInst *LoadZU = Builder.CreateAlignedLoad(I32Ty, GEPZU, Align(4));
2840b57cec5SDimitry Andric 
285*bdd1243dSDimitry Andric   MDNode *MD = MDNode::get(Mod->getContext(), std::nullopt);
2860b57cec5SDimitry Andric   LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
2870b57cec5SDimitry Andric   LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
2880b57cec5SDimitry Andric   ST.makeLIDRangeMetadata(LoadZU);
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   // Extract y component. Upper half of LoadZU should be zero already.
2910b57cec5SDimitry Andric   Value *Y = Builder.CreateLShr(LoadXY, 16);
2920b57cec5SDimitry Andric 
293*bdd1243dSDimitry Andric   return std::pair(Y, LoadZU);
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric 
296e8d8bef9SDimitry Andric Value *AMDGPUPromoteAllocaImpl::getWorkitemID(IRBuilder<> &Builder,
297e8d8bef9SDimitry Andric                                               unsigned N) {
298349cc55cSDimitry Andric   Function *F = Builder.GetInsertBlock()->getParent();
299349cc55cSDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, *F);
300480093f4SDimitry Andric   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
301349cc55cSDimitry Andric   StringRef AttrName;
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   switch (N) {
3040b57cec5SDimitry Andric   case 0:
305480093f4SDimitry Andric     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_x
306480093f4SDimitry Andric                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_x;
307349cc55cSDimitry Andric     AttrName = "amdgpu-no-workitem-id-x";
3080b57cec5SDimitry Andric     break;
3090b57cec5SDimitry Andric   case 1:
310480093f4SDimitry Andric     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_y
311480093f4SDimitry Andric                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_y;
312349cc55cSDimitry Andric     AttrName = "amdgpu-no-workitem-id-y";
3130b57cec5SDimitry Andric     break;
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   case 2:
316480093f4SDimitry Andric     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_z
317480093f4SDimitry Andric                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_z;
318349cc55cSDimitry Andric     AttrName = "amdgpu-no-workitem-id-z";
3190b57cec5SDimitry Andric     break;
3200b57cec5SDimitry Andric   default:
3210b57cec5SDimitry Andric     llvm_unreachable("invalid dimension");
3220b57cec5SDimitry Andric   }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
3250b57cec5SDimitry Andric   CallInst *CI = Builder.CreateCall(WorkitemIdFn);
3260b57cec5SDimitry Andric   ST.makeLIDRangeMetadata(CI);
327349cc55cSDimitry Andric   F->removeFnAttr(AttrName);
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   return CI;
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric 
3325ffd83dbSDimitry Andric static FixedVectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
3335ffd83dbSDimitry Andric   return FixedVectorType::get(ArrayTy->getElementType(),
3340b57cec5SDimitry Andric                               ArrayTy->getNumElements());
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric static Value *
3380b57cec5SDimitry Andric calculateVectorIndex(Value *Ptr,
3390b57cec5SDimitry Andric                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
34081ad6265SDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts());
3415ffd83dbSDimitry Andric   if (!GEP)
34281ad6265SDimitry Andric     return ConstantInt::getNullValue(Type::getInt32Ty(Ptr->getContext()));
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   auto I = GEPIdx.find(GEP);
34581ad6265SDimitry Andric   assert(I != GEPIdx.end() && "Must have entry for GEP!");
34681ad6265SDimitry Andric   return I->second;
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
34981ad6265SDimitry Andric static Value *GEPToVectorIndex(GetElementPtrInst *GEP, AllocaInst *Alloca,
35081ad6265SDimitry Andric                                Type *VecElemTy, const DataLayout &DL) {
35181ad6265SDimitry Andric   // TODO: Extracting a "multiple of X" from a GEP might be a useful generic
35281ad6265SDimitry Andric   // helper.
35381ad6265SDimitry Andric   unsigned BW = DL.getIndexTypeSizeInBits(GEP->getType());
35481ad6265SDimitry Andric   MapVector<Value *, APInt> VarOffsets;
35581ad6265SDimitry Andric   APInt ConstOffset(BW, 0);
35681ad6265SDimitry Andric   if (GEP->getPointerOperand()->stripPointerCasts() != Alloca ||
35781ad6265SDimitry Andric       !GEP->collectOffset(DL, BW, VarOffsets, ConstOffset))
3580b57cec5SDimitry Andric     return nullptr;
3590b57cec5SDimitry Andric 
36081ad6265SDimitry Andric   unsigned VecElemSize = DL.getTypeAllocSize(VecElemTy);
36181ad6265SDimitry Andric   if (VarOffsets.size() > 1)
3620b57cec5SDimitry Andric     return nullptr;
3630b57cec5SDimitry Andric 
36481ad6265SDimitry Andric   if (VarOffsets.size() == 1) {
36581ad6265SDimitry Andric     // Only handle cases where we don't need to insert extra arithmetic
3660b57cec5SDimitry Andric     // instructions.
36781ad6265SDimitry Andric     const auto &VarOffset = VarOffsets.front();
36881ad6265SDimitry Andric     if (!ConstOffset.isZero() || VarOffset.second != VecElemSize)
36981ad6265SDimitry Andric       return nullptr;
37081ad6265SDimitry Andric     return VarOffset.first;
3710b57cec5SDimitry Andric   }
3725ffd83dbSDimitry Andric 
37381ad6265SDimitry Andric   APInt Quot;
37481ad6265SDimitry Andric   uint64_t Rem;
37581ad6265SDimitry Andric   APInt::udivrem(ConstOffset, VecElemSize, Quot, Rem);
37681ad6265SDimitry Andric   if (Rem != 0)
37781ad6265SDimitry Andric     return nullptr;
3785ffd83dbSDimitry Andric 
37981ad6265SDimitry Andric   return ConstantInt::get(GEP->getContext(), Quot);
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric 
382*bdd1243dSDimitry Andric struct MemTransferInfo {
383*bdd1243dSDimitry Andric   ConstantInt *SrcIndex = nullptr;
384*bdd1243dSDimitry Andric   ConstantInt *DestIndex = nullptr;
385*bdd1243dSDimitry Andric };
386*bdd1243dSDimitry Andric 
3875ffd83dbSDimitry Andric static bool tryPromoteAllocaToVector(AllocaInst *Alloca, const DataLayout &DL,
3885ffd83dbSDimitry Andric                                      unsigned MaxVGPRs) {
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   if (DisablePromoteAllocaToVector) {
3910b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
3920b57cec5SDimitry Andric     return false;
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
3955ffd83dbSDimitry Andric   Type *AllocaTy = Alloca->getAllocatedType();
3965ffd83dbSDimitry Andric   auto *VectorTy = dyn_cast<FixedVectorType>(AllocaTy);
3975ffd83dbSDimitry Andric   if (auto *ArrayTy = dyn_cast<ArrayType>(AllocaTy)) {
3985ffd83dbSDimitry Andric     if (VectorType::isValidElementType(ArrayTy->getElementType()) &&
3995ffd83dbSDimitry Andric         ArrayTy->getNumElements() > 0)
4005ffd83dbSDimitry Andric       VectorTy = arrayTypeToVecType(ArrayTy);
4015ffd83dbSDimitry Andric   }
4025ffd83dbSDimitry Andric 
4035ffd83dbSDimitry Andric   // Use up to 1/4 of available register budget for vectorization.
4045ffd83dbSDimitry Andric   unsigned Limit = PromoteAllocaToVectorLimit ? PromoteAllocaToVectorLimit * 8
4055ffd83dbSDimitry Andric                                               : (MaxVGPRs * 32);
4065ffd83dbSDimitry Andric 
4075ffd83dbSDimitry Andric   if (DL.getTypeSizeInBits(AllocaTy) * 4 > Limit) {
4085ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "  Alloca too big for vectorization with "
4095ffd83dbSDimitry Andric                       << MaxVGPRs << " registers available\n");
4105ffd83dbSDimitry Andric     return false;
4115ffd83dbSDimitry Andric   }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   // FIXME: There is no reason why we can't support larger arrays, we
4160b57cec5SDimitry Andric   // are just being conservative for now.
4170b57cec5SDimitry Andric   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
4180b57cec5SDimitry Andric   // could also be promoted but we don't currently handle this case
4195ffd83dbSDimitry Andric   if (!VectorTy || VectorTy->getNumElements() > 16 ||
4205ffd83dbSDimitry Andric       VectorTy->getNumElements() < 2) {
4210b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
4220b57cec5SDimitry Andric     return false;
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
42681ad6265SDimitry Andric   SmallVector<Instruction *> WorkList;
427*bdd1243dSDimitry Andric   SmallVector<Instruction *> DeferredInsts;
42881ad6265SDimitry Andric   SmallVector<Use *, 8> Uses;
429*bdd1243dSDimitry Andric   DenseMap<MemTransferInst *, MemTransferInfo> TransferInfo;
430*bdd1243dSDimitry Andric 
43181ad6265SDimitry Andric   for (Use &U : Alloca->uses())
43281ad6265SDimitry Andric     Uses.push_back(&U);
4335ffd83dbSDimitry Andric 
43481ad6265SDimitry Andric   Type *VecEltTy = VectorTy->getElementType();
435*bdd1243dSDimitry Andric   unsigned ElementSize = DL.getTypeSizeInBits(VecEltTy) / 8;
43681ad6265SDimitry Andric   while (!Uses.empty()) {
43781ad6265SDimitry Andric     Use *U = Uses.pop_back_val();
438*bdd1243dSDimitry Andric     Instruction *Inst = cast<Instruction>(U->getUser());
43981ad6265SDimitry Andric 
44081ad6265SDimitry Andric     if (Value *Ptr = getLoadStorePointerOperand(Inst)) {
44181ad6265SDimitry Andric       // This is a store of the pointer, not to the pointer.
44281ad6265SDimitry Andric       if (isa<StoreInst>(Inst) &&
44381ad6265SDimitry Andric           U->getOperandNo() != StoreInst::getPointerOperandIndex())
4440b57cec5SDimitry Andric         return false;
4450b57cec5SDimitry Andric 
44681ad6265SDimitry Andric       Type *AccessTy = getLoadStoreType(Inst);
44781ad6265SDimitry Andric       Ptr = Ptr->stripPointerCasts();
44881ad6265SDimitry Andric 
44981ad6265SDimitry Andric       // Alloca already accessed as vector, leave alone.
45081ad6265SDimitry Andric       if (Ptr == Alloca && DL.getTypeStoreSize(Alloca->getAllocatedType()) ==
45181ad6265SDimitry Andric                                DL.getTypeStoreSize(AccessTy))
4525ffd83dbSDimitry Andric         continue;
4535ffd83dbSDimitry Andric 
45481ad6265SDimitry Andric       // Check that this is a simple access of a vector element.
45581ad6265SDimitry Andric       bool IsSimple = isa<LoadInst>(Inst) ? cast<LoadInst>(Inst)->isSimple()
45681ad6265SDimitry Andric                                           : cast<StoreInst>(Inst)->isSimple();
45781ad6265SDimitry Andric       if (!IsSimple ||
45881ad6265SDimitry Andric           !CastInst::isBitOrNoopPointerCastable(VecEltTy, AccessTy, DL))
45981ad6265SDimitry Andric         return false;
4605ffd83dbSDimitry Andric 
46181ad6265SDimitry Andric       WorkList.push_back(Inst);
4625ffd83dbSDimitry Andric       continue;
4635ffd83dbSDimitry Andric     }
4645ffd83dbSDimitry Andric 
46581ad6265SDimitry Andric     if (isa<BitCastInst>(Inst)) {
46681ad6265SDimitry Andric       // Look through bitcasts.
46781ad6265SDimitry Andric       for (Use &U : Inst->uses())
46881ad6265SDimitry Andric         Uses.push_back(&U);
4690b57cec5SDimitry Andric       continue;
4700b57cec5SDimitry Andric     }
4710b57cec5SDimitry Andric 
47281ad6265SDimitry Andric     if (auto *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
4730b57cec5SDimitry Andric       // If we can't compute a vector index from this GEP, then we can't
4740b57cec5SDimitry Andric       // promote this alloca to vector.
47581ad6265SDimitry Andric       Value *Index = GEPToVectorIndex(GEP, Alloca, VecEltTy, DL);
4760b57cec5SDimitry Andric       if (!Index) {
4770b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
4780b57cec5SDimitry Andric                           << '\n');
4790b57cec5SDimitry Andric         return false;
4800b57cec5SDimitry Andric       }
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric       GEPVectorIdx[GEP] = Index;
48381ad6265SDimitry Andric       for (Use &U : Inst->uses())
48481ad6265SDimitry Andric         Uses.push_back(&U);
48581ad6265SDimitry Andric       continue;
48681ad6265SDimitry Andric     }
48781ad6265SDimitry Andric 
488*bdd1243dSDimitry Andric     if (MemTransferInst *TransferInst = dyn_cast<MemTransferInst>(Inst)) {
489*bdd1243dSDimitry Andric       if (TransferInst->isVolatile())
490*bdd1243dSDimitry Andric         return false;
491*bdd1243dSDimitry Andric 
492*bdd1243dSDimitry Andric       ConstantInt *Len = dyn_cast<ConstantInt>(TransferInst->getLength());
493*bdd1243dSDimitry Andric       if (!Len || !!(Len->getZExtValue() % ElementSize))
494*bdd1243dSDimitry Andric         return false;
495*bdd1243dSDimitry Andric 
496*bdd1243dSDimitry Andric       if (!TransferInfo.count(TransferInst)) {
497*bdd1243dSDimitry Andric         DeferredInsts.push_back(Inst);
498*bdd1243dSDimitry Andric         WorkList.push_back(Inst);
499*bdd1243dSDimitry Andric         TransferInfo[TransferInst] = MemTransferInfo();
500*bdd1243dSDimitry Andric       }
501*bdd1243dSDimitry Andric 
502*bdd1243dSDimitry Andric       auto getPointerIndexOfAlloca = [&](Value *Ptr) -> ConstantInt * {
503*bdd1243dSDimitry Andric         GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
504*bdd1243dSDimitry Andric         if (Ptr != Alloca && !GEPVectorIdx.count(GEP))
505*bdd1243dSDimitry Andric           return nullptr;
506*bdd1243dSDimitry Andric 
507*bdd1243dSDimitry Andric         return dyn_cast<ConstantInt>(calculateVectorIndex(Ptr, GEPVectorIdx));
508*bdd1243dSDimitry Andric       };
509*bdd1243dSDimitry Andric 
510*bdd1243dSDimitry Andric       unsigned OpNum = U->getOperandNo();
511*bdd1243dSDimitry Andric       MemTransferInfo *TI = &TransferInfo[TransferInst];
512*bdd1243dSDimitry Andric       if (OpNum == 0) {
513*bdd1243dSDimitry Andric         Value *Dest = TransferInst->getDest();
514*bdd1243dSDimitry Andric         ConstantInt *Index = getPointerIndexOfAlloca(Dest);
515*bdd1243dSDimitry Andric         if (!Index)
516*bdd1243dSDimitry Andric           return false;
517*bdd1243dSDimitry Andric         TI->DestIndex = Index;
518*bdd1243dSDimitry Andric       } else {
519*bdd1243dSDimitry Andric         assert(OpNum == 1);
520*bdd1243dSDimitry Andric         Value *Src = TransferInst->getSource();
521*bdd1243dSDimitry Andric         ConstantInt *Index = getPointerIndexOfAlloca(Src);
522*bdd1243dSDimitry Andric         if (!Index)
523*bdd1243dSDimitry Andric           return false;
524*bdd1243dSDimitry Andric         TI->SrcIndex = Index;
525*bdd1243dSDimitry Andric       }
526*bdd1243dSDimitry Andric       continue;
527*bdd1243dSDimitry Andric     }
528*bdd1243dSDimitry Andric 
52981ad6265SDimitry Andric     // Ignore assume-like intrinsics and comparisons used in assumes.
53081ad6265SDimitry Andric     if (isAssumeLikeIntrinsic(Inst))
53181ad6265SDimitry Andric       continue;
53281ad6265SDimitry Andric 
53381ad6265SDimitry Andric     if (isa<ICmpInst>(Inst) && all_of(Inst->users(), [](User *U) {
53481ad6265SDimitry Andric           return isAssumeLikeIntrinsic(cast<Instruction>(U));
53581ad6265SDimitry Andric         }))
53681ad6265SDimitry Andric       continue;
53781ad6265SDimitry Andric 
53881ad6265SDimitry Andric     // Unknown user.
53981ad6265SDimitry Andric     return false;
5400b57cec5SDimitry Andric   }
5410b57cec5SDimitry Andric 
542*bdd1243dSDimitry Andric   while (!DeferredInsts.empty()) {
543*bdd1243dSDimitry Andric     Instruction *Inst = DeferredInsts.pop_back_val();
544*bdd1243dSDimitry Andric     MemTransferInst *TransferInst = cast<MemTransferInst>(Inst);
545*bdd1243dSDimitry Andric     // TODO: Support the case if the pointers are from different alloca or
546*bdd1243dSDimitry Andric     // from different address spaces.
547*bdd1243dSDimitry Andric     MemTransferInfo &Info = TransferInfo[TransferInst];
548*bdd1243dSDimitry Andric     if (!Info.SrcIndex || !Info.DestIndex)
549*bdd1243dSDimitry Andric       return false;
550*bdd1243dSDimitry Andric   }
551*bdd1243dSDimitry Andric 
5520b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
5530b57cec5SDimitry Andric                     << *VectorTy << '\n');
5540b57cec5SDimitry Andric 
55581ad6265SDimitry Andric   for (Instruction *Inst : WorkList) {
5560b57cec5SDimitry Andric     IRBuilder<> Builder(Inst);
5570b57cec5SDimitry Andric     switch (Inst->getOpcode()) {
5580b57cec5SDimitry Andric     case Instruction::Load: {
5595ffd83dbSDimitry Andric       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
5605ffd83dbSDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
56181ad6265SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(Alloca->getAddressSpace());
5620b57cec5SDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
563*bdd1243dSDimitry Andric       Value *VecValue =
564*bdd1243dSDimitry Andric           Builder.CreateAlignedLoad(VectorTy, BitCast, Alloca->getAlign());
5650b57cec5SDimitry Andric       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
5665ffd83dbSDimitry Andric       if (Inst->getType() != VecEltTy)
5675ffd83dbSDimitry Andric         ExtractElement = Builder.CreateBitOrPointerCast(ExtractElement, Inst->getType());
5680b57cec5SDimitry Andric       Inst->replaceAllUsesWith(ExtractElement);
5690b57cec5SDimitry Andric       Inst->eraseFromParent();
5700b57cec5SDimitry Andric       break;
5710b57cec5SDimitry Andric     }
5720b57cec5SDimitry Andric     case Instruction::Store: {
5730b57cec5SDimitry Andric       StoreInst *SI = cast<StoreInst>(Inst);
5745ffd83dbSDimitry Andric       Value *Ptr = SI->getPointerOperand();
5755ffd83dbSDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
57681ad6265SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(Alloca->getAddressSpace());
5770b57cec5SDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
578*bdd1243dSDimitry Andric       Value *VecValue =
579*bdd1243dSDimitry Andric           Builder.CreateAlignedLoad(VectorTy, BitCast, Alloca->getAlign());
5805ffd83dbSDimitry Andric       Value *Elt = SI->getValueOperand();
5815ffd83dbSDimitry Andric       if (Elt->getType() != VecEltTy)
5825ffd83dbSDimitry Andric         Elt = Builder.CreateBitOrPointerCast(Elt, VecEltTy);
5835ffd83dbSDimitry Andric       Value *NewVecValue = Builder.CreateInsertElement(VecValue, Elt, Index);
584*bdd1243dSDimitry Andric       Builder.CreateAlignedStore(NewVecValue, BitCast, Alloca->getAlign());
5850b57cec5SDimitry Andric       Inst->eraseFromParent();
5860b57cec5SDimitry Andric       break;
5870b57cec5SDimitry Andric     }
588*bdd1243dSDimitry Andric     case Instruction::Call: {
589*bdd1243dSDimitry Andric       if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst)) {
590*bdd1243dSDimitry Andric         ConstantInt *Length = cast<ConstantInt>(MTI->getLength());
591*bdd1243dSDimitry Andric         unsigned NumCopied = Length->getZExtValue() / ElementSize;
592*bdd1243dSDimitry Andric         MemTransferInfo *TI = &TransferInfo[cast<MemTransferInst>(Inst)];
593*bdd1243dSDimitry Andric         unsigned SrcBegin = TI->SrcIndex->getZExtValue();
594*bdd1243dSDimitry Andric         unsigned DestBegin = TI->DestIndex->getZExtValue();
595*bdd1243dSDimitry Andric 
596*bdd1243dSDimitry Andric         SmallVector<int> Mask;
597*bdd1243dSDimitry Andric         for (unsigned Idx = 0; Idx < VectorTy->getNumElements(); ++Idx) {
598*bdd1243dSDimitry Andric           if (Idx >= DestBegin && Idx < DestBegin + NumCopied) {
599*bdd1243dSDimitry Andric             Mask.push_back(SrcBegin++);
600*bdd1243dSDimitry Andric           } else {
601*bdd1243dSDimitry Andric             Mask.push_back(Idx);
602*bdd1243dSDimitry Andric           }
603*bdd1243dSDimitry Andric         }
604*bdd1243dSDimitry Andric         Type *VecPtrTy = VectorTy->getPointerTo(Alloca->getAddressSpace());
605*bdd1243dSDimitry Andric         Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
606*bdd1243dSDimitry Andric         Value *VecValue =
607*bdd1243dSDimitry Andric             Builder.CreateAlignedLoad(VectorTy, BitCast, Alloca->getAlign());
608*bdd1243dSDimitry Andric         Value *NewVecValue = Builder.CreateShuffleVector(VecValue, Mask);
609*bdd1243dSDimitry Andric         Builder.CreateAlignedStore(NewVecValue, BitCast, Alloca->getAlign());
610*bdd1243dSDimitry Andric 
611*bdd1243dSDimitry Andric         Inst->eraseFromParent();
612*bdd1243dSDimitry Andric       } else {
613*bdd1243dSDimitry Andric         llvm_unreachable("Unsupported call when promoting alloca to vector");
614*bdd1243dSDimitry Andric       }
615*bdd1243dSDimitry Andric       break;
616*bdd1243dSDimitry Andric     }
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric     default:
6190b57cec5SDimitry Andric       llvm_unreachable("Inconsistency in instructions promotable to vector");
6200b57cec5SDimitry Andric     }
6210b57cec5SDimitry Andric   }
6220b57cec5SDimitry Andric   return true;
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric static bool isCallPromotable(CallInst *CI) {
6260b57cec5SDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
6270b57cec5SDimitry Andric   if (!II)
6280b57cec5SDimitry Andric     return false;
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric   switch (II->getIntrinsicID()) {
6310b57cec5SDimitry Andric   case Intrinsic::memcpy:
6320b57cec5SDimitry Andric   case Intrinsic::memmove:
6330b57cec5SDimitry Andric   case Intrinsic::memset:
6340b57cec5SDimitry Andric   case Intrinsic::lifetime_start:
6350b57cec5SDimitry Andric   case Intrinsic::lifetime_end:
6360b57cec5SDimitry Andric   case Intrinsic::invariant_start:
6370b57cec5SDimitry Andric   case Intrinsic::invariant_end:
6380b57cec5SDimitry Andric   case Intrinsic::launder_invariant_group:
6390b57cec5SDimitry Andric   case Intrinsic::strip_invariant_group:
6400b57cec5SDimitry Andric   case Intrinsic::objectsize:
6410b57cec5SDimitry Andric     return true;
6420b57cec5SDimitry Andric   default:
6430b57cec5SDimitry Andric     return false;
6440b57cec5SDimitry Andric   }
6450b57cec5SDimitry Andric }
6460b57cec5SDimitry Andric 
647e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::binaryOpIsDerivedFromSameAlloca(
648e8d8bef9SDimitry Andric     Value *BaseAlloca, Value *Val, Instruction *Inst, int OpIdx0,
6490b57cec5SDimitry Andric     int OpIdx1) const {
6500b57cec5SDimitry Andric   // Figure out which operand is the one we might not be promoting.
6510b57cec5SDimitry Andric   Value *OtherOp = Inst->getOperand(OpIdx0);
6520b57cec5SDimitry Andric   if (Val == OtherOp)
6530b57cec5SDimitry Andric     OtherOp = Inst->getOperand(OpIdx1);
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(OtherOp))
6560b57cec5SDimitry Andric     return true;
6570b57cec5SDimitry Andric 
658e8d8bef9SDimitry Andric   Value *OtherObj = getUnderlyingObject(OtherOp);
6590b57cec5SDimitry Andric   if (!isa<AllocaInst>(OtherObj))
6600b57cec5SDimitry Andric     return false;
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   // TODO: We should be able to replace undefs with the right pointer type.
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   // TODO: If we know the other base object is another promotable
6650b57cec5SDimitry Andric   // alloca, not necessarily this alloca, we can do this. The
6660b57cec5SDimitry Andric   // important part is both must have the same address space at
6670b57cec5SDimitry Andric   // the end.
6680b57cec5SDimitry Andric   if (OtherObj != BaseAlloca) {
6690b57cec5SDimitry Andric     LLVM_DEBUG(
6700b57cec5SDimitry Andric         dbgs() << "Found a binary instruction with another alloca object\n");
6710b57cec5SDimitry Andric     return false;
6720b57cec5SDimitry Andric   }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   return true;
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
677e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::collectUsesWithPtrTypes(
678e8d8bef9SDimitry Andric     Value *BaseAlloca, Value *Val, std::vector<Value *> &WorkList) const {
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   for (User *User : Val->users()) {
6810b57cec5SDimitry Andric     if (is_contained(WorkList, User))
6820b57cec5SDimitry Andric       continue;
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(User)) {
6850b57cec5SDimitry Andric       if (!isCallPromotable(CI))
6860b57cec5SDimitry Andric         return false;
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric       WorkList.push_back(User);
6890b57cec5SDimitry Andric       continue;
6900b57cec5SDimitry Andric     }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric     Instruction *UseInst = cast<Instruction>(User);
6930b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::PtrToInt)
6940b57cec5SDimitry Andric       return false;
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
6970b57cec5SDimitry Andric       if (LI->isVolatile())
6980b57cec5SDimitry Andric         return false;
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric       continue;
7010b57cec5SDimitry Andric     }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
7040b57cec5SDimitry Andric       if (SI->isVolatile())
7050b57cec5SDimitry Andric         return false;
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric       // Reject if the stored value is not the pointer operand.
7080b57cec5SDimitry Andric       if (SI->getPointerOperand() != Val)
7090b57cec5SDimitry Andric         return false;
7100b57cec5SDimitry Andric     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
7110b57cec5SDimitry Andric       if (RMW->isVolatile())
7120b57cec5SDimitry Andric         return false;
7130b57cec5SDimitry Andric     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
7140b57cec5SDimitry Andric       if (CAS->isVolatile())
7150b57cec5SDimitry Andric         return false;
7160b57cec5SDimitry Andric     }
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric     // Only promote a select if we know that the other select operand
7190b57cec5SDimitry Andric     // is from another pointer that will also be promoted.
7200b57cec5SDimitry Andric     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
7210b57cec5SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
7220b57cec5SDimitry Andric         return false;
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric       // May need to rewrite constant operands.
7250b57cec5SDimitry Andric       WorkList.push_back(ICmp);
7260b57cec5SDimitry Andric     }
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
7290b57cec5SDimitry Andric       // Give up if the pointer may be captured.
7300b57cec5SDimitry Andric       if (PointerMayBeCaptured(UseInst, true, true))
7310b57cec5SDimitry Andric         return false;
7320b57cec5SDimitry Andric       // Don't collect the users of this.
7330b57cec5SDimitry Andric       WorkList.push_back(User);
7340b57cec5SDimitry Andric       continue;
7350b57cec5SDimitry Andric     }
7360b57cec5SDimitry Andric 
737fe6060f1SDimitry Andric     // Do not promote vector/aggregate type instructions. It is hard to track
738fe6060f1SDimitry Andric     // their users.
739fe6060f1SDimitry Andric     if (isa<InsertValueInst>(User) || isa<InsertElementInst>(User))
740fe6060f1SDimitry Andric       return false;
741fe6060f1SDimitry Andric 
7420b57cec5SDimitry Andric     if (!User->getType()->isPointerTy())
7430b57cec5SDimitry Andric       continue;
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
7460b57cec5SDimitry Andric       // Be conservative if an address could be computed outside the bounds of
7470b57cec5SDimitry Andric       // the alloca.
7480b57cec5SDimitry Andric       if (!GEP->isInBounds())
7490b57cec5SDimitry Andric         return false;
7500b57cec5SDimitry Andric     }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric     // Only promote a select if we know that the other select operand is from
7530b57cec5SDimitry Andric     // another pointer that will also be promoted.
7540b57cec5SDimitry Andric     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
7550b57cec5SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
7560b57cec5SDimitry Andric         return false;
7570b57cec5SDimitry Andric     }
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric     // Repeat for phis.
7600b57cec5SDimitry Andric     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
7610b57cec5SDimitry Andric       // TODO: Handle more complex cases. We should be able to replace loops
7620b57cec5SDimitry Andric       // over arrays.
7630b57cec5SDimitry Andric       switch (Phi->getNumIncomingValues()) {
7640b57cec5SDimitry Andric       case 1:
7650b57cec5SDimitry Andric         break;
7660b57cec5SDimitry Andric       case 2:
7670b57cec5SDimitry Andric         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
7680b57cec5SDimitry Andric           return false;
7690b57cec5SDimitry Andric         break;
7700b57cec5SDimitry Andric       default:
7710b57cec5SDimitry Andric         return false;
7720b57cec5SDimitry Andric       }
7730b57cec5SDimitry Andric     }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric     WorkList.push_back(User);
7760b57cec5SDimitry Andric     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
7770b57cec5SDimitry Andric       return false;
7780b57cec5SDimitry Andric   }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   return true;
7810b57cec5SDimitry Andric }
7820b57cec5SDimitry Andric 
783e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::hasSufficientLocalMem(const Function &F) {
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   FunctionType *FTy = F.getFunctionType();
786e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   // If the function has any arguments in the local address space, then it's
7890b57cec5SDimitry Andric   // possible these arguments require the entire local memory space, so
7900b57cec5SDimitry Andric   // we cannot use local memory in the pass.
7910b57cec5SDimitry Andric   for (Type *ParamTy : FTy->params()) {
7920b57cec5SDimitry Andric     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
7930b57cec5SDimitry Andric     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
7940b57cec5SDimitry Andric       LocalMemLimit = 0;
7950b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
7960b57cec5SDimitry Andric                            "local memory disabled.\n");
7970b57cec5SDimitry Andric       return false;
7980b57cec5SDimitry Andric     }
7990b57cec5SDimitry Andric   }
8000b57cec5SDimitry Andric 
801*bdd1243dSDimitry Andric   LocalMemLimit = ST.getAddressableLocalMemorySize();
8020b57cec5SDimitry Andric   if (LocalMemLimit == 0)
8030b57cec5SDimitry Andric     return false;
8040b57cec5SDimitry Andric 
805e8d8bef9SDimitry Andric   SmallVector<const Constant *, 16> Stack;
806e8d8bef9SDimitry Andric   SmallPtrSet<const Constant *, 8> VisitedConstants;
807e8d8bef9SDimitry Andric   SmallPtrSet<const GlobalVariable *, 8> UsedLDS;
8080b57cec5SDimitry Andric 
809e8d8bef9SDimitry Andric   auto visitUsers = [&](const GlobalVariable *GV, const Constant *Val) -> bool {
810e8d8bef9SDimitry Andric     for (const User *U : Val->users()) {
811e8d8bef9SDimitry Andric       if (const Instruction *Use = dyn_cast<Instruction>(U)) {
812e8d8bef9SDimitry Andric         if (Use->getParent()->getParent() == &F)
813e8d8bef9SDimitry Andric           return true;
814e8d8bef9SDimitry Andric       } else {
815e8d8bef9SDimitry Andric         const Constant *C = cast<Constant>(U);
816e8d8bef9SDimitry Andric         if (VisitedConstants.insert(C).second)
817e8d8bef9SDimitry Andric           Stack.push_back(C);
818e8d8bef9SDimitry Andric       }
819e8d8bef9SDimitry Andric     }
820e8d8bef9SDimitry Andric 
821e8d8bef9SDimitry Andric     return false;
822e8d8bef9SDimitry Andric   };
823e8d8bef9SDimitry Andric 
8240b57cec5SDimitry Andric   for (GlobalVariable &GV : Mod->globals()) {
825480093f4SDimitry Andric     if (GV.getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
8260b57cec5SDimitry Andric       continue;
8270b57cec5SDimitry Andric 
828e8d8bef9SDimitry Andric     if (visitUsers(&GV, &GV)) {
829e8d8bef9SDimitry Andric       UsedLDS.insert(&GV);
830e8d8bef9SDimitry Andric       Stack.clear();
8310b57cec5SDimitry Andric       continue;
832e8d8bef9SDimitry Andric     }
8330b57cec5SDimitry Andric 
834e8d8bef9SDimitry Andric     // For any ConstantExpr uses, we need to recursively search the users until
835e8d8bef9SDimitry Andric     // we see a function.
836e8d8bef9SDimitry Andric     while (!Stack.empty()) {
837e8d8bef9SDimitry Andric       const Constant *C = Stack.pop_back_val();
838e8d8bef9SDimitry Andric       if (visitUsers(&GV, C)) {
839e8d8bef9SDimitry Andric         UsedLDS.insert(&GV);
840e8d8bef9SDimitry Andric         Stack.clear();
8410b57cec5SDimitry Andric         break;
8420b57cec5SDimitry Andric       }
8430b57cec5SDimitry Andric     }
8440b57cec5SDimitry Andric   }
8450b57cec5SDimitry Andric 
846e8d8bef9SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
847e8d8bef9SDimitry Andric   SmallVector<std::pair<uint64_t, Align>, 16> AllocatedSizes;
848e8d8bef9SDimitry Andric   AllocatedSizes.reserve(UsedLDS.size());
849e8d8bef9SDimitry Andric 
850e8d8bef9SDimitry Andric   for (const GlobalVariable *GV : UsedLDS) {
851e8d8bef9SDimitry Andric     Align Alignment =
852e8d8bef9SDimitry Andric         DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
853e8d8bef9SDimitry Andric     uint64_t AllocSize = DL.getTypeAllocSize(GV->getValueType());
85404eeddc0SDimitry Andric 
85504eeddc0SDimitry Andric     // HIP uses an extern unsized array in local address space for dynamically
85604eeddc0SDimitry Andric     // allocated shared memory.  In that case, we have to disable the promotion.
85704eeddc0SDimitry Andric     if (GV->hasExternalLinkage() && AllocSize == 0) {
85804eeddc0SDimitry Andric       LocalMemLimit = 0;
85904eeddc0SDimitry Andric       LLVM_DEBUG(dbgs() << "Function has a reference to externally allocated "
86004eeddc0SDimitry Andric                            "local memory. Promoting to local memory "
86104eeddc0SDimitry Andric                            "disabled.\n");
86204eeddc0SDimitry Andric       return false;
86304eeddc0SDimitry Andric     }
86404eeddc0SDimitry Andric 
865e8d8bef9SDimitry Andric     AllocatedSizes.emplace_back(AllocSize, Alignment);
866e8d8bef9SDimitry Andric   }
867e8d8bef9SDimitry Andric 
868e8d8bef9SDimitry Andric   // Sort to try to estimate the worst case alignment padding
869e8d8bef9SDimitry Andric   //
870e8d8bef9SDimitry Andric   // FIXME: We should really do something to fix the addresses to a more optimal
871e8d8bef9SDimitry Andric   // value instead
87281ad6265SDimitry Andric   llvm::sort(AllocatedSizes, llvm::less_second());
873e8d8bef9SDimitry Andric 
874e8d8bef9SDimitry Andric   // Check how much local memory is being used by global objects
875e8d8bef9SDimitry Andric   CurrentLocalMemUsage = 0;
876e8d8bef9SDimitry Andric 
877e8d8bef9SDimitry Andric   // FIXME: Try to account for padding here. The real padding and address is
878e8d8bef9SDimitry Andric   // currently determined from the inverse order of uses in the function when
879e8d8bef9SDimitry Andric   // legalizing, which could also potentially change. We try to estimate the
880e8d8bef9SDimitry Andric   // worst case here, but we probably should fix the addresses earlier.
881e8d8bef9SDimitry Andric   for (auto Alloc : AllocatedSizes) {
882e8d8bef9SDimitry Andric     CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Alloc.second);
883e8d8bef9SDimitry Andric     CurrentLocalMemUsage += Alloc.first;
884e8d8bef9SDimitry Andric   }
885e8d8bef9SDimitry Andric 
8860b57cec5SDimitry Andric   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
8870b57cec5SDimitry Andric                                                           F);
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // Restrict local memory usage so that we don't drastically reduce occupancy,
8900b57cec5SDimitry Andric   // unless it is already significantly reduced.
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   // TODO: Have some sort of hint or other heuristics to guess occupancy based
8930b57cec5SDimitry Andric   // on other factors..
8940b57cec5SDimitry Andric   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
8950b57cec5SDimitry Andric   if (OccupancyHint == 0)
8960b57cec5SDimitry Andric     OccupancyHint = 7;
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   // Clamp to max value.
8990b57cec5SDimitry Andric   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   // Check the hint but ignore it if it's obviously wrong from the existing LDS
9020b57cec5SDimitry Andric   // usage.
9030b57cec5SDimitry Andric   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   // Round up to the next tier of usage.
9070b57cec5SDimitry Andric   unsigned MaxSizeWithWaveCount
9080b57cec5SDimitry Andric     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   // Program is possibly broken by using more local mem than available.
9110b57cec5SDimitry Andric   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
9120b57cec5SDimitry Andric     return false;
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   LocalMemLimit = MaxSizeWithWaveCount;
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
9170b57cec5SDimitry Andric                     << " bytes of LDS\n"
9180b57cec5SDimitry Andric                     << "  Rounding size to " << MaxSizeWithWaveCount
9190b57cec5SDimitry Andric                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
9200b57cec5SDimitry Andric                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
9210b57cec5SDimitry Andric                     << " available for promotion\n");
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   return true;
9240b57cec5SDimitry Andric }
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric // FIXME: Should try to pick the most likely to be profitable allocas first.
927e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaImpl::handleAlloca(AllocaInst &I, bool SufficientLDS) {
9280b57cec5SDimitry Andric   // Array allocations are probably not worth handling, since an allocation of
9290b57cec5SDimitry Andric   // the array type is the canonical form.
9300b57cec5SDimitry Andric   if (!I.isStaticAlloca() || I.isArrayAllocation())
9310b57cec5SDimitry Andric     return false;
9320b57cec5SDimitry Andric 
9335ffd83dbSDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
9340b57cec5SDimitry Andric   IRBuilder<> Builder(&I);
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   // First try to replace the alloca with a vector
9370b57cec5SDimitry Andric   Type *AllocaTy = I.getAllocatedType();
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
9400b57cec5SDimitry Andric 
9415ffd83dbSDimitry Andric   if (tryPromoteAllocaToVector(&I, DL, MaxVGPRs))
9420b57cec5SDimitry Andric     return true; // Promoted to vector.
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   if (DisablePromoteAllocaToLDS)
9450b57cec5SDimitry Andric     return false;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   const Function &ContainingFunction = *I.getParent()->getParent();
9480b57cec5SDimitry Andric   CallingConv::ID CC = ContainingFunction.getCallingConv();
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   // Don't promote the alloca to LDS for shader calling conventions as the work
9510b57cec5SDimitry Andric   // item ID intrinsics are not supported for these calling conventions.
9520b57cec5SDimitry Andric   // Furthermore not all LDS is available for some of the stages.
9530b57cec5SDimitry Andric   switch (CC) {
9540b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
9550b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
9560b57cec5SDimitry Andric     break;
9570b57cec5SDimitry Andric   default:
9580b57cec5SDimitry Andric     LLVM_DEBUG(
9590b57cec5SDimitry Andric         dbgs()
9600b57cec5SDimitry Andric         << " promote alloca to LDS not supported with calling convention.\n");
9610b57cec5SDimitry Andric     return false;
9620b57cec5SDimitry Andric   }
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   // Not likely to have sufficient local memory for promotion.
9650b57cec5SDimitry Andric   if (!SufficientLDS)
9660b57cec5SDimitry Andric     return false;
9670b57cec5SDimitry Andric 
968e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, ContainingFunction);
9690b57cec5SDimitry Andric   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
9700b57cec5SDimitry Andric 
9715ffd83dbSDimitry Andric   Align Alignment =
9725ffd83dbSDimitry Andric       DL.getValueOrABITypeAlignment(I.getAlign(), I.getAllocatedType());
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   // FIXME: This computed padding is likely wrong since it depends on inverse
9750b57cec5SDimitry Andric   // usage order.
9760b57cec5SDimitry Andric   //
9770b57cec5SDimitry Andric   // FIXME: It is also possible that if we're allowed to use all of the memory
97881ad6265SDimitry Andric   // could end up using more than the maximum due to alignment padding.
9790b57cec5SDimitry Andric 
9805ffd83dbSDimitry Andric   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Alignment);
9810b57cec5SDimitry Andric   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
9820b57cec5SDimitry Andric   NewSize += AllocSize;
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   if (NewSize > LocalMemLimit) {
9850b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << AllocSize
9860b57cec5SDimitry Andric                       << " bytes of local memory not available to promote\n");
9870b57cec5SDimitry Andric     return false;
9880b57cec5SDimitry Andric   }
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric   CurrentLocalMemUsage = NewSize;
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   std::vector<Value*> WorkList;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
9950b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
9960b57cec5SDimitry Andric     return false;
9970b57cec5SDimitry Andric   }
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   Function *F = I.getParent()->getParent();
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
10040b57cec5SDimitry Andric   GlobalVariable *GV = new GlobalVariable(
1005*bdd1243dSDimitry Andric       *Mod, GVTy, false, GlobalValue::InternalLinkage, PoisonValue::get(GVTy),
1006*bdd1243dSDimitry Andric       Twine(F->getName()) + Twine('.') + I.getName(), nullptr,
1007*bdd1243dSDimitry Andric       GlobalVariable::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS);
10080b57cec5SDimitry Andric   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
10090eae32dcSDimitry Andric   GV->setAlignment(I.getAlign());
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   Value *TCntY, *TCntZ;
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
10140b57cec5SDimitry Andric   Value *TIdX = getWorkitemID(Builder, 0);
10150b57cec5SDimitry Andric   Value *TIdY = getWorkitemID(Builder, 1);
10160b57cec5SDimitry Andric   Value *TIdZ = getWorkitemID(Builder, 2);
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
10190b57cec5SDimitry Andric   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
10200b57cec5SDimitry Andric   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
10210b57cec5SDimitry Andric   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
10220b57cec5SDimitry Andric   TID = Builder.CreateAdd(TID, TIdZ);
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   Value *Indices[] = {
10250b57cec5SDimitry Andric     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
10260b57cec5SDimitry Andric     TID
10270b57cec5SDimitry Andric   };
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
10300b57cec5SDimitry Andric   I.mutateType(Offset->getType());
10310b57cec5SDimitry Andric   I.replaceAllUsesWith(Offset);
10320b57cec5SDimitry Andric   I.eraseFromParent();
10330b57cec5SDimitry Andric 
1034fe6060f1SDimitry Andric   SmallVector<IntrinsicInst *> DeferredIntrs;
1035fe6060f1SDimitry Andric 
10360b57cec5SDimitry Andric   for (Value *V : WorkList) {
10370b57cec5SDimitry Andric     CallInst *Call = dyn_cast<CallInst>(V);
10380b57cec5SDimitry Andric     if (!Call) {
10390b57cec5SDimitry Andric       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
10400b57cec5SDimitry Andric         Value *Src0 = CI->getOperand(0);
1041fe6060f1SDimitry Andric         PointerType *NewTy = PointerType::getWithSamePointeeType(
1042fe6060f1SDimitry Andric             cast<PointerType>(Src0->getType()), AMDGPUAS::LOCAL_ADDRESS);
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(0)))
10450b57cec5SDimitry Andric           CI->setOperand(0, ConstantPointerNull::get(NewTy));
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(1)))
10480b57cec5SDimitry Andric           CI->setOperand(1, ConstantPointerNull::get(NewTy));
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric         continue;
10510b57cec5SDimitry Andric       }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric       // The operand's value should be corrected on its own and we don't want to
10540b57cec5SDimitry Andric       // touch the users.
10550b57cec5SDimitry Andric       if (isa<AddrSpaceCastInst>(V))
10560b57cec5SDimitry Andric         continue;
10570b57cec5SDimitry Andric 
1058fe6060f1SDimitry Andric       PointerType *NewTy = PointerType::getWithSamePointeeType(
1059fe6060f1SDimitry Andric           cast<PointerType>(V->getType()), AMDGPUAS::LOCAL_ADDRESS);
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric       // FIXME: It doesn't really make sense to try to do this for all
10620b57cec5SDimitry Andric       // instructions.
10630b57cec5SDimitry Andric       V->mutateType(NewTy);
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric       // Adjust the types of any constant operands.
10660b57cec5SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
10670b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(1)))
10680b57cec5SDimitry Andric           SI->setOperand(1, ConstantPointerNull::get(NewTy));
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(2)))
10710b57cec5SDimitry Andric           SI->setOperand(2, ConstantPointerNull::get(NewTy));
10720b57cec5SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
10730b57cec5SDimitry Andric         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
10740b57cec5SDimitry Andric           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
10750b57cec5SDimitry Andric             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
10760b57cec5SDimitry Andric         }
10770b57cec5SDimitry Andric       }
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric       continue;
10800b57cec5SDimitry Andric     }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
10830b57cec5SDimitry Andric     Builder.SetInsertPoint(Intr);
10840b57cec5SDimitry Andric     switch (Intr->getIntrinsicID()) {
10850b57cec5SDimitry Andric     case Intrinsic::lifetime_start:
10860b57cec5SDimitry Andric     case Intrinsic::lifetime_end:
10870b57cec5SDimitry Andric       // These intrinsics are for address space 0 only
10880b57cec5SDimitry Andric       Intr->eraseFromParent();
10890b57cec5SDimitry Andric       continue;
1090fe6060f1SDimitry Andric     case Intrinsic::memcpy:
1091fe6060f1SDimitry Andric     case Intrinsic::memmove:
1092fe6060f1SDimitry Andric       // These have 2 pointer operands. In case if second pointer also needs
1093fe6060f1SDimitry Andric       // to be replaced we defer processing of these intrinsics until all
1094fe6060f1SDimitry Andric       // other values are processed.
1095fe6060f1SDimitry Andric       DeferredIntrs.push_back(Intr);
10960b57cec5SDimitry Andric       continue;
10970b57cec5SDimitry Andric     case Intrinsic::memset: {
10980b57cec5SDimitry Andric       MemSetInst *MemSet = cast<MemSetInst>(Intr);
1099*bdd1243dSDimitry Andric       Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
1100*bdd1243dSDimitry Andric                            MemSet->getLength(), MemSet->getDestAlign(),
1101*bdd1243dSDimitry Andric                            MemSet->isVolatile());
11020b57cec5SDimitry Andric       Intr->eraseFromParent();
11030b57cec5SDimitry Andric       continue;
11040b57cec5SDimitry Andric     }
11050b57cec5SDimitry Andric     case Intrinsic::invariant_start:
11060b57cec5SDimitry Andric     case Intrinsic::invariant_end:
11070b57cec5SDimitry Andric     case Intrinsic::launder_invariant_group:
11080b57cec5SDimitry Andric     case Intrinsic::strip_invariant_group:
11090b57cec5SDimitry Andric       Intr->eraseFromParent();
11100b57cec5SDimitry Andric       // FIXME: I think the invariant marker should still theoretically apply,
11110b57cec5SDimitry Andric       // but the intrinsics need to be changed to accept pointers with any
11120b57cec5SDimitry Andric       // address space.
11130b57cec5SDimitry Andric       continue;
11140b57cec5SDimitry Andric     case Intrinsic::objectsize: {
11150b57cec5SDimitry Andric       Value *Src = Intr->getOperand(0);
1116fe6060f1SDimitry Andric       Function *ObjectSize = Intrinsic::getDeclaration(
1117fe6060f1SDimitry Andric           Mod, Intrinsic::objectsize,
1118fe6060f1SDimitry Andric           {Intr->getType(),
1119fe6060f1SDimitry Andric            PointerType::getWithSamePointeeType(
1120fe6060f1SDimitry Andric                cast<PointerType>(Src->getType()), AMDGPUAS::LOCAL_ADDRESS)});
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric       CallInst *NewCall = Builder.CreateCall(
11230b57cec5SDimitry Andric           ObjectSize,
11240b57cec5SDimitry Andric           {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
11250b57cec5SDimitry Andric       Intr->replaceAllUsesWith(NewCall);
11260b57cec5SDimitry Andric       Intr->eraseFromParent();
11270b57cec5SDimitry Andric       continue;
11280b57cec5SDimitry Andric     }
11290b57cec5SDimitry Andric     default:
11300b57cec5SDimitry Andric       Intr->print(errs());
11310b57cec5SDimitry Andric       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
11320b57cec5SDimitry Andric     }
11330b57cec5SDimitry Andric   }
1134fe6060f1SDimitry Andric 
1135fe6060f1SDimitry Andric   for (IntrinsicInst *Intr : DeferredIntrs) {
1136fe6060f1SDimitry Andric     Builder.SetInsertPoint(Intr);
1137fe6060f1SDimitry Andric     Intrinsic::ID ID = Intr->getIntrinsicID();
1138fe6060f1SDimitry Andric     assert(ID == Intrinsic::memcpy || ID == Intrinsic::memmove);
1139fe6060f1SDimitry Andric 
1140fe6060f1SDimitry Andric     MemTransferInst *MI = cast<MemTransferInst>(Intr);
1141fe6060f1SDimitry Andric     auto *B =
1142fe6060f1SDimitry Andric       Builder.CreateMemTransferInst(ID, MI->getRawDest(), MI->getDestAlign(),
1143fe6060f1SDimitry Andric                                     MI->getRawSource(), MI->getSourceAlign(),
1144fe6060f1SDimitry Andric                                     MI->getLength(), MI->isVolatile());
1145fe6060f1SDimitry Andric 
1146349cc55cSDimitry Andric     for (unsigned I = 0; I != 2; ++I) {
1147349cc55cSDimitry Andric       if (uint64_t Bytes = Intr->getParamDereferenceableBytes(I)) {
1148349cc55cSDimitry Andric         B->addDereferenceableParamAttr(I, Bytes);
1149fe6060f1SDimitry Andric       }
1150fe6060f1SDimitry Andric     }
1151fe6060f1SDimitry Andric 
1152fe6060f1SDimitry Andric     Intr->eraseFromParent();
1153fe6060f1SDimitry Andric   }
1154fe6060f1SDimitry Andric 
11550b57cec5SDimitry Andric   return true;
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
1158e8d8bef9SDimitry Andric bool handlePromoteAllocaToVector(AllocaInst &I, unsigned MaxVGPRs) {
1159e8d8bef9SDimitry Andric   // Array allocations are probably not worth handling, since an allocation of
1160e8d8bef9SDimitry Andric   // the array type is the canonical form.
1161e8d8bef9SDimitry Andric   if (!I.isStaticAlloca() || I.isArrayAllocation())
11625ffd83dbSDimitry Andric     return false;
11635ffd83dbSDimitry Andric 
1164e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
1165e8d8bef9SDimitry Andric 
1166e8d8bef9SDimitry Andric   Module *Mod = I.getParent()->getParent()->getParent();
1167e8d8bef9SDimitry Andric   return tryPromoteAllocaToVector(&I, Mod->getDataLayout(), MaxVGPRs);
1168e8d8bef9SDimitry Andric }
1169e8d8bef9SDimitry Andric 
1170e8d8bef9SDimitry Andric bool promoteAllocasToVector(Function &F, TargetMachine &TM) {
1171e8d8bef9SDimitry Andric   if (DisablePromoteAllocaToVector)
11725ffd83dbSDimitry Andric     return false;
11735ffd83dbSDimitry Andric 
1174e8d8bef9SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
11755ffd83dbSDimitry Andric   if (!ST.isPromoteAllocaEnabled())
11765ffd83dbSDimitry Andric     return false;
11775ffd83dbSDimitry Andric 
1178e8d8bef9SDimitry Andric   unsigned MaxVGPRs;
1179e8d8bef9SDimitry Andric   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
1180e8d8bef9SDimitry Andric     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
11815ffd83dbSDimitry Andric     MaxVGPRs = ST.getMaxNumVGPRs(ST.getWavesPerEU(F).first);
1182349cc55cSDimitry Andric     // A non-entry function has only 32 caller preserved registers.
1183349cc55cSDimitry Andric     // Do not promote alloca which will force spilling.
1184349cc55cSDimitry Andric     if (!AMDGPU::isEntryFunctionCC(F.getCallingConv()))
1185349cc55cSDimitry Andric       MaxVGPRs = std::min(MaxVGPRs, 32u);
11865ffd83dbSDimitry Andric   } else {
11875ffd83dbSDimitry Andric     MaxVGPRs = 128;
11885ffd83dbSDimitry Andric   }
11895ffd83dbSDimitry Andric 
11905ffd83dbSDimitry Andric   bool Changed = false;
11915ffd83dbSDimitry Andric   BasicBlock &EntryBB = *F.begin();
11925ffd83dbSDimitry Andric 
11935ffd83dbSDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
11945ffd83dbSDimitry Andric   for (Instruction &I : EntryBB) {
11955ffd83dbSDimitry Andric     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
11965ffd83dbSDimitry Andric       Allocas.push_back(AI);
11975ffd83dbSDimitry Andric   }
11985ffd83dbSDimitry Andric 
11995ffd83dbSDimitry Andric   for (AllocaInst *AI : Allocas) {
1200e8d8bef9SDimitry Andric     if (handlePromoteAllocaToVector(*AI, MaxVGPRs))
12015ffd83dbSDimitry Andric       Changed = true;
12025ffd83dbSDimitry Andric   }
12035ffd83dbSDimitry Andric 
12045ffd83dbSDimitry Andric   return Changed;
12055ffd83dbSDimitry Andric }
12065ffd83dbSDimitry Andric 
1207e8d8bef9SDimitry Andric bool AMDGPUPromoteAllocaToVector::runOnFunction(Function &F) {
1208e8d8bef9SDimitry Andric   if (skipFunction(F))
12095ffd83dbSDimitry Andric     return false;
1210e8d8bef9SDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1211e8d8bef9SDimitry Andric     return promoteAllocasToVector(F, TPC->getTM<TargetMachine>());
1212e8d8bef9SDimitry Andric   }
1213e8d8bef9SDimitry Andric   return false;
1214e8d8bef9SDimitry Andric }
12155ffd83dbSDimitry Andric 
1216e8d8bef9SDimitry Andric PreservedAnalyses
1217e8d8bef9SDimitry Andric AMDGPUPromoteAllocaToVectorPass::run(Function &F, FunctionAnalysisManager &AM) {
1218e8d8bef9SDimitry Andric   bool Changed = promoteAllocasToVector(F, TM);
1219e8d8bef9SDimitry Andric   if (Changed) {
1220e8d8bef9SDimitry Andric     PreservedAnalyses PA;
1221e8d8bef9SDimitry Andric     PA.preserveSet<CFGAnalyses>();
1222e8d8bef9SDimitry Andric     return PA;
1223e8d8bef9SDimitry Andric   }
1224e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
12255ffd83dbSDimitry Andric }
12265ffd83dbSDimitry Andric 
12270b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUPromoteAlloca() {
12280b57cec5SDimitry Andric   return new AMDGPUPromoteAlloca();
12290b57cec5SDimitry Andric }
12305ffd83dbSDimitry Andric 
12315ffd83dbSDimitry Andric FunctionPass *llvm::createAMDGPUPromoteAllocaToVector() {
12325ffd83dbSDimitry Andric   return new AMDGPUPromoteAllocaToVector();
12335ffd83dbSDimitry Andric }
1234