1 //===-- GenericToNVVM.cpp - Convert generic module to NVVM module - C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Convert generic global variables into either .global or .const access based
11 // on the variable's "constant" qualifier.
13 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/NVPTXBaseInfo.h"
17 #include "NVPTXUtilities.h"
18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueMap.h"
28 #include "llvm/PassManager.h"
33 void initializeGenericToNVVMPass(PassRegistry &);
37 class GenericToNVVM : public ModulePass {
41 GenericToNVVM() : ModulePass(ID) {}
43 bool runOnModule(Module &M) override;
45 void getAnalysisUsage(AnalysisUsage &AU) const override {}
48 Value *getOrInsertCVTA(Module *M, Function *F, GlobalVariable *GV,
49 IRBuilder<> &Builder);
50 Value *remapConstant(Module *M, Function *F, Constant *C,
51 IRBuilder<> &Builder);
52 Value *remapConstantVectorOrConstantAggregate(Module *M, Function *F,
54 IRBuilder<> &Builder);
55 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
56 IRBuilder<> &Builder);
57 void remapNamedMDNode(Module *M, NamedMDNode *N);
58 MDNode *remapMDNode(Module *M, MDNode *N);
60 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
61 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
63 ConstantToValueMapTy ConstantToValueMap;
67 char GenericToNVVM::ID = 0;
69 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
72 GenericToNVVM, "generic-to-nvvm",
73 "Ensure that the global variables are in the global address space", false,
76 bool 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
82 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
84 GlobalVariable *GV = I++;
85 if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
86 !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
87 !llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
88 GlobalVariable *NewGV = new GlobalVariable(
89 M, GV->getType()->getElementType(), GV->isConstant(),
91 GV->hasInitializer() ? GV->getInitializer() : nullptr,
92 "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
93 NewGV->copyAttributesFrom(GV);
98 // Return immediately, if every global variable has a specific address space
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()) {
111 IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
112 for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
114 for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
116 for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
117 Value *Operand = II->getOperand(i);
118 if (isa<Constant>(Operand)) {
120 i, remapConstant(&M, I, cast<Constant>(Operand), Builder));
125 ConstantToValueMap.clear();
128 // Walk through the metadata section and update the debug information
129 // associated with the global variables in the default address space.
130 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
131 E = M.named_metadata_end();
133 remapNamedMDNode(&M, I);
136 // Walk through the global variable initializers, and replace any use of
137 // original global variables in GVMap with a use of the corresponding copies
138 // in GVMap. The copies need to be bitcast to the original global variable
139 // types, as we cannot use cvta in global variable initializers.
140 for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
141 GlobalVariable *GV = I->first;
142 GlobalVariable *NewGV = I->second;
144 Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
145 // At this point, the remaining uses of GV should be found only in global
146 // variable initializers, as other uses have been already been removed
147 // while walking through the instructions in function definitions.
148 for (Value::use_iterator UI = GV->use_begin(), UE = GV->use_end();
150 (UI++)->set(BitCastNewGV);
151 std::string Name = GV->getName();
152 GV->removeDeadConstantUsers();
153 GV->eraseFromParent();
154 NewGV->setName(Name);
161 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
163 IRBuilder<> &Builder) {
164 PointerType *GVType = GV->getType();
165 Value *CVTA = nullptr;
167 // See if the address space conversion requires the operand to be bitcast
168 // to i8 addrspace(n)* first.
169 EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
170 if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
171 // A bitcast to i8 addrspace(n)* on the operand is needed.
172 LLVMContext &Context = M->getContext();
173 unsigned int AddrSpace = GVType->getAddressSpace();
174 Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
175 CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
176 // Insert the address space conversion.
178 PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
179 SmallVector<Type *, 2> ParamTypes;
180 ParamTypes.push_back(ResultType);
181 ParamTypes.push_back(DestTy);
182 Function *CVTAFunction = Intrinsic::getDeclaration(
183 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
184 CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
185 // Another bitcast from i8 * to <the element type of GVType> * is
188 PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
189 CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
191 // A simple CVTA is enough.
192 SmallVector<Type *, 2> ParamTypes;
193 ParamTypes.push_back(PointerType::get(GVType->getElementType(),
194 llvm::ADDRESS_SPACE_GENERIC));
195 ParamTypes.push_back(GVType);
196 Function *CVTAFunction = Intrinsic::getDeclaration(
197 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
198 CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
204 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
205 IRBuilder<> &Builder) {
206 // If the constant C has been converted already in the given function F, just
207 // return the converted value.
208 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
209 if (CTII != ConstantToValueMap.end()) {
214 if (isa<GlobalVariable>(C)) {
215 // If the constant C is a global variable and is found in GVMap, generate a
216 // set set of instructions that convert the clone of C with the global
217 // address space specifier to a generic pointer.
218 // The constant C cannot be used here, as it will be erased from the
219 // module eventually. And the clone of C with the global address space
220 // specifier cannot be used here either, as it will affect the types of
221 // other instructions in the function. Hence, this address space conversion
223 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
224 if (I != GVMap.end()) {
225 NewValue = getOrInsertCVTA(M, F, I->second, Builder);
227 } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
228 isa<ConstantStruct>(C)) {
229 // If any element in the constant vector or aggregate C is or uses a global
230 // variable in GVMap, the constant C needs to be reconstructed, using a set
232 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
233 } else if (isa<ConstantExpr>(C)) {
234 // If any operand in the constant expression C is or uses a global variable
235 // in GVMap, the constant expression C needs to be reconstructed, using a
236 // set of instructions.
237 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
240 ConstantToValueMap[C] = NewValue;
244 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
245 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
246 bool OperandChanged = false;
247 SmallVector<Value *, 4> NewOperands;
248 unsigned NumOperands = C->getNumOperands();
250 // Check if any element is or uses a global variable in GVMap, and thus
251 // converted to another value.
252 for (unsigned i = 0; i < NumOperands; ++i) {
253 Value *Operand = C->getOperand(i);
254 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
255 OperandChanged |= Operand != NewOperand;
256 NewOperands.push_back(NewOperand);
259 // If none of the elements has been modified, return C as it is.
260 if (!OperandChanged) {
264 // If any of the elements has been modified, construct the equivalent
265 // vector or aggregate value with a set instructions and the converted
267 Value *NewValue = UndefValue::get(C->getType());
268 if (isa<ConstantVector>(C)) {
269 for (unsigned i = 0; i < NumOperands; ++i) {
270 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
271 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
274 for (unsigned i = 0; i < NumOperands; ++i) {
276 Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
283 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
284 IRBuilder<> &Builder) {
285 bool OperandChanged = false;
286 SmallVector<Value *, 4> NewOperands;
287 unsigned NumOperands = C->getNumOperands();
289 // Check if any operand is or uses a global variable in GVMap, and thus
290 // converted to another value.
291 for (unsigned i = 0; i < NumOperands; ++i) {
292 Value *Operand = C->getOperand(i);
293 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
294 OperandChanged |= Operand != NewOperand;
295 NewOperands.push_back(NewOperand);
298 // If none of the operands has been modified, return C as it is.
299 if (!OperandChanged) {
303 // If any of the operands has been modified, construct the instruction with
304 // the converted operands.
305 unsigned Opcode = C->getOpcode();
307 case Instruction::ICmp:
308 // CompareConstantExpr (icmp)
309 return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
310 NewOperands[0], NewOperands[1]);
311 case Instruction::FCmp:
312 // CompareConstantExpr (fcmp)
313 assert(false && "Address space conversion should have no effect "
314 "on float point CompareConstantExpr (fcmp)!");
316 case Instruction::ExtractElement:
317 // ExtractElementConstantExpr
318 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
319 case Instruction::InsertElement:
320 // InsertElementConstantExpr
321 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
323 case Instruction::ShuffleVector:
325 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
327 case Instruction::ExtractValue:
328 // ExtractValueConstantExpr
329 return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
330 case Instruction::InsertValue:
331 // InsertValueConstantExpr
332 return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
334 case Instruction::GetElementPtr:
335 // GetElementPtrConstantExpr
336 return cast<GEPOperator>(C)->isInBounds()
339 makeArrayRef(&NewOperands[1], NumOperands - 1))
340 : Builder.CreateInBoundsGEP(
342 makeArrayRef(&NewOperands[1], NumOperands - 1));
343 case Instruction::Select:
344 // SelectConstantExpr
345 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
347 // BinaryConstantExpr
348 if (Instruction::isBinaryOp(Opcode)) {
349 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
350 NewOperands[0], NewOperands[1]);
353 if (Instruction::isCast(Opcode)) {
354 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
355 NewOperands[0], C->getType());
357 assert(false && "GenericToNVVM encountered an unsupported ConstantExpr");
362 void GenericToNVVM::remapNamedMDNode(Module *M, NamedMDNode *N) {
364 bool OperandChanged = false;
365 SmallVector<MDNode *, 16> NewOperands;
366 unsigned NumOperands = N->getNumOperands();
368 // Check if any operand is or contains a global variable in GVMap, and thus
369 // converted to another value.
370 for (unsigned i = 0; i < NumOperands; ++i) {
371 MDNode *Operand = N->getOperand(i);
372 MDNode *NewOperand = remapMDNode(M, Operand);
373 OperandChanged |= Operand != NewOperand;
374 NewOperands.push_back(NewOperand);
377 // If none of the operands has been modified, return immediately.
378 if (!OperandChanged) {
382 // Replace the old operands with the new operands.
383 N->dropAllReferences();
384 for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
385 E = NewOperands.end();
391 MDNode *GenericToNVVM::remapMDNode(Module *M, MDNode *N) {
393 bool OperandChanged = false;
394 SmallVector<Value *, 8> NewOperands;
395 unsigned NumOperands = N->getNumOperands();
397 // Check if any operand is or contains a global variable in GVMap, and thus
398 // converted to another value.
399 for (unsigned i = 0; i < NumOperands; ++i) {
400 Value *Operand = N->getOperand(i);
401 Value *NewOperand = Operand;
403 if (isa<GlobalVariable>(Operand)) {
404 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(Operand));
405 if (I != GVMap.end()) {
406 NewOperand = I->second;
407 if (++i < NumOperands) {
408 NewOperands.push_back(NewOperand);
409 // Address space of the global variable follows the global variable
410 // in the global variable debug info (see createGlobalVariable in
411 // lib/Analysis/DIBuilder.cpp).
413 ConstantInt::get(Type::getInt32Ty(M->getContext()),
414 I->second->getType()->getAddressSpace());
417 } else if (isa<MDNode>(Operand)) {
418 NewOperand = remapMDNode(M, cast<MDNode>(Operand));
421 OperandChanged |= Operand != NewOperand;
422 NewOperands.push_back(NewOperand);
425 // If none of the operands has been modified, return N as it is.
426 if (!OperandChanged) {
430 // If any of the operands has been modified, create a new MDNode with the new
432 return MDNode::get(M->getContext(), makeArrayRef(NewOperands));