1 //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass eliminates allocas by either converting them into vectors or
10 // by migrating them to local address space.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPU.h"
15 #include "AMDGPUSubtarget.h"
16 #include "Utils/AMDGPUBaseInfo.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/IntrinsicsAMDGPU.h"
41 #include "llvm/IR/IntrinsicsR600.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/PassManager.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/User.h"
48 #include "llvm/IR/Value.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <cstdint>
59 #include <map>
60 #include <tuple>
61 #include <utility>
62 #include <vector>
63 
64 #define DEBUG_TYPE "amdgpu-promote-alloca"
65 
66 using namespace llvm;
67 
68 namespace {
69 
70 static cl::opt<bool> DisablePromoteAllocaToVector(
71   "disable-promote-alloca-to-vector",
72   cl::desc("Disable promote alloca to vector"),
73   cl::init(false));
74 
75 static cl::opt<bool> DisablePromoteAllocaToLDS(
76   "disable-promote-alloca-to-lds",
77   cl::desc("Disable promote alloca to LDS"),
78   cl::init(false));
79 
80 static cl::opt<unsigned> PromoteAllocaToVectorLimit(
81   "amdgpu-promote-alloca-to-vector-limit",
82   cl::desc("Maximum byte size to consider promote alloca to vector"),
83   cl::init(0));
84 
85 // FIXME: This can create globals so should be a module pass.
86 class AMDGPUPromoteAlloca : public FunctionPass {
87 public:
88   static char ID;
89 
90   AMDGPUPromoteAlloca() : FunctionPass(ID) {}
91 
92   bool runOnFunction(Function &F) override;
93 
94   StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
95 
96   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
97 
98   void getAnalysisUsage(AnalysisUsage &AU) const override {
99     AU.setPreservesCFG();
100     FunctionPass::getAnalysisUsage(AU);
101   }
102 };
103 
104 class AMDGPUPromoteAllocaImpl {
105 private:
106   const TargetMachine &TM;
107   Module *Mod = nullptr;
108   const DataLayout *DL = nullptr;
109 
110   // FIXME: This should be per-kernel.
111   uint32_t LocalMemLimit = 0;
112   uint32_t CurrentLocalMemUsage = 0;
113   unsigned MaxVGPRs;
114 
115   bool IsAMDGCN = false;
116   bool IsAMDHSA = false;
117 
118   std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
119   Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
120 
121   /// BaseAlloca is the alloca root the search started from.
122   /// Val may be that alloca or a recursive user of it.
123   bool collectUsesWithPtrTypes(Value *BaseAlloca,
124                                Value *Val,
125                                std::vector<Value*> &WorkList) const;
126 
127   /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
128   /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
129   /// Returns true if both operands are derived from the same alloca. Val should
130   /// be the same value as one of the input operands of UseInst.
131   bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
132                                        Instruction *UseInst,
133                                        int OpIdx0, int OpIdx1) const;
134 
135   /// Check whether we have enough local memory for promotion.
136   bool hasSufficientLocalMem(const Function &F);
137 
138   bool handleAlloca(AllocaInst &I, bool SufficientLDS);
139 
140 public:
141   AMDGPUPromoteAllocaImpl(TargetMachine &TM) : TM(TM) {}
142   bool run(Function &F);
143 };
144 
145 class AMDGPUPromoteAllocaToVector : public FunctionPass {
146 public:
147   static char ID;
148 
149   AMDGPUPromoteAllocaToVector() : FunctionPass(ID) {}
150 
151   bool runOnFunction(Function &F) override;
152 
153   StringRef getPassName() const override {
154     return "AMDGPU Promote Alloca to vector";
155   }
156 
157   void getAnalysisUsage(AnalysisUsage &AU) const override {
158     AU.setPreservesCFG();
159     FunctionPass::getAnalysisUsage(AU);
160   }
161 };
162 
163 } // end anonymous namespace
164 
165 char AMDGPUPromoteAlloca::ID = 0;
166 char AMDGPUPromoteAllocaToVector::ID = 0;
167 
168 INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
169                 "AMDGPU promote alloca to vector or LDS", false, false)
170 
171 INITIALIZE_PASS(AMDGPUPromoteAllocaToVector, DEBUG_TYPE "-to-vector",
172                 "AMDGPU promote alloca to vector", false, false)
173 
174 char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
175 char &llvm::AMDGPUPromoteAllocaToVectorID = AMDGPUPromoteAllocaToVector::ID;
176 
177 bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
178   if (skipFunction(F))
179     return false;
180 
181   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
182     return AMDGPUPromoteAllocaImpl(TPC->getTM<TargetMachine>()).run(F);
183   }
184   return false;
185 }
186 
187 PreservedAnalyses AMDGPUPromoteAllocaPass::run(Function &F,
188                                                FunctionAnalysisManager &AM) {
189   bool Changed = AMDGPUPromoteAllocaImpl(TM).run(F);
190   if (Changed) {
191     PreservedAnalyses PA;
192     PA.preserveSet<CFGAnalyses>();
193     return PA;
194   }
195   return PreservedAnalyses::all();
196 }
197 
198 bool AMDGPUPromoteAllocaImpl::run(Function &F) {
199   Mod = F.getParent();
200   DL = &Mod->getDataLayout();
201 
202   const Triple &TT = TM.getTargetTriple();
203   IsAMDGCN = TT.getArch() == Triple::amdgcn;
204   IsAMDHSA = TT.getOS() == Triple::AMDHSA;
205 
206   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
207   if (!ST.isPromoteAllocaEnabled())
208     return false;
209 
210   if (IsAMDGCN) {
211     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
212     MaxVGPRs = ST.getMaxNumVGPRs(ST.getWavesPerEU(F).first);
213   } else {
214     MaxVGPRs = 128;
215   }
216 
217   bool SufficientLDS = hasSufficientLocalMem(F);
218   bool Changed = false;
219   BasicBlock &EntryBB = *F.begin();
220 
221   SmallVector<AllocaInst *, 16> Allocas;
222   for (Instruction &I : EntryBB) {
223     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
224       Allocas.push_back(AI);
225   }
226 
227   for (AllocaInst *AI : Allocas) {
228     if (handleAlloca(*AI, SufficientLDS))
229       Changed = true;
230   }
231 
232   return Changed;
233 }
234 
235 std::pair<Value *, Value *>
236 AMDGPUPromoteAllocaImpl::getLocalSizeYZ(IRBuilder<> &Builder) {
237   const Function &F = *Builder.GetInsertBlock()->getParent();
238   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
239 
240   if (!IsAMDHSA) {
241     Function *LocalSizeYFn
242       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
243     Function *LocalSizeZFn
244       = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
245 
246     CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
247     CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
248 
249     ST.makeLIDRangeMetadata(LocalSizeY);
250     ST.makeLIDRangeMetadata(LocalSizeZ);
251 
252     return std::make_pair(LocalSizeY, LocalSizeZ);
253   }
254 
255   // We must read the size out of the dispatch pointer.
256   assert(IsAMDGCN);
257 
258   // We are indexing into this struct, and want to extract the workgroup_size_*
259   // fields.
260   //
261   //   typedef struct hsa_kernel_dispatch_packet_s {
262   //     uint16_t header;
263   //     uint16_t setup;
264   //     uint16_t workgroup_size_x ;
265   //     uint16_t workgroup_size_y;
266   //     uint16_t workgroup_size_z;
267   //     uint16_t reserved0;
268   //     uint32_t grid_size_x ;
269   //     uint32_t grid_size_y ;
270   //     uint32_t grid_size_z;
271   //
272   //     uint32_t private_segment_size;
273   //     uint32_t group_segment_size;
274   //     uint64_t kernel_object;
275   //
276   // #ifdef HSA_LARGE_MODEL
277   //     void *kernarg_address;
278   // #elif defined HSA_LITTLE_ENDIAN
279   //     void *kernarg_address;
280   //     uint32_t reserved1;
281   // #else
282   //     uint32_t reserved1;
283   //     void *kernarg_address;
284   // #endif
285   //     uint64_t reserved2;
286   //     hsa_signal_t completion_signal; // uint64_t wrapper
287   //   } hsa_kernel_dispatch_packet_t
288   //
289   Function *DispatchPtrFn
290     = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
291 
292   CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
293   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
294   DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
295 
296   // Size of the dispatch packet struct.
297   DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
298 
299   Type *I32Ty = Type::getInt32Ty(Mod->getContext());
300   Value *CastDispatchPtr = Builder.CreateBitCast(
301     DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
302 
303   // We could do a single 64-bit load here, but it's likely that the basic
304   // 32-bit and extract sequence is already present, and it is probably easier
305   // to CSE this. The loads should be mergable later anyway.
306   Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 1);
307   LoadInst *LoadXY = Builder.CreateAlignedLoad(I32Ty, GEPXY, Align(4));
308 
309   Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 2);
310   LoadInst *LoadZU = Builder.CreateAlignedLoad(I32Ty, GEPZU, Align(4));
311 
312   MDNode *MD = MDNode::get(Mod->getContext(), None);
313   LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
314   LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
315   ST.makeLIDRangeMetadata(LoadZU);
316 
317   // Extract y component. Upper half of LoadZU should be zero already.
318   Value *Y = Builder.CreateLShr(LoadXY, 16);
319 
320   return std::make_pair(Y, LoadZU);
321 }
322 
323 Value *AMDGPUPromoteAllocaImpl::getWorkitemID(IRBuilder<> &Builder,
324                                               unsigned N) {
325   const AMDGPUSubtarget &ST =
326       AMDGPUSubtarget::get(TM, *Builder.GetInsertBlock()->getParent());
327   Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
328 
329   switch (N) {
330   case 0:
331     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_x
332                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_x;
333     break;
334   case 1:
335     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_y
336                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_y;
337     break;
338 
339   case 2:
340     IntrID = IsAMDGCN ? (Intrinsic::ID)Intrinsic::amdgcn_workitem_id_z
341                       : (Intrinsic::ID)Intrinsic::r600_read_tidig_z;
342     break;
343   default:
344     llvm_unreachable("invalid dimension");
345   }
346 
347   Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
348   CallInst *CI = Builder.CreateCall(WorkitemIdFn);
349   ST.makeLIDRangeMetadata(CI);
350 
351   return CI;
352 }
353 
354 static FixedVectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
355   return FixedVectorType::get(ArrayTy->getElementType(),
356                               ArrayTy->getNumElements());
357 }
358 
359 static Value *stripBitcasts(Value *V) {
360   while (Instruction *I = dyn_cast<Instruction>(V)) {
361     if (I->getOpcode() != Instruction::BitCast)
362       break;
363     V = I->getOperand(0);
364   }
365   return V;
366 }
367 
368 static Value *
369 calculateVectorIndex(Value *Ptr,
370                      const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
371   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(stripBitcasts(Ptr));
372   if (!GEP)
373     return nullptr;
374 
375   auto I = GEPIdx.find(GEP);
376   return I == GEPIdx.end() ? nullptr : I->second;
377 }
378 
379 static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
380   // FIXME we only support simple cases
381   if (GEP->getNumOperands() != 3)
382     return nullptr;
383 
384   ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
385   if (!I0 || !I0->isZero())
386     return nullptr;
387 
388   return GEP->getOperand(2);
389 }
390 
391 // Not an instruction handled below to turn into a vector.
392 //
393 // TODO: Check isTriviallyVectorizable for calls and handle other
394 // instructions.
395 static bool canVectorizeInst(Instruction *Inst, User *User,
396                              const DataLayout &DL) {
397   switch (Inst->getOpcode()) {
398   case Instruction::Load: {
399     // Currently only handle the case where the Pointer Operand is a GEP.
400     // Also we could not vectorize volatile or atomic loads.
401     LoadInst *LI = cast<LoadInst>(Inst);
402     if (isa<AllocaInst>(User) &&
403         LI->getPointerOperandType() == User->getType() &&
404         isa<VectorType>(LI->getType()))
405       return true;
406 
407     Instruction *PtrInst = dyn_cast<Instruction>(LI->getPointerOperand());
408     if (!PtrInst)
409       return false;
410 
411     return (PtrInst->getOpcode() == Instruction::GetElementPtr ||
412             PtrInst->getOpcode() == Instruction::BitCast) &&
413            LI->isSimple();
414   }
415   case Instruction::BitCast:
416     return true;
417   case Instruction::Store: {
418     // Must be the stored pointer operand, not a stored value, plus
419     // since it should be canonical form, the User should be a GEP.
420     // Also we could not vectorize volatile or atomic stores.
421     StoreInst *SI = cast<StoreInst>(Inst);
422     if (isa<AllocaInst>(User) &&
423         SI->getPointerOperandType() == User->getType() &&
424         isa<VectorType>(SI->getValueOperand()->getType()))
425       return true;
426 
427     Instruction *UserInst = dyn_cast<Instruction>(User);
428     if (!UserInst)
429       return false;
430 
431     return (SI->getPointerOperand() == User) &&
432            (UserInst->getOpcode() == Instruction::GetElementPtr ||
433             UserInst->getOpcode() == Instruction::BitCast) &&
434            SI->isSimple();
435   }
436   default:
437     return false;
438   }
439 }
440 
441 static bool tryPromoteAllocaToVector(AllocaInst *Alloca, const DataLayout &DL,
442                                      unsigned MaxVGPRs) {
443 
444   if (DisablePromoteAllocaToVector) {
445     LLVM_DEBUG(dbgs() << "  Promotion alloca to vector is disabled\n");
446     return false;
447   }
448 
449   Type *AllocaTy = Alloca->getAllocatedType();
450   auto *VectorTy = dyn_cast<FixedVectorType>(AllocaTy);
451   if (auto *ArrayTy = dyn_cast<ArrayType>(AllocaTy)) {
452     if (VectorType::isValidElementType(ArrayTy->getElementType()) &&
453         ArrayTy->getNumElements() > 0)
454       VectorTy = arrayTypeToVecType(ArrayTy);
455   }
456 
457   // Use up to 1/4 of available register budget for vectorization.
458   unsigned Limit = PromoteAllocaToVectorLimit ? PromoteAllocaToVectorLimit * 8
459                                               : (MaxVGPRs * 32);
460 
461   if (DL.getTypeSizeInBits(AllocaTy) * 4 > Limit) {
462     LLVM_DEBUG(dbgs() << "  Alloca too big for vectorization with "
463                       << MaxVGPRs << " registers available\n");
464     return false;
465   }
466 
467   LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
468 
469   // FIXME: There is no reason why we can't support larger arrays, we
470   // are just being conservative for now.
471   // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
472   // could also be promoted but we don't currently handle this case
473   if (!VectorTy || VectorTy->getNumElements() > 16 ||
474       VectorTy->getNumElements() < 2) {
475     LLVM_DEBUG(dbgs() << "  Cannot convert type to vector\n");
476     return false;
477   }
478 
479   std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
480   std::vector<Value *> WorkList;
481   SmallVector<User *, 8> Users(Alloca->users());
482   SmallVector<User *, 8> UseUsers(Users.size(), Alloca);
483   Type *VecEltTy = VectorTy->getElementType();
484   while (!Users.empty()) {
485     User *AllocaUser = Users.pop_back_val();
486     User *UseUser = UseUsers.pop_back_val();
487     Instruction *Inst = dyn_cast<Instruction>(AllocaUser);
488 
489     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
490     if (!GEP) {
491       if (!canVectorizeInst(Inst, UseUser, DL))
492         return false;
493 
494       if (Inst->getOpcode() == Instruction::BitCast) {
495         Type *FromTy = Inst->getOperand(0)->getType()->getPointerElementType();
496         Type *ToTy = Inst->getType()->getPointerElementType();
497         if (FromTy->isAggregateType() || ToTy->isAggregateType() ||
498             DL.getTypeSizeInBits(FromTy) != DL.getTypeSizeInBits(ToTy))
499           continue;
500 
501         for (User *CastUser : Inst->users()) {
502           if (isAssumeLikeIntrinsic(cast<Instruction>(CastUser)))
503             continue;
504           Users.push_back(CastUser);
505           UseUsers.push_back(Inst);
506         }
507 
508         continue;
509       }
510 
511       WorkList.push_back(AllocaUser);
512       continue;
513     }
514 
515     Value *Index = GEPToVectorIndex(GEP);
516 
517     // If we can't compute a vector index from this GEP, then we can't
518     // promote this alloca to vector.
519     if (!Index) {
520       LLVM_DEBUG(dbgs() << "  Cannot compute vector index for GEP " << *GEP
521                         << '\n');
522       return false;
523     }
524 
525     GEPVectorIdx[GEP] = Index;
526     Users.append(GEP->user_begin(), GEP->user_end());
527     UseUsers.append(GEP->getNumUses(), GEP);
528   }
529 
530   LLVM_DEBUG(dbgs() << "  Converting alloca to vector " << *AllocaTy << " -> "
531                     << *VectorTy << '\n');
532 
533   for (Value *V : WorkList) {
534     Instruction *Inst = cast<Instruction>(V);
535     IRBuilder<> Builder(Inst);
536     switch (Inst->getOpcode()) {
537     case Instruction::Load: {
538       if (Inst->getType() == AllocaTy || Inst->getType()->isVectorTy())
539         break;
540 
541       Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
542       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
543       if (!Index)
544         break;
545 
546       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
547       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
548       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
549       Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
550       if (Inst->getType() != VecEltTy)
551         ExtractElement = Builder.CreateBitOrPointerCast(ExtractElement, Inst->getType());
552       Inst->replaceAllUsesWith(ExtractElement);
553       Inst->eraseFromParent();
554       break;
555     }
556     case Instruction::Store: {
557       StoreInst *SI = cast<StoreInst>(Inst);
558       if (SI->getValueOperand()->getType() == AllocaTy ||
559           SI->getValueOperand()->getType()->isVectorTy())
560         break;
561 
562       Value *Ptr = SI->getPointerOperand();
563       Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
564       if (!Index)
565         break;
566 
567       Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
568       Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
569       Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
570       Value *Elt = SI->getValueOperand();
571       if (Elt->getType() != VecEltTy)
572         Elt = Builder.CreateBitOrPointerCast(Elt, VecEltTy);
573       Value *NewVecValue = Builder.CreateInsertElement(VecValue, Elt, Index);
574       Builder.CreateStore(NewVecValue, BitCast);
575       Inst->eraseFromParent();
576       break;
577     }
578 
579     default:
580       llvm_unreachable("Inconsistency in instructions promotable to vector");
581     }
582   }
583   return true;
584 }
585 
586 static bool isCallPromotable(CallInst *CI) {
587   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
588   if (!II)
589     return false;
590 
591   switch (II->getIntrinsicID()) {
592   case Intrinsic::memcpy:
593   case Intrinsic::memmove:
594   case Intrinsic::memset:
595   case Intrinsic::lifetime_start:
596   case Intrinsic::lifetime_end:
597   case Intrinsic::invariant_start:
598   case Intrinsic::invariant_end:
599   case Intrinsic::launder_invariant_group:
600   case Intrinsic::strip_invariant_group:
601   case Intrinsic::objectsize:
602     return true;
603   default:
604     return false;
605   }
606 }
607 
608 bool AMDGPUPromoteAllocaImpl::binaryOpIsDerivedFromSameAlloca(
609     Value *BaseAlloca, Value *Val, Instruction *Inst, int OpIdx0,
610     int OpIdx1) const {
611   // Figure out which operand is the one we might not be promoting.
612   Value *OtherOp = Inst->getOperand(OpIdx0);
613   if (Val == OtherOp)
614     OtherOp = Inst->getOperand(OpIdx1);
615 
616   if (isa<ConstantPointerNull>(OtherOp))
617     return true;
618 
619   Value *OtherObj = getUnderlyingObject(OtherOp);
620   if (!isa<AllocaInst>(OtherObj))
621     return false;
622 
623   // TODO: We should be able to replace undefs with the right pointer type.
624 
625   // TODO: If we know the other base object is another promotable
626   // alloca, not necessarily this alloca, we can do this. The
627   // important part is both must have the same address space at
628   // the end.
629   if (OtherObj != BaseAlloca) {
630     LLVM_DEBUG(
631         dbgs() << "Found a binary instruction with another alloca object\n");
632     return false;
633   }
634 
635   return true;
636 }
637 
638 bool AMDGPUPromoteAllocaImpl::collectUsesWithPtrTypes(
639     Value *BaseAlloca, Value *Val, std::vector<Value *> &WorkList) const {
640 
641   for (User *User : Val->users()) {
642     if (is_contained(WorkList, User))
643       continue;
644 
645     if (CallInst *CI = dyn_cast<CallInst>(User)) {
646       if (!isCallPromotable(CI))
647         return false;
648 
649       WorkList.push_back(User);
650       continue;
651     }
652 
653     Instruction *UseInst = cast<Instruction>(User);
654     if (UseInst->getOpcode() == Instruction::PtrToInt)
655       return false;
656 
657     if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
658       if (LI->isVolatile())
659         return false;
660 
661       continue;
662     }
663 
664     if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
665       if (SI->isVolatile())
666         return false;
667 
668       // Reject if the stored value is not the pointer operand.
669       if (SI->getPointerOperand() != Val)
670         return false;
671     } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
672       if (RMW->isVolatile())
673         return false;
674     } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
675       if (CAS->isVolatile())
676         return false;
677     }
678 
679     // Only promote a select if we know that the other select operand
680     // is from another pointer that will also be promoted.
681     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
682       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
683         return false;
684 
685       // May need to rewrite constant operands.
686       WorkList.push_back(ICmp);
687     }
688 
689     if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
690       // Give up if the pointer may be captured.
691       if (PointerMayBeCaptured(UseInst, true, true))
692         return false;
693       // Don't collect the users of this.
694       WorkList.push_back(User);
695       continue;
696     }
697 
698     if (!User->getType()->isPointerTy())
699       continue;
700 
701     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
702       // Be conservative if an address could be computed outside the bounds of
703       // the alloca.
704       if (!GEP->isInBounds())
705         return false;
706     }
707 
708     // Only promote a select if we know that the other select operand is from
709     // another pointer that will also be promoted.
710     if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
711       if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
712         return false;
713     }
714 
715     // Repeat for phis.
716     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
717       // TODO: Handle more complex cases. We should be able to replace loops
718       // over arrays.
719       switch (Phi->getNumIncomingValues()) {
720       case 1:
721         break;
722       case 2:
723         if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
724           return false;
725         break;
726       default:
727         return false;
728       }
729     }
730 
731     WorkList.push_back(User);
732     if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
733       return false;
734   }
735 
736   return true;
737 }
738 
739 bool AMDGPUPromoteAllocaImpl::hasSufficientLocalMem(const Function &F) {
740 
741   FunctionType *FTy = F.getFunctionType();
742   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
743 
744   // If the function has any arguments in the local address space, then it's
745   // possible these arguments require the entire local memory space, so
746   // we cannot use local memory in the pass.
747   for (Type *ParamTy : FTy->params()) {
748     PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
749     if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
750       LocalMemLimit = 0;
751       LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
752                            "local memory disabled.\n");
753       return false;
754     }
755   }
756 
757   LocalMemLimit = ST.getLocalMemorySize();
758   if (LocalMemLimit == 0)
759     return false;
760 
761   SmallVector<const Constant *, 16> Stack;
762   SmallPtrSet<const Constant *, 8> VisitedConstants;
763   SmallPtrSet<const GlobalVariable *, 8> UsedLDS;
764 
765   auto visitUsers = [&](const GlobalVariable *GV, const Constant *Val) -> bool {
766     for (const User *U : Val->users()) {
767       if (const Instruction *Use = dyn_cast<Instruction>(U)) {
768         if (Use->getParent()->getParent() == &F)
769           return true;
770       } else {
771         const Constant *C = cast<Constant>(U);
772         if (VisitedConstants.insert(C).second)
773           Stack.push_back(C);
774       }
775     }
776 
777     return false;
778   };
779 
780   for (GlobalVariable &GV : Mod->globals()) {
781     if (GV.getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
782       continue;
783 
784     if (visitUsers(&GV, &GV)) {
785       UsedLDS.insert(&GV);
786       Stack.clear();
787       continue;
788     }
789 
790     // For any ConstantExpr uses, we need to recursively search the users until
791     // we see a function.
792     while (!Stack.empty()) {
793       const Constant *C = Stack.pop_back_val();
794       if (visitUsers(&GV, C)) {
795         UsedLDS.insert(&GV);
796         Stack.clear();
797         break;
798       }
799     }
800   }
801 
802   const DataLayout &DL = Mod->getDataLayout();
803   SmallVector<std::pair<uint64_t, Align>, 16> AllocatedSizes;
804   AllocatedSizes.reserve(UsedLDS.size());
805 
806   for (const GlobalVariable *GV : UsedLDS) {
807     Align Alignment =
808         DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
809     uint64_t AllocSize = DL.getTypeAllocSize(GV->getValueType());
810     AllocatedSizes.emplace_back(AllocSize, Alignment);
811   }
812 
813   // Sort to try to estimate the worst case alignment padding
814   //
815   // FIXME: We should really do something to fix the addresses to a more optimal
816   // value instead
817   llvm::sort(AllocatedSizes.begin(), AllocatedSizes.end(),
818              [](std::pair<uint64_t, Align> LHS, std::pair<uint64_t, Align> RHS) {
819                return LHS.second < RHS.second;
820              });
821 
822   // Check how much local memory is being used by global objects
823   CurrentLocalMemUsage = 0;
824 
825   // FIXME: Try to account for padding here. The real padding and address is
826   // currently determined from the inverse order of uses in the function when
827   // legalizing, which could also potentially change. We try to estimate the
828   // worst case here, but we probably should fix the addresses earlier.
829   for (auto Alloc : AllocatedSizes) {
830     CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Alloc.second);
831     CurrentLocalMemUsage += Alloc.first;
832   }
833 
834   unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
835                                                           F);
836 
837   // Restrict local memory usage so that we don't drastically reduce occupancy,
838   // unless it is already significantly reduced.
839 
840   // TODO: Have some sort of hint or other heuristics to guess occupancy based
841   // on other factors..
842   unsigned OccupancyHint = ST.getWavesPerEU(F).second;
843   if (OccupancyHint == 0)
844     OccupancyHint = 7;
845 
846   // Clamp to max value.
847   OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
848 
849   // Check the hint but ignore it if it's obviously wrong from the existing LDS
850   // usage.
851   MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
852 
853 
854   // Round up to the next tier of usage.
855   unsigned MaxSizeWithWaveCount
856     = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
857 
858   // Program is possibly broken by using more local mem than available.
859   if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
860     return false;
861 
862   LocalMemLimit = MaxSizeWithWaveCount;
863 
864   LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
865                     << " bytes of LDS\n"
866                     << "  Rounding size to " << MaxSizeWithWaveCount
867                     << " with a maximum occupancy of " << MaxOccupancy << '\n'
868                     << " and " << (LocalMemLimit - CurrentLocalMemUsage)
869                     << " available for promotion\n");
870 
871   return true;
872 }
873 
874 // FIXME: Should try to pick the most likely to be profitable allocas first.
875 bool AMDGPUPromoteAllocaImpl::handleAlloca(AllocaInst &I, bool SufficientLDS) {
876   // Array allocations are probably not worth handling, since an allocation of
877   // the array type is the canonical form.
878   if (!I.isStaticAlloca() || I.isArrayAllocation())
879     return false;
880 
881   const DataLayout &DL = Mod->getDataLayout();
882   IRBuilder<> Builder(&I);
883 
884   // First try to replace the alloca with a vector
885   Type *AllocaTy = I.getAllocatedType();
886 
887   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
888 
889   if (tryPromoteAllocaToVector(&I, DL, MaxVGPRs))
890     return true; // Promoted to vector.
891 
892   if (DisablePromoteAllocaToLDS)
893     return false;
894 
895   const Function &ContainingFunction = *I.getParent()->getParent();
896   CallingConv::ID CC = ContainingFunction.getCallingConv();
897 
898   // Don't promote the alloca to LDS for shader calling conventions as the work
899   // item ID intrinsics are not supported for these calling conventions.
900   // Furthermore not all LDS is available for some of the stages.
901   switch (CC) {
902   case CallingConv::AMDGPU_KERNEL:
903   case CallingConv::SPIR_KERNEL:
904     break;
905   default:
906     LLVM_DEBUG(
907         dbgs()
908         << " promote alloca to LDS not supported with calling convention.\n");
909     return false;
910   }
911 
912   // Not likely to have sufficient local memory for promotion.
913   if (!SufficientLDS)
914     return false;
915 
916   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, ContainingFunction);
917   unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
918 
919   Align Alignment =
920       DL.getValueOrABITypeAlignment(I.getAlign(), I.getAllocatedType());
921 
922   // FIXME: This computed padding is likely wrong since it depends on inverse
923   // usage order.
924   //
925   // FIXME: It is also possible that if we're allowed to use all of the memory
926   // could could end up using more than the maximum due to alignment padding.
927 
928   uint32_t NewSize = alignTo(CurrentLocalMemUsage, Alignment);
929   uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
930   NewSize += AllocSize;
931 
932   if (NewSize > LocalMemLimit) {
933     LLVM_DEBUG(dbgs() << "  " << AllocSize
934                       << " bytes of local memory not available to promote\n");
935     return false;
936   }
937 
938   CurrentLocalMemUsage = NewSize;
939 
940   std::vector<Value*> WorkList;
941 
942   if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
943     LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
944     return false;
945   }
946 
947   LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
948 
949   Function *F = I.getParent()->getParent();
950 
951   Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
952   GlobalVariable *GV = new GlobalVariable(
953       *Mod, GVTy, false, GlobalValue::InternalLinkage,
954       UndefValue::get(GVTy),
955       Twine(F->getName()) + Twine('.') + I.getName(),
956       nullptr,
957       GlobalVariable::NotThreadLocal,
958       AMDGPUAS::LOCAL_ADDRESS);
959   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
960   GV->setAlignment(MaybeAlign(I.getAlignment()));
961 
962   Value *TCntY, *TCntZ;
963 
964   std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
965   Value *TIdX = getWorkitemID(Builder, 0);
966   Value *TIdY = getWorkitemID(Builder, 1);
967   Value *TIdZ = getWorkitemID(Builder, 2);
968 
969   Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
970   Tmp0 = Builder.CreateMul(Tmp0, TIdX);
971   Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
972   Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
973   TID = Builder.CreateAdd(TID, TIdZ);
974 
975   Value *Indices[] = {
976     Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
977     TID
978   };
979 
980   Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
981   I.mutateType(Offset->getType());
982   I.replaceAllUsesWith(Offset);
983   I.eraseFromParent();
984 
985   for (Value *V : WorkList) {
986     CallInst *Call = dyn_cast<CallInst>(V);
987     if (!Call) {
988       if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
989         Value *Src0 = CI->getOperand(0);
990         Type *EltTy = Src0->getType()->getPointerElementType();
991         PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
992 
993         if (isa<ConstantPointerNull>(CI->getOperand(0)))
994           CI->setOperand(0, ConstantPointerNull::get(NewTy));
995 
996         if (isa<ConstantPointerNull>(CI->getOperand(1)))
997           CI->setOperand(1, ConstantPointerNull::get(NewTy));
998 
999         continue;
1000       }
1001 
1002       // The operand's value should be corrected on its own and we don't want to
1003       // touch the users.
1004       if (isa<AddrSpaceCastInst>(V))
1005         continue;
1006 
1007       Type *EltTy = V->getType()->getPointerElementType();
1008       PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
1009 
1010       // FIXME: It doesn't really make sense to try to do this for all
1011       // instructions.
1012       V->mutateType(NewTy);
1013 
1014       // Adjust the types of any constant operands.
1015       if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1016         if (isa<ConstantPointerNull>(SI->getOperand(1)))
1017           SI->setOperand(1, ConstantPointerNull::get(NewTy));
1018 
1019         if (isa<ConstantPointerNull>(SI->getOperand(2)))
1020           SI->setOperand(2, ConstantPointerNull::get(NewTy));
1021       } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
1022         for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1023           if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
1024             Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
1025         }
1026       }
1027 
1028       continue;
1029     }
1030 
1031     IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
1032     Builder.SetInsertPoint(Intr);
1033     switch (Intr->getIntrinsicID()) {
1034     case Intrinsic::lifetime_start:
1035     case Intrinsic::lifetime_end:
1036       // These intrinsics are for address space 0 only
1037       Intr->eraseFromParent();
1038       continue;
1039     case Intrinsic::memcpy: {
1040       MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
1041       Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlign(),
1042                            MemCpy->getRawSource(), MemCpy->getSourceAlign(),
1043                            MemCpy->getLength(), MemCpy->isVolatile());
1044       Intr->eraseFromParent();
1045       continue;
1046     }
1047     case Intrinsic::memmove: {
1048       MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
1049       Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlign(),
1050                             MemMove->getRawSource(), MemMove->getSourceAlign(),
1051                             MemMove->getLength(), MemMove->isVolatile());
1052       Intr->eraseFromParent();
1053       continue;
1054     }
1055     case Intrinsic::memset: {
1056       MemSetInst *MemSet = cast<MemSetInst>(Intr);
1057       Builder.CreateMemSet(
1058           MemSet->getRawDest(), MemSet->getValue(), MemSet->getLength(),
1059           MaybeAlign(MemSet->getDestAlignment()), MemSet->isVolatile());
1060       Intr->eraseFromParent();
1061       continue;
1062     }
1063     case Intrinsic::invariant_start:
1064     case Intrinsic::invariant_end:
1065     case Intrinsic::launder_invariant_group:
1066     case Intrinsic::strip_invariant_group:
1067       Intr->eraseFromParent();
1068       // FIXME: I think the invariant marker should still theoretically apply,
1069       // but the intrinsics need to be changed to accept pointers with any
1070       // address space.
1071       continue;
1072     case Intrinsic::objectsize: {
1073       Value *Src = Intr->getOperand(0);
1074       Type *SrcTy = Src->getType()->getPointerElementType();
1075       Function *ObjectSize = Intrinsic::getDeclaration(Mod,
1076         Intrinsic::objectsize,
1077         { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
1078       );
1079 
1080       CallInst *NewCall = Builder.CreateCall(
1081           ObjectSize,
1082           {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
1083       Intr->replaceAllUsesWith(NewCall);
1084       Intr->eraseFromParent();
1085       continue;
1086     }
1087     default:
1088       Intr->print(errs());
1089       llvm_unreachable("Don't know how to promote alloca intrinsic use.");
1090     }
1091   }
1092   return true;
1093 }
1094 
1095 bool handlePromoteAllocaToVector(AllocaInst &I, unsigned MaxVGPRs) {
1096   // Array allocations are probably not worth handling, since an allocation of
1097   // the array type is the canonical form.
1098   if (!I.isStaticAlloca() || I.isArrayAllocation())
1099     return false;
1100 
1101   LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
1102 
1103   Module *Mod = I.getParent()->getParent()->getParent();
1104   return tryPromoteAllocaToVector(&I, Mod->getDataLayout(), MaxVGPRs);
1105 }
1106 
1107 bool promoteAllocasToVector(Function &F, TargetMachine &TM) {
1108   if (DisablePromoteAllocaToVector)
1109     return false;
1110 
1111   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(TM, F);
1112   if (!ST.isPromoteAllocaEnabled())
1113     return false;
1114 
1115   unsigned MaxVGPRs;
1116   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
1117     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
1118     MaxVGPRs = ST.getMaxNumVGPRs(ST.getWavesPerEU(F).first);
1119   } else {
1120     MaxVGPRs = 128;
1121   }
1122 
1123   bool Changed = false;
1124   BasicBlock &EntryBB = *F.begin();
1125 
1126   SmallVector<AllocaInst *, 16> Allocas;
1127   for (Instruction &I : EntryBB) {
1128     if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
1129       Allocas.push_back(AI);
1130   }
1131 
1132   for (AllocaInst *AI : Allocas) {
1133     if (handlePromoteAllocaToVector(*AI, MaxVGPRs))
1134       Changed = true;
1135   }
1136 
1137   return Changed;
1138 }
1139 
1140 bool AMDGPUPromoteAllocaToVector::runOnFunction(Function &F) {
1141   if (skipFunction(F))
1142     return false;
1143   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1144     return promoteAllocasToVector(F, TPC->getTM<TargetMachine>());
1145   }
1146   return false;
1147 }
1148 
1149 PreservedAnalyses
1150 AMDGPUPromoteAllocaToVectorPass::run(Function &F, FunctionAnalysisManager &AM) {
1151   bool Changed = promoteAllocasToVector(F, TM);
1152   if (Changed) {
1153     PreservedAnalyses PA;
1154     PA.preserveSet<CFGAnalyses>();
1155     return PA;
1156   }
1157   return PreservedAnalyses::all();
1158 }
1159 
1160 FunctionPass *llvm::createAMDGPUPromoteAlloca() {
1161   return new AMDGPUPromoteAlloca();
1162 }
1163 
1164 FunctionPass *llvm::createAMDGPUPromoteAllocaToVector() {
1165   return new AMDGPUPromoteAllocaToVector();
1166 }
1167