Add support for __nvvm_reflect changes in libdevice in CUDA-7.0
[oota-llvm.git] / lib / Target / NVPTX / NVVMReflect.cpp
1 //===- NVVMReflect.cpp - NVVM Emulate conditional compilation -------------===//
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 replaces occurrences of __nvvm_reflect("string") with an
11 // integer based on -nvvm-reflect-list string=<int> option given to this pass.
12 // If an undefined string value is seen in a call to __nvvm_reflect("string"),
13 // a default value of 0 will be used.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "NVPTX.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_os_ostream.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include <map>
34 #include <sstream>
35 #include <string>
36 #include <vector>
37
38 #define NVVM_REFLECT_FUNCTION "__nvvm_reflect"
39
40 using namespace llvm;
41
42 #define DEBUG_TYPE "nvptx-reflect"
43
44 namespace llvm { void initializeNVVMReflectPass(PassRegistry &); }
45
46 namespace {
47 class NVVMReflect : public ModulePass {
48 private:
49   StringMap<int> VarMap;
50   typedef DenseMap<std::string, int>::iterator VarMapIter;
51
52 public:
53   static char ID;
54   NVVMReflect() : ModulePass(ID) {
55     initializeNVVMReflectPass(*PassRegistry::getPassRegistry());
56     VarMap.clear();
57   }
58
59   NVVMReflect(const StringMap<int> &Mapping)
60   : ModulePass(ID) {
61     initializeNVVMReflectPass(*PassRegistry::getPassRegistry());
62     for (StringMap<int>::const_iterator I = Mapping.begin(), E = Mapping.end();
63          I != E; ++I) {
64       VarMap[(*I).getKey()] = (*I).getValue();
65     }
66   }
67
68   void getAnalysisUsage(AnalysisUsage &AU) const override {
69     AU.setPreservesAll();
70   }
71   bool runOnModule(Module &) override;
72
73 private:
74   bool handleFunction(Function *ReflectFunction);
75   void setVarMap();
76 };
77 }
78
79 ModulePass *llvm::createNVVMReflectPass() {
80   return new NVVMReflect();
81 }
82
83 ModulePass *llvm::createNVVMReflectPass(const StringMap<int>& Mapping) {
84   return new NVVMReflect(Mapping);
85 }
86
87 static cl::opt<bool>
88 NVVMReflectEnabled("nvvm-reflect-enable", cl::init(true), cl::Hidden,
89                    cl::desc("NVVM reflection, enabled by default"));
90
91 char NVVMReflect::ID = 0;
92 INITIALIZE_PASS(NVVMReflect, "nvvm-reflect",
93                 "Replace occurrences of __nvvm_reflect() calls with 0/1", false,
94                 false)
95
96 static cl::list<std::string>
97 ReflectList("nvvm-reflect-list", cl::value_desc("name=<int>"), cl::Hidden,
98             cl::desc("A list of string=num assignments"),
99             cl::ValueRequired);
100
101 /// The command line can look as follows :
102 /// -nvvm-reflect-list a=1,b=2 -nvvm-reflect-list c=3,d=0 -R e=2
103 /// The strings "a=1,b=2", "c=3,d=0", "e=2" are available in the
104 /// ReflectList vector. First, each of ReflectList[i] is 'split'
105 /// using "," as the delimiter. Then each of this part is split
106 /// using "=" as the delimiter.
107 void NVVMReflect::setVarMap() {
108   for (unsigned i = 0, e = ReflectList.size(); i != e; ++i) {
109     DEBUG(dbgs() << "Option : "  << ReflectList[i] << "\n");
110     SmallVector<StringRef, 4> NameValList;
111     StringRef(ReflectList[i]).split(NameValList, ",");
112     for (unsigned j = 0, ej = NameValList.size(); j != ej; ++j) {
113       SmallVector<StringRef, 2> NameValPair;
114       NameValList[j].split(NameValPair, "=");
115       assert(NameValPair.size() == 2 && "name=val expected");
116       std::stringstream ValStream(NameValPair[1]);
117       int Val;
118       ValStream >> Val;
119       assert((!(ValStream.fail())) && "integer value expected");
120       VarMap[NameValPair[0]] = Val;
121     }
122   }
123 }
124
125 bool NVVMReflect::handleFunction(Function *ReflectFunction) {
126   // Validate _reflect function
127   assert(ReflectFunction->isDeclaration() &&
128          "_reflect function should not have a body");
129   assert(ReflectFunction->getReturnType()->isIntegerTy() &&
130          "_reflect's return type should be integer");
131
132   std::vector<Instruction *> ToRemove;
133
134   // Go through the uses of ReflectFunction in this Function.
135   // Each of them should a CallInst with a ConstantArray argument.
136   // First validate that. If the c-string corresponding to the
137   // ConstantArray can be found successfully, see if it can be
138   // found in VarMap. If so, replace the uses of CallInst with the
139   // value found in VarMap. If not, replace the use  with value 0.
140
141   // IR for __nvvm_reflect calls differs between CUDA versions:
142   // CUDA 6.5 and earlier uses this sequence:
143   //    %ptr = tail call i8* @llvm.nvvm.ptr.constant.to.gen.p0i8.p4i8
144   //        (i8 addrspace(4)* getelementptr inbounds
145   //           ([8 x i8], [8 x i8] addrspace(4)* @str, i32 0, i32 0))
146   //    %reflect = tail call i32 @__nvvm_reflect(i8* %ptr)
147   //
148   // Value returned by Sym->getOperand(0) is a Constant with a
149   // ConstantDataSequential operand which can be converted to string and used
150   // for lookup.
151   //
152   // CUDA 7.0 does it slightly differently:
153   //   %reflect = call i32 @__nvvm_reflect(i8* addrspacecast
154   //        (i8 addrspace(1)* getelementptr inbounds
155   //           ([8 x i8], [8 x i8] addrspace(1)* @str, i32 0, i32 0) to i8*))
156   //
157   // In this case, we get a Constant with a GlobalVariable operand and we need
158   // to dig deeper to find its initializer with the string we'll use for lookup.
159
160   for (User *U : ReflectFunction->users()) {
161     assert(isa<CallInst>(U) && "Only a call instruction can use _reflect");
162     CallInst *Reflect = cast<CallInst>(U);
163
164     assert((Reflect->getNumOperands() == 2) &&
165            "Only one operand expect for _reflect function");
166     // In cuda, we will have an extra constant-to-generic conversion of
167     // the string.
168     const Value *Str = Reflect->getArgOperand(0);
169     if (isa<CallInst>(Str)) {
170       // CUDA path
171       const CallInst *ConvCall = cast<CallInst>(Str);
172       Str = ConvCall->getArgOperand(0);
173     }
174     assert(isa<ConstantExpr>(Str) &&
175            "Format of _reflect function not recognized");
176     const ConstantExpr *GEP = cast<ConstantExpr>(Str);
177
178     const Value *Sym = GEP->getOperand(0);
179     assert(isa<Constant>(Sym) && "Format of _reflect function not recognized");
180
181     const Value *Operand = cast<Constant>(Sym)->getOperand(0);
182     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand)) {
183       // For CUDA-7.0 style __nvvm_reflect calls we need to find operand's
184       // initializer.
185       assert(GV->hasInitializer() &&
186              "Format of _reflect function not recognized");
187       const Constant *Initializer = GV->getInitializer();
188       Operand = Initializer;
189     }
190
191     assert(isa<ConstantDataSequential>(Operand) &&
192            "Format of _reflect function not recognized");
193     assert(cast<ConstantDataSequential>(Operand)->isCString() &&
194            "Format of _reflect function not recognized");
195
196     std::string ReflectArg =
197         cast<ConstantDataSequential>(Operand)->getAsString();
198
199     ReflectArg = ReflectArg.substr(0, ReflectArg.size() - 1);
200     DEBUG(dbgs() << "Arg of _reflect : " << ReflectArg << "\n");
201
202     int ReflectVal = 0; // The default value is 0
203     if (VarMap.find(ReflectArg) != VarMap.end()) {
204       ReflectVal = VarMap[ReflectArg];
205     }
206     Reflect->replaceAllUsesWith(
207         ConstantInt::get(Reflect->getType(), ReflectVal));
208     ToRemove.push_back(Reflect);
209   }
210   if (ToRemove.size() == 0)
211     return false;
212
213   for (unsigned i = 0, e = ToRemove.size(); i != e; ++i)
214     ToRemove[i]->eraseFromParent();
215   return true;
216 }
217
218 bool NVVMReflect::runOnModule(Module &M) {
219   if (!NVVMReflectEnabled)
220     return false;
221
222   setVarMap();
223
224
225   bool Res = false;
226   std::string Name;
227   Type *Tys[1];
228   Type *I8Ty = Type::getInt8Ty(M.getContext());
229   Function *ReflectFunction;
230
231   // Check for standard overloaded versions of llvm.nvvm.reflect
232
233   for (unsigned i = 0; i != 5; ++i) {
234     Tys[0] = PointerType::get(I8Ty, i);
235     Name = Intrinsic::getName(Intrinsic::nvvm_reflect, Tys);
236     ReflectFunction = M.getFunction(Name);
237     if(ReflectFunction != 0) {
238       Res |= handleFunction(ReflectFunction);
239     }
240   }
241
242   ReflectFunction = M.getFunction(NVVM_REFLECT_FUNCTION);
243   // If reflect function is not used, then there will be
244   // no entry in the module.
245   if (ReflectFunction != 0)
246     Res |= handleFunction(ReflectFunction);
247
248   return Res;
249 }