OSDN Git Service

390776212ce7ee7248a5384b58b7bc1663105030
[android-x86/external-llvm.git] / lib / Target / NVPTX / NVPTXGenericToNVVM.cpp
1 //===-- 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"
16 #include "MCTargetDesc/NVPTXBaseInfo.h"
17 #include "NVPTXUtilities.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/LegacyPassManager.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueMap.h"
28 #include "llvm/Transforms/Utils/ValueMapper.h"
29
30 using namespace llvm;
31
32 namespace llvm {
33 void initializeGenericToNVVMPass(PassRegistry &);
34 }
35
36 namespace {
37 class GenericToNVVM : public ModulePass {
38 public:
39   static char ID;
40
41   GenericToNVVM() : ModulePass(ID) {}
42
43   bool runOnModule(Module &M) override;
44
45   void getAnalysisUsage(AnalysisUsage &AU) const override {}
46
47 private:
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,
53                                                 Constant *C,
54                                                 IRBuilder<> &Builder);
55   Value *remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
56                            IRBuilder<> &Builder);
57
58   typedef ValueMap<GlobalVariable *, GlobalVariable *> GVMapTy;
59   typedef ValueMap<Constant *, Value *> ConstantToValueMapTy;
60   GVMapTy GVMap;
61   ConstantToValueMapTy ConstantToValueMap;
62 };
63 } // end namespace
64
65 char GenericToNVVM::ID = 0;
66
67 ModulePass *llvm::createGenericToNVVMPass() { return new GenericToNVVM(); }
68
69 INITIALIZE_PASS(
70     GenericToNVVM, "generic-to-nvvm",
71     "Ensure that the global variables are in the global address space", false,
72     false)
73
74 bool GenericToNVVM::runOnModule(Module &M) {
75   // Create a clone of each global variable that has the default address space.
76   // The clone is created with the global address space  specifier, and the pair
77   // of original global variable and its clone is placed in the GVMap for later
78   // use.
79
80   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
81        I != E;) {
82     GlobalVariable *GV = &*I++;
83     if (GV->getType()->getAddressSpace() == llvm::ADDRESS_SPACE_GENERIC &&
84         !llvm::isTexture(*GV) && !llvm::isSurface(*GV) &&
85         !llvm::isSampler(*GV) && !GV->getName().startswith("llvm.")) {
86       GlobalVariable *NewGV = new GlobalVariable(
87           M, GV->getValueType(), GV->isConstant(),
88           GV->getLinkage(),
89           GV->hasInitializer() ? GV->getInitializer() : nullptr,
90           "", GV, GV->getThreadLocalMode(), llvm::ADDRESS_SPACE_GLOBAL);
91       NewGV->copyAttributesFrom(GV);
92       GVMap[GV] = NewGV;
93     }
94   }
95
96   // Return immediately, if every global variable has a specific address space
97   // specifier.
98   if (GVMap.empty()) {
99     return false;
100   }
101
102   // Walk through the instructions in function defitinions, and replace any use
103   // of original global variables in GVMap with a use of the corresponding
104   // copies in GVMap.  If necessary, promote constants to instructions.
105   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
106     if (I->isDeclaration()) {
107       continue;
108     }
109     IRBuilder<> Builder(I->getEntryBlock().getFirstNonPHIOrDbg());
110     for (Function::iterator BBI = I->begin(), BBE = I->end(); BBI != BBE;
111          ++BBI) {
112       for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE;
113            ++II) {
114         for (unsigned i = 0, e = II->getNumOperands(); i < e; ++i) {
115           Value *Operand = II->getOperand(i);
116           if (isa<Constant>(Operand)) {
117             II->setOperand(
118                 i, remapConstant(&M, &*I, cast<Constant>(Operand), Builder));
119           }
120         }
121       }
122     }
123     ConstantToValueMap.clear();
124   }
125
126   // Copy GVMap over to a standard value map.
127   ValueToValueMapTy VM;
128   for (auto I = GVMap.begin(), E = GVMap.end(); I != E; ++I)
129     VM[I->first] = I->second;
130
131   // Walk through the global variable  initializers, and replace any use of
132   // original global variables in GVMap with a use of the corresponding copies
133   // in GVMap.  The copies need to be bitcast to the original global variable
134   // types, as we cannot use cvta in global variable initializers.
135   for (GVMapTy::iterator I = GVMap.begin(), E = GVMap.end(); I != E;) {
136     GlobalVariable *GV = I->first;
137     GlobalVariable *NewGV = I->second;
138
139     // Remove GV from the map so that it can be RAUWed.  Note that
140     // DenseMap::erase() won't invalidate any iterators but this one.
141     auto Next = std::next(I);
142     GVMap.erase(I);
143     I = Next;
144
145     Constant *BitCastNewGV = ConstantExpr::getPointerCast(NewGV, GV->getType());
146     // At this point, the remaining uses of GV should be found only in global
147     // variable initializers, as other uses have been already been removed
148     // while walking through the instructions in function definitions.
149     GV->replaceAllUsesWith(BitCastNewGV);
150     std::string Name = GV->getName();
151     GV->eraseFromParent();
152     NewGV->setName(Name);
153   }
154   assert(GVMap.empty() && "Expected it to be empty by now");
155
156   return true;
157 }
158
159 Value *GenericToNVVM::getOrInsertCVTA(Module *M, Function *F,
160                                       GlobalVariable *GV,
161                                       IRBuilder<> &Builder) {
162   PointerType *GVType = GV->getType();
163   Value *CVTA = nullptr;
164
165   // See if the address space conversion requires the operand to be bitcast
166   // to i8 addrspace(n)* first.
167   EVT ExtendedGVType = EVT::getEVT(GV->getValueType(), true);
168   if (!ExtendedGVType.isInteger() && !ExtendedGVType.isFloatingPoint()) {
169     // A bitcast to i8 addrspace(n)* on the operand is needed.
170     LLVMContext &Context = M->getContext();
171     unsigned int AddrSpace = GVType->getAddressSpace();
172     Type *DestTy = PointerType::get(Type::getInt8Ty(Context), AddrSpace);
173     CVTA = Builder.CreateBitCast(GV, DestTy, "cvta");
174     // Insert the address space conversion.
175     Type *ResultType =
176         PointerType::get(Type::getInt8Ty(Context), llvm::ADDRESS_SPACE_GENERIC);
177     Function *CVTAFunction = Intrinsic::getDeclaration(
178         M, Intrinsic::nvvm_ptr_global_to_gen, {ResultType, DestTy});
179     CVTA = Builder.CreateCall(CVTAFunction, CVTA, "cvta");
180     // Another bitcast from i8 * to <the element type of GVType> * is
181     // required.
182     DestTy =
183         PointerType::get(GV->getValueType(), llvm::ADDRESS_SPACE_GENERIC);
184     CVTA = Builder.CreateBitCast(CVTA, DestTy, "cvta");
185   } else {
186     // A simple CVTA is enough.
187     SmallVector<Type *, 2> ParamTypes;
188     ParamTypes.push_back(PointerType::get(GV->getValueType(),
189                                           llvm::ADDRESS_SPACE_GENERIC));
190     ParamTypes.push_back(GVType);
191     Function *CVTAFunction = Intrinsic::getDeclaration(
192         M, Intrinsic::nvvm_ptr_global_to_gen, ParamTypes);
193     CVTA = Builder.CreateCall(CVTAFunction, GV, "cvta");
194   }
195
196   return CVTA;
197 }
198
199 Value *GenericToNVVM::remapConstant(Module *M, Function *F, Constant *C,
200                                     IRBuilder<> &Builder) {
201   // If the constant C has been converted already in the given function  F, just
202   // return the converted value.
203   ConstantToValueMapTy::iterator CTII = ConstantToValueMap.find(C);
204   if (CTII != ConstantToValueMap.end()) {
205     return CTII->second;
206   }
207
208   Value *NewValue = C;
209   if (isa<GlobalVariable>(C)) {
210     // If the constant C is a global variable and is found in  GVMap, generate a
211     // set set of instructions that convert the clone of C with the global
212     // address space specifier to a generic pointer.
213     // The constant C cannot be used here, as it will be erased from the
214     // module eventually.  And the clone of C with the global address space
215     // specifier cannot be used here either, as it will affect the types of
216     // other instructions in the function.  Hence, this address space conversion
217     // is required.
218     GVMapTy::iterator I = GVMap.find(cast<GlobalVariable>(C));
219     if (I != GVMap.end()) {
220       NewValue = getOrInsertCVTA(M, F, I->second, Builder);
221     }
222   } else if (isa<ConstantAggregate>(C)) {
223     // If any element in the constant vector or aggregate C is or uses a global
224     // variable in GVMap, the constant C needs to be reconstructed, using a set
225     // of instructions.
226     NewValue = remapConstantVectorOrConstantAggregate(M, F, C, Builder);
227   } else if (isa<ConstantExpr>(C)) {
228     // If any operand in the constant expression C is or uses a global variable
229     // in GVMap, the constant expression C needs to be reconstructed, using a
230     // set of instructions.
231     NewValue = remapConstantExpr(M, F, cast<ConstantExpr>(C), Builder);
232   }
233
234   ConstantToValueMap[C] = NewValue;
235   return NewValue;
236 }
237
238 Value *GenericToNVVM::remapConstantVectorOrConstantAggregate(
239     Module *M, Function *F, Constant *C, IRBuilder<> &Builder) {
240   bool OperandChanged = false;
241   SmallVector<Value *, 4> NewOperands;
242   unsigned NumOperands = C->getNumOperands();
243
244   // Check if any element is or uses a global variable in  GVMap, and thus
245   // converted to another value.
246   for (unsigned i = 0; i < NumOperands; ++i) {
247     Value *Operand = C->getOperand(i);
248     Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
249     OperandChanged |= Operand != NewOperand;
250     NewOperands.push_back(NewOperand);
251   }
252
253   // If none of the elements has been modified, return C as it is.
254   if (!OperandChanged) {
255     return C;
256   }
257
258   // If any of the elements has been  modified, construct the equivalent
259   // vector or aggregate value with a set instructions and the converted
260   // elements.
261   Value *NewValue = UndefValue::get(C->getType());
262   if (isa<ConstantVector>(C)) {
263     for (unsigned i = 0; i < NumOperands; ++i) {
264       Value *Idx = ConstantInt::get(Type::getInt32Ty(M->getContext()), i);
265       NewValue = Builder.CreateInsertElement(NewValue, NewOperands[i], Idx);
266     }
267   } else {
268     for (unsigned i = 0; i < NumOperands; ++i) {
269       NewValue =
270           Builder.CreateInsertValue(NewValue, NewOperands[i], makeArrayRef(i));
271     }
272   }
273
274   return NewValue;
275 }
276
277 Value *GenericToNVVM::remapConstantExpr(Module *M, Function *F, ConstantExpr *C,
278                                         IRBuilder<> &Builder) {
279   bool OperandChanged = false;
280   SmallVector<Value *, 4> NewOperands;
281   unsigned NumOperands = C->getNumOperands();
282
283   // Check if any operand is or uses a global variable in  GVMap, and thus
284   // converted to another value.
285   for (unsigned i = 0; i < NumOperands; ++i) {
286     Value *Operand = C->getOperand(i);
287     Value *NewOperand = remapConstant(M, F, cast<Constant>(Operand), Builder);
288     OperandChanged |= Operand != NewOperand;
289     NewOperands.push_back(NewOperand);
290   }
291
292   // If none of the operands has been modified, return C as it is.
293   if (!OperandChanged) {
294     return C;
295   }
296
297   // If any of the operands has been modified, construct the instruction with
298   // the converted operands.
299   unsigned Opcode = C->getOpcode();
300   switch (Opcode) {
301   case Instruction::ICmp:
302     // CompareConstantExpr (icmp)
303     return Builder.CreateICmp(CmpInst::Predicate(C->getPredicate()),
304                               NewOperands[0], NewOperands[1]);
305   case Instruction::FCmp:
306     // CompareConstantExpr (fcmp)
307     llvm_unreachable("Address space conversion should have no effect "
308                      "on float point CompareConstantExpr (fcmp)!");
309   case Instruction::ExtractElement:
310     // ExtractElementConstantExpr
311     return Builder.CreateExtractElement(NewOperands[0], NewOperands[1]);
312   case Instruction::InsertElement:
313     // InsertElementConstantExpr
314     return Builder.CreateInsertElement(NewOperands[0], NewOperands[1],
315                                        NewOperands[2]);
316   case Instruction::ShuffleVector:
317     // ShuffleVector
318     return Builder.CreateShuffleVector(NewOperands[0], NewOperands[1],
319                                        NewOperands[2]);
320   case Instruction::ExtractValue:
321     // ExtractValueConstantExpr
322     return Builder.CreateExtractValue(NewOperands[0], C->getIndices());
323   case Instruction::InsertValue:
324     // InsertValueConstantExpr
325     return Builder.CreateInsertValue(NewOperands[0], NewOperands[1],
326                                      C->getIndices());
327   case Instruction::GetElementPtr:
328     // GetElementPtrConstantExpr
329     return cast<GEPOperator>(C)->isInBounds()
330                ? Builder.CreateGEP(
331                      cast<GEPOperator>(C)->getSourceElementType(),
332                      NewOperands[0],
333                      makeArrayRef(&NewOperands[1], NumOperands - 1))
334                : Builder.CreateInBoundsGEP(
335                      cast<GEPOperator>(C)->getSourceElementType(),
336                      NewOperands[0],
337                      makeArrayRef(&NewOperands[1], NumOperands - 1));
338   case Instruction::Select:
339     // SelectConstantExpr
340     return Builder.CreateSelect(NewOperands[0], NewOperands[1], NewOperands[2]);
341   default:
342     // BinaryConstantExpr
343     if (Instruction::isBinaryOp(Opcode)) {
344       return Builder.CreateBinOp(Instruction::BinaryOps(C->getOpcode()),
345                                  NewOperands[0], NewOperands[1]);
346     }
347     // UnaryConstantExpr
348     if (Instruction::isCast(Opcode)) {
349       return Builder.CreateCast(Instruction::CastOps(C->getOpcode()),
350                                 NewOperands[0], C->getType());
351     }
352     llvm_unreachable("GenericToNVVM encountered an unsupported ConstantExpr");
353   }
354 }