18f0fd8f6SDimitry Andric //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
28f0fd8f6SDimitry Andric //
38f0fd8f6SDimitry Andric //                     The LLVM Compiler Infrastructure
48f0fd8f6SDimitry Andric //
58f0fd8f6SDimitry Andric // This file is distributed under the University of Illinois Open Source
68f0fd8f6SDimitry Andric // License. See LICENSE.TXT for details.
78f0fd8f6SDimitry Andric //
88f0fd8f6SDimitry Andric //===----------------------------------------------------------------------===//
98f0fd8f6SDimitry Andric //
108f0fd8f6SDimitry Andric // This pass eliminates allocas by either converting them into vectors or
118f0fd8f6SDimitry Andric // by migrating them to local address space.
128f0fd8f6SDimitry Andric //
138f0fd8f6SDimitry Andric //===----------------------------------------------------------------------===//
148f0fd8f6SDimitry Andric 
158f0fd8f6SDimitry Andric #include "AMDGPU.h"
168f0fd8f6SDimitry Andric #include "AMDGPUSubtarget.h"
177a7e6055SDimitry Andric #include "Utils/AMDGPUBaseInfo.h"
187a7e6055SDimitry Andric #include "llvm/ADT/APInt.h"
197a7e6055SDimitry Andric #include "llvm/ADT/None.h"
207a7e6055SDimitry Andric #include "llvm/ADT/STLExtras.h"
217a7e6055SDimitry Andric #include "llvm/ADT/StringRef.h"
227a7e6055SDimitry Andric #include "llvm/ADT/Triple.h"
237a7e6055SDimitry Andric #include "llvm/ADT/Twine.h"
247a7e6055SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
258f0fd8f6SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
26d8866befSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
277a7e6055SDimitry Andric #include "llvm/IR/Attributes.h"
287a7e6055SDimitry Andric #include "llvm/IR/BasicBlock.h"
297a7e6055SDimitry Andric #include "llvm/IR/Constant.h"
307a7e6055SDimitry Andric #include "llvm/IR/Constants.h"
317a7e6055SDimitry Andric #include "llvm/IR/DataLayout.h"
327a7e6055SDimitry Andric #include "llvm/IR/DerivedTypes.h"
337a7e6055SDimitry Andric #include "llvm/IR/Function.h"
347a7e6055SDimitry Andric #include "llvm/IR/GlobalValue.h"
357a7e6055SDimitry Andric #include "llvm/IR/GlobalVariable.h"
36db17bf38SDimitry Andric #include "llvm/IR/IRBuilder.h"
377a7e6055SDimitry Andric #include "llvm/IR/Instruction.h"
387a7e6055SDimitry Andric #include "llvm/IR/Instructions.h"
393ca95b02SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
407a7e6055SDimitry Andric #include "llvm/IR/Intrinsics.h"
417a7e6055SDimitry Andric #include "llvm/IR/LLVMContext.h"
427a7e6055SDimitry Andric #include "llvm/IR/Metadata.h"
437a7e6055SDimitry Andric #include "llvm/IR/Module.h"
447a7e6055SDimitry Andric #include "llvm/IR/Type.h"
457a7e6055SDimitry Andric #include "llvm/IR/User.h"
467a7e6055SDimitry Andric #include "llvm/IR/Value.h"
477a7e6055SDimitry Andric #include "llvm/Pass.h"
487a7e6055SDimitry Andric #include "llvm/Support/Casting.h"
498f0fd8f6SDimitry Andric #include "llvm/Support/Debug.h"
507a7e6055SDimitry Andric #include "llvm/Support/ErrorHandling.h"
517a7e6055SDimitry Andric #include "llvm/Support/MathExtras.h"
528f0fd8f6SDimitry Andric #include "llvm/Support/raw_ostream.h"
537a7e6055SDimitry Andric #include "llvm/Target/TargetMachine.h"
547a7e6055SDimitry Andric #include <algorithm>
557a7e6055SDimitry Andric #include <cassert>
567a7e6055SDimitry Andric #include <cstdint>
577a7e6055SDimitry Andric #include <map>
587a7e6055SDimitry Andric #include <tuple>
597a7e6055SDimitry Andric #include <utility>
607a7e6055SDimitry Andric #include <vector>
618f0fd8f6SDimitry Andric 
628f0fd8f6SDimitry Andric #define DEBUG_TYPE "amdgpu-promote-alloca"
638f0fd8f6SDimitry Andric 
648f0fd8f6SDimitry Andric using namespace llvm;
658f0fd8f6SDimitry Andric 
668f0fd8f6SDimitry Andric namespace {
678f0fd8f6SDimitry Andric 
684ba319b5SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToVector(
694ba319b5SDimitry Andric   "disable-promote-alloca-to-vector",
704ba319b5SDimitry Andric   cl::desc("Disable promote alloca to vector"),
714ba319b5SDimitry Andric   cl::init(false));
724ba319b5SDimitry Andric 
73*b5893f02SDimitry Andric static cl::opt<bool> DisablePromoteAllocaToLDS(
74*b5893f02SDimitry Andric   "disable-promote-alloca-to-lds",
75*b5893f02SDimitry Andric   cl::desc("Disable promote alloca to LDS"),
76*b5893f02SDimitry Andric   cl::init(false));
77*b5893f02SDimitry Andric 
783ca95b02SDimitry Andric // FIXME: This can create globals so should be a module pass.
793ca95b02SDimitry Andric class AMDGPUPromoteAlloca : public FunctionPass {
803ca95b02SDimitry Andric private:
813ca95b02SDimitry Andric   const TargetMachine *TM;
827a7e6055SDimitry Andric   Module *Mod = nullptr;
837a7e6055SDimitry Andric   const DataLayout *DL = nullptr;
843ca95b02SDimitry Andric 
853ca95b02SDimitry Andric   // FIXME: This should be per-kernel.
867a7e6055SDimitry Andric   uint32_t LocalMemLimit = 0;
877a7e6055SDimitry Andric   uint32_t CurrentLocalMemUsage = 0;
883ca95b02SDimitry Andric 
897a7e6055SDimitry Andric   bool IsAMDGCN = false;
907a7e6055SDimitry Andric   bool IsAMDHSA = false;
913ca95b02SDimitry Andric 
923ca95b02SDimitry Andric   std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
933ca95b02SDimitry Andric   Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
943ca95b02SDimitry Andric 
953ca95b02SDimitry Andric   /// BaseAlloca is the alloca root the search started from.
963ca95b02SDimitry Andric   /// Val may be that alloca or a recursive user of it.
973ca95b02SDimitry Andric   bool collectUsesWithPtrTypes(Value *BaseAlloca,
983ca95b02SDimitry Andric                                Value *Val,
993ca95b02SDimitry Andric                                std::vector<Value*> &WorkList) const;
1003ca95b02SDimitry Andric 
1013ca95b02SDimitry Andric   /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
1023ca95b02SDimitry Andric   /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
1033ca95b02SDimitry Andric   /// Returns true if both operands are derived from the same alloca. Val should
1043ca95b02SDimitry Andric   /// be the same value as one of the input operands of UseInst.
1053ca95b02SDimitry Andric   bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
1063ca95b02SDimitry Andric                                        Instruction *UseInst,
1073ca95b02SDimitry Andric                                        int OpIdx0, int OpIdx1) const;
1088f0fd8f6SDimitry Andric 
109302affcbSDimitry Andric   /// Check whether we have enough local memory for promotion.
110302affcbSDimitry Andric   bool hasSufficientLocalMem(const Function &F);
111302affcbSDimitry Andric 
1128f0fd8f6SDimitry Andric public:
1133ca95b02SDimitry Andric   static char ID;
1143ca95b02SDimitry Andric 
AMDGPUPromoteAlloca()115d8866befSDimitry Andric   AMDGPUPromoteAlloca() : FunctionPass(ID) {}
1163ca95b02SDimitry Andric 
1178f0fd8f6SDimitry Andric   bool doInitialization(Module &M) override;
1188f0fd8f6SDimitry Andric   bool runOnFunction(Function &F) override;
1193ca95b02SDimitry Andric 
getPassName() const120d88c1a5aSDimitry Andric   StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
1213ca95b02SDimitry Andric 
122302affcbSDimitry Andric   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
1233ca95b02SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1243ca95b02SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1253ca95b02SDimitry Andric     AU.setPreservesCFG();
1263ca95b02SDimitry Andric     FunctionPass::getAnalysisUsage(AU);
1273ca95b02SDimitry Andric   }
1288f0fd8f6SDimitry Andric };
1298f0fd8f6SDimitry Andric 
1307a7e6055SDimitry Andric } // end anonymous namespace
1318f0fd8f6SDimitry Andric 
1328f0fd8f6SDimitry Andric char AMDGPUPromoteAlloca::ID = 0;
1338f0fd8f6SDimitry Andric 
134d8866befSDimitry Andric INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
1353ca95b02SDimitry Andric                 "AMDGPU promote alloca to vector or LDS", false, false)
1363ca95b02SDimitry Andric 
1373ca95b02SDimitry Andric char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
1383ca95b02SDimitry Andric 
doInitialization(Module & M)1398f0fd8f6SDimitry Andric bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
1408f0fd8f6SDimitry Andric   Mod = &M;
1413ca95b02SDimitry Andric   DL = &Mod->getDataLayout();
1423ca95b02SDimitry Andric 
1438f0fd8f6SDimitry Andric   return false;
1448f0fd8f6SDimitry Andric }
1458f0fd8f6SDimitry Andric 
runOnFunction(Function & F)1468f0fd8f6SDimitry Andric bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
147d8866befSDimitry Andric   if (skipFunction(F))
1483ca95b02SDimitry Andric     return false;
1493ca95b02SDimitry Andric 
150d8866befSDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
151d8866befSDimitry Andric     TM = &TPC->getTM<TargetMachine>();
152d8866befSDimitry Andric   else
153d8866befSDimitry Andric     return false;
154d8866befSDimitry Andric 
155d8866befSDimitry Andric   const Triple &TT = TM->getTargetTriple();
156d8866befSDimitry Andric   IsAMDGCN = TT.getArch() == Triple::amdgcn;
157d8866befSDimitry Andric   IsAMDHSA = TT.getOS() == Triple::AMDHSA;
158d8866befSDimitry Andric 
1594ba319b5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
1603ca95b02SDimitry Andric   if (!ST.isPromoteAllocaEnabled())
1613ca95b02SDimitry Andric     return false;
162302affcbSDimitry Andric 
163302affcbSDimitry Andric   bool SufficientLDS = hasSufficientLocalMem(F);
164302affcbSDimitry Andric   bool Changed = false;
1653ca95b02SDimitry Andric   BasicBlock &EntryBB = *F.begin();
1663ca95b02SDimitry Andric   for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
1673ca95b02SDimitry Andric     AllocaInst *AI = dyn_cast<AllocaInst>(I);
1683ca95b02SDimitry Andric 
1693ca95b02SDimitry Andric     ++I;
1703ca95b02SDimitry Andric     if (AI)
171302affcbSDimitry Andric       Changed |= handleAlloca(*AI, SufficientLDS);
1723ca95b02SDimitry Andric   }
1733ca95b02SDimitry Andric 
174302affcbSDimitry Andric   return Changed;
1753ca95b02SDimitry Andric }
1763ca95b02SDimitry Andric 
1773ca95b02SDimitry Andric std::pair<Value *, Value *>
getLocalSizeYZ(IRBuilder<> & Builder)1783ca95b02SDimitry Andric AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
1794ba319b5SDimitry Andric   const Function &F = *Builder.GetInsertBlock()->getParent();
1804ba319b5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
1817a7e6055SDimitry Andric 
1823ca95b02SDimitry Andric   if (!IsAMDHSA) {
1833ca95b02SDimitry Andric     Function *LocalSizeYFn
1843ca95b02SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
1853ca95b02SDimitry Andric     Function *LocalSizeZFn
1863ca95b02SDimitry Andric       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
1873ca95b02SDimitry Andric 
1883ca95b02SDimitry Andric     CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
1893ca95b02SDimitry Andric     CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
1903ca95b02SDimitry Andric 
1917a7e6055SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeY);
1927a7e6055SDimitry Andric     ST.makeLIDRangeMetadata(LocalSizeZ);
1933ca95b02SDimitry Andric 
1943ca95b02SDimitry Andric     return std::make_pair(LocalSizeY, LocalSizeZ);
1953ca95b02SDimitry Andric   }
1963ca95b02SDimitry Andric 
1973ca95b02SDimitry Andric   // We must read the size out of the dispatch pointer.
1983ca95b02SDimitry Andric   assert(IsAMDGCN);
1993ca95b02SDimitry Andric 
2003ca95b02SDimitry Andric   // We are indexing into this struct, and want to extract the workgroup_size_*
2013ca95b02SDimitry Andric   // fields.
2023ca95b02SDimitry Andric   //
2033ca95b02SDimitry Andric   //   typedef struct hsa_kernel_dispatch_packet_s {
2043ca95b02SDimitry Andric   //     uint16_t header;
2053ca95b02SDimitry Andric   //     uint16_t setup;
2063ca95b02SDimitry Andric   //     uint16_t workgroup_size_x ;
2073ca95b02SDimitry Andric   //     uint16_t workgroup_size_y;
2083ca95b02SDimitry Andric   //     uint16_t workgroup_size_z;
2093ca95b02SDimitry Andric   //     uint16_t reserved0;
2103ca95b02SDimitry Andric   //     uint32_t grid_size_x ;
2113ca95b02SDimitry Andric   //     uint32_t grid_size_y ;
2123ca95b02SDimitry Andric   //     uint32_t grid_size_z;
2133ca95b02SDimitry Andric   //
2143ca95b02SDimitry Andric   //     uint32_t private_segment_size;
2153ca95b02SDimitry Andric   //     uint32_t group_segment_size;
2163ca95b02SDimitry Andric   //     uint64_t kernel_object;
2173ca95b02SDimitry Andric   //
2183ca95b02SDimitry Andric   // #ifdef HSA_LARGE_MODEL
2193ca95b02SDimitry Andric   //     void *kernarg_address;
2203ca95b02SDimitry Andric   // #elif defined HSA_LITTLE_ENDIAN
2213ca95b02SDimitry Andric   //     void *kernarg_address;
2223ca95b02SDimitry Andric   //     uint32_t reserved1;
2233ca95b02SDimitry Andric   // #else
2243ca95b02SDimitry Andric   //     uint32_t reserved1;
2253ca95b02SDimitry Andric   //     void *kernarg_address;
2263ca95b02SDimitry Andric   // #endif
2273ca95b02SDimitry Andric   //     uint64_t reserved2;
2283ca95b02SDimitry Andric   //     hsa_signal_t completion_signal; // uint64_t wrapper
2293ca95b02SDimitry Andric   //   } hsa_kernel_dispatch_packet_t
2303ca95b02SDimitry Andric   //
2313ca95b02SDimitry Andric   Function *DispatchPtrFn
2323ca95b02SDimitry Andric     = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
2333ca95b02SDimitry Andric 
2343ca95b02SDimitry Andric   CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
2357a7e6055SDimitry Andric   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
2367a7e6055SDimitry Andric   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
2373ca95b02SDimitry Andric 
2383ca95b02SDimitry Andric   // Size of the dispatch packet struct.
2397a7e6055SDimitry Andric   DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
2403ca95b02SDimitry Andric 
2413ca95b02SDimitry Andric   Type *I32Ty = Type::getInt32Ty(Mod->getContext());
2423ca95b02SDimitry Andric   Value *CastDispatchPtr = Builder.CreateBitCast(
243*b5893f02SDimitry Andric     DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
2443ca95b02SDimitry Andric 
2453ca95b02SDimitry Andric   // We could do a single 64-bit load here, but it's likely that the basic
2463ca95b02SDimitry Andric   // 32-bit and extract sequence is already present, and it is probably easier
2473ca95b02SDimitry Andric   // to CSE this. The loads should be mergable later anyway.
2483ca95b02SDimitry Andric   Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
2493ca95b02SDimitry Andric   LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
2503ca95b02SDimitry Andric 
2513ca95b02SDimitry Andric   Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
2523ca95b02SDimitry Andric   LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
2533ca95b02SDimitry Andric 
2547a7e6055SDimitry Andric   MDNode *MD = MDNode::get(Mod->getContext(), None);
2553ca95b02SDimitry Andric   LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
2563ca95b02SDimitry Andric   LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
2577a7e6055SDimitry Andric   ST.makeLIDRangeMetadata(LoadZU);
2583ca95b02SDimitry Andric 
2593ca95b02SDimitry Andric   // Extract y component. Upper half of LoadZU should be zero already.
2603ca95b02SDimitry Andric   Value *Y = Builder.CreateLShr(LoadXY, 16);
2613ca95b02SDimitry Andric 
2623ca95b02SDimitry Andric   return std::make_pair(Y, LoadZU);
2633ca95b02SDimitry Andric }
2643ca95b02SDimitry Andric 
getWorkitemID(IRBuilder<> & Builder,unsigned N)2653ca95b02SDimitry Andric Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
2664ba319b5SDimitry Andric   const AMDGPUSubtarget &ST =
2674ba319b5SDimitry Andric       AMDGPUSubtarget::get(*TM, *Builder.GetInsertBlock()->getParent());
2683ca95b02SDimitry Andric   Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
2693ca95b02SDimitry Andric 
2703ca95b02SDimitry Andric   switch (N) {
2713ca95b02SDimitry Andric   case 0:
2723ca95b02SDimitry Andric     IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
2733ca95b02SDimitry Andric       : Intrinsic::r600_read_tidig_x;
2743ca95b02SDimitry Andric     break;
2753ca95b02SDimitry Andric   case 1:
2763ca95b02SDimitry Andric     IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
2773ca95b02SDimitry Andric       : Intrinsic::r600_read_tidig_y;
2783ca95b02SDimitry Andric     break;
2793ca95b02SDimitry Andric 
2803ca95b02SDimitry Andric   case 2:
2813ca95b02SDimitry Andric     IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
2823ca95b02SDimitry Andric       : Intrinsic::r600_read_tidig_z;
2833ca95b02SDimitry Andric     break;
2843ca95b02SDimitry Andric   default:
2853ca95b02SDimitry Andric     llvm_unreachable("invalid dimension");
2863ca95b02SDimitry Andric   }
2873ca95b02SDimitry Andric 
2883ca95b02SDimitry Andric   Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
2893ca95b02SDimitry Andric   CallInst *CI = Builder.CreateCall(WorkitemIdFn);
2907a7e6055SDimitry Andric   ST.makeLIDRangeMetadata(CI);
2913ca95b02SDimitry Andric 
2923ca95b02SDimitry Andric   return CI;
2938f0fd8f6SDimitry Andric }
2948f0fd8f6SDimitry Andric 
arrayTypeToVecType(ArrayType * ArrayTy)2952cab237bSDimitry Andric static VectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
2962cab237bSDimitry Andric   return VectorType::get(ArrayTy->getElementType(),
2972cab237bSDimitry Andric                          ArrayTy->getNumElements());
2988f0fd8f6SDimitry Andric }
2998f0fd8f6SDimitry Andric 
3008f0fd8f6SDimitry Andric static Value *
calculateVectorIndex(Value * Ptr,const std::map<GetElementPtrInst *,Value * > & GEPIdx)3018f0fd8f6SDimitry Andric calculateVectorIndex(Value *Ptr,
3028f0fd8f6SDimitry Andric                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
3038f0fd8f6SDimitry Andric   GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
3048f0fd8f6SDimitry Andric 
3058f0fd8f6SDimitry Andric   auto I = GEPIdx.find(GEP);
3068f0fd8f6SDimitry Andric   return I == GEPIdx.end() ? nullptr : I->second;
3078f0fd8f6SDimitry Andric }
3088f0fd8f6SDimitry Andric 
GEPToVectorIndex(GetElementPtrInst * GEP)3098f0fd8f6SDimitry Andric static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
3108f0fd8f6SDimitry Andric   // FIXME we only support simple cases
3118f0fd8f6SDimitry Andric   if (GEP->getNumOperands() != 3)
3126c4bc1bdSDimitry Andric     return nullptr;
3138f0fd8f6SDimitry Andric 
3148f0fd8f6SDimitry Andric   ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
3158f0fd8f6SDimitry Andric   if (!I0 || !I0->isZero())
3166c4bc1bdSDimitry Andric     return nullptr;
3178f0fd8f6SDimitry Andric 
3188f0fd8f6SDimitry Andric   return GEP->getOperand(2);
3198f0fd8f6SDimitry Andric }
3208f0fd8f6SDimitry Andric 
3218f0fd8f6SDimitry Andric // Not an instruction handled below to turn into a vector.
3228f0fd8f6SDimitry Andric //
3238f0fd8f6SDimitry Andric // TODO: Check isTriviallyVectorizable for calls and handle other
3248f0fd8f6SDimitry Andric // instructions.
canVectorizeInst(Instruction * Inst,User * User)3259a4b3118SDimitry Andric static bool canVectorizeInst(Instruction *Inst, User *User) {
3268f0fd8f6SDimitry Andric   switch (Inst->getOpcode()) {
3275517e702SDimitry Andric   case Instruction::Load: {
3284ba319b5SDimitry Andric     // Currently only handle the case where the Pointer Operand is a GEP.
3294ba319b5SDimitry Andric     // Also we could not vectorize volatile or atomic loads.
3305517e702SDimitry Andric     LoadInst *LI = cast<LoadInst>(Inst);
331*b5893f02SDimitry Andric     if (isa<AllocaInst>(User) &&
332*b5893f02SDimitry Andric         LI->getPointerOperandType() == User->getType() &&
333*b5893f02SDimitry Andric         isa<VectorType>(LI->getType()))
334*b5893f02SDimitry Andric       return true;
3354ba319b5SDimitry Andric     return isa<GetElementPtrInst>(LI->getPointerOperand()) && LI->isSimple();
3365517e702SDimitry Andric   }
3378f0fd8f6SDimitry Andric   case Instruction::BitCast:
3388f0fd8f6SDimitry Andric     return true;
3399a4b3118SDimitry Andric   case Instruction::Store: {
340db17bf38SDimitry Andric     // Must be the stored pointer operand, not a stored value, plus
341db17bf38SDimitry Andric     // since it should be canonical form, the User should be a GEP.
3424ba319b5SDimitry Andric     // Also we could not vectorize volatile or atomic stores.
3439a4b3118SDimitry Andric     StoreInst *SI = cast<StoreInst>(Inst);
344*b5893f02SDimitry Andric     if (isa<AllocaInst>(User) &&
345*b5893f02SDimitry Andric         SI->getPointerOperandType() == User->getType() &&
346*b5893f02SDimitry Andric         isa<VectorType>(SI->getValueOperand()->getType()))
347*b5893f02SDimitry Andric       return true;
3484ba319b5SDimitry Andric     return (SI->getPointerOperand() == User) && isa<GetElementPtrInst>(User) && SI->isSimple();
3499a4b3118SDimitry Andric   }
3508f0fd8f6SDimitry Andric   default:
3518f0fd8f6SDimitry Andric     return false;
3528f0fd8f6SDimitry Andric   }
3538f0fd8f6SDimitry Andric }
3548f0fd8f6SDimitry Andric 
tryPromoteAllocaToVector(AllocaInst * Alloca)355*b5893f02SDimitry Andric static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
3564ba319b5SDimitry Andric 
3574ba319b5SDimitry Andric   if (DisablePromoteAllocaToVector) {
3584ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
3594ba319b5SDimitry Andric     return false;
3604ba319b5SDimitry Andric   }
3614ba319b5SDimitry Andric 
362*b5893f02SDimitry Andric   Type *AT = Alloca->getAllocatedType();
363*b5893f02SDimitry Andric   SequentialType *AllocaTy = dyn_cast<SequentialType>(AT);
3648f0fd8f6SDimitry Andric 
3654ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
3668f0fd8f6SDimitry Andric 
3678f0fd8f6SDimitry Andric   // FIXME: There is no reason why we can't support larger arrays, we
3688f0fd8f6SDimitry Andric   // are just being conservative for now.
369db17bf38SDimitry Andric   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
370db17bf38SDimitry Andric   // could also be promoted but we don't currently handle this case
3713ca95b02SDimitry Andric   if (!AllocaTy ||
3724ba319b5SDimitry Andric       AllocaTy->getNumElements() > 16 ||
3732cab237bSDimitry Andric       AllocaTy->getNumElements() < 2 ||
3742cab237bSDimitry Andric       !VectorType::isValidElementType(AllocaTy->getElementType())) {
3754ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
3768f0fd8f6SDimitry Andric     return false;
3778f0fd8f6SDimitry Andric   }
3788f0fd8f6SDimitry Andric 
3798f0fd8f6SDimitry Andric   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
3808f0fd8f6SDimitry Andric   std::vector<Value*> WorkList;
3818f0fd8f6SDimitry Andric   for (User *AllocaUser : Alloca->users()) {
3828f0fd8f6SDimitry Andric     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
3838f0fd8f6SDimitry Andric     if (!GEP) {
3849a4b3118SDimitry Andric       if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
3858f0fd8f6SDimitry Andric         return false;
3868f0fd8f6SDimitry Andric 
3878f0fd8f6SDimitry Andric       WorkList.push_back(AllocaUser);
3888f0fd8f6SDimitry Andric       continue;
3898f0fd8f6SDimitry Andric     }
3908f0fd8f6SDimitry Andric 
3918f0fd8f6SDimitry Andric     Value *Index = GEPToVectorIndex(GEP);
3928f0fd8f6SDimitry Andric 
3938f0fd8f6SDimitry Andric     // If we can't compute a vector index from this GEP, then we can't
3948f0fd8f6SDimitry Andric     // promote this alloca to vector.
3958f0fd8f6SDimitry Andric     if (!Index) {
3964ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
3974ba319b5SDimitry Andric                         << '\n');
3988f0fd8f6SDimitry Andric       return false;
3998f0fd8f6SDimitry Andric     }
4008f0fd8f6SDimitry Andric 
4018f0fd8f6SDimitry Andric     GEPVectorIdx[GEP] = Index;
4028f0fd8f6SDimitry Andric     for (User *GEPUser : AllocaUser->users()) {
4039a4b3118SDimitry Andric       if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
4048f0fd8f6SDimitry Andric         return false;
4058f0fd8f6SDimitry Andric 
4068f0fd8f6SDimitry Andric       WorkList.push_back(GEPUser);
4078f0fd8f6SDimitry Andric     }
4088f0fd8f6SDimitry Andric   }
4098f0fd8f6SDimitry Andric 
410*b5893f02SDimitry Andric   VectorType *VectorTy = dyn_cast<VectorType>(AllocaTy);
411*b5893f02SDimitry Andric   if (!VectorTy)
412*b5893f02SDimitry Andric     VectorTy = arrayTypeToVecType(cast<ArrayType>(AllocaTy));
4138f0fd8f6SDimitry Andric 
4144ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
4154ba319b5SDimitry Andric                     << *VectorTy << '\n');
4168f0fd8f6SDimitry Andric 
4173ca95b02SDimitry Andric   for (Value *V : WorkList) {
4183ca95b02SDimitry Andric     Instruction *Inst = cast<Instruction>(V);
4198f0fd8f6SDimitry Andric     IRBuilder<> Builder(Inst);
4208f0fd8f6SDimitry Andric     switch (Inst->getOpcode()) {
4218f0fd8f6SDimitry Andric     case Instruction::Load: {
422*b5893f02SDimitry Andric       if (Inst->getType() == AT)
423*b5893f02SDimitry Andric         break;
424*b5893f02SDimitry Andric 
425*b5893f02SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
426db17bf38SDimitry Andric       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
4278f0fd8f6SDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
4286c4bc1bdSDimitry Andric 
4296c4bc1bdSDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
4308f0fd8f6SDimitry Andric       Value *VecValue = Builder.CreateLoad(BitCast);
4318f0fd8f6SDimitry Andric       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
4328f0fd8f6SDimitry Andric       Inst->replaceAllUsesWith(ExtractElement);
4338f0fd8f6SDimitry Andric       Inst->eraseFromParent();
4348f0fd8f6SDimitry Andric       break;
4358f0fd8f6SDimitry Andric     }
4368f0fd8f6SDimitry Andric     case Instruction::Store: {
437db17bf38SDimitry Andric       StoreInst *SI = cast<StoreInst>(Inst);
438*b5893f02SDimitry Andric       if (SI->getValueOperand()->getType() == AT)
439*b5893f02SDimitry Andric         break;
440*b5893f02SDimitry Andric 
441*b5893f02SDimitry Andric       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
442db17bf38SDimitry Andric       Value *Ptr = SI->getPointerOperand();
4438f0fd8f6SDimitry Andric       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
4446c4bc1bdSDimitry Andric       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
4458f0fd8f6SDimitry Andric       Value *VecValue = Builder.CreateLoad(BitCast);
4468f0fd8f6SDimitry Andric       Value *NewVecValue = Builder.CreateInsertElement(VecValue,
447db17bf38SDimitry Andric                                                        SI->getValueOperand(),
4488f0fd8f6SDimitry Andric                                                        Index);
4498f0fd8f6SDimitry Andric       Builder.CreateStore(NewVecValue, BitCast);
4508f0fd8f6SDimitry Andric       Inst->eraseFromParent();
4518f0fd8f6SDimitry Andric       break;
4528f0fd8f6SDimitry Andric     }
4538f0fd8f6SDimitry Andric     case Instruction::BitCast:
4548f0fd8f6SDimitry Andric     case Instruction::AddrSpaceCast:
4558f0fd8f6SDimitry Andric       break;
4568f0fd8f6SDimitry Andric 
4578f0fd8f6SDimitry Andric     default:
4588f0fd8f6SDimitry Andric       llvm_unreachable("Inconsistency in instructions promotable to vector");
4598f0fd8f6SDimitry Andric     }
4608f0fd8f6SDimitry Andric   }
4618f0fd8f6SDimitry Andric   return true;
4628f0fd8f6SDimitry Andric }
4638f0fd8f6SDimitry Andric 
isCallPromotable(CallInst * CI)4643ca95b02SDimitry Andric static bool isCallPromotable(CallInst *CI) {
4653ca95b02SDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
4663ca95b02SDimitry Andric   if (!II)
4673ca95b02SDimitry Andric     return false;
4683ca95b02SDimitry Andric 
4693ca95b02SDimitry Andric   switch (II->getIntrinsicID()) {
4703ca95b02SDimitry Andric   case Intrinsic::memcpy:
4713ca95b02SDimitry Andric   case Intrinsic::memmove:
4723ca95b02SDimitry Andric   case Intrinsic::memset:
4733ca95b02SDimitry Andric   case Intrinsic::lifetime_start:
4743ca95b02SDimitry Andric   case Intrinsic::lifetime_end:
4753ca95b02SDimitry Andric   case Intrinsic::invariant_start:
4763ca95b02SDimitry Andric   case Intrinsic::invariant_end:
4774ba319b5SDimitry Andric   case Intrinsic::launder_invariant_group:
4784ba319b5SDimitry Andric   case Intrinsic::strip_invariant_group:
4793ca95b02SDimitry Andric   case Intrinsic::objectsize:
4803ca95b02SDimitry Andric     return true;
4813ca95b02SDimitry Andric   default:
4823ca95b02SDimitry Andric     return false;
4833ca95b02SDimitry Andric   }
4843ca95b02SDimitry Andric }
4853ca95b02SDimitry Andric 
binaryOpIsDerivedFromSameAlloca(Value * BaseAlloca,Value * Val,Instruction * Inst,int OpIdx0,int OpIdx1) const4863ca95b02SDimitry Andric bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
4873ca95b02SDimitry Andric                                                           Value *Val,
4883ca95b02SDimitry Andric                                                           Instruction *Inst,
4893ca95b02SDimitry Andric                                                           int OpIdx0,
4903ca95b02SDimitry Andric                                                           int OpIdx1) const {
4913ca95b02SDimitry Andric   // Figure out which operand is the one we might not be promoting.
4923ca95b02SDimitry Andric   Value *OtherOp = Inst->getOperand(OpIdx0);
4933ca95b02SDimitry Andric   if (Val == OtherOp)
4943ca95b02SDimitry Andric     OtherOp = Inst->getOperand(OpIdx1);
4953ca95b02SDimitry Andric 
4963ca95b02SDimitry Andric   if (isa<ConstantPointerNull>(OtherOp))
4973ca95b02SDimitry Andric     return true;
4983ca95b02SDimitry Andric 
4993ca95b02SDimitry Andric   Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
5003ca95b02SDimitry Andric   if (!isa<AllocaInst>(OtherObj))
5013ca95b02SDimitry Andric     return false;
5023ca95b02SDimitry Andric 
5033ca95b02SDimitry Andric   // TODO: We should be able to replace undefs with the right pointer type.
5043ca95b02SDimitry Andric 
5053ca95b02SDimitry Andric   // TODO: If we know the other base object is another promotable
5063ca95b02SDimitry Andric   // alloca, not necessarily this alloca, we can do this. The
5073ca95b02SDimitry Andric   // important part is both must have the same address space at
5083ca95b02SDimitry Andric   // the end.
5093ca95b02SDimitry Andric   if (OtherObj != BaseAlloca) {
5104ba319b5SDimitry Andric     LLVM_DEBUG(
5114ba319b5SDimitry Andric         dbgs() << "Found a binary instruction with another alloca object\n");
5123ca95b02SDimitry Andric     return false;
5133ca95b02SDimitry Andric   }
5143ca95b02SDimitry Andric 
5153ca95b02SDimitry Andric   return true;
5163ca95b02SDimitry Andric }
5173ca95b02SDimitry Andric 
collectUsesWithPtrTypes(Value * BaseAlloca,Value * Val,std::vector<Value * > & WorkList) const5183ca95b02SDimitry Andric bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
5193ca95b02SDimitry Andric   Value *BaseAlloca,
5203ca95b02SDimitry Andric   Value *Val,
5213ca95b02SDimitry Andric   std::vector<Value*> &WorkList) const {
5223ca95b02SDimitry Andric 
5233ca95b02SDimitry Andric   for (User *User : Val->users()) {
524d88c1a5aSDimitry Andric     if (is_contained(WorkList, User))
5253ca95b02SDimitry Andric       continue;
5263ca95b02SDimitry Andric 
5273ca95b02SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(User)) {
5283ca95b02SDimitry Andric       if (!isCallPromotable(CI))
5293ca95b02SDimitry Andric         return false;
5303ca95b02SDimitry Andric 
5318f0fd8f6SDimitry Andric       WorkList.push_back(User);
5328f0fd8f6SDimitry Andric       continue;
5338f0fd8f6SDimitry Andric     }
5348f0fd8f6SDimitry Andric 
5353ca95b02SDimitry Andric     Instruction *UseInst = cast<Instruction>(User);
5363ca95b02SDimitry Andric     if (UseInst->getOpcode() == Instruction::PtrToInt)
5378f0fd8f6SDimitry Andric       return false;
5388f0fd8f6SDimitry Andric 
539d88c1a5aSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
5403ca95b02SDimitry Andric       if (LI->isVolatile())
5413ca95b02SDimitry Andric         return false;
5423ca95b02SDimitry Andric 
5433ca95b02SDimitry Andric       continue;
5443ca95b02SDimitry Andric     }
5453ca95b02SDimitry Andric 
5463ca95b02SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
5473ca95b02SDimitry Andric       if (SI->isVolatile())
5483ca95b02SDimitry Andric         return false;
5493ca95b02SDimitry Andric 
5509a4b3118SDimitry Andric       // Reject if the stored value is not the pointer operand.
5519a4b3118SDimitry Andric       if (SI->getPointerOperand() != Val)
5529a4b3118SDimitry Andric         return false;
553d88c1a5aSDimitry Andric     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
5543ca95b02SDimitry Andric       if (RMW->isVolatile())
5553ca95b02SDimitry Andric         return false;
556d88c1a5aSDimitry Andric     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
5573ca95b02SDimitry Andric       if (CAS->isVolatile())
5583ca95b02SDimitry Andric         return false;
5593ca95b02SDimitry Andric     }
5603ca95b02SDimitry Andric 
5613ca95b02SDimitry Andric     // Only promote a select if we know that the other select operand
5623ca95b02SDimitry Andric     // is from another pointer that will also be promoted.
5633ca95b02SDimitry Andric     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
5643ca95b02SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
5653ca95b02SDimitry Andric         return false;
5663ca95b02SDimitry Andric 
5673ca95b02SDimitry Andric       // May need to rewrite constant operands.
5683ca95b02SDimitry Andric       WorkList.push_back(ICmp);
5699a4b3118SDimitry Andric     }
5709a4b3118SDimitry Andric 
571d88c1a5aSDimitry Andric     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
5727a7e6055SDimitry Andric       // Give up if the pointer may be captured.
5737a7e6055SDimitry Andric       if (PointerMayBeCaptured(UseInst, true, true))
5747a7e6055SDimitry Andric         return false;
575d88c1a5aSDimitry Andric       // Don't collect the users of this.
576d88c1a5aSDimitry Andric       WorkList.push_back(User);
577d88c1a5aSDimitry Andric       continue;
578d88c1a5aSDimitry Andric     }
579d88c1a5aSDimitry Andric 
5808f0fd8f6SDimitry Andric     if (!User->getType()->isPointerTy())
5818f0fd8f6SDimitry Andric       continue;
5828f0fd8f6SDimitry Andric 
5833ca95b02SDimitry Andric     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
5843ca95b02SDimitry Andric       // Be conservative if an address could be computed outside the bounds of
5853ca95b02SDimitry Andric       // the alloca.
5863ca95b02SDimitry Andric       if (!GEP->isInBounds())
5873ca95b02SDimitry Andric         return false;
5883ca95b02SDimitry Andric     }
5893ca95b02SDimitry Andric 
5903ca95b02SDimitry Andric     // Only promote a select if we know that the other select operand is from
5913ca95b02SDimitry Andric     // another pointer that will also be promoted.
5923ca95b02SDimitry Andric     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
5933ca95b02SDimitry Andric       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
5943ca95b02SDimitry Andric         return false;
5953ca95b02SDimitry Andric     }
5963ca95b02SDimitry Andric 
5973ca95b02SDimitry Andric     // Repeat for phis.
5983ca95b02SDimitry Andric     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
5993ca95b02SDimitry Andric       // TODO: Handle more complex cases. We should be able to replace loops
6003ca95b02SDimitry Andric       // over arrays.
6013ca95b02SDimitry Andric       switch (Phi->getNumIncomingValues()) {
6023ca95b02SDimitry Andric       case 1:
6033ca95b02SDimitry Andric         break;
6043ca95b02SDimitry Andric       case 2:
6053ca95b02SDimitry Andric         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
6063ca95b02SDimitry Andric           return false;
6073ca95b02SDimitry Andric         break;
6083ca95b02SDimitry Andric       default:
6093ca95b02SDimitry Andric         return false;
6103ca95b02SDimitry Andric       }
6113ca95b02SDimitry Andric     }
6123ca95b02SDimitry Andric 
6138f0fd8f6SDimitry Andric     WorkList.push_back(User);
6143ca95b02SDimitry Andric     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
6153ca95b02SDimitry Andric       return false;
6168f0fd8f6SDimitry Andric   }
6178f0fd8f6SDimitry Andric 
6183ca95b02SDimitry Andric   return true;
6193ca95b02SDimitry Andric }
6203ca95b02SDimitry Andric 
hasSufficientLocalMem(const Function & F)621302affcbSDimitry Andric bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
622302affcbSDimitry Andric 
623302affcbSDimitry Andric   FunctionType *FTy = F.getFunctionType();
6244ba319b5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
625302affcbSDimitry Andric 
626302affcbSDimitry Andric   // If the function has any arguments in the local address space, then it's
627302affcbSDimitry Andric   // possible these arguments require the entire local memory space, so
628302affcbSDimitry Andric   // we cannot use local memory in the pass.
629302affcbSDimitry Andric   for (Type *ParamTy : FTy->params()) {
630302affcbSDimitry Andric     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
631*b5893f02SDimitry Andric     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
632302affcbSDimitry Andric       LocalMemLimit = 0;
6334ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
634302affcbSDimitry Andric                            "local memory disabled.\n");
635302affcbSDimitry Andric       return false;
636302affcbSDimitry Andric     }
637302affcbSDimitry Andric   }
638302affcbSDimitry Andric 
639302affcbSDimitry Andric   LocalMemLimit = ST.getLocalMemorySize();
640302affcbSDimitry Andric   if (LocalMemLimit == 0)
641302affcbSDimitry Andric     return false;
642302affcbSDimitry Andric 
643302affcbSDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
644302affcbSDimitry Andric 
645302affcbSDimitry Andric   // Check how much local memory is being used by global objects
646302affcbSDimitry Andric   CurrentLocalMemUsage = 0;
647302affcbSDimitry Andric   for (GlobalVariable &GV : Mod->globals()) {
648*b5893f02SDimitry Andric     if (GV.getType()->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
649302affcbSDimitry Andric       continue;
650302affcbSDimitry Andric 
651302affcbSDimitry Andric     for (const User *U : GV.users()) {
652302affcbSDimitry Andric       const Instruction *Use = dyn_cast<Instruction>(U);
653302affcbSDimitry Andric       if (!Use)
654302affcbSDimitry Andric         continue;
655302affcbSDimitry Andric 
656302affcbSDimitry Andric       if (Use->getParent()->getParent() == &F) {
657302affcbSDimitry Andric         unsigned Align = GV.getAlignment();
658302affcbSDimitry Andric         if (Align == 0)
659302affcbSDimitry Andric           Align = DL.getABITypeAlignment(GV.getValueType());
660302affcbSDimitry Andric 
661302affcbSDimitry Andric         // FIXME: Try to account for padding here. The padding is currently
662302affcbSDimitry Andric         // determined from the inverse order of uses in the function. I'm not
663302affcbSDimitry Andric         // sure if the use list order is in any way connected to this, so the
664302affcbSDimitry Andric         // total reported size is likely incorrect.
665302affcbSDimitry Andric         uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
666302affcbSDimitry Andric         CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
667302affcbSDimitry Andric         CurrentLocalMemUsage += AllocSize;
668302affcbSDimitry Andric         break;
669302affcbSDimitry Andric       }
670302affcbSDimitry Andric     }
671302affcbSDimitry Andric   }
672302affcbSDimitry Andric 
673302affcbSDimitry Andric   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
674302affcbSDimitry Andric                                                           F);
675302affcbSDimitry Andric 
676302affcbSDimitry Andric   // Restrict local memory usage so that we don't drastically reduce occupancy,
677302affcbSDimitry Andric   // unless it is already significantly reduced.
678302affcbSDimitry Andric 
679302affcbSDimitry Andric   // TODO: Have some sort of hint or other heuristics to guess occupancy based
680302affcbSDimitry Andric   // on other factors..
681302affcbSDimitry Andric   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
682302affcbSDimitry Andric   if (OccupancyHint == 0)
683302affcbSDimitry Andric     OccupancyHint = 7;
684302affcbSDimitry Andric 
685302affcbSDimitry Andric   // Clamp to max value.
686302affcbSDimitry Andric   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
687302affcbSDimitry Andric 
688302affcbSDimitry Andric   // Check the hint but ignore it if it's obviously wrong from the existing LDS
689302affcbSDimitry Andric   // usage.
690302affcbSDimitry Andric   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
691302affcbSDimitry Andric 
692302affcbSDimitry Andric 
693302affcbSDimitry Andric   // Round up to the next tier of usage.
694302affcbSDimitry Andric   unsigned MaxSizeWithWaveCount
695302affcbSDimitry Andric     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
696302affcbSDimitry Andric 
697302affcbSDimitry Andric   // Program is possibly broken by using more local mem than available.
698302affcbSDimitry Andric   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
699302affcbSDimitry Andric     return false;
700302affcbSDimitry Andric 
701302affcbSDimitry Andric   LocalMemLimit = MaxSizeWithWaveCount;
702302affcbSDimitry Andric 
7034ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
7044ba319b5SDimitry Andric                     << " bytes of LDS\n"
705302affcbSDimitry Andric                     << "  Rounding size to " << MaxSizeWithWaveCount
706302affcbSDimitry Andric                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
707302affcbSDimitry Andric                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
7084ba319b5SDimitry Andric                     << " available for promotion\n");
709302affcbSDimitry Andric 
710302affcbSDimitry Andric   return true;
711302affcbSDimitry Andric }
712302affcbSDimitry Andric 
7133ca95b02SDimitry Andric // FIXME: Should try to pick the most likely to be profitable allocas first.
handleAlloca(AllocaInst & I,bool SufficientLDS)714302affcbSDimitry Andric bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
7153ca95b02SDimitry Andric   // Array allocations are probably not worth handling, since an allocation of
7163ca95b02SDimitry Andric   // the array type is the canonical form.
7173ca95b02SDimitry Andric   if (!I.isStaticAlloca() || I.isArrayAllocation())
718302affcbSDimitry Andric     return false;
7197d523365SDimitry Andric 
7208f0fd8f6SDimitry Andric   IRBuilder<> Builder(&I);
7218f0fd8f6SDimitry Andric 
7228f0fd8f6SDimitry Andric   // First try to replace the alloca with a vector
7238f0fd8f6SDimitry Andric   Type *AllocaTy = I.getAllocatedType();
7248f0fd8f6SDimitry Andric 
7254ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
7268f0fd8f6SDimitry Andric 
727*b5893f02SDimitry Andric   if (tryPromoteAllocaToVector(&I))
728302affcbSDimitry Andric     return true; // Promoted to vector.
7298f0fd8f6SDimitry Andric 
730*b5893f02SDimitry Andric   if (DisablePromoteAllocaToLDS)
731*b5893f02SDimitry Andric     return false;
732*b5893f02SDimitry Andric 
7333ca95b02SDimitry Andric   const Function &ContainingFunction = *I.getParent()->getParent();
734f37b6182SDimitry Andric   CallingConv::ID CC = ContainingFunction.getCallingConv();
7353ca95b02SDimitry Andric 
7363ca95b02SDimitry Andric   // Don't promote the alloca to LDS for shader calling conventions as the work
7373ca95b02SDimitry Andric   // item ID intrinsics are not supported for these calling conventions.
7383ca95b02SDimitry Andric   // Furthermore not all LDS is available for some of the stages.
739f37b6182SDimitry Andric   switch (CC) {
740f37b6182SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
741f37b6182SDimitry Andric   case CallingConv::SPIR_KERNEL:
742f37b6182SDimitry Andric     break;
743f37b6182SDimitry Andric   default:
7444ba319b5SDimitry Andric     LLVM_DEBUG(
7454ba319b5SDimitry Andric         dbgs()
7464ba319b5SDimitry Andric         << " promote alloca to LDS not supported with calling convention.\n");
747302affcbSDimitry Andric     return false;
748f37b6182SDimitry Andric   }
7493ca95b02SDimitry Andric 
750302affcbSDimitry Andric   // Not likely to have sufficient local memory for promotion.
751302affcbSDimitry Andric   if (!SufficientLDS)
752302affcbSDimitry Andric     return false;
753302affcbSDimitry Andric 
7544ba319b5SDimitry Andric   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, ContainingFunction);
755d88c1a5aSDimitry Andric   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
7563ca95b02SDimitry Andric 
7573ca95b02SDimitry Andric   const DataLayout &DL = Mod->getDataLayout();
7583ca95b02SDimitry Andric 
7593ca95b02SDimitry Andric   unsigned Align = I.getAlignment();
7603ca95b02SDimitry Andric   if (Align == 0)
7613ca95b02SDimitry Andric     Align = DL.getABITypeAlignment(I.getAllocatedType());
7623ca95b02SDimitry Andric 
7633ca95b02SDimitry Andric   // FIXME: This computed padding is likely wrong since it depends on inverse
7643ca95b02SDimitry Andric   // usage order.
7653ca95b02SDimitry Andric   //
7663ca95b02SDimitry Andric   // FIXME: It is also possible that if we're allowed to use all of the memory
7673ca95b02SDimitry Andric   // could could end up using more than the maximum due to alignment padding.
7683ca95b02SDimitry Andric 
7693ca95b02SDimitry Andric   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
7703ca95b02SDimitry Andric   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
7713ca95b02SDimitry Andric   NewSize += AllocSize;
7723ca95b02SDimitry Andric 
7733ca95b02SDimitry Andric   if (NewSize > LocalMemLimit) {
7744ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << AllocSize
7753ca95b02SDimitry Andric                       << " bytes of local memory not available to promote\n");
776302affcbSDimitry Andric     return false;
7773ca95b02SDimitry Andric   }
7783ca95b02SDimitry Andric 
7793ca95b02SDimitry Andric   CurrentLocalMemUsage = NewSize;
7803ca95b02SDimitry Andric 
7818f0fd8f6SDimitry Andric   std::vector<Value*> WorkList;
7828f0fd8f6SDimitry Andric 
7833ca95b02SDimitry Andric   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
7844ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
785302affcbSDimitry Andric     return false;
7868f0fd8f6SDimitry Andric   }
7878f0fd8f6SDimitry Andric 
7884ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
7898f0fd8f6SDimitry Andric 
7903ca95b02SDimitry Andric   Function *F = I.getParent()->getParent();
7913ca95b02SDimitry Andric 
7923ca95b02SDimitry Andric   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
7938f0fd8f6SDimitry Andric   GlobalVariable *GV = new GlobalVariable(
7943ca95b02SDimitry Andric       *Mod, GVTy, false, GlobalValue::InternalLinkage,
7953ca95b02SDimitry Andric       UndefValue::get(GVTy),
7963ca95b02SDimitry Andric       Twine(F->getName()) + Twine('.') + I.getName(),
7973ca95b02SDimitry Andric       nullptr,
7983ca95b02SDimitry Andric       GlobalVariable::NotThreadLocal,
799*b5893f02SDimitry Andric       AMDGPUAS::LOCAL_ADDRESS);
8003ca95b02SDimitry Andric   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
8013ca95b02SDimitry Andric   GV->setAlignment(I.getAlignment());
8028f0fd8f6SDimitry Andric 
8033ca95b02SDimitry Andric   Value *TCntY, *TCntZ;
8048f0fd8f6SDimitry Andric 
8053ca95b02SDimitry Andric   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
8063ca95b02SDimitry Andric   Value *TIdX = getWorkitemID(Builder, 0);
8073ca95b02SDimitry Andric   Value *TIdY = getWorkitemID(Builder, 1);
8083ca95b02SDimitry Andric   Value *TIdZ = getWorkitemID(Builder, 2);
8098f0fd8f6SDimitry Andric 
8103ca95b02SDimitry Andric   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
8118f0fd8f6SDimitry Andric   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
8123ca95b02SDimitry Andric   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
8138f0fd8f6SDimitry Andric   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
8148f0fd8f6SDimitry Andric   TID = Builder.CreateAdd(TID, TIdZ);
8158f0fd8f6SDimitry Andric 
8163ca95b02SDimitry Andric   Value *Indices[] = {
8173ca95b02SDimitry Andric     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
8183ca95b02SDimitry Andric     TID
8193ca95b02SDimitry Andric   };
8208f0fd8f6SDimitry Andric 
8213ca95b02SDimitry Andric   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
8228f0fd8f6SDimitry Andric   I.mutateType(Offset->getType());
8238f0fd8f6SDimitry Andric   I.replaceAllUsesWith(Offset);
8248f0fd8f6SDimitry Andric   I.eraseFromParent();
8258f0fd8f6SDimitry Andric 
8263ca95b02SDimitry Andric   for (Value *V : WorkList) {
8278f0fd8f6SDimitry Andric     CallInst *Call = dyn_cast<CallInst>(V);
8288f0fd8f6SDimitry Andric     if (!Call) {
8293ca95b02SDimitry Andric       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
8303ca95b02SDimitry Andric         Value *Src0 = CI->getOperand(0);
8313ca95b02SDimitry Andric         Type *EltTy = Src0->getType()->getPointerElementType();
832*b5893f02SDimitry Andric         PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
8338f0fd8f6SDimitry Andric 
8343ca95b02SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(0)))
8353ca95b02SDimitry Andric           CI->setOperand(0, ConstantPointerNull::get(NewTy));
8363ca95b02SDimitry Andric 
8373ca95b02SDimitry Andric         if (isa<ConstantPointerNull>(CI->getOperand(1)))
8383ca95b02SDimitry Andric           CI->setOperand(1, ConstantPointerNull::get(NewTy));
8393ca95b02SDimitry Andric 
8403ca95b02SDimitry Andric         continue;
8413ca95b02SDimitry Andric       }
8423ca95b02SDimitry Andric 
843d88c1a5aSDimitry Andric       // The operand's value should be corrected on its own and we don't want to
844d88c1a5aSDimitry Andric       // touch the users.
8458f0fd8f6SDimitry Andric       if (isa<AddrSpaceCastInst>(V))
8468f0fd8f6SDimitry Andric         continue;
8478f0fd8f6SDimitry Andric 
8483ca95b02SDimitry Andric       Type *EltTy = V->getType()->getPointerElementType();
849*b5893f02SDimitry Andric       PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
8503ca95b02SDimitry Andric 
8518f0fd8f6SDimitry Andric       // FIXME: It doesn't really make sense to try to do this for all
8528f0fd8f6SDimitry Andric       // instructions.
8538f0fd8f6SDimitry Andric       V->mutateType(NewTy);
8543ca95b02SDimitry Andric 
8553ca95b02SDimitry Andric       // Adjust the types of any constant operands.
8563ca95b02SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
8573ca95b02SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(1)))
8583ca95b02SDimitry Andric           SI->setOperand(1, ConstantPointerNull::get(NewTy));
8593ca95b02SDimitry Andric 
8603ca95b02SDimitry Andric         if (isa<ConstantPointerNull>(SI->getOperand(2)))
8613ca95b02SDimitry Andric           SI->setOperand(2, ConstantPointerNull::get(NewTy));
8623ca95b02SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
8633ca95b02SDimitry Andric         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
8643ca95b02SDimitry Andric           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
8653ca95b02SDimitry Andric             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
8663ca95b02SDimitry Andric         }
8673ca95b02SDimitry Andric       }
8683ca95b02SDimitry Andric 
8698f0fd8f6SDimitry Andric       continue;
8708f0fd8f6SDimitry Andric     }
8718f0fd8f6SDimitry Andric 
8726c4bc1bdSDimitry Andric     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
8738f0fd8f6SDimitry Andric     Builder.SetInsertPoint(Intr);
8748f0fd8f6SDimitry Andric     switch (Intr->getIntrinsicID()) {
8758f0fd8f6SDimitry Andric     case Intrinsic::lifetime_start:
8768f0fd8f6SDimitry Andric     case Intrinsic::lifetime_end:
8778f0fd8f6SDimitry Andric       // These intrinsics are for address space 0 only
8788f0fd8f6SDimitry Andric       Intr->eraseFromParent();
8798f0fd8f6SDimitry Andric       continue;
8808f0fd8f6SDimitry Andric     case Intrinsic::memcpy: {
8818f0fd8f6SDimitry Andric       MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
8824ba319b5SDimitry Andric       Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlignment(),
8834ba319b5SDimitry Andric                            MemCpy->getRawSource(), MemCpy->getSourceAlignment(),
8844ba319b5SDimitry Andric                            MemCpy->getLength(), MemCpy->isVolatile());
8858f0fd8f6SDimitry Andric       Intr->eraseFromParent();
8868f0fd8f6SDimitry Andric       continue;
8878f0fd8f6SDimitry Andric     }
8883ca95b02SDimitry Andric     case Intrinsic::memmove: {
8893ca95b02SDimitry Andric       MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
8904ba319b5SDimitry Andric       Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlignment(),
8914ba319b5SDimitry Andric                             MemMove->getRawSource(), MemMove->getSourceAlignment(),
8924ba319b5SDimitry Andric                             MemMove->getLength(), MemMove->isVolatile());
8933ca95b02SDimitry Andric       Intr->eraseFromParent();
8943ca95b02SDimitry Andric       continue;
8953ca95b02SDimitry Andric     }
8968f0fd8f6SDimitry Andric     case Intrinsic::memset: {
8978f0fd8f6SDimitry Andric       MemSetInst *MemSet = cast<MemSetInst>(Intr);
8988f0fd8f6SDimitry Andric       Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
8994ba319b5SDimitry Andric                            MemSet->getLength(), MemSet->getDestAlignment(),
9008f0fd8f6SDimitry Andric                            MemSet->isVolatile());
9018f0fd8f6SDimitry Andric       Intr->eraseFromParent();
9028f0fd8f6SDimitry Andric       continue;
9038f0fd8f6SDimitry Andric     }
9043ca95b02SDimitry Andric     case Intrinsic::invariant_start:
9053ca95b02SDimitry Andric     case Intrinsic::invariant_end:
9064ba319b5SDimitry Andric     case Intrinsic::launder_invariant_group:
9074ba319b5SDimitry Andric     case Intrinsic::strip_invariant_group:
9083ca95b02SDimitry Andric       Intr->eraseFromParent();
9093ca95b02SDimitry Andric       // FIXME: I think the invariant marker should still theoretically apply,
9103ca95b02SDimitry Andric       // but the intrinsics need to be changed to accept pointers with any
9113ca95b02SDimitry Andric       // address space.
9123ca95b02SDimitry Andric       continue;
9133ca95b02SDimitry Andric     case Intrinsic::objectsize: {
9143ca95b02SDimitry Andric       Value *Src = Intr->getOperand(0);
9153ca95b02SDimitry Andric       Type *SrcTy = Src->getType()->getPointerElementType();
9163ca95b02SDimitry Andric       Function *ObjectSize = Intrinsic::getDeclaration(Mod,
9173ca95b02SDimitry Andric         Intrinsic::objectsize,
918*b5893f02SDimitry Andric         { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
9193ca95b02SDimitry Andric       );
9203ca95b02SDimitry Andric 
9217a7e6055SDimitry Andric       CallInst *NewCall = Builder.CreateCall(
9227a7e6055SDimitry Andric           ObjectSize, {Src, Intr->getOperand(1), Intr->getOperand(2)});
9233ca95b02SDimitry Andric       Intr->replaceAllUsesWith(NewCall);
9243ca95b02SDimitry Andric       Intr->eraseFromParent();
9253ca95b02SDimitry Andric       continue;
9263ca95b02SDimitry Andric     }
9278f0fd8f6SDimitry Andric     default:
9287a7e6055SDimitry Andric       Intr->print(errs());
9298f0fd8f6SDimitry Andric       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
9308f0fd8f6SDimitry Andric     }
9318f0fd8f6SDimitry Andric   }
932302affcbSDimitry Andric   return true;
9338f0fd8f6SDimitry Andric }
9348f0fd8f6SDimitry Andric 
createAMDGPUPromoteAlloca()935d8866befSDimitry Andric FunctionPass *llvm::createAMDGPUPromoteAlloca() {
936d8866befSDimitry Andric   return new AMDGPUPromoteAlloca();
9378f0fd8f6SDimitry Andric }
938