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/ADT/ValueMap.h"
19 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/PassManager.h"
33 void initializeGenericToNVVMPass(PassRegistry &);
37 class GenericToNVVM : public ModulePass {
41 GenericToNVVM() : ModulePass(ID) {}
43 virtual bool runOnModule(Module &M);
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
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,
55 IRBuilder<> &Builder);
56 Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
57 IRBuilder<> &Builder);
58 void remapNamedMDNode(Module *M, NamedMDNode *N);
59 MDNode *remapMDNode(Module *M, MDNode *N);
61 typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
62 typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
64 ConstantToValueMapTy ConstantToValueMap;
68 char GenericToNVVM::ID = 0;
70 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
73 GenericToNVVM, "generic-to-nvvm",
74 "Ensure that the global variables are in the global address space", false,
77 bool GenericToNVVM::runOnModule(Module &M) {
78 // Create a clone of each global variable that has the default address space.
79 // The clone is created with the global address space specifier, and the pair
80 // of original global variable and its clone is placed in the GVMap for later
83 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
85 GlobalVariable *GV = I++;
86 if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
87 !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
88 !GV->getName().startswith("llvm.")) {
89 GlobalVariable *NewGV = new GlobalVariable(
90 M, GV->getType()->getElementType(), GV->isConstant(),
91 GV->getLinkage(), GV->hasInitializer() ? GV->getInitializer() : NULL,
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 Use &U = (UI++).getUse();
153 std::string Name = GV->getName();
154 GV->removeDeadConstantUsers();
155 GV->eraseFromParent();
156 NewGV->setName(Name);
163 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
165 IRBuilder<> &Builder) {
166 PointerType *GVType = GV->getType();
169 // See if the address space conversion requires the operand to be bitcast
170 // to i8 addrspace(n)* first.
171 EVT ExtendedGVType = EVT::getEVT(GVType->getElementType(), true);
172 if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
173 // A bitcast to i8 addrspace(n)* on the operand is needed.
174 LLVMContext &Context = M->getContext();
175 unsigned int AddrSpace = GVType->getAddressSpace();
176 Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
177 CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
178 // Insert the address space conversion.
180 PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
181 SmallVector<Type *, 2> ParamTypes;
182 ParamTypes.push_back(ResultType);
183 ParamTypes.push_back(DestTy);
184 Function *CVTAFunction = Intrinsic::getDeclaration(
185 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
186 CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
187 // Another bitcast from i8 * to <the element type of GVType> * is
190 PointerType::get(GVType->getElementType(), llvm::ADDRESS_SPACE_GENERIC);
191 CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
193 // A simple CVTA is enough.
194 SmallVector<Type *, 2> ParamTypes;
195 ParamTypes.push_back(PointerType::get(GVType->getElementType(),
196 llvm::ADDRESS_SPACE_GENERIC));
197 ParamTypes.push_back(GVType);
198 Function *CVTAFunction = Intrinsic::getDeclaration(
199 M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
200 CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
206 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
207 IRBuilder<> &Builder) {
208 // If the constant C has been converted already in the given function F, just
209 // return the converted value.
210 ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
211 if (CTII != ConstantToValueMap.end()) {
216 if (isa<GlobalVariable>(C)) {
217 // If the constant C is a global variable and is found in GVMap, generate a
218 // set set of instructions that convert the clone of C with the global
219 // address space specifier to a generic pointer.
220 // The constant C cannot be used here, as it will be erased from the
221 // module eventually. And the clone of C with the global address space
222 // specifier cannot be used here either, as it will affect the types of
223 // other instructions in the function. Hence, this address space conversion
225 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
226 if (I != GVMap.end()) {
227 NewValue = getOrInsertCVTA(M, F, I->second, Builder);
229 } else if (isa<ConstantVector>(C) || isa<ConstantArray>(C) ||
230 isa<ConstantStruct>(C)) {
231 // If any element in the constant vector or aggregate C is or uses a global
232 // variable in GVMap, the constant C needs to be reconstructed, using a set
234 NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
235 } else if (isa<ConstantExpr>(C)) {
236 // If any operand in the constant expression C is or uses a global variable
237 // in GVMap, the constant expression C needs to be reconstructed, using a
238 // set of instructions.
239 NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
242 ConstantToValueMap[C] = NewValue;
246 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
247 Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
248 bool OperandChanged = false;
249 SmallVector<Value *, 4> NewOperands;
250 unsigned NumOperands = C->getNumOperands();
252 // Check if any element is or uses a global variable in GVMap, and thus
253 // converted to another value.
254 for (unsigned i = 0; i < NumOperands; ++i) {
255 Value *Operand = C->getOperand(i);
256 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
257 OperandChanged |= Operand != NewOperand;
258 NewOperands.push_back(NewOperand);
261 // If none of the elements has been modified, return C as it is.
262 if (!OperandChanged) {
266 // If any of the elements has been modified, construct the equivalent
267 // vector or aggregate value with a set instructions and the converted
269 Value *NewValue = UndefValue::get(C->getType());
270 if (isa<ConstantVector>(C)) {
271 for (unsigned i = 0; i < NumOperands; ++i) {
272 Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
273 NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
276 for (unsigned i = 0; i < NumOperands; ++i) {
278 Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
285 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
286 IRBuilder<> &Builder) {
287 bool OperandChanged = false;
288 SmallVector<Value *, 4> NewOperands;
289 unsigned NumOperands = C->getNumOperands();
291 // Check if any operand is or uses a global variable in GVMap, and thus
292 // converted to another value.
293 for (unsigned i = 0; i < NumOperands; ++i) {
294 Value *Operand = C->getOperand(i);
295 Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
296 OperandChanged |= Operand != NewOperand;
297 NewOperands.push_back(NewOperand);
300 // If none of the operands has been modified, return C as it is.
301 if (!OperandChanged) {
305 // If any of the operands has been modified, construct the instruction with
306 // the converted operands.
307 unsigned Opcode = C->getOpcode();
309 case Instruction::ICmp:
310 // CompareConstantExpr (icmp)
311 return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
312 NewOperands[0], NewOperands[1]);
313 case Instruction::FCmp:
314 // CompareConstantExpr (fcmp)
315 assert(false && "Address space conversion should have no effect "
316 "on float point CompareConstantExpr (fcmp)!");
318 case Instruction::ExtractElement:
319 // ExtractElementConstantExpr
320 return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
321 case Instruction::InsertElement:
322 // InsertElementConstantExpr
323 return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
325 case Instruction::ShuffleVector:
327 return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
329 case Instruction::ExtractValue:
330 // ExtractValueConstantExpr
331 return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
332 case Instruction::InsertValue:
333 // InsertValueConstantExpr
334 return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
336 case Instruction::GetElementPtr:
337 // GetElementPtrConstantExpr
338 return cast<GEPOperator>(C)->isInBounds()
341 makeArrayRef(&NewOperands[1], NumOperands - 1))
342 : Builder.CreateInBoundsGEP(
344 makeArrayRef(&NewOperands[1], NumOperands - 1));
345 case Instruction::Select:
346 // SelectConstantExpr
347 return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
349 // BinaryConstantExpr
350 if (Instruction::isBinaryOp(Opcode)) {
351 return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
352 NewOperands[0], NewOperands[1]);
355 if (Instruction::isCast(Opcode)) {
356 return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
357 NewOperands[0], C->getType());
359 assert(false && "GenericToNVVM encountered an unsupported ConstantExpr");
364 void GenericToNVVM::remapNamedMDNode(Module *M, NamedMDNode *N) {
366 bool OperandChanged = false;
367 SmallVector<MDNode *, 16> NewOperands;
368 unsigned NumOperands = N->getNumOperands();
370 // Check if any operand is or contains a global variable in GVMap, and thus
371 // converted to another value.
372 for (unsigned i = 0; i < NumOperands; ++i) {
373 MDNode *Operand = N->getOperand(i);
374 MDNode *NewOperand = remapMDNode(M, Operand);
375 OperandChanged |= Operand != NewOperand;
376 NewOperands.push_back(NewOperand);
379 // If none of the operands has been modified, return immediately.
380 if (!OperandChanged) {
384 // Replace the old operands with the new operands.
385 N->dropAllReferences();
386 for (SmallVectorImpl<MDNode *>::iterator I = NewOperands.begin(),
387 E = NewOperands.end();
393 MDNode *GenericToNVVM::remapMDNode(Module *M, MDNode *N) {
395 bool OperandChanged = false;
396 SmallVector<Value *, 8> NewOperands;
397 unsigned NumOperands = N->getNumOperands();
399 // Check if any operand is or contains a global variable in GVMap, and thus
400 // converted to another value.
401 for (unsigned i = 0; i < NumOperands; ++i) {
402 Value *Operand = N->getOperand(i);
403 Value *NewOperand = Operand;
405 if (isa<GlobalVariable>(Operand)) {
406 GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(Operand));
407 if (I != GVMap.end()) {
408 NewOperand = I->second;
409 if (++i < NumOperands) {
410 NewOperands.push_back(NewOperand);
411 // Address space of the global variable follows the global variable
412 // in the global variable debug info (see createGlobalVariable in
413 // lib/Analysis/DIBuilder.cpp).
415 ConstantInt::get(Type::getInt32Ty(M->getContext()),
416 I->second->getType()->getAddressSpace());
419 } else if (isa<MDNode>(Operand)) {
420 NewOperand = remapMDNode(M, cast<MDNode>(Operand));
423 OperandChanged |= Operand != NewOperand;
424 NewOperands.push_back(NewOperand);
427 // If none of the operands has been modified, return N as it is.
428 if (!OperandChanged) {
432 // If any of the operands has been modified, create a new MDNode with the new
434 return MDNode::get(M->getContext(), makeArrayRef(NewOperands));