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