blob: 7231cf92d865e65debe74d264053271c515cef20 [file] [log] [blame]
Justin Holewinski01f89f02013-05-20 12:13:32 +00001//===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
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// Convert generic global variables into either .global or .const access based
11// on the variable's "constant" qualifier.
12//
13//===----------------------------------------------------------------------===//
14
15#include "NVPTX.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000016#include "MCTargetDesc/NVPTXBaseInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000017#include "NVPTXUtilities.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/CodeGen/MachineFunctionAnalysis.h"
19#include "llvm/CodeGen/ValueTypes.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/IR/IRBuilder.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000023#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Intrinsics.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000025#include "llvm/IR/LegacyPassManager.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000028#include "llvm/IR/ValueMap.h"
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +000029#include "llvm/Transforms/Utils/ValueMapper.h"
Justin Holewinski01f89f02013-05-20 12:13:32 +000030
31using namespace llvm;
32
33namespace llvm {
34void initializeGenericToNVVMPass(PassRegistry &);
35}
36
37namespace {
38class GenericToNVVM : public ModulePass {
39public:
40 static char ID;
41
42 GenericToNVVM() : ModulePass(ID) {}
43
Craig Topper2865c982014-04-29 07:57:44 +000044 bool runOnModule(Module &M) override;
Justin Holewinski01f89f02013-05-20 12:13:32 +000045
Craig Topper2865c982014-04-29 07:57:44 +000046 void getAnalysisUsage(AnalysisUsage &AU) const override {}
Justin Holewinski01f89f02013-05-20 12:13:32 +000047
48private:
49 Value *getOrInsertCVTA(Module *M, Function *F, GlobalVariable *GV,
50 IRBuilder<> &Builder);
51 Value *remapConstant(Module *M, Function *F, Constant *C,
52 IRBuilder<> &Builder);
53 Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
54 Constant *C,
55 IRBuilder<> &Builder);
56 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
57 IRBuilder<> &Builder);
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +000058 void remapNamedMDNode(ValueToValueMapTy &VM, NamedMDNode *N);
Justin Holewinski01f89f02013-05-20 12:13:32 +000059
60 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
61 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
62 GVMapTy GVMap;
63 ConstantToValueMapTy ConstantToValueMap;
64};
Gautam Chakrabarti35bd9522014-01-27 20:03:35 +000065} // end namespace
Justin Holewinski01f89f02013-05-20 12:13:32 +000066
67char GenericToNVVM::ID = 0;
68
69ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
70
71INITIALIZE_PASS(
72 GenericToNVVM, "generic-to-nvvm",
73 "Ensure that the global variables are in the global address space", false,
74 false)
75
76bool GenericToNVVM::runOnModule(Module &M) {
77 // Create a clone of each global variable that has the default address space.
78 // The clone is created with the global address space specifier, and the pair
79 // of original global variable and its clone is placed in the GVMap for later
80 // use.
81
82 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
83 I != E;) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +000084 GlobalVariable *GV = &*I++;
Justin Holewinski01f89f02013-05-20 12:13:32 +000085 if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
86 !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
Justin Holewinskie519a432014-06-27 18:36:02 +000087 !llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
Justin Holewinski01f89f02013-05-20 12:13:32 +000088 GlobalVariable *NewGV = new GlobalVariable(
89 M, GV->getType()->getElementType(), GV->isConstant(),
Craig Topper062a2ba2014-04-25 05:30:21 +000090 GV->getLinkage(),
91 GV->hasInitializer() ? GV->getInitializer() : nullptr,
Justin Holewinski01f89f02013-05-20 12:13:32 +000092 "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
93 NewGV->copyAttributesFrom(GV);
94 GVMap[GV] = NewGV;
95 }
96 }
97
98 // Return immediately, if every global variable has a specific address space
99 // specifier.
100 if (GVMap.empty()) {
101 return false;
102 }
103
104 // Walk through the instructions in function defitinions, and replace any use
105 // of original global variables in GVMap with a use of the corresponding
106 // copies in GVMap. If necessary, promote constants to instructions.
107 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
108 if (I->isDeclaration()) {
109 continue;
110 }
111 IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
112 for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
113 ++BBI) {
114 for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
115 ++II) {
116 for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
117 Value *Operand = II->getOperand(i);
118 if (isa<Constant>(Operand)) {
119 II->setOperand(
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000120 i, remapConstant(&M, &*I, cast<Constant>(Operand), Builder));
Justin Holewinski01f89f02013-05-20 12:13:32 +0000121 }
122 }
123 }
124 }
125 ConstantToValueMap.clear();
126 }
127
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +0000128 // Copy GVMap over to a standard value map.
129 ValueToValueMapTy VM;
130 for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
131 VM[I->first] = I->second;
132
Justin Holewinski01f89f02013-05-20 12:13:32 +0000133 // Walk through the metadata section and update the debug information
134 // associated with the global variables in the default address space.
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000135 for (NamedMDNode &I : M.named_metadata()) {
136 remapNamedMDNode(VM, &I);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000137 }
138
139 // Walk through the global variable initializers, and replace any use of
140 // original global variables in GVMap with a use of the corresponding copies
141 // in GVMap. The copies need to be bitcast to the original global variable
142 // types, as we cannot use cvta in global variable initializers.
143 for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
144 GlobalVariable *GV = I->first;
145 GlobalVariable *NewGV = I->second;
Duncan P. N. Exon Smith7b859ff2014-08-19 00:20:02 +0000146
147 // Remove GV from the map so that it can be RAUWed. Note that
148 // DenseMap::erase() won't invalidate any iterators but this one.
149 auto Next = std::next(I);
150 GVMap.erase(I);
151 I = Next;
152
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000153 Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
Justin Holewinski01f89f02013-05-20 12:13:32 +0000154 // At this point, the remaining uses of GV should be found only in global
155 // variable initializers, as other uses have been already been removed
156 // while walking through the instructions in function definitions.
Duncan P. N. Exon Smith7b859ff2014-08-19 00:20:02 +0000157 GV->replaceAllUsesWith(BitCastNewGV);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000158 std::string Name = GV->getName();
Justin Holewinski01f89f02013-05-20 12:13:32 +0000159 GV->eraseFromParent();
160 NewGV->setName(Name);
161 }
Duncan P. N. Exon Smith7b859ff2014-08-19 00:20:02 +0000162 assert(GVMap.empty() && "Expected it to be empty by now");
Justin Holewinski01f89f02013-05-20 12:13:32 +0000163
164 return true;
165}
166
167Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
168 GlobalVariable *GV,
169 IRBuilder<> &Builder) {
170 PointerType *GVType = GV->getType();
Craig Topper062a2ba2014-04-25 05:30:21 +0000171 Value *CVTA = nullptr;
Justin Holewinski01f89f02013-05-20 12:13:32 +0000172
173 // See if the address space conversion requires the operand to be bitcast
174 // to i8 addrspace(n)* first.
175 EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
176 if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
177 // A bitcast to i8 addrspace(n)* on the operand is needed.
178 LLVMContext &Context = M->getContext();
179 unsigned int AddrSpace = GVType->getAddressSpace();
180 Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
181 CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
182 // Insert the address space conversion.
183 Type *ResultType =
184 PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
185 SmallVector<Type *, 2> ParamTypes;
186 ParamTypes.push_back(ResultType);
187 ParamTypes.push_back(DestTy);
188 Function *CVTAFunction = Intrinsic::getDeclaration(
189 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
190 CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
191 // Another bitcast from i8 * to <the element type of GVType> * is
192 // required.
193 DestTy =
194 PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
195 CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
196 } else {
197 // A simple CVTA is enough.
198 SmallVector<Type *, 2> ParamTypes;
199 ParamTypes.push_back(PointerType::get(GVType->getElementType(),
200 llvm::ADDRESS_SPACE_GENERIC));
201 ParamTypes.push_back(GVType);
202 Function *CVTAFunction = Intrinsic::getDeclaration(
203 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
204 CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
205 }
206
207 return CVTA;
208}
209
210Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
211 IRBuilder<> &Builder) {
212 // If the constant C has been converted already in the given function F, just
213 // return the converted value.
214 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
215 if (CTII != ConstantToValueMap.end()) {
216 return CTII->second;
217 }
218
219 Value *NewValue = C;
220 if (isa<GlobalVariable>(C)) {
221 // If the constant C is a global variable and is found in GVMap, generate a
222 // set set of instructions that convert the clone of C with the global
223 // address space specifier to a generic pointer.
224 // The constant C cannot be used here, as it will be erased from the
225 // module eventually. And the clone of C with the global address space
226 // specifier cannot be used here either, as it will affect the types of
227 // other instructions in the function. Hence, this address space conversion
228 // is required.
229 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
230 if (I != GVMap.end()) {
231 NewValue = getOrInsertCVTA(M, F, I->second, Builder);
232 }
233 } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
234 isa<ConstantStruct>(C)) {
235 // If any element in the constant vector or aggregate C is or uses a global
236 // variable in GVMap, the constant C needs to be reconstructed, using a set
237 // of instructions.
238 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
239 } else if (isa<ConstantExpr>(C)) {
240 // If any operand in the constant expression C is or uses a global variable
241 // in GVMap, the constant expression C needs to be reconstructed, using a
242 // set of instructions.
243 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
244 }
245
246 ConstantToValueMap[C] = NewValue;
247 return NewValue;
248}
249
250Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
251 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
252 bool OperandChanged = false;
253 SmallVector<Value *, 4> NewOperands;
254 unsigned NumOperands = C->getNumOperands();
255
256 // Check if any element is or uses a global variable in GVMap, and thus
257 // converted to another value.
258 for (unsigned i = 0; i < NumOperands; ++i) {
259 Value *Operand = C->getOperand(i);
260 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
261 OperandChanged |= Operand != NewOperand;
262 NewOperands.push_back(NewOperand);
263 }
264
265 // If none of the elements has been modified, return C as it is.
266 if (!OperandChanged) {
267 return C;
268 }
269
270 // If any of the elements has been modified, construct the equivalent
271 // vector or aggregate value with a set instructions and the converted
272 // elements.
273 Value *NewValue = UndefValue::get(C->getType());
274 if (isa<ConstantVector>(C)) {
275 for (unsigned i = 0; i < NumOperands; ++i) {
276 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
277 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
278 }
279 } else {
280 for (unsigned i = 0; i < NumOperands; ++i) {
281 NewValue =
282 Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
283 }
284 }
285
286 return NewValue;
287}
288
289Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
290 IRBuilder<> &Builder) {
291 bool OperandChanged = false;
292 SmallVector<Value *, 4> NewOperands;
293 unsigned NumOperands = C->getNumOperands();
294
295 // Check if any operand is or uses a global variable in GVMap, and thus
296 // converted to another value.
297 for (unsigned i = 0; i < NumOperands; ++i) {
298 Value *Operand = C->getOperand(i);
299 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
300 OperandChanged |= Operand != NewOperand;
301 NewOperands.push_back(NewOperand);
302 }
303
304 // If none of the operands has been modified, return C as it is.
305 if (!OperandChanged) {
306 return C;
307 }
308
309 // If any of the operands has been modified, construct the instruction with
310 // the converted operands.
311 unsigned Opcode = C->getOpcode();
312 switch (Opcode) {
313 case Instruction::ICmp:
314 // CompareConstantExpr (icmp)
315 return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
316 NewOperands[0], NewOperands[1]);
317 case Instruction::FCmp:
318 // CompareConstantExpr (fcmp)
Benjamin Kramer8ceb3232015-10-25 22:28:27 +0000319 llvm_unreachable("Address space conversion should have no effect "
320 "on float point CompareConstantExpr (fcmp)!");
Justin Holewinski01f89f02013-05-20 12:13:32 +0000321 return C;
322 case Instruction::ExtractElement:
323 // ExtractElementConstantExpr
324 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
325 case Instruction::InsertElement:
326 // InsertElementConstantExpr
327 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
328 NewOperands[2]);
329 case Instruction::ShuffleVector:
330 // ShuffleVector
331 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
332 NewOperands[2]);
333 case Instruction::ExtractValue:
334 // ExtractValueConstantExpr
335 return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
336 case Instruction::InsertValue:
337 // InsertValueConstantExpr
338 return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
339 C->getIndices());
340 case Instruction::GetElementPtr:
341 // GetElementPtrConstantExpr
342 return cast<GEPOperator>(C)->isInBounds()
343 ? Builder.CreateGEP(
David Blaikie156d46e2015-03-24 23:34:31 +0000344 cast<GEPOperator>(C)->getSourceElementType(),
Justin Holewinski01f89f02013-05-20 12:13:32 +0000345 NewOperands[0],
346 makeArrayRef(&NewOperands[1], NumOperands - 1))
347 : Builder.CreateInBoundsGEP(
David Blaikieaa41cd52015-04-03 21:33:42 +0000348 cast<GEPOperator>(C)->getSourceElementType(),
Justin Holewinski01f89f02013-05-20 12:13:32 +0000349 NewOperands[0],
350 makeArrayRef(&NewOperands[1], NumOperands - 1));
351 case Instruction::Select:
352 // SelectConstantExpr
353 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
354 default:
355 // BinaryConstantExpr
356 if (Instruction::isBinaryOp(Opcode)) {
357 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
358 NewOperands[0], NewOperands[1]);
359 }
360 // UnaryConstantExpr
361 if (Instruction::isCast(Opcode)) {
362 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
363 NewOperands[0], C->getType());
364 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +0000365 llvm_unreachable("GenericToNVVM encountered an unsupported ConstantExpr");
Justin Holewinski01f89f02013-05-20 12:13:32 +0000366 return C;
367 }
368}
369
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +0000370void GenericToNVVM::remapNamedMDNode(ValueToValueMapTy &VM, NamedMDNode *N) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000371
372 bool OperandChanged = false;
373 SmallVector<MDNode *, 16> NewOperands;
374 unsigned NumOperands = N->getNumOperands();
375
376 // Check if any operand is or contains a global variable in GVMap, and thus
377 // converted to another value.
378 for (unsigned i = 0; i < NumOperands; ++i) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000379 MDNode *Operand = N->getOperand(i);
Duncan P. N. Exon Smith9f6bddd2015-01-14 05:14:30 +0000380 MDNode *NewOperand = MapMetadata(Operand, VM);
Justin Holewinski01f89f02013-05-20 12:13:32 +0000381 OperandChanged |= Operand != NewOperand;
382 NewOperands.push_back(NewOperand);
383 }
384
385 // If none of the operands has been modified, return immediately.
386 if (!OperandChanged) {
387 return;
388 }
389
390 // Replace the old operands with the new operands.
391 N->dropAllReferences();
Craig Topperaf0dea12013-07-04 01:31:24 +0000392 for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
Justin Holewinski01f89f02013-05-20 12:13:32 +0000393 E = NewOperands.end();
394 I != E; ++I) {
395 N->addOperand(*I);
396 }
397}