blob: e4c9d6685d4ab14d44d49532caf5439fe71e7605 [file] [log] [blame]
Tom Stellard880a80a2014-06-17 16:53:14 +00001//===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Tom Stellard880a80a2014-06-17 16:53:14 +00006//
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"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000016#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"
Changpeng Fangc85abbd2017-01-24 19:06:28 +000023#include "llvm/Analysis/CaptureTracking.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000024#include "llvm/Analysis/ValueTracking.h"
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000025#include "llvm/CodeGen/TargetPassConfig.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000026#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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000035#include "llvm/IR/IRBuilder.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000036#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000038#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000039#include "llvm/IR/Intrinsics.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000040#include "llvm/IR/LLVMContext.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000041#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"
Tom Stellard880a80a2014-06-17 16:53:14 +000048#include "llvm/Support/Debug.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000049#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000051#include "llvm/Support/raw_ostream.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000052#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>
Tom Stellard880a80a2014-06-17 16:53:14 +000060
61#define DEBUG_TYPE "amdgpu-promote-alloca"
62
63using namespace llvm;
64
65namespace {
66
Changpeng Fangba920592018-02-16 19:14:17 +000067static cl::opt<bool> DisablePromoteAllocaToVector(
68 "disable-promote-alloca-to-vector",
69 cl::desc("Disable promote alloca to vector"),
70 cl::init(false));
71
Yaxun Liu73bf0af2018-11-06 21:28:17 +000072static cl::opt<bool> DisablePromoteAllocaToLDS(
73 "disable-promote-alloca-to-lds",
74 cl::desc("Disable promote alloca to LDS"),
75 cl::init(false));
76
Matt Arsenaulte0132462016-01-30 05:19:45 +000077// FIXME: This can create globals so should be a module pass.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000078class AMDGPUPromoteAlloca : public FunctionPass {
Matt Arsenaulte0132462016-01-30 05:19:45 +000079private:
80 const TargetMachine *TM;
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000081 Module *Mod = nullptr;
82 const DataLayout *DL = nullptr;
Matt Arsenaulte0132462016-01-30 05:19:45 +000083
84 // FIXME: This should be per-kernel.
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000085 uint32_t LocalMemLimit = 0;
86 uint32_t CurrentLocalMemUsage = 0;
Tom Stellard880a80a2014-06-17 16:53:14 +000087
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000088 bool IsAMDGCN = false;
89 bool IsAMDHSA = false;
Matt Arsenaulte0132462016-01-30 05:19:45 +000090
91 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
92 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
93
Matt Arsenaulta61cb482016-05-12 01:58:58 +000094 /// BaseAlloca is the alloca root the search started from.
95 /// Val may be that alloca or a recursive user of it.
96 bool collectUsesWithPtrTypes(Value *BaseAlloca,
97 Value *Val,
98 std::vector<Value*> &WorkList) const;
99
100 /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
101 /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
102 /// Returns true if both operands are derived from the same alloca. Val should
103 /// be the same value as one of the input operands of UseInst.
104 bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
105 Instruction *UseInst,
106 int OpIdx0, int OpIdx1) const;
107
Changpeng Fang1dbace12017-05-23 20:25:41 +0000108 /// Check whether we have enough local memory for promotion.
109 bool hasSufficientLocalMem(const Function &F);
110
Tom Stellard880a80a2014-06-17 16:53:14 +0000111public:
Matt Arsenaulte0132462016-01-30 05:19:45 +0000112 static char ID;
113
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000114 AMDGPUPromoteAlloca() : FunctionPass(ID) {}
Matt Arsenaulte0132462016-01-30 05:19:45 +0000115
Benjamin Kramer8c90fd72014-09-03 11:41:21 +0000116 bool doInitialization(Module &M) override;
117 bool runOnFunction(Function &F) override;
Matt Arsenaulte0132462016-01-30 05:19:45 +0000118
Mehdi Amini117296c2016-10-01 02:56:57 +0000119 StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
Matt Arsenaulte0132462016-01-30 05:19:45 +0000120
Changpeng Fang1dbace12017-05-23 20:25:41 +0000121 bool handleAlloca(AllocaInst &I, bool SufficientLDS);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000122
123 void getAnalysisUsage(AnalysisUsage &AU) const override {
124 AU.setPreservesCFG();
125 FunctionPass::getAnalysisUsage(AU);
126 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000127};
128
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000129} // end anonymous namespace
Tom Stellard880a80a2014-06-17 16:53:14 +0000130
131char AMDGPUPromoteAlloca::ID = 0;
132
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000133INITIALIZE_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
134 "AMDGPU promote alloca to vector or LDS", false, false)
Matt Arsenaulte0132462016-01-30 05:19:45 +0000135
136char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
137
Tom Stellard880a80a2014-06-17 16:53:14 +0000138bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
139 Mod = &M;
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000140 DL = &Mod->getDataLayout();
Matt Arsenaulte0132462016-01-30 05:19:45 +0000141
Tom Stellard880a80a2014-06-17 16:53:14 +0000142 return false;
143}
144
145bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000146 if (skipFunction(F))
Matt Arsenaulte0132462016-01-30 05:19:45 +0000147 return false;
148
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000149 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>())
150 TM = &TPC->getTM<TargetMachine>();
151 else
152 return false;
153
154 const Triple &TT = TM->getTargetTriple();
155 IsAMDGCN = TT.getArch() == Triple::amdgcn;
156 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
157
Tom Stellard5bfbae52018-07-11 20:59:01 +0000158 const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
Matt Arsenault03d85842016-06-27 20:32:13 +0000159 if (!ST.isPromoteAllocaEnabled())
160 return false;
Changpeng Fang1dbace12017-05-23 20:25:41 +0000161
Changpeng Fang1dbace12017-05-23 20:25:41 +0000162 bool SufficientLDS = hasSufficientLocalMem(F);
163 bool Changed = false;
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000164 BasicBlock &EntryBB = *F.begin();
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000165
Matt Arsenault23f03f52019-06-18 12:23:44 +0000166 SmallVector<AllocaInst *, 16> Allocas;
167 for (Instruction &I : EntryBB) {
168 if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
169 Allocas.push_back(AI);
170 }
171
172 for (AllocaInst *AI : Allocas) {
173 if (handleAlloca(*AI, SufficientLDS))
174 Changed = true;
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000175 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000176
Changpeng Fang1dbace12017-05-23 20:25:41 +0000177 return Changed;
Tom Stellard880a80a2014-06-17 16:53:14 +0000178}
179
Matt Arsenaulte0132462016-01-30 05:19:45 +0000180std::pair<Value *, Value *>
181AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
Tom Stellardc5a154d2018-06-28 23:47:12 +0000182 const Function &F = *Builder.GetInsertBlock()->getParent();
Tom Stellard5bfbae52018-07-11 20:59:01 +0000183 const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000184
Matt Arsenaulte0132462016-01-30 05:19:45 +0000185 if (!IsAMDHSA) {
186 Function *LocalSizeYFn
187 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
188 Function *LocalSizeZFn
189 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
190
191 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
192 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
193
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000194 ST.makeLIDRangeMetadata(LocalSizeY);
195 ST.makeLIDRangeMetadata(LocalSizeZ);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000196
197 return std::make_pair(LocalSizeY, LocalSizeZ);
198 }
199
200 // We must read the size out of the dispatch pointer.
201 assert(IsAMDGCN);
202
203 // We are indexing into this struct, and want to extract the workgroup_size_*
204 // fields.
205 //
206 // typedef struct hsa_kernel_dispatch_packet_s {
207 // uint16_t header;
208 // uint16_t setup;
209 // uint16_t workgroup_size_x ;
210 // uint16_t workgroup_size_y;
211 // uint16_t workgroup_size_z;
212 // uint16_t reserved0;
213 // uint32_t grid_size_x ;
214 // uint32_t grid_size_y ;
215 // uint32_t grid_size_z;
216 //
217 // uint32_t private_segment_size;
218 // uint32_t group_segment_size;
219 // uint64_t kernel_object;
220 //
221 // #ifdef HSA_LARGE_MODEL
222 // void *kernarg_address;
223 // #elif defined HSA_LITTLE_ENDIAN
224 // void *kernarg_address;
225 // uint32_t reserved1;
226 // #else
227 // uint32_t reserved1;
228 // void *kernarg_address;
229 // #endif
230 // uint64_t reserved2;
231 // hsa_signal_t completion_signal; // uint64_t wrapper
232 // } hsa_kernel_dispatch_packet_t
233 //
234 Function *DispatchPtrFn
235 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
236
237 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
Reid Klecknerb5180542017-03-21 16:57:19 +0000238 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
239 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000240
241 // Size of the dispatch packet struct.
Reid Klecknerb5180542017-03-21 16:57:19 +0000242 DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000243
244 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
245 Value *CastDispatchPtr = Builder.CreateBitCast(
Matt Arsenault0da63502018-08-31 05:49:54 +0000246 DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
Matt Arsenaulte0132462016-01-30 05:19:45 +0000247
248 // We could do a single 64-bit load here, but it's likely that the basic
249 // 32-bit and extract sequence is already present, and it is probably easier
250 // to CSE this. The loads should be mergable later anyway.
James Y Knight77160752019-02-01 20:44:47 +0000251 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 1);
James Y Knight14359ef2019-02-01 20:44:24 +0000252 LoadInst *LoadXY = Builder.CreateAlignedLoad(I32Ty, GEPXY, 4);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000253
James Y Knight77160752019-02-01 20:44:47 +0000254 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(I32Ty, CastDispatchPtr, 2);
James Y Knight14359ef2019-02-01 20:44:24 +0000255 LoadInst *LoadZU = Builder.CreateAlignedLoad(I32Ty, GEPZU, 4);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000256
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000257 MDNode *MD = MDNode::get(Mod->getContext(), None);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000258 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
259 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000260 ST.makeLIDRangeMetadata(LoadZU);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000261
262 // Extract y component. Upper half of LoadZU should be zero already.
263 Value *Y = Builder.CreateLShr(LoadXY, 16);
264
265 return std::make_pair(Y, LoadZU);
266}
267
268Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
Tom Stellard5bfbae52018-07-11 20:59:01 +0000269 const AMDGPUSubtarget &ST =
270 AMDGPUSubtarget::get(*TM, *Builder.GetInsertBlock()->getParent());
Matt Arsenaulte0132462016-01-30 05:19:45 +0000271 Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
272
273 switch (N) {
274 case 0:
275 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
276 : Intrinsic::r600_read_tidig_x;
277 break;
278 case 1:
279 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
280 : Intrinsic::r600_read_tidig_y;
281 break;
282
283 case 2:
284 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
285 : Intrinsic::r600_read_tidig_z;
286 break;
287 default:
288 llvm_unreachable("invalid dimension");
289 }
290
291 Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
292 CallInst *CI = Builder.CreateCall(WorkitemIdFn);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000293 ST.makeLIDRangeMetadata(CI);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000294
295 return CI;
296}
297
Matt Arsenault37ab4cf2017-09-14 18:02:29 +0000298static VectorType *arrayTypeToVecType(ArrayType *ArrayTy) {
299 return VectorType::get(ArrayTy->getElementType(),
300 ArrayTy->getNumElements());
Tom Stellard880a80a2014-06-17 16:53:14 +0000301}
302
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000303static Value *
304calculateVectorIndex(Value *Ptr,
305 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000306 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
307
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000308 auto I = GEPIdx.find(GEP);
309 return I == GEPIdx.end() ? nullptr : I->second;
Tom Stellard880a80a2014-06-17 16:53:14 +0000310}
311
312static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
313 // FIXME we only support simple cases
314 if (GEP->getNumOperands() != 3)
Matt Arsenaultefb24542016-07-18 18:34:53 +0000315 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000316
317 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
318 if (!I0 || !I0->isZero())
Matt Arsenaultefb24542016-07-18 18:34:53 +0000319 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000320
321 return GEP->getOperand(2);
322}
323
Matt Arsenault642d2e72014-06-27 16:52:49 +0000324// Not an instruction handled below to turn into a vector.
325//
326// TODO: Check isTriviallyVectorizable for calls and handle other
327// instructions.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000328static bool canVectorizeInst(Instruction *Inst, User *User) {
Matt Arsenault642d2e72014-06-27 16:52:49 +0000329 switch (Inst->getOpcode()) {
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000330 case Instruction::Load: {
Changpeng Fang860d4602018-05-17 21:49:44 +0000331 // Currently only handle the case where the Pointer Operand is a GEP.
332 // Also we could not vectorize volatile or atomic loads.
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000333 LoadInst *LI = cast<LoadInst>(Inst);
Stanislav Mekhanoshin6cc8b2f2018-11-08 00:16:23 +0000334 if (isa<AllocaInst>(User) &&
335 LI->getPointerOperandType() == User->getType() &&
336 isa<VectorType>(LI->getType()))
337 return true;
Changpeng Fang860d4602018-05-17 21:49:44 +0000338 return isa<GetElementPtrInst>(LI->getPointerOperand()) && LI->isSimple();
Changpeng Fang161e8c39af2017-05-12 20:31:12 +0000339 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000340 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000341 return true;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000342 case Instruction::Store: {
David Stuttard82618ba2017-06-09 14:16:22 +0000343 // Must be the stored pointer operand, not a stored value, plus
344 // since it should be canonical form, the User should be a GEP.
Changpeng Fang860d4602018-05-17 21:49:44 +0000345 // Also we could not vectorize volatile or atomic stores.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000346 StoreInst *SI = cast<StoreInst>(Inst);
Stanislav Mekhanoshin6cc8b2f2018-11-08 00:16:23 +0000347 if (isa<AllocaInst>(User) &&
348 SI->getPointerOperandType() == User->getType() &&
349 isa<VectorType>(SI->getValueOperand()->getType()))
350 return true;
Changpeng Fang860d4602018-05-17 21:49:44 +0000351 return (SI->getPointerOperand() == User) && isa<GetElementPtrInst>(User) && SI->isSimple();
Matt Arsenault7227cc12015-07-28 18:47:00 +0000352 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000353 default:
354 return false;
355 }
356}
357
Matt Arsenault0da63502018-08-31 05:49:54 +0000358static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
Changpeng Fangba920592018-02-16 19:14:17 +0000359
360 if (DisablePromoteAllocaToVector) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000361 LLVM_DEBUG(dbgs() << " Promotion alloca to vector is disabled\n");
Changpeng Fangba920592018-02-16 19:14:17 +0000362 return false;
363 }
364
Stanislav Mekhanoshin6cc8b2f2018-11-08 00:16:23 +0000365 Type *AT = Alloca->getAllocatedType();
366 SequentialType *AllocaTy = dyn_cast<SequentialType>(AT);
Tom Stellard880a80a2014-06-17 16:53:14 +0000367
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000368 LLVM_DEBUG(dbgs() << "Alloca candidate for vectorization\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000369
370 // FIXME: There is no reason why we can't support larger arrays, we
371 // are just being conservative for now.
David Stuttard82618ba2017-06-09 14:16:22 +0000372 // FIXME: We also reject alloca's of the form [ 2 x [ 2 x i32 ]] or equivalent. Potentially these
373 // could also be promoted but we don't currently handle this case
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000374 if (!AllocaTy ||
Changpeng Fangba920592018-02-16 19:14:17 +0000375 AllocaTy->getNumElements() > 16 ||
Matt Arsenault37ab4cf2017-09-14 18:02:29 +0000376 AllocaTy->getNumElements() < 2 ||
377 !VectorType::isValidElementType(AllocaTy->getElementType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000378 LLVM_DEBUG(dbgs() << " Cannot convert type to vector\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000379 return false;
380 }
381
382 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
383 std::vector<Value*> WorkList;
384 for (User *AllocaUser : Alloca->users()) {
385 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
386 if (!GEP) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000387 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000388 return false;
389
Tom Stellard880a80a2014-06-17 16:53:14 +0000390 WorkList.push_back(AllocaUser);
391 continue;
392 }
393
394 Value *Index = GEPToVectorIndex(GEP);
395
396 // If we can't compute a vector index from this GEP, then we can't
397 // promote this alloca to vector.
398 if (!Index) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000399 LLVM_DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP
400 << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000401 return false;
402 }
403
404 GEPVectorIdx[GEP] = Index;
405 for (User *GEPUser : AllocaUser->users()) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000406 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000407 return false;
408
Tom Stellard880a80a2014-06-17 16:53:14 +0000409 WorkList.push_back(GEPUser);
410 }
411 }
412
Stanislav Mekhanoshin6cc8b2f2018-11-08 00:16:23 +0000413 VectorType *VectorTy = dyn_cast<VectorType>(AllocaTy);
414 if (!VectorTy)
415 VectorTy = arrayTypeToVecType(cast<ArrayType>(AllocaTy));
Tom Stellard880a80a2014-06-17 16:53:14 +0000416
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000417 LLVM_DEBUG(dbgs() << " Converting alloca to vector " << *AllocaTy << " -> "
418 << *VectorTy << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000419
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000420 for (Value *V : WorkList) {
421 Instruction *Inst = cast<Instruction>(V);
Tom Stellard880a80a2014-06-17 16:53:14 +0000422 IRBuilder<> Builder(Inst);
423 switch (Inst->getOpcode()) {
424 case Instruction::Load: {
Stanislav Mekhanoshin6cc8b2f2018-11-08 00:16:23 +0000425 if (Inst->getType() == AT)
426 break;
427
Matt Arsenault0da63502018-08-31 05:49:54 +0000428 Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
David Stuttard82618ba2017-06-09 14:16:22 +0000429 Value *Ptr = cast<LoadInst>(Inst)->getPointerOperand();
Tom Stellard880a80a2014-06-17 16:53:14 +0000430 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000431
432 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000433 Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
Tom Stellard880a80a2014-06-17 16:53:14 +0000434 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
435 Inst->replaceAllUsesWith(ExtractElement);
436 Inst->eraseFromParent();
437 break;
438 }
439 case Instruction::Store: {
David Stuttard82618ba2017-06-09 14:16:22 +0000440 StoreInst *SI = cast<StoreInst>(Inst);
Stanislav Mekhanoshin6cc8b2f2018-11-08 00:16:23 +0000441 if (SI->getValueOperand()->getType() == AT)
442 break;
443
444 Type *VecPtrTy = VectorTy->getPointerTo(AMDGPUAS::PRIVATE_ADDRESS);
David Stuttard82618ba2017-06-09 14:16:22 +0000445 Value *Ptr = SI->getPointerOperand();
Tom Stellard880a80a2014-06-17 16:53:14 +0000446 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000447 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000448 Value *VecValue = Builder.CreateLoad(VectorTy, BitCast);
Tom Stellard880a80a2014-06-17 16:53:14 +0000449 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
David Stuttard82618ba2017-06-09 14:16:22 +0000450 SI->getValueOperand(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000451 Index);
452 Builder.CreateStore(NewVecValue, BitCast);
453 Inst->eraseFromParent();
454 break;
455 }
456 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000457 case Instruction::AddrSpaceCast:
Tom Stellard880a80a2014-06-17 16:53:14 +0000458 break;
459
460 default:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000461 llvm_unreachable("Inconsistency in instructions promotable to vector");
Tom Stellard880a80a2014-06-17 16:53:14 +0000462 }
463 }
464 return true;
465}
466
Matt Arsenaultad134842016-02-02 19:18:53 +0000467static bool isCallPromotable(CallInst *CI) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000468 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
469 if (!II)
470 return false;
471
472 switch (II->getIntrinsicID()) {
473 case Intrinsic::memcpy:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000474 case Intrinsic::memmove:
Matt Arsenaultad134842016-02-02 19:18:53 +0000475 case Intrinsic::memset:
476 case Intrinsic::lifetime_start:
477 case Intrinsic::lifetime_end:
478 case Intrinsic::invariant_start:
479 case Intrinsic::invariant_end:
Piotr Padlewski5dde8092018-05-03 11:03:01 +0000480 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +0000481 case Intrinsic::strip_invariant_group:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000482 case Intrinsic::objectsize:
Matt Arsenaultad134842016-02-02 19:18:53 +0000483 return true;
484 default:
485 return false;
486 }
487}
488
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000489bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
490 Value *Val,
491 Instruction *Inst,
492 int OpIdx0,
493 int OpIdx1) const {
494 // Figure out which operand is the one we might not be promoting.
495 Value *OtherOp = Inst->getOperand(OpIdx0);
496 if (Val == OtherOp)
497 OtherOp = Inst->getOperand(OpIdx1);
498
Matt Arsenault891fccc2016-05-18 15:57:21 +0000499 if (isa<ConstantPointerNull>(OtherOp))
500 return true;
501
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000502 Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
503 if (!isa<AllocaInst>(OtherObj))
504 return false;
505
506 // TODO: We should be able to replace undefs with the right pointer type.
507
508 // TODO: If we know the other base object is another promotable
509 // alloca, not necessarily this alloca, we can do this. The
510 // important part is both must have the same address space at
511 // the end.
512 if (OtherObj != BaseAlloca) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000513 LLVM_DEBUG(
514 dbgs() << "Found a binary instruction with another alloca object\n");
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000515 return false;
516 }
517
518 return true;
519}
520
521bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
522 Value *BaseAlloca,
523 Value *Val,
524 std::vector<Value*> &WorkList) const {
525
Tom Stellard880a80a2014-06-17 16:53:14 +0000526 for (User *User : Val->users()) {
David Majnemer0d955d02016-08-11 22:21:41 +0000527 if (is_contained(WorkList, User))
Tom Stellard880a80a2014-06-17 16:53:14 +0000528 continue;
Matt Arsenaultad134842016-02-02 19:18:53 +0000529
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000530 if (CallInst *CI = dyn_cast<CallInst>(User)) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000531 if (!isCallPromotable(CI))
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000532 return false;
533
Tom Stellard880a80a2014-06-17 16:53:14 +0000534 WorkList.push_back(User);
535 continue;
536 }
Tom Stellard5b2927f2014-10-31 20:52:04 +0000537
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000538 Instruction *UseInst = cast<Instruction>(User);
539 if (UseInst->getOpcode() == Instruction::PtrToInt)
Tom Stellard5b2927f2014-10-31 20:52:04 +0000540 return false;
541
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000542 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
Matt Arsenaultc438ef52016-05-18 23:20:24 +0000543 if (LI->isVolatile())
544 return false;
545
546 continue;
547 }
548
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000549 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000550 if (SI->isVolatile())
551 return false;
552
Matt Arsenault7227cc12015-07-28 18:47:00 +0000553 // Reject if the stored value is not the pointer operand.
554 if (SI->getPointerOperand() != Val)
555 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000556 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000557 if (RMW->isVolatile())
558 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000559 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000560 if (CAS->isVolatile())
561 return false;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000562 }
563
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000564 // Only promote a select if we know that the other select operand
565 // is from another pointer that will also be promoted.
566 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
567 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
568 return false;
Matt Arsenault891fccc2016-05-18 15:57:21 +0000569
570 // May need to rewrite constant operands.
571 WorkList.push_back(ICmp);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000572 }
573
Matt Arsenault2402b952016-12-10 00:52:50 +0000574 if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
Changpeng Fangc85abbd2017-01-24 19:06:28 +0000575 // Give up if the pointer may be captured.
576 if (PointerMayBeCaptured(UseInst, true, true))
577 return false;
Matt Arsenault2402b952016-12-10 00:52:50 +0000578 // Don't collect the users of this.
579 WorkList.push_back(User);
580 continue;
581 }
582
Tom Stellard880a80a2014-06-17 16:53:14 +0000583 if (!User->getType()->isPointerTy())
584 continue;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000585
Matt Arsenaultde420812016-02-02 21:16:12 +0000586 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
587 // Be conservative if an address could be computed outside the bounds of
588 // the alloca.
589 if (!GEP->isInBounds())
590 return false;
591 }
592
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000593 // Only promote a select if we know that the other select operand is from
594 // another pointer that will also be promoted.
595 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
596 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
597 return false;
598 }
599
600 // Repeat for phis.
601 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
602 // TODO: Handle more complex cases. We should be able to replace loops
603 // over arrays.
604 switch (Phi->getNumIncomingValues()) {
605 case 1:
606 break;
607 case 2:
608 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
609 return false;
610 break;
611 default:
612 return false;
613 }
614 }
615
Tom Stellard880a80a2014-06-17 16:53:14 +0000616 WorkList.push_back(User);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000617 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
Matt Arsenaultad134842016-02-02 19:18:53 +0000618 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000619 }
Matt Arsenaultad134842016-02-02 19:18:53 +0000620
621 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000622}
623
Changpeng Fang1dbace12017-05-23 20:25:41 +0000624bool AMDGPUPromoteAlloca::hasSufficientLocalMem(const Function &F) {
625
626 FunctionType *FTy = F.getFunctionType();
Tom Stellard5bfbae52018-07-11 20:59:01 +0000627 const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, F);
Changpeng Fang1dbace12017-05-23 20:25:41 +0000628
629 // If the function has any arguments in the local address space, then it's
630 // possible these arguments require the entire local memory space, so
631 // we cannot use local memory in the pass.
632 for (Type *ParamTy : FTy->params()) {
633 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
Matt Arsenault0da63502018-08-31 05:49:54 +0000634 if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
Changpeng Fang1dbace12017-05-23 20:25:41 +0000635 LocalMemLimit = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000636 LLVM_DEBUG(dbgs() << "Function has local memory argument. Promoting to "
637 "local memory disabled.\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000638 return false;
639 }
640 }
641
642 LocalMemLimit = ST.getLocalMemorySize();
643 if (LocalMemLimit == 0)
644 return false;
645
646 const DataLayout &DL = Mod->getDataLayout();
647
648 // Check how much local memory is being used by global objects
649 CurrentLocalMemUsage = 0;
650 for (GlobalVariable &GV : Mod->globals()) {
Matt Arsenault0da63502018-08-31 05:49:54 +0000651 if (GV.getType()->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
Changpeng Fang1dbace12017-05-23 20:25:41 +0000652 continue;
653
654 for (const User *U : GV.users()) {
655 const Instruction *Use = dyn_cast<Instruction>(U);
656 if (!Use)
657 continue;
658
659 if (Use->getParent()->getParent() == &F) {
660 unsigned Align = GV.getAlignment();
661 if (Align == 0)
662 Align = DL.getABITypeAlignment(GV.getValueType());
663
664 // FIXME: Try to account for padding here. The padding is currently
665 // determined from the inverse order of uses in the function. I'm not
666 // sure if the use list order is in any way connected to this, so the
667 // total reported size is likely incorrect.
668 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
669 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
670 CurrentLocalMemUsage += AllocSize;
671 break;
672 }
673 }
674 }
675
676 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
677 F);
678
679 // Restrict local memory usage so that we don't drastically reduce occupancy,
680 // unless it is already significantly reduced.
681
682 // TODO: Have some sort of hint or other heuristics to guess occupancy based
683 // on other factors..
684 unsigned OccupancyHint = ST.getWavesPerEU(F).second;
685 if (OccupancyHint == 0)
686 OccupancyHint = 7;
687
688 // Clamp to max value.
689 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
690
691 // Check the hint but ignore it if it's obviously wrong from the existing LDS
692 // usage.
693 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
694
695
696 // Round up to the next tier of usage.
697 unsigned MaxSizeWithWaveCount
698 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
699
700 // Program is possibly broken by using more local mem than available.
701 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
702 return false;
703
704 LocalMemLimit = MaxSizeWithWaveCount;
705
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000706 LLVM_DEBUG(dbgs() << F.getName() << " uses " << CurrentLocalMemUsage
707 << " bytes of LDS\n"
708 << " Rounding size to " << MaxSizeWithWaveCount
709 << " with a maximum occupancy of " << MaxOccupancy << '\n'
710 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
711 << " available for promotion\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000712
713 return true;
714}
715
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000716// FIXME: Should try to pick the most likely to be profitable allocas first.
Changpeng Fang1dbace12017-05-23 20:25:41 +0000717bool AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I, bool SufficientLDS) {
Matt Arsenaultc5fce692016-04-28 18:38:48 +0000718 // Array allocations are probably not worth handling, since an allocation of
719 // the array type is the canonical form.
720 if (!I.isStaticAlloca() || I.isArrayAllocation())
Changpeng Fang1dbace12017-05-23 20:25:41 +0000721 return false;
Matt Arsenault19c54882015-08-26 18:37:13 +0000722
Tom Stellard880a80a2014-06-17 16:53:14 +0000723 IRBuilder<> Builder(&I);
724
725 // First try to replace the alloca with a vector
726 Type *AllocaTy = I.getAllocatedType();
727
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000728 LLVM_DEBUG(dbgs() << "Trying to promote " << I << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000729
Matt Arsenault0da63502018-08-31 05:49:54 +0000730 if (tryPromoteAllocaToVector(&I))
Changpeng Fang1dbace12017-05-23 20:25:41 +0000731 return true; // Promoted to vector.
Tom Stellard880a80a2014-06-17 16:53:14 +0000732
Yaxun Liu73bf0af2018-11-06 21:28:17 +0000733 if (DisablePromoteAllocaToLDS)
734 return false;
735
Tom Stellard79a1fd72016-04-14 16:27:07 +0000736 const Function &ContainingFunction = *I.getParent()->getParent();
Matt Arsenault5c806182017-05-02 18:33:18 +0000737 CallingConv::ID CC = ContainingFunction.getCallingConv();
Tom Stellard79a1fd72016-04-14 16:27:07 +0000738
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000739 // Don't promote the alloca to LDS for shader calling conventions as the work
740 // item ID intrinsics are not supported for these calling conventions.
741 // Furthermore not all LDS is available for some of the stages.
Matt Arsenault5c806182017-05-02 18:33:18 +0000742 switch (CC) {
743 case CallingConv::AMDGPU_KERNEL:
744 case CallingConv::SPIR_KERNEL:
745 break;
746 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000747 LLVM_DEBUG(
748 dbgs()
749 << " promote alloca to LDS not supported with calling convention.\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000750 return false;
Matt Arsenault5c806182017-05-02 18:33:18 +0000751 }
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000752
Changpeng Fang1dbace12017-05-23 20:25:41 +0000753 // Not likely to have sufficient local memory for promotion.
754 if (!SufficientLDS)
755 return false;
756
Tom Stellard5bfbae52018-07-11 20:59:01 +0000757 const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(*TM, ContainingFunction);
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000758 unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
Tom Stellard79a1fd72016-04-14 16:27:07 +0000759
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000760 const DataLayout &DL = Mod->getDataLayout();
Tom Stellard880a80a2014-06-17 16:53:14 +0000761
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000762 unsigned Align = I.getAlignment();
763 if (Align == 0)
764 Align = DL.getABITypeAlignment(I.getAllocatedType());
765
766 // FIXME: This computed padding is likely wrong since it depends on inverse
767 // usage order.
768 //
769 // FIXME: It is also possible that if we're allowed to use all of the memory
770 // could could end up using more than the maximum due to alignment padding.
771
772 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
773 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
774 NewSize += AllocSize;
775
776 if (NewSize > LocalMemLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000777 LLVM_DEBUG(dbgs() << " " << AllocSize
778 << " bytes of local memory not available to promote\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000779 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000780 }
781
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000782 CurrentLocalMemUsage = NewSize;
783
Tom Stellard5b2927f2014-10-31 20:52:04 +0000784 std::vector<Value*> WorkList;
785
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000786 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000787 LLVM_DEBUG(dbgs() << " Do not know how to convert all uses\n");
Changpeng Fang1dbace12017-05-23 20:25:41 +0000788 return false;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000789 }
790
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000791 LLVM_DEBUG(dbgs() << "Promoting alloca to local memory\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000792
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000793 Function *F = I.getParent()->getParent();
794
Tom Stellard79a1fd72016-04-14 16:27:07 +0000795 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
Tom Stellard880a80a2014-06-17 16:53:14 +0000796 GlobalVariable *GV = new GlobalVariable(
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000797 *Mod, GVTy, false, GlobalValue::InternalLinkage,
798 UndefValue::get(GVTy),
799 Twine(F->getName()) + Twine('.') + I.getName(),
800 nullptr,
801 GlobalVariable::NotThreadLocal,
Matt Arsenault0da63502018-08-31 05:49:54 +0000802 AMDGPUAS::LOCAL_ADDRESS);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000803 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000804 GV->setAlignment(I.getAlignment());
Tom Stellard880a80a2014-06-17 16:53:14 +0000805
Matt Arsenaulte0132462016-01-30 05:19:45 +0000806 Value *TCntY, *TCntZ;
Tom Stellard880a80a2014-06-17 16:53:14 +0000807
Matt Arsenaulte0132462016-01-30 05:19:45 +0000808 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
809 Value *TIdX = getWorkitemID(Builder, 0);
810 Value *TIdY = getWorkitemID(Builder, 1);
811 Value *TIdZ = getWorkitemID(Builder, 2);
Tom Stellard880a80a2014-06-17 16:53:14 +0000812
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000813 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000814 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000815 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000816 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
817 TID = Builder.CreateAdd(TID, TIdZ);
818
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000819 Value *Indices[] = {
820 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
821 TID
822 };
Tom Stellard880a80a2014-06-17 16:53:14 +0000823
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000824 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
Tom Stellard880a80a2014-06-17 16:53:14 +0000825 I.mutateType(Offset->getType());
826 I.replaceAllUsesWith(Offset);
827 I.eraseFromParent();
828
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000829 for (Value *V : WorkList) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000830 CallInst *Call = dyn_cast<CallInst>(V);
831 if (!Call) {
Matt Arsenault891fccc2016-05-18 15:57:21 +0000832 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
833 Value *Src0 = CI->getOperand(0);
834 Type *EltTy = Src0->getType()->getPointerElementType();
Matt Arsenault0da63502018-08-31 05:49:54 +0000835 PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000836
837 if (isa<ConstantPointerNull>(CI->getOperand(0)))
838 CI->setOperand(0, ConstantPointerNull::get(NewTy));
839
840 if (isa<ConstantPointerNull>(CI->getOperand(1)))
841 CI->setOperand(1, ConstantPointerNull::get(NewTy));
842
843 continue;
844 }
Matt Arsenault65f67e42014-09-15 15:41:44 +0000845
Matt Arsenault2402b952016-12-10 00:52:50 +0000846 // The operand's value should be corrected on its own and we don't want to
847 // touch the users.
Matt Arsenault65f67e42014-09-15 15:41:44 +0000848 if (isa<AddrSpaceCastInst>(V))
849 continue;
850
Matt Arsenault891fccc2016-05-18 15:57:21 +0000851 Type *EltTy = V->getType()->getPointerElementType();
Matt Arsenault0da63502018-08-31 05:49:54 +0000852 PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000853
Matt Arsenault65f67e42014-09-15 15:41:44 +0000854 // FIXME: It doesn't really make sense to try to do this for all
855 // instructions.
Tom Stellard880a80a2014-06-17 16:53:14 +0000856 V->mutateType(NewTy);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000857
858 // Adjust the types of any constant operands.
859 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
860 if (isa<ConstantPointerNull>(SI->getOperand(1)))
861 SI->setOperand(1, ConstantPointerNull::get(NewTy));
862
863 if (isa<ConstantPointerNull>(SI->getOperand(2)))
864 SI->setOperand(2, ConstantPointerNull::get(NewTy));
865 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
866 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
867 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
868 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
869 }
870 }
871
Tom Stellard880a80a2014-06-17 16:53:14 +0000872 continue;
873 }
874
Matt Arsenault2e08e182016-07-18 18:34:48 +0000875 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
Tom Stellard880a80a2014-06-17 16:53:14 +0000876 Builder.SetInsertPoint(Intr);
877 switch (Intr->getIntrinsicID()) {
878 case Intrinsic::lifetime_start:
879 case Intrinsic::lifetime_end:
880 // These intrinsics are for address space 0 only
881 Intr->eraseFromParent();
882 continue;
883 case Intrinsic::memcpy: {
884 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
Daniel Neilsona60f4622018-02-09 21:56:15 +0000885 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getDestAlignment(),
886 MemCpy->getRawSource(), MemCpy->getSourceAlignment(),
887 MemCpy->getLength(), MemCpy->isVolatile());
Tom Stellard880a80a2014-06-17 16:53:14 +0000888 Intr->eraseFromParent();
889 continue;
890 }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000891 case Intrinsic::memmove: {
892 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
Daniel Neilsona60f4622018-02-09 21:56:15 +0000893 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getDestAlignment(),
894 MemMove->getRawSource(), MemMove->getSourceAlignment(),
895 MemMove->getLength(), MemMove->isVolatile());
Matt Arsenault7e747f12016-02-02 20:28:10 +0000896 Intr->eraseFromParent();
897 continue;
898 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000899 case Intrinsic::memset: {
900 MemSetInst *MemSet = cast<MemSetInst>(Intr);
901 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
Daniel Neilsona60f4622018-02-09 21:56:15 +0000902 MemSet->getLength(), MemSet->getDestAlignment(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000903 MemSet->isVolatile());
904 Intr->eraseFromParent();
905 continue;
906 }
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000907 case Intrinsic::invariant_start:
908 case Intrinsic::invariant_end:
Piotr Padlewski5dde8092018-05-03 11:03:01 +0000909 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +0000910 case Intrinsic::strip_invariant_group:
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000911 Intr->eraseFromParent();
912 // FIXME: I think the invariant marker should still theoretically apply,
913 // but the intrinsics need to be changed to accept pointers with any
914 // address space.
915 continue;
Matt Arsenault7e747f12016-02-02 20:28:10 +0000916 case Intrinsic::objectsize: {
917 Value *Src = Intr->getOperand(0);
918 Type *SrcTy = Src->getType()->getPointerElementType();
919 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
920 Intrinsic::objectsize,
Matt Arsenault0da63502018-08-31 05:49:54 +0000921 { Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000922 );
923
George Burgess IV56c7e882017-03-21 20:08:59 +0000924 CallInst *NewCall = Builder.CreateCall(
Erik Pilkington600e9de2019-01-30 20:34:35 +0000925 ObjectSize,
926 {Src, Intr->getOperand(1), Intr->getOperand(2), Intr->getOperand(3)});
Matt Arsenault7e747f12016-02-02 20:28:10 +0000927 Intr->replaceAllUsesWith(NewCall);
928 Intr->eraseFromParent();
929 continue;
930 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000931 default:
Matthias Braun8c209aa2017-01-28 02:02:38 +0000932 Intr->print(errs());
Tom Stellard880a80a2014-06-17 16:53:14 +0000933 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
934 }
935 }
Changpeng Fang1dbace12017-05-23 20:25:41 +0000936 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000937}
938
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000939FunctionPass *llvm::createAMDGPUPromoteAlloca() {
940 return new AMDGPUPromoteAlloca();
Tom Stellard880a80a2014-06-17 16:53:14 +0000941}