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