blob: 36dcc699d4eab40e39cc5f974fc9fb5a908a45f3 [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"
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
Matt Arsenaulte0132462016-01-30 05:19:45 +000067// FIXME: This can create globals so should be a module pass.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +000068class AMDGPUPromoteAlloca : public FunctionPass {
Matt Arsenaulte0132462016-01-30 05:19:45 +000069private:
70 const TargetMachine *TM;
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000071 Module *Mod = nullptr;
72 const DataLayout *DL = nullptr;
Yaxun Liu1a14bfa2017-03-27 14:04:01 +000073 AMDGPUAS AS;
Matt Arsenaulte0132462016-01-30 05:19:45 +000074
75 // FIXME: This should be per-kernel.
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000076 uint32_t LocalMemLimit = 0;
77 uint32_t CurrentLocalMemUsage = 0;
Tom Stellard880a80a2014-06-17 16:53:14 +000078
Eugene Zelenko734bb7b2017-01-20 17:52:16 +000079 bool IsAMDGCN = false;
80 bool IsAMDHSA = false;
Matt Arsenaulte0132462016-01-30 05:19:45 +000081
82 std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
83 Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
84
Matt Arsenaulta61cb482016-05-12 01:58:58 +000085 /// 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
Tom Stellard880a80a2014-06-17 16:53:14 +000099public:
Matt Arsenaulte0132462016-01-30 05:19:45 +0000100 static char ID;
101
102 AMDGPUPromoteAlloca(const TargetMachine *TM_ = nullptr) :
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000103 FunctionPass(ID), TM(TM_) {}
Matt Arsenaulte0132462016-01-30 05:19:45 +0000104
Benjamin Kramer8c90fd72014-09-03 11:41:21 +0000105 bool doInitialization(Module &M) override;
106 bool runOnFunction(Function &F) override;
Matt Arsenaulte0132462016-01-30 05:19:45 +0000107
Mehdi Amini117296c2016-10-01 02:56:57 +0000108 StringRef getPassName() const override { return "AMDGPU Promote Alloca"; }
Matt Arsenaulte0132462016-01-30 05:19:45 +0000109
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000110 void handleAlloca(AllocaInst &I);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000111
112 void getAnalysisUsage(AnalysisUsage &AU) const override {
113 AU.setPreservesCFG();
114 FunctionPass::getAnalysisUsage(AU);
115 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000116};
117
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000118} // end anonymous namespace
Tom Stellard880a80a2014-06-17 16:53:14 +0000119
120char AMDGPUPromoteAlloca::ID = 0;
121
Matt Arsenaulte0132462016-01-30 05:19:45 +0000122INITIALIZE_TM_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
123 "AMDGPU promote alloca to vector or LDS", false, false)
124
125char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
126
Tom Stellard880a80a2014-06-17 16:53:14 +0000127bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
Matt Arsenaulte0132462016-01-30 05:19:45 +0000128 if (!TM)
129 return false;
130
Tom Stellard880a80a2014-06-17 16:53:14 +0000131 Mod = &M;
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000132 DL = &Mod->getDataLayout();
Matt Arsenaulte0132462016-01-30 05:19:45 +0000133
Matt Arsenaulte0132462016-01-30 05:19:45 +0000134 const Triple &TT = TM->getTargetTriple();
135
136 IsAMDGCN = TT.getArch() == Triple::amdgcn;
137 IsAMDHSA = TT.getOS() == Triple::AMDHSA;
138
Tom Stellard880a80a2014-06-17 16:53:14 +0000139 return false;
140}
141
142bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
Andrew Kaylor7de74af2016-04-25 22:23:44 +0000143 if (!TM || skipFunction(F))
Matt Arsenaulte0132462016-01-30 05:19:45 +0000144 return false;
145
Matt Arsenault03d85842016-06-27 20:32:13 +0000146 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
147 if (!ST.isPromoteAllocaEnabled())
148 return false;
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000149 AS = AMDGPU::getAMDGPUAS(*F.getParent());
Matt Arsenault03d85842016-06-27 20:32:13 +0000150
Craig Toppere3dcce92015-08-01 22:20:21 +0000151 FunctionType *FTy = F.getFunctionType();
Tom Stellard880a80a2014-06-17 16:53:14 +0000152
153 // If the function has any arguments in the local address space, then it's
154 // possible these arguments require the entire local memory space, so
155 // we cannot use local memory in the pass.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000156 for (Type *ParamTy : FTy->params()) {
157 PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000158 if (PtrTy && PtrTy->getAddressSpace() == AS.LOCAL_ADDRESS) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000159 LocalMemLimit = 0;
160 DEBUG(dbgs() << "Function has local memory argument. Promoting to "
Tom Stellard880a80a2014-06-17 16:53:14 +0000161 "local memory disabled.\n");
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000162 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000163 }
164 }
165
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000166 LocalMemLimit = ST.getLocalMemorySize();
167 if (LocalMemLimit == 0)
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000168 return false;
169
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000170 const DataLayout &DL = Mod->getDataLayout();
171
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000172 // Check how much local memory is being used by global objects
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000173 CurrentLocalMemUsage = 0;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000174 for (GlobalVariable &GV : Mod->globals()) {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000175 if (GV.getType()->getAddressSpace() != AS.LOCAL_ADDRESS)
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000176 continue;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000177
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000178 for (const User *U : GV.users()) {
179 const Instruction *Use = dyn_cast<Instruction>(U);
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000180 if (!Use)
Tom Stellard880a80a2014-06-17 16:53:14 +0000181 continue;
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000182
Matt Arsenault0547b012016-04-27 21:05:08 +0000183 if (Use->getParent()->getParent() == &F) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000184 unsigned Align = GV.getAlignment();
185 if (Align == 0)
186 Align = DL.getABITypeAlignment(GV.getValueType());
187
188 // FIXME: Try to account for padding here. The padding is currently
189 // determined from the inverse order of uses in the function. I'm not
190 // sure if the use list order is in any way connected to this, so the
191 // total reported size is likely incorrect.
192 uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
193 CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
194 CurrentLocalMemUsage += AllocSize;
Matt Arsenault0547b012016-04-27 21:05:08 +0000195 break;
196 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000197 }
198 }
199
Stanislav Mekhanoshin2b913b12017-02-01 22:59:50 +0000200 unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage,
201 F);
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000202
203 // Restrict local memory usage so that we don't drastically reduce occupancy,
204 // unless it is already significantly reduced.
205
206 // TODO: Have some sort of hint or other heuristics to guess occupancy based
207 // on other factors..
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000208 unsigned OccupancyHint = ST.getWavesPerEU(F).second;
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000209 if (OccupancyHint == 0)
210 OccupancyHint = 7;
211
212 // Clamp to max value.
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000213 OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerEU());
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000214
215 // Check the hint but ignore it if it's obviously wrong from the existing LDS
216 // usage.
217 MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
218
219
220 // Round up to the next tier of usage.
221 unsigned MaxSizeWithWaveCount
Stanislav Mekhanoshin2b913b12017-02-01 22:59:50 +0000222 = ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy, F);
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000223
224 // Program is possibly broken by using more local mem than available.
225 if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
226 return false;
227
228 LocalMemLimit = MaxSizeWithWaveCount;
229
230 DEBUG(
231 dbgs() << F.getName() << " uses " << CurrentLocalMemUsage << " bytes of LDS\n"
232 << " Rounding size to " << MaxSizeWithWaveCount
233 << " with a maximum occupancy of " << MaxOccupancy << '\n'
234 << " and " << (LocalMemLimit - CurrentLocalMemUsage)
235 << " available for promotion\n"
236 );
Tom Stellard880a80a2014-06-17 16:53:14 +0000237
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000238 BasicBlock &EntryBB = *F.begin();
239 for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
240 AllocaInst *AI = dyn_cast<AllocaInst>(I);
241
242 ++I;
243 if (AI)
244 handleAlloca(*AI);
245 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000246
Matt Arsenaulte5737f72016-02-02 19:18:57 +0000247 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000248}
249
Matt Arsenaulte0132462016-01-30 05:19:45 +0000250std::pair<Value *, Value *>
251AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000252 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(
253 *Builder.GetInsertBlock()->getParent());
254
Matt Arsenaulte0132462016-01-30 05:19:45 +0000255 if (!IsAMDHSA) {
256 Function *LocalSizeYFn
257 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
258 Function *LocalSizeZFn
259 = Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
260
261 CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
262 CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
263
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000264 ST.makeLIDRangeMetadata(LocalSizeY);
265 ST.makeLIDRangeMetadata(LocalSizeZ);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000266
267 return std::make_pair(LocalSizeY, LocalSizeZ);
268 }
269
270 // We must read the size out of the dispatch pointer.
271 assert(IsAMDGCN);
272
273 // We are indexing into this struct, and want to extract the workgroup_size_*
274 // fields.
275 //
276 // typedef struct hsa_kernel_dispatch_packet_s {
277 // uint16_t header;
278 // uint16_t setup;
279 // uint16_t workgroup_size_x ;
280 // uint16_t workgroup_size_y;
281 // uint16_t workgroup_size_z;
282 // uint16_t reserved0;
283 // uint32_t grid_size_x ;
284 // uint32_t grid_size_y ;
285 // uint32_t grid_size_z;
286 //
287 // uint32_t private_segment_size;
288 // uint32_t group_segment_size;
289 // uint64_t kernel_object;
290 //
291 // #ifdef HSA_LARGE_MODEL
292 // void *kernarg_address;
293 // #elif defined HSA_LITTLE_ENDIAN
294 // void *kernarg_address;
295 // uint32_t reserved1;
296 // #else
297 // uint32_t reserved1;
298 // void *kernarg_address;
299 // #endif
300 // uint64_t reserved2;
301 // hsa_signal_t completion_signal; // uint64_t wrapper
302 // } hsa_kernel_dispatch_packet_t
303 //
304 Function *DispatchPtrFn
305 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
306
307 CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
Reid Klecknerb5180542017-03-21 16:57:19 +0000308 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
309 DispatchPtr->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000310
311 // Size of the dispatch packet struct.
Reid Klecknerb5180542017-03-21 16:57:19 +0000312 DispatchPtr->addDereferenceableAttr(AttributeList::ReturnIndex, 64);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000313
314 Type *I32Ty = Type::getInt32Ty(Mod->getContext());
315 Value *CastDispatchPtr = Builder.CreateBitCast(
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000316 DispatchPtr, PointerType::get(I32Ty, AS.CONSTANT_ADDRESS));
Matt Arsenaulte0132462016-01-30 05:19:45 +0000317
318 // We could do a single 64-bit load here, but it's likely that the basic
319 // 32-bit and extract sequence is already present, and it is probably easier
320 // to CSE this. The loads should be mergable later anyway.
321 Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
322 LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
323
324 Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
325 LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
326
Eugene Zelenko734bb7b2017-01-20 17:52:16 +0000327 MDNode *MD = MDNode::get(Mod->getContext(), None);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000328 LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
329 LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000330 ST.makeLIDRangeMetadata(LoadZU);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000331
332 // Extract y component. Upper half of LoadZU should be zero already.
333 Value *Y = Builder.CreateLShr(LoadXY, 16);
334
335 return std::make_pair(Y, LoadZU);
336}
337
338Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000339 const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(
340 *Builder.GetInsertBlock()->getParent());
Matt Arsenaulte0132462016-01-30 05:19:45 +0000341 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);
Stanislav Mekhanoshinc90347d2017-04-12 20:48:56 +0000363 ST.makeLIDRangeMetadata(CI);
Matt Arsenaulte0132462016-01-30 05:19:45 +0000364
365 return CI;
366}
367
Craig Toppere3dcce92015-08-01 22:20:21 +0000368static VectorType *arrayTypeToVecType(Type *ArrayTy) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000369 return VectorType::get(ArrayTy->getArrayElementType(),
370 ArrayTy->getArrayNumElements());
371}
372
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000373static Value *
374calculateVectorIndex(Value *Ptr,
375 const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000376 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
377
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000378 auto I = GEPIdx.find(GEP);
379 return I == GEPIdx.end() ? nullptr : I->second;
Tom Stellard880a80a2014-06-17 16:53:14 +0000380}
381
382static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
383 // FIXME we only support simple cases
384 if (GEP->getNumOperands() != 3)
Matt Arsenaultefb24542016-07-18 18:34:53 +0000385 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000386
387 ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
388 if (!I0 || !I0->isZero())
Matt Arsenaultefb24542016-07-18 18:34:53 +0000389 return nullptr;
Tom Stellard880a80a2014-06-17 16:53:14 +0000390
391 return GEP->getOperand(2);
392}
393
Matt Arsenault642d2e72014-06-27 16:52:49 +0000394// Not an instruction handled below to turn into a vector.
395//
396// TODO: Check isTriviallyVectorizable for calls and handle other
397// instructions.
Matt Arsenault7227cc12015-07-28 18:47:00 +0000398static bool canVectorizeInst(Instruction *Inst, User *User) {
Matt Arsenault642d2e72014-06-27 16:52:49 +0000399 switch (Inst->getOpcode()) {
400 case Instruction::Load:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000401 case Instruction::BitCast:
402 case Instruction::AddrSpaceCast:
403 return true;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000404 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 }
Matt Arsenault642d2e72014-06-27 16:52:49 +0000409 default:
410 return false;
411 }
412}
413
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000414static bool tryPromoteAllocaToVector(AllocaInst *Alloca, AMDGPUAS AS) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000415 ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
Tom Stellard880a80a2014-06-17 16:53:14 +0000416
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000417 DEBUG(dbgs() << "Alloca candidate for vectorization\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000418
419 // FIXME: There is no reason why we can't support larger arrays, we
420 // are just being conservative for now.
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000421 if (!AllocaTy ||
422 AllocaTy->getElementType()->isVectorTy() ||
Matt Arsenaultefb24542016-07-18 18:34:53 +0000423 AllocaTy->getNumElements() > 4 ||
424 AllocaTy->getNumElements() < 2) {
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000425 DEBUG(dbgs() << " Cannot convert type to vector\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000426 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) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000434 if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000435 return false;
436
Tom Stellard880a80a2014-06-17 16:53:14 +0000437 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) {
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000446 DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000447 return false;
448 }
449
450 GEPVectorIdx[GEP] = Index;
451 for (User *GEPUser : AllocaUser->users()) {
Matt Arsenault7227cc12015-07-28 18:47:00 +0000452 if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
Matt Arsenault642d2e72014-06-27 16:52:49 +0000453 return false;
454
Tom Stellard880a80a2014-06-17 16:53:14 +0000455 WorkList.push_back(GEPUser);
456 }
457 }
458
459 VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
460
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000461 DEBUG(dbgs() << " Converting alloca to vector "
462 << *AllocaTy << " -> " << *VectorTy << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000463
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000464 for (Value *V : WorkList) {
465 Instruction *Inst = cast<Instruction>(V);
Tom Stellard880a80a2014-06-17 16:53:14 +0000466 IRBuilder<> Builder(Inst);
467 switch (Inst->getOpcode()) {
468 case Instruction::Load: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000469 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Tom Stellard880a80a2014-06-17 16:53:14 +0000470 Value *Ptr = Inst->getOperand(0);
471 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000472
473 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000474 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: {
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000481 Type *VecPtrTy = VectorTy->getPointerTo(AS.PRIVATE_ADDRESS);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000482
Tom Stellard880a80a2014-06-17 16:53:14 +0000483 Value *Ptr = Inst->getOperand(1);
484 Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Matt Arsenaultefb24542016-07-18 18:34:53 +0000485 Value *BitCast = Builder.CreateBitCast(Alloca, VecPtrTy);
Tom Stellard880a80a2014-06-17 16:53:14 +0000486 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:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000495 case Instruction::AddrSpaceCast:
Tom Stellard880a80a2014-06-17 16:53:14 +0000496 break;
497
498 default:
Matt Arsenault642d2e72014-06-27 16:52:49 +0000499 llvm_unreachable("Inconsistency in instructions promotable to vector");
Tom Stellard880a80a2014-06-17 16:53:14 +0000500 }
501 }
502 return true;
503}
504
Matt Arsenaultad134842016-02-02 19:18:53 +0000505static bool isCallPromotable(CallInst *CI) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000506 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
507 if (!II)
508 return false;
509
510 switch (II->getIntrinsicID()) {
511 case Intrinsic::memcpy:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000512 case Intrinsic::memmove:
Matt Arsenaultad134842016-02-02 19:18:53 +0000513 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:
Matt Arsenault7e747f12016-02-02 20:28:10 +0000519 case Intrinsic::objectsize:
Matt Arsenaultad134842016-02-02 19:18:53 +0000520 return true;
521 default:
522 return false;
523 }
524}
525
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000526bool 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
Matt Arsenault891fccc2016-05-18 15:57:21 +0000536 if (isa<ConstantPointerNull>(OtherOp))
537 return true;
538
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000539 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
557bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
558 Value *BaseAlloca,
559 Value *Val,
560 std::vector<Value*> &WorkList) const {
561
Tom Stellard880a80a2014-06-17 16:53:14 +0000562 for (User *User : Val->users()) {
David Majnemer0d955d02016-08-11 22:21:41 +0000563 if (is_contained(WorkList, User))
Tom Stellard880a80a2014-06-17 16:53:14 +0000564 continue;
Matt Arsenaultad134842016-02-02 19:18:53 +0000565
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000566 if (CallInst *CI = dyn_cast<CallInst>(User)) {
Matt Arsenaultad134842016-02-02 19:18:53 +0000567 if (!isCallPromotable(CI))
Matt Arsenaultfdcd39a2015-07-28 18:29:14 +0000568 return false;
569
Tom Stellard880a80a2014-06-17 16:53:14 +0000570 WorkList.push_back(User);
571 continue;
572 }
Tom Stellard5b2927f2014-10-31 20:52:04 +0000573
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000574 Instruction *UseInst = cast<Instruction>(User);
575 if (UseInst->getOpcode() == Instruction::PtrToInt)
Tom Stellard5b2927f2014-10-31 20:52:04 +0000576 return false;
577
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000578 if (LoadInst *LI = dyn_cast<LoadInst>(UseInst)) {
Matt Arsenaultc438ef52016-05-18 23:20:24 +0000579 if (LI->isVolatile())
580 return false;
581
582 continue;
583 }
584
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000585 if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000586 if (SI->isVolatile())
587 return false;
588
Matt Arsenault7227cc12015-07-28 18:47:00 +0000589 // Reject if the stored value is not the pointer operand.
590 if (SI->getPointerOperand() != Val)
591 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000592 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000593 if (RMW->isVolatile())
594 return false;
Matt Arsenault210b7cf2016-07-18 19:00:07 +0000595 } else if (AtomicCmpXchgInst *CAS = dyn_cast<AtomicCmpXchgInst>(UseInst)) {
Matt Arsenault0a30e452016-03-23 23:17:29 +0000596 if (CAS->isVolatile())
597 return false;
Matt Arsenault7227cc12015-07-28 18:47:00 +0000598 }
599
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000600 // 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;
Matt Arsenault891fccc2016-05-18 15:57:21 +0000605
606 // May need to rewrite constant operands.
607 WorkList.push_back(ICmp);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000608 }
609
Matt Arsenault2402b952016-12-10 00:52:50 +0000610 if (UseInst->getOpcode() == Instruction::AddrSpaceCast) {
Changpeng Fangc85abbd2017-01-24 19:06:28 +0000611 // Give up if the pointer may be captured.
612 if (PointerMayBeCaptured(UseInst, true, true))
613 return false;
Matt Arsenault2402b952016-12-10 00:52:50 +0000614 // Don't collect the users of this.
615 WorkList.push_back(User);
616 continue;
617 }
618
Tom Stellard880a80a2014-06-17 16:53:14 +0000619 if (!User->getType()->isPointerTy())
620 continue;
Tom Stellard5b2927f2014-10-31 20:52:04 +0000621
Matt Arsenaultde420812016-02-02 21:16:12 +0000622 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
623 // Be conservative if an address could be computed outside the bounds of
624 // the alloca.
625 if (!GEP->isInBounds())
626 return false;
627 }
628
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000629 // Only promote a select if we know that the other select operand is from
630 // another pointer that will also be promoted.
631 if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
632 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
633 return false;
634 }
635
636 // Repeat for phis.
637 if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
638 // TODO: Handle more complex cases. We should be able to replace loops
639 // over arrays.
640 switch (Phi->getNumIncomingValues()) {
641 case 1:
642 break;
643 case 2:
644 if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
645 return false;
646 break;
647 default:
648 return false;
649 }
650 }
651
Tom Stellard880a80a2014-06-17 16:53:14 +0000652 WorkList.push_back(User);
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000653 if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
Matt Arsenaultad134842016-02-02 19:18:53 +0000654 return false;
Tom Stellard880a80a2014-06-17 16:53:14 +0000655 }
Matt Arsenaultad134842016-02-02 19:18:53 +0000656
657 return true;
Tom Stellard880a80a2014-06-17 16:53:14 +0000658}
659
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000660// FIXME: Should try to pick the most likely to be profitable allocas first.
Matt Arsenaultbafc9dc2016-03-11 08:20:50 +0000661void AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I) {
Matt Arsenaultc5fce692016-04-28 18:38:48 +0000662 // Array allocations are probably not worth handling, since an allocation of
663 // the array type is the canonical form.
664 if (!I.isStaticAlloca() || I.isArrayAllocation())
Matt Arsenault19c54882015-08-26 18:37:13 +0000665 return;
666
Tom Stellard880a80a2014-06-17 16:53:14 +0000667 IRBuilder<> Builder(&I);
668
669 // First try to replace the alloca with a vector
670 Type *AllocaTy = I.getAllocatedType();
671
Matt Arsenault6f62cf82014-06-27 02:36:59 +0000672 DEBUG(dbgs() << "Trying to promote " << I << '\n');
Tom Stellard880a80a2014-06-17 16:53:14 +0000673
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000674 if (tryPromoteAllocaToVector(&I, AS)) {
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000675 DEBUG(dbgs() << " alloca is not a candidate for vectorization.\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000676 return;
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000677 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000678
Tom Stellard79a1fd72016-04-14 16:27:07 +0000679 const Function &ContainingFunction = *I.getParent()->getParent();
Matt Arsenault5c806182017-05-02 18:33:18 +0000680 CallingConv::ID CC = ContainingFunction.getCallingConv();
Tom Stellard79a1fd72016-04-14 16:27:07 +0000681
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000682 // Don't promote the alloca to LDS for shader calling conventions as the work
683 // item ID intrinsics are not supported for these calling conventions.
684 // Furthermore not all LDS is available for some of the stages.
Matt Arsenault5c806182017-05-02 18:33:18 +0000685 switch (CC) {
686 case CallingConv::AMDGPU_KERNEL:
687 case CallingConv::SPIR_KERNEL:
688 break;
689 default:
690 DEBUG(dbgs() << " promote alloca to LDS not supported with calling convention.\n");
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000691 return;
Matt Arsenault5c806182017-05-02 18:33:18 +0000692 }
Nicolai Haehnlebef1ceb2016-07-18 09:02:47 +0000693
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000694 const AMDGPUSubtarget &ST =
695 TM->getSubtarget<AMDGPUSubtarget>(ContainingFunction);
Konstantin Zhuravlyov1d650262016-09-06 20:22:28 +0000696 unsigned WorkGroupSize = ST.getFlatWorkGroupSizes(ContainingFunction).second;
Tom Stellard79a1fd72016-04-14 16:27:07 +0000697
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000698 const DataLayout &DL = Mod->getDataLayout();
Tom Stellard880a80a2014-06-17 16:53:14 +0000699
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000700 unsigned Align = I.getAlignment();
701 if (Align == 0)
702 Align = DL.getABITypeAlignment(I.getAllocatedType());
703
704 // FIXME: This computed padding is likely wrong since it depends on inverse
705 // usage order.
706 //
707 // FIXME: It is also possible that if we're allowed to use all of the memory
708 // could could end up using more than the maximum due to alignment padding.
709
710 uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
711 uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
712 NewSize += AllocSize;
713
714 if (NewSize > LocalMemLimit) {
715 DEBUG(dbgs() << " " << AllocSize
716 << " bytes of local memory not available to promote\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000717 return;
718 }
719
Matt Arsenault8a028bf2016-05-16 21:19:59 +0000720 CurrentLocalMemUsage = NewSize;
721
Tom Stellard5b2927f2014-10-31 20:52:04 +0000722 std::vector<Value*> WorkList;
723
Matt Arsenaulta61cb482016-05-12 01:58:58 +0000724 if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
Tom Stellard5b2927f2014-10-31 20:52:04 +0000725 DEBUG(dbgs() << " Do not know how to convert all uses\n");
726 return;
727 }
728
Tom Stellard880a80a2014-06-17 16:53:14 +0000729 DEBUG(dbgs() << "Promoting alloca to local memory\n");
Tom Stellard880a80a2014-06-17 16:53:14 +0000730
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000731 Function *F = I.getParent()->getParent();
732
Tom Stellard79a1fd72016-04-14 16:27:07 +0000733 Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
Tom Stellard880a80a2014-06-17 16:53:14 +0000734 GlobalVariable *GV = new GlobalVariable(
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000735 *Mod, GVTy, false, GlobalValue::InternalLinkage,
736 UndefValue::get(GVTy),
737 Twine(F->getName()) + Twine('.') + I.getName(),
738 nullptr,
739 GlobalVariable::NotThreadLocal,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000740 AS.LOCAL_ADDRESS);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000741 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Matt Arsenaultcf84e262016-02-05 19:47:23 +0000742 GV->setAlignment(I.getAlignment());
Tom Stellard880a80a2014-06-17 16:53:14 +0000743
Matt Arsenaulte0132462016-01-30 05:19:45 +0000744 Value *TCntY, *TCntZ;
Tom Stellard880a80a2014-06-17 16:53:14 +0000745
Matt Arsenaulte0132462016-01-30 05:19:45 +0000746 std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
747 Value *TIdX = getWorkitemID(Builder, 0);
748 Value *TIdY = getWorkitemID(Builder, 1);
749 Value *TIdZ = getWorkitemID(Builder, 2);
Tom Stellard880a80a2014-06-17 16:53:14 +0000750
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000751 Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000752 Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000753 Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Tom Stellard880a80a2014-06-17 16:53:14 +0000754 Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
755 TID = Builder.CreateAdd(TID, TIdZ);
756
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000757 Value *Indices[] = {
758 Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
759 TID
760 };
Tom Stellard880a80a2014-06-17 16:53:14 +0000761
Matt Arsenault853a1fc2016-02-02 19:18:48 +0000762 Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
Tom Stellard880a80a2014-06-17 16:53:14 +0000763 I.mutateType(Offset->getType());
764 I.replaceAllUsesWith(Offset);
765 I.eraseFromParent();
766
Matt Arsenaultfb8cdba2016-02-02 19:32:35 +0000767 for (Value *V : WorkList) {
Tom Stellard880a80a2014-06-17 16:53:14 +0000768 CallInst *Call = dyn_cast<CallInst>(V);
769 if (!Call) {
Matt Arsenault891fccc2016-05-18 15:57:21 +0000770 if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
771 Value *Src0 = CI->getOperand(0);
772 Type *EltTy = Src0->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000773 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000774
775 if (isa<ConstantPointerNull>(CI->getOperand(0)))
776 CI->setOperand(0, ConstantPointerNull::get(NewTy));
777
778 if (isa<ConstantPointerNull>(CI->getOperand(1)))
779 CI->setOperand(1, ConstantPointerNull::get(NewTy));
780
781 continue;
782 }
Matt Arsenault65f67e42014-09-15 15:41:44 +0000783
Matt Arsenault2402b952016-12-10 00:52:50 +0000784 // The operand's value should be corrected on its own and we don't want to
785 // touch the users.
Matt Arsenault65f67e42014-09-15 15:41:44 +0000786 if (isa<AddrSpaceCastInst>(V))
787 continue;
788
Matt Arsenault891fccc2016-05-18 15:57:21 +0000789 Type *EltTy = V->getType()->getPointerElementType();
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000790 PointerType *NewTy = PointerType::get(EltTy, AS.LOCAL_ADDRESS);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000791
Matt Arsenault65f67e42014-09-15 15:41:44 +0000792 // FIXME: It doesn't really make sense to try to do this for all
793 // instructions.
Tom Stellard880a80a2014-06-17 16:53:14 +0000794 V->mutateType(NewTy);
Matt Arsenault891fccc2016-05-18 15:57:21 +0000795
796 // Adjust the types of any constant operands.
797 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
798 if (isa<ConstantPointerNull>(SI->getOperand(1)))
799 SI->setOperand(1, ConstantPointerNull::get(NewTy));
800
801 if (isa<ConstantPointerNull>(SI->getOperand(2)))
802 SI->setOperand(2, ConstantPointerNull::get(NewTy));
803 } else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
804 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
805 if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
806 Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
807 }
808 }
809
Tom Stellard880a80a2014-06-17 16:53:14 +0000810 continue;
811 }
812
Matt Arsenault2e08e182016-07-18 18:34:48 +0000813 IntrinsicInst *Intr = cast<IntrinsicInst>(Call);
Tom Stellard880a80a2014-06-17 16:53:14 +0000814 Builder.SetInsertPoint(Intr);
815 switch (Intr->getIntrinsicID()) {
816 case Intrinsic::lifetime_start:
817 case Intrinsic::lifetime_end:
818 // These intrinsics are for address space 0 only
819 Intr->eraseFromParent();
820 continue;
821 case Intrinsic::memcpy: {
822 MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
823 Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000824 MemCpy->getLength(), MemCpy->getAlignment(),
825 MemCpy->isVolatile());
Tom Stellard880a80a2014-06-17 16:53:14 +0000826 Intr->eraseFromParent();
827 continue;
828 }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000829 case Intrinsic::memmove: {
830 MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
831 Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getRawSource(),
832 MemMove->getLength(), MemMove->getAlignment(),
833 MemMove->isVolatile());
834 Intr->eraseFromParent();
835 continue;
836 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000837 case Intrinsic::memset: {
838 MemSetInst *MemSet = cast<MemSetInst>(Intr);
839 Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000840 MemSet->getLength(), MemSet->getAlignment(),
Tom Stellard880a80a2014-06-17 16:53:14 +0000841 MemSet->isVolatile());
842 Intr->eraseFromParent();
843 continue;
844 }
Matt Arsenault0b783ef02016-01-22 19:47:54 +0000845 case Intrinsic::invariant_start:
846 case Intrinsic::invariant_end:
847 case Intrinsic::invariant_group_barrier:
848 Intr->eraseFromParent();
849 // FIXME: I think the invariant marker should still theoretically apply,
850 // but the intrinsics need to be changed to accept pointers with any
851 // address space.
852 continue;
Matt Arsenault7e747f12016-02-02 20:28:10 +0000853 case Intrinsic::objectsize: {
854 Value *Src = Intr->getOperand(0);
855 Type *SrcTy = Src->getType()->getPointerElementType();
856 Function *ObjectSize = Intrinsic::getDeclaration(Mod,
857 Intrinsic::objectsize,
Yaxun Liu1a14bfa2017-03-27 14:04:01 +0000858 { Intr->getType(), PointerType::get(SrcTy, AS.LOCAL_ADDRESS) }
Matt Arsenault7e747f12016-02-02 20:28:10 +0000859 );
860
George Burgess IV56c7e882017-03-21 20:08:59 +0000861 CallInst *NewCall = Builder.CreateCall(
862 ObjectSize, {Src, Intr->getOperand(1), Intr->getOperand(2)});
Matt Arsenault7e747f12016-02-02 20:28:10 +0000863 Intr->replaceAllUsesWith(NewCall);
864 Intr->eraseFromParent();
865 continue;
866 }
Tom Stellard880a80a2014-06-17 16:53:14 +0000867 default:
Matthias Braun8c209aa2017-01-28 02:02:38 +0000868 Intr->print(errs());
Tom Stellard880a80a2014-06-17 16:53:14 +0000869 llvm_unreachable("Don't know how to promote alloca intrinsic use.");
870 }
871 }
872}
873
Matt Arsenaulte0132462016-01-30 05:19:45 +0000874FunctionPass *llvm::createAMDGPUPromoteAlloca(const TargetMachine *TM) {
875 return new AMDGPUPromoteAlloca(TM);
Tom Stellard880a80a2014-06-17 16:53:14 +0000876}