blob: 96bc53d06cd9531b785b41eac7b06a13a0c2e5bd [file] [log] [blame]
Tom Stellard880a80a2014-06-17 16:53:14 +00001//===-- 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"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000017#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"
Changpeng Fangc85abbd2017-01-24 19:06:28 +000024#include "llvm/Analysis/CaptureTracking.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000025#include "llvm/Analysis/ValueTracking.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"
35#include "llvm/IR/Instruction.h"
36#include "llvm/IR/Instructions.h"
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000037#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000038#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/LLVMContext.h"
Matt Arsenaulte0132462016-01-30 05:19:45 +000041#include "llvm/IR/MDBuilder.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000042#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/User.h"
46#include "llvm/IR/Value.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/Casting.h"
Tom Stellard880a80a2014-06-17 16:53:14 +000049#include "llvm/Support/Debug.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000050#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/MathExtras.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000052#include "llvm/Support/raw_ostream.h"
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000053#include "llvm/Target/TargetMachine.h"
54#include <algorithm>
55#include <cassert>
56#include <cstdint>
57#include <map>
58#include <tuple>
59#include <utility>
60#include <vector>
Tom Stellard880a80a2014-06-17 16:53:14 +000061
62#define DEBUG_TYPE "amdgpu-promote-alloca"
63
64using namespace llvm;
65
66namespace {
67
Matt Arsenaulte0132462016-01-30 05:19:45 +000068// FIXME: This can create globals so should be a module pass.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000069class AMDGPUPromoteAlloca : public FunctionPass {
Matt Arsenaulte0132462016-01-30 05:19:45 +000070private:
71 const TargetMachine *TM;
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000072 Module *Mod = nullptr;
73 const DataLayout *DL = nullptr;
74 MDNode *MaxWorkGroupSizeRange = nullptr;
Yaxun Liu1a14bfa2017-03-27 14:04:01 +000075 AMDGPUAS AS;
Matt Arsenaulte0132462016-01-30 05:19:45 +000076
77 // FIXME: This should be per-kernel.
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000078 uint32_t LocalMemLimit = 0;
79 uint32_t CurrentLocalMemUsage = 0;
Tom Stellard880a80a2014-06-17 16:53:14 +000080
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000081 bool IsAMDGCN = false;
82 bool IsAMDHSA = false;
Matt Arsenaulte0132462016-01-30 05:19:45 +000083
84 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
85 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
86
Matt Arsenaulta61cb482016-05-12 01:58:58 +000087 /// BaseAlloca is the alloca root the search started from.
88 /// Val may be that alloca or a recursive user of it.
89 bool collectUsesWithPtrTypes(Value *BaseAlloca,
90 Value *Val,
91 std::vector<Value*> &WorkList) const;
92
93 /// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
94 /// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
95 /// Returns true if both operands are derived from the same alloca. Val should
96 /// be the same value as one of the input operands of UseInst.
97 bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
98 Instruction *UseInst,
99 int OpIdx0, int OpIdx1) const;
100
Tom Stellard880a80a2014-06-17 16:53:14 +0000101public:
Matt Arsenaulte0132462016-01-30 05:19:45 +0000102 static char ID;
103
104 AMDGPUPromoteAlloca(const TargetMachine *TM_ = nullptr) :
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000105 FunctionPass(ID), TM(TM_) {}
Matt Arsenaulte0132462016-01-30 05:19:45 +0000106
Benjamin Kramer8c90fd72014-09-03 11:41:21 +0000107 bool doInitialization(Module &M) override;
108 bool runOnFunction(Function &F) override;
Matt Arsenaulte0132462016-01-30 05:19:45 +0000109
Mehdi Amini117296c2016-10-01 02:56:57 +0000110 StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
Matt Arsenaulte0132462016-01-30 05:19:45 +0000111
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000112 void handleAlloca(AllocaInst &I);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000113
114 void getAnalysisUsage(AnalysisUsage &AU) const override {
115 AU.setPreservesCFG();
116 FunctionPass::getAnalysisUsage(AU);
117 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000118};
119
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000120} // end anonymous namespace
Tom Stellard880a80a2014-06-17 16:53:14 +0000121
122char AMDGPUPromoteAlloca::ID = 0;
123
Matt Arsenaulte0132462016-01-30 05:19:45 +0000124INITIALIZE_TM_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
125 "AMDGPU promote alloca to vector or LDS", false, false)
126
127char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
128
Tom Stellard880a80a2014-06-17 16:53:14 +0000129bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
Matt Arsenaulte0132462016-01-30 05:19:45 +0000130 if (!TM)
131 return false;
132
Tom Stellard880a80a2014-06-17 16:53:14 +0000133 Mod = &M;
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000134 DL = &Mod->getDataLayout();
Matt Arsenaulte0132462016-01-30 05:19:45 +0000135
136 // The maximum workitem id.
137 //
138 // FIXME: Should get as subtarget property. Usually runtime enforced max is
139 // 256.
140 MDBuilder MDB(Mod->getContext());
141 MaxWorkGroupSizeRange = MDB.createRange(APInt(32, 0), APInt(32, 2048));
142
143 const Triple &TT = TM->getTargetTriple();
144
145 IsAMDGCN = TT.getArch() == Triple::amdgcn;
146 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
147
Tom Stellard880a80a2014-06-17 16:53:14 +0000148 return false;
149}
150
151bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
Andrew Kaylor7de74af2016-04-25 22:23:44 +0000152 if (!TM || skipFunction(F))
Matt Arsenaulte0132462016-01-30 05:19:45 +0000153 return false;
154
Matt Arsenault03d85842016-06-27 20:32:13 +0000155 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
156 if (!ST.isPromoteAllocaEnabled())
157 return false;
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000158 AS = AMDGPU::getAMDGPUAS(*F.getParent());
Matt Arsenault03d85842016-06-27 20:32:13 +0000159
Craig Toppere3dcce92015-08-01 22:20:21 +0000160 FunctionType *FTy = F.getFunctionType();
Tom Stellard880a80a2014-06-17 16:53:14 +0000161
162 // If the function has any arguments in the local address space, then it's
163 // possible these arguments require the entire local memory space, so
164 // we cannot use local memory in the pass.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000165 for (Type *ParamTy : FTy->params()) {
166 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000167 if (PtrTy && PtrTy->getAddressSpace() == AS.LOCAL_ADDRESS) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000168 LocalMemLimit = 0;
169 DEBUG(dbgs() << "Function has local memory argument. Promoting to "
Tom Stellard880a80a2014-06-17 16:53:14 +0000170 "local memory disabled.\n");
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000171 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000172 }
173 }
174
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000175 LocalMemLimit = ST.getLocalMemorySize();
176 if (LocalMemLimit == 0)
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000177 return false;
178
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000179 const DataLayout &DL = Mod->getDataLayout();
180
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000181 // Check how much local memory is being used by global objects
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000182 CurrentLocalMemUsage = 0;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000183 for (GlobalVariable &GV : Mod->globals()) {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000184 if (GV.getType()->getAddressSpace() != AS.LOCAL_ADDRESS)
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000185 continue;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000186
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000187 for (const User *U : GV.users()) {
188 const Instruction *Use = dyn_cast<Instruction>(U);
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000189 if (!Use)
Tom Stellard880a80a2014-06-17 16:53:14 +0000190 continue;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000191
Matt Arsenault0547b012016-04-27 21:05:08 +0000192 if (Use->getParent()->getParent() == &F) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000193 unsigned Align = GV.getAlignment();
194 if (Align == 0)
195 Align = DL.getABITypeAlignment(GV.getValueType());
196
197 // FIXME: Try to account for padding here. The padding is currently
198 // determined from the inverse order of uses in the function. I'm not
199 // sure if the use list order is in any way connected to this, so the
200 // total reported size is likely incorrect.
201 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
202 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
203 CurrentLocalMemUsage += AllocSize;
Matt Arsenault0547b012016-04-27 21:05:08 +0000204 break;
205 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000206 }
207 }
208
Stanislav Mekhanoshin2b913b12017-02-01 22:59:50 +0000209 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
210 F);
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000211
212 // Restrict local memory usage so that we don't drastically reduce occupancy,
213 // unless it is already significantly reduced.
214
215 // TODO: Have some sort of hint or other heuristics to guess occupancy based
216 // on other factors..
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000217 unsigned OccupancyHint = ST.getWavesPerEU(F).second;
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000218 if (OccupancyHint == 0)
219 OccupancyHint = 7;
220
221 // Clamp to max value.
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000222 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000223
224 // Check the hint but ignore it if it's obviously wrong from the existing LDS
225 // usage.
226 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
227
228
229 // Round up to the next tier of usage.
230 unsigned MaxSizeWithWaveCount
Stanislav Mekhanoshin2b913b12017-02-01 22:59:50 +0000231 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000232
233 // Program is possibly broken by using more local mem than available.
234 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
235 return false;
236
237 LocalMemLimit = MaxSizeWithWaveCount;
238
239 DEBUG(
240 dbgs() << F.getName() << " uses " << CurrentLocalMemUsage << " bytes of LDS\n"
241 << " Rounding size to " << MaxSizeWithWaveCount
242 << " with a maximum occupancy of " << MaxOccupancy << '\n'
243 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
244 << " available for promotion\n"
245 );
Tom Stellard880a80a2014-06-17 16:53:14 +0000246
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000247 BasicBlock &EntryBB = *F.begin();
248 for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
249 AllocaInst *AI = dyn_cast<AllocaInst>(I);
250
251 ++I;
252 if (AI)
253 handleAlloca(*AI);
254 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000255
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000256 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000257}
258
Matt Arsenaulte0132462016-01-30 05:19:45 +0000259std::pair<Value *, Value *>
260AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
261 if (!IsAMDHSA) {
262 Function *LocalSizeYFn
263 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
264 Function *LocalSizeZFn
265 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
266
267 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
268 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
269
270 LocalSizeY->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
271 LocalSizeZ->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
272
273 return std::make_pair(LocalSizeY, LocalSizeZ);
274 }
275
276 // We must read the size out of the dispatch pointer.
277 assert(IsAMDGCN);
278
279 // We are indexing into this struct, and want to extract the workgroup_size_*
280 // fields.
281 //
282 // typedef struct hsa_kernel_dispatch_packet_s {
283 // uint16_t header;
284 // uint16_t setup;
285 // uint16_t workgroup_size_x ;
286 // uint16_t workgroup_size_y;
287 // uint16_t workgroup_size_z;
288 // uint16_t reserved0;
289 // uint32_t grid_size_x ;
290 // uint32_t grid_size_y ;
291 // uint32_t grid_size_z;
292 //
293 // uint32_t private_segment_size;
294 // uint32_t group_segment_size;
295 // uint64_t kernel_object;
296 //
297 // #ifdef HSA_LARGE_MODEL
298 // void *kernarg_address;
299 // #elif defined HSA_LITTLE_ENDIAN
300 // void *kernarg_address;
301 // uint32_t reserved1;
302 // #else
303 // uint32_t reserved1;
304 // void *kernarg_address;
305 // #endif
306 // uint64_t reserved2;
307 // hsa_signal_t completion_signal; // uint64_t wrapper
308 // } hsa_kernel_dispatch_packet_t
309 //
310 Function *DispatchPtrFn
311 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
312
313 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
Reid Klecknerb5180542017-03-21 16:57:19 +0000314 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
315 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000316
317 // Size of the dispatch packet struct.
Reid Klecknerb5180542017-03-21 16:57:19 +0000318 DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000319
320 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
321 Value *CastDispatchPtr = Builder.CreateBitCast(
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000322 DispatchPtr, PointerType::get(I32Ty, AS.CONSTANT_ADDRESS));
Matt Arsenaulte0132462016-01-30 05:19:45 +0000323
324 // We could do a single 64-bit load here, but it's likely that the basic
325 // 32-bit and extract sequence is already present, and it is probably easier
326 // to CSE this. The loads should be mergable later anyway.
327 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
328 LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
329
330 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
331 LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
332
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000333 MDNode *MD = MDNode::get(Mod->getContext(), None);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000334 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
335 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
336 LoadZU->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
337
338 // Extract y component. Upper half of LoadZU should be zero already.
339 Value *Y = Builder.CreateLShr(LoadXY, 16);
340
341 return std::make_pair(Y, LoadZU);
342}
343
344Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
345 Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
346
347 switch (N) {
348 case 0:
349 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
350 : Intrinsic::r600_read_tidig_x;
351 break;
352 case 1:
353 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
354 : Intrinsic::r600_read_tidig_y;
355 break;
356
357 case 2:
358 IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
359 : Intrinsic::r600_read_tidig_z;
360 break;
361 default:
362 llvm_unreachable("invalid dimension");
363 }
364
365 Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
366 CallInst *CI = Builder.CreateCall(WorkitemIdFn);
367 CI->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
368
369 return CI;
370}
371
Craig Toppere3dcce92015-08-01 22:20:21 +0000372static VectorType *arrayTypeToVecType(Type *ArrayTy) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000373 return VectorType::get(ArrayTy->getArrayElementType(),
374 ArrayTy->getArrayNumElements());
375}
376
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000377static Value *
378calculateVectorIndex(Value *Ptr,
379 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000380 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
381
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000382 auto I = GEPIdx.find(GEP);
383 return I == GEPIdx.end() ? nullptr : I->second;
Tom Stellard880a80a2014-06-17 16:53:14 +0000384}
385
386static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
387 // FIXME we only support simple cases
388 if (GEP->getNumOperands() != 3)
Matt Arsenaultefb24542016-07-18 18:34:53 +0000389 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000390
391 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
392 if (!I0 || !I0->isZero())
Matt Arsenaultefb24542016-07-18 18:34:53 +0000393 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000394
395 return GEP->getOperand(2);
396}
397
Matt Arsenault642d2e72014-06-27 16:52:49 +0000398// Not an instruction handled below to turn into a vector.
399//
400// TODO: Check isTriviallyVectorizable for calls and handle other
401// instructions.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000402static bool canVectorizeInst(Instruction *Inst, User *User) {
Matt Arsenault642d2e72014-06-27 16:52:49 +0000403 switch (Inst->getOpcode()) {
404 case Instruction::Load:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000405 case Instruction::BitCast:
406 case Instruction::AddrSpaceCast:
407 return true;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000408 case Instruction::Store: {
409 // Must be the stored pointer operand, not a stored value.
410 StoreInst *SI = cast<StoreInst>(Inst);
411 return SI->getPointerOperand() == User;
412 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000413 default:
414 return false;
415 }
416}
417
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000418static bool tryPromoteAllocaToVector(AllocaInst *Alloca, AMDGPUAS AS) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000419 ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
Tom Stellard880a80a2014-06-17 16:53:14 +0000420
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000421 DEBUG(dbgs() << "Alloca candidate for vectorization\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000422
423 // FIXME: There is no reason why we can't support larger arrays, we
424 // are just being conservative for now.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000425 if (!AllocaTy ||
426 AllocaTy->getElementType()->isVectorTy() ||
Matt Arsenaultefb24542016-07-18 18:34:53 +0000427 AllocaTy->getNumElements() > 4 ||
428 AllocaTy->getNumElements() < 2) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000429 DEBUG(dbgs() << " Cannot convert type to vector\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000430 return false;
431 }
432
433 std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
434 std::vector<Value*> WorkList;
435 for (User *AllocaUser : Alloca->users()) {
436 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
437 if (!GEP) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000438 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000439 return false;
440
Tom Stellard880a80a2014-06-17 16:53:14 +0000441 WorkList.push_back(AllocaUser);
442 continue;
443 }
444
445 Value *Index = GEPToVectorIndex(GEP);
446
447 // If we can't compute a vector index from this GEP, then we can't
448 // promote this alloca to vector.
449 if (!Index) {
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000450 DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000451 return false;
452 }
453
454 GEPVectorIdx[GEP] = Index;
455 for (User *GEPUser : AllocaUser->users()) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000456 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000457 return false;
458
Tom Stellard880a80a2014-06-17 16:53:14 +0000459 WorkList.push_back(GEPUser);
460 }
461 }
462
463 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
464
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000465 DEBUG(dbgs() << " Converting alloca to vector "
466 << *AllocaTy << " -> " << *VectorTy << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000467
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000468 for (Value *V : WorkList) {
469 Instruction *Inst = cast<Instruction>(V);
Tom Stellard880a80a2014-06-17 16:53:14 +0000470 IRBuilder<> Builder(Inst);
471 switch (Inst->getOpcode()) {
472 case Instruction::Load: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000473 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Tom Stellard880a80a2014-06-17 16:53:14 +0000474 Value *Ptr = Inst->getOperand(0);
475 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000476
477 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000478 Value *VecValue = Builder.CreateLoad(BitCast);
479 Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
480 Inst->replaceAllUsesWith(ExtractElement);
481 Inst->eraseFromParent();
482 break;
483 }
484 case Instruction::Store: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000485 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000486
Tom Stellard880a80a2014-06-17 16:53:14 +0000487 Value *Ptr = Inst->getOperand(1);
488 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000489 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000490 Value *VecValue = Builder.CreateLoad(BitCast);
491 Value *NewVecValue = Builder.CreateInsertElement(VecValue,
492 Inst->getOperand(0),
493 Index);
494 Builder.CreateStore(NewVecValue, BitCast);
495 Inst->eraseFromParent();
496 break;
497 }
498 case Instruction::BitCast:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000499 case Instruction::AddrSpaceCast:
Tom Stellard880a80a2014-06-17 16:53:14 +0000500 break;
501
502 default:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000503 llvm_unreachable("Inconsistency in instructions promotable to vector");
Tom Stellard880a80a2014-06-17 16:53:14 +0000504 }
505 }
506 return true;
507}
508
Matt Arsenaultad134842016-02-02 19:18:53 +0000509static bool isCallPromotable(CallInst *CI) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000510 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
511 if (!II)
512 return false;
513
514 switch (II->getIntrinsicID()) {
515 case Intrinsic::memcpy:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000516 case Intrinsic::memmove:
Matt Arsenaultad134842016-02-02 19:18:53 +0000517 case Intrinsic::memset:
518 case Intrinsic::lifetime_start:
519 case Intrinsic::lifetime_end:
520 case Intrinsic::invariant_start:
521 case Intrinsic::invariant_end:
522 case Intrinsic::invariant_group_barrier:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000523 case Intrinsic::objectsize:
Matt Arsenaultad134842016-02-02 19:18:53 +0000524 return true;
525 default:
526 return false;
527 }
528}
529
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000530bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
531 Value *Val,
532 Instruction *Inst,
533 int OpIdx0,
534 int OpIdx1) const {
535 // Figure out which operand is the one we might not be promoting.
536 Value *OtherOp = Inst->getOperand(OpIdx0);
537 if (Val == OtherOp)
538 OtherOp = Inst->getOperand(OpIdx1);
539
Matt Arsenault891fccc2016-05-18 15:57:21 +0000540 if (isa<ConstantPointerNull>(OtherOp))
541 return true;
542
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000543 Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
544 if (!isa<AllocaInst>(OtherObj))
545 return false;
546
547 // TODO: We should be able to replace undefs with the right pointer type.
548
549 // TODO: If we know the other base object is another promotable
550 // alloca, not necessarily this alloca, we can do this. The
551 // important part is both must have the same address space at
552 // the end.
553 if (OtherObj != BaseAlloca) {
554 DEBUG(dbgs() << "Found a binary instruction with another alloca object\n");
555 return false;
556 }
557
558 return true;
559}
560
561bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
562 Value *BaseAlloca,
563 Value *Val,
564 std::vector<Value*> &WorkList) const {
565
Tom Stellard880a80a2014-06-17 16:53:14 +0000566 for (User *User : Val->users()) {
David Majnemer0d955d02016-08-11 22:21:41 +0000567 if (is_contained(WorkList, User))
Tom Stellard880a80a2014-06-17 16:53:14 +0000568 continue;
Matt Arsenaultad134842016-02-02 19:18:53 +0000569
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000570 if (CallInst *CI = dyn_cast<CallInst>(User)) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000571 if (!isCallPromotable(CI))
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000572 return false;
573
Tom Stellard880a80a2014-06-17 16:53:14 +0000574 WorkList.push_back(User);
575 continue;
576 }
Tom Stellard5b2927f2014-10-31 20:52:04 +0000577
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000578 Instruction *UseInst = cast<Instruction>(User);
579 if (UseInst->getOpcode() == Instruction::PtrToInt)
Tom Stellard5b2927f2014-10-31 20:52:04 +0000580 return false;
581
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000582 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
Matt Arsenaultc438ef52016-05-18 23:20:24 +0000583 if (LI->isVolatile())
584 return false;
585
586 continue;
587 }
588
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000589 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000590 if (SI->isVolatile())
591 return false;
592
Matt Arsenault7227cc12015-07-28 18:47:00 +0000593 // Reject if the stored value is not the pointer operand.
594 if (SI->getPointerOperand() != Val)
595 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000596 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000597 if (RMW->isVolatile())
598 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000599 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000600 if (CAS->isVolatile())
601 return false;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000602 }
603
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000604 // Only promote a select if we know that the other select operand
605 // is from another pointer that will also be promoted.
606 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
607 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
608 return false;
Matt Arsenault891fccc2016-05-18 15:57:21 +0000609
610 // May need to rewrite constant operands.
611 WorkList.push_back(ICmp);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000612 }
613
Matt Arsenault2402b952016-12-10 00:52:50 +0000614 if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
Changpeng Fangc85abbd2017-01-24 19:06:28 +0000615 // Give up if the pointer may be captured.
616 if (PointerMayBeCaptured(UseInst, true, true))
617 return false;
Matt Arsenault2402b952016-12-10 00:52:50 +0000618 // Don't collect the users of this.
619 WorkList.push_back(User);
620 continue;
621 }
622
Tom Stellard880a80a2014-06-17 16:53:14 +0000623 if (!User->getType()->isPointerTy())
624 continue;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000625
Matt Arsenaultde420812016-02-02 21:16:12 +0000626 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
627 // Be conservative if an address could be computed outside the bounds of
628 // the alloca.
629 if (!GEP->isInBounds())
630 return false;
631 }
632
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000633 // Only promote a select if we know that the other select operand is from
634 // another pointer that will also be promoted.
635 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
636 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
637 return false;
638 }
639
640 // Repeat for phis.
641 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
642 // TODO: Handle more complex cases. We should be able to replace loops
643 // over arrays.
644 switch (Phi->getNumIncomingValues()) {
645 case 1:
646 break;
647 case 2:
648 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
649 return false;
650 break;
651 default:
652 return false;
653 }
654 }
655
Tom Stellard880a80a2014-06-17 16:53:14 +0000656 WorkList.push_back(User);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000657 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
Matt Arsenaultad134842016-02-02 19:18:53 +0000658 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000659 }
Matt Arsenaultad134842016-02-02 19:18:53 +0000660
661 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000662}
663
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000664// FIXME: Should try to pick the most likely to be profitable allocas first.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000665void AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I) {
Matt Arsenaultc5fce692016-04-28 18:38:48 +0000666 // Array allocations are probably not worth handling, since an allocation of
667 // the array type is the canonical form.
668 if (!I.isStaticAlloca() || I.isArrayAllocation())
Matt Arsenault19c54882015-08-26 18:37:13 +0000669 return;
670
Tom Stellard880a80a2014-06-17 16:53:14 +0000671 IRBuilder<> Builder(&I);
672
673 // First try to replace the alloca with a vector
674 Type *AllocaTy = I.getAllocatedType();
675
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000676 DEBUG(dbgs() << "Trying to promote " << I << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000677
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000678 if (tryPromoteAllocaToVector(&I, AS)) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000679 DEBUG(dbgs() << " alloca is not a candidate for vectorization.\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000680 return;
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000681 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000682
Tom Stellard79a1fd72016-04-14 16:27:07 +0000683 const Function &ContainingFunction = *I.getParent()->getParent();
684
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000685 // Don't promote the alloca to LDS for shader calling conventions as the work
686 // item ID intrinsics are not supported for these calling conventions.
687 // Furthermore not all LDS is available for some of the stages.
688 if (AMDGPU::isShader(ContainingFunction.getCallingConv()))
689 return;
690
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000691 const AMDGPUSubtarget &ST =
692 TM->getSubtarget<AMDGPUSubtarget>(ContainingFunction);
Tom Stellard79a1fd72016-04-14 16:27:07 +0000693 // FIXME: We should also try to get this value from the reqd_work_group_size
694 // function attribute if it is available.
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000695 unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
Tom Stellard79a1fd72016-04-14 16:27:07 +0000696
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000697 const DataLayout &DL = Mod->getDataLayout();
Tom Stellard880a80a2014-06-17 16:53:14 +0000698
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000699 unsigned Align = I.getAlignment();
700 if (Align == 0)
701 Align = DL.getABITypeAlignment(I.getAllocatedType());
702
703 // FIXME: This computed padding is likely wrong since it depends on inverse
704 // usage order.
705 //
706 // FIXME: It is also possible that if we're allowed to use all of the memory
707 // could could end up using more than the maximum due to alignment padding.
708
709 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
710 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
711 NewSize += AllocSize;
712
713 if (NewSize > LocalMemLimit) {
714 DEBUG(dbgs() << " " << AllocSize
715 << " bytes of local memory not available to promote\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000716 return;
717 }
718
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000719 CurrentLocalMemUsage = NewSize;
720
Tom Stellard5b2927f2014-10-31 20:52:04 +0000721 std::vector<Value*> WorkList;
722
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000723 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
Tom Stellard5b2927f2014-10-31 20:52:04 +0000724 DEBUG(dbgs() << " Do not know how to convert all uses\n");
725 return;
726 }
727
Tom Stellard880a80a2014-06-17 16:53:14 +0000728 DEBUG(dbgs() << "Promoting alloca to local memory\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000729
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000730 Function *F = I.getParent()->getParent();
731
Tom Stellard79a1fd72016-04-14 16:27:07 +0000732 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
Tom Stellard880a80a2014-06-17 16:53:14 +0000733 GlobalVariable *GV = new GlobalVariable(
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000734 *Mod, GVTy, false, GlobalValue::InternalLinkage,
735 UndefValue::get(GVTy),
736 Twine(F->getName()) + Twine('.') + I.getName(),
737 nullptr,
738 GlobalVariable::NotThreadLocal,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000739 AS.LOCAL_ADDRESS);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000740 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000741 GV->setAlignment(I.getAlignment());
Tom Stellard880a80a2014-06-17 16:53:14 +0000742
Matt Arsenaulte0132462016-01-30 05:19:45 +0000743 Value *TCntY, *TCntZ;
Tom Stellard880a80a2014-06-17 16:53:14 +0000744
Matt Arsenaulte0132462016-01-30 05:19:45 +0000745 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
746 Value *TIdX = getWorkitemID(Builder, 0);
747 Value *TIdY = getWorkitemID(Builder, 1);
748 Value *TIdZ = getWorkitemID(Builder, 2);
Tom Stellard880a80a2014-06-17 16:53:14 +0000749
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000750 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000751 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000752 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000753 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
754 TID = Builder.CreateAdd(TID, TIdZ);
755
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000756 Value *Indices[] = {
757 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
758 TID
759 };
Tom Stellard880a80a2014-06-17 16:53:14 +0000760
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000761 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
Tom Stellard880a80a2014-06-17 16:53:14 +0000762 I.mutateType(Offset->getType());
763 I.replaceAllUsesWith(Offset);
764 I.eraseFromParent();
765
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000766 for (Value *V : WorkList) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000767 CallInst *Call = dyn_cast<CallInst>(V);
768 if (!Call) {
Matt Arsenault891fccc2016-05-18 15:57:21 +0000769 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
770 Value *Src0 = CI->getOperand(0);
771 Type *EltTy = Src0->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000772 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000773
774 if (isa<ConstantPointerNull>(CI->getOperand(0)))
775 CI->setOperand(0, ConstantPointerNull::get(NewTy));
776
777 if (isa<ConstantPointerNull>(CI->getOperand(1)))
778 CI->setOperand(1, ConstantPointerNull::get(NewTy));
779
780 continue;
781 }
Matt Arsenault65f67e42014-09-15 15:41:44 +0000782
Matt Arsenault2402b952016-12-10 00:52:50 +0000783 // The operand's value should be corrected on its own and we don't want to
784 // touch the users.
Matt Arsenault65f67e42014-09-15 15:41:44 +0000785 if (isa<AddrSpaceCastInst>(V))
786 continue;
787
Matt Arsenault891fccc2016-05-18 15:57:21 +0000788 Type *EltTy = V->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000789 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000790
Matt Arsenault65f67e42014-09-15 15:41:44 +0000791 // FIXME: It doesn't really make sense to try to do this for all
792 // instructions.
Tom Stellard880a80a2014-06-17 16:53:14 +0000793 V->mutateType(NewTy);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000794
795 // Adjust the types of any constant operands.
796 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
797 if (isa<ConstantPointerNull>(SI->getOperand(1)))
798 SI->setOperand(1, ConstantPointerNull::get(NewTy));
799
800 if (isa<ConstantPointerNull>(SI->getOperand(2)))
801 SI->setOperand(2, ConstantPointerNull::get(NewTy));
802 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
803 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
804 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
805 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
806 }
807 }
808
Tom Stellard880a80a2014-06-17 16:53:14 +0000809 continue;
810 }
811
Matt Arsenault2e08e182016-07-18 18:34:48 +0000812 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
Tom Stellard880a80a2014-06-17 16:53:14 +0000813 Builder.SetInsertPoint(Intr);
814 switch (Intr->getIntrinsicID()) {
815 case Intrinsic::lifetime_start:
816 case Intrinsic::lifetime_end:
817 // These intrinsics are for address space 0 only
818 Intr->eraseFromParent();
819 continue;
820 case Intrinsic::memcpy: {
821 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
822 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000823 MemCpy->getLength(), MemCpy->getAlignment(),
824 MemCpy->isVolatile());
Tom Stellard880a80a2014-06-17 16:53:14 +0000825 Intr->eraseFromParent();
826 continue;
827 }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000828 case Intrinsic::memmove: {
829 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
830 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getRawSource(),
831 MemMove->getLength(), MemMove->getAlignment(),
832 MemMove->isVolatile());
833 Intr->eraseFromParent();
834 continue;
835 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000836 case Intrinsic::memset: {
837 MemSetInst *MemSet = cast<MemSetInst>(Intr);
838 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000839 MemSet->getLength(), MemSet->getAlignment(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000840 MemSet->isVolatile());
841 Intr->eraseFromParent();
842 continue;
843 }
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000844 case Intrinsic::invariant_start:
845 case Intrinsic::invariant_end:
846 case Intrinsic::invariant_group_barrier:
847 Intr->eraseFromParent();
848 // FIXME: I think the invariant marker should still theoretically apply,
849 // but the intrinsics need to be changed to accept pointers with any
850 // address space.
851 continue;
Matt Arsenault7e747f12016-02-02 20:28:10 +0000852 case Intrinsic::objectsize: {
853 Value *Src = Intr->getOperand(0);
854 Type *SrcTy = Src->getType()->getPointerElementType();
855 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
856 Intrinsic::objectsize,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000857 { Intr->getType(), PointerType::get(SrcTy, AS.LOCAL_ADDRESS) }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000858 );
859
George Burgess IV56c7e882017-03-21 20:08:59 +0000860 CallInst *NewCall = Builder.CreateCall(
861 ObjectSize, {Src, Intr->getOperand(1), Intr->getOperand(2)});
Matt Arsenault7e747f12016-02-02 20:28:10 +0000862 Intr->replaceAllUsesWith(NewCall);
863 Intr->eraseFromParent();
864 continue;
865 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000866 default:
Matthias Braun8c209aa2017-01-28 02:02:38 +0000867 Intr->print(errs());
Tom Stellard880a80a2014-06-17 16:53:14 +0000868 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
869 }
870 }
871}
872
Matt Arsenaulte0132462016-01-30 05:19:45 +0000873FunctionPass *llvm::createAMDGPUPromoteAlloca(const TargetMachine *TM) {
874 return new AMDGPUPromoteAlloca(TM);
Tom Stellard880a80a2014-06-17 16:53:14 +0000875}