LLVM  mainline
NVPTXUtilities.cpp
Go to the documentation of this file.
00001 //===- NVPTXUtilities.cpp - Utility Functions -----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains miscellaneous utility functions
00011 //===----------------------------------------------------------------------===//
00012 
00013 #include "NVPTXUtilities.h"
00014 #include "NVPTX.h"
00015 #include "llvm/IR/Constants.h"
00016 #include "llvm/IR/Function.h"
00017 #include "llvm/IR/GlobalVariable.h"
00018 #include "llvm/IR/InstIterator.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/IR/Operator.h"
00021 #include "llvm/Support/ManagedStatic.h"
00022 #include "llvm/Support/MutexGuard.h"
00023 #include <algorithm>
00024 #include <cstring>
00025 #include <map>
00026 #include <string>
00027 #include <vector>
00028 
00029 using namespace llvm;
00030 
00031 typedef std::map<std::string, std::vector<unsigned> > key_val_pair_t;
00032 typedef std::map<const GlobalValue *, key_val_pair_t> global_val_annot_t;
00033 typedef std::map<const Module *, global_val_annot_t> per_module_annot_t;
00034 
00035 ManagedStatic<per_module_annot_t> annotationCache;
00036 static sys::Mutex Lock;
00037 
00038 void llvm::clearAnnotationCache(const llvm::Module *Mod) {
00039   MutexGuard Guard(Lock);
00040   annotationCache->erase(Mod);
00041 }
00042 
00043 static void cacheAnnotationFromMD(const MDNode *md, key_val_pair_t &retval) {
00044   MutexGuard Guard(Lock);
00045   assert(md && "Invalid mdnode for annotation");
00046   assert((md->getNumOperands() % 2) == 1 && "Invalid number of operands");
00047   // start index = 1, to skip the global variable key
00048   // increment = 2, to skip the value for each property-value pairs
00049   for (unsigned i = 1, e = md->getNumOperands(); i != e; i += 2) {
00050     // property
00051     const MDString *prop = dyn_cast<MDString>(md->getOperand(i));
00052     assert(prop && "Annotation property not a string");
00053 
00054     // value
00055     ConstantInt *Val = mdconst::dyn_extract<ConstantInt>(md->getOperand(i + 1));
00056     assert(Val && "Value operand not a constant int");
00057 
00058     std::string keyname = prop->getString().str();
00059     if (retval.find(keyname) != retval.end())
00060       retval[keyname].push_back(Val->getZExtValue());
00061     else {
00062       std::vector<unsigned> tmp;
00063       tmp.push_back(Val->getZExtValue());
00064       retval[keyname] = tmp;
00065     }
00066   }
00067 }
00068 
00069 static void cacheAnnotationFromMD(const Module *m, const GlobalValue *gv) {
00070   MutexGuard Guard(Lock);
00071   NamedMDNode *NMD = m->getNamedMetadata(llvm::NamedMDForAnnotations);
00072   if (!NMD)
00073     return;
00074   key_val_pair_t tmp;
00075   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
00076     const MDNode *elem = NMD->getOperand(i);
00077 
00078     GlobalValue *entity =
00079         mdconst::dyn_extract_or_null<GlobalValue>(elem->getOperand(0));
00080     // entity may be null due to DCE
00081     if (!entity)
00082       continue;
00083     if (entity != gv)
00084       continue;
00085 
00086     // accumulate annotations for entity in tmp
00087     cacheAnnotationFromMD(elem, tmp);
00088   }
00089 
00090   if (tmp.empty()) // no annotations for this gv
00091     return;
00092 
00093   if ((*annotationCache).find(m) != (*annotationCache).end())
00094     (*annotationCache)[m][gv] = std::move(tmp);
00095   else {
00096     global_val_annot_t tmp1;
00097     tmp1[gv] = std::move(tmp);
00098     (*annotationCache)[m] = std::move(tmp1);
00099   }
00100 }
00101 
00102 bool llvm::findOneNVVMAnnotation(const GlobalValue *gv, std::string prop,
00103                                  unsigned &retval) {
00104   MutexGuard Guard(Lock);
00105   const Module *m = gv->getParent();
00106   if ((*annotationCache).find(m) == (*annotationCache).end())
00107     cacheAnnotationFromMD(m, gv);
00108   else if ((*annotationCache)[m].find(gv) == (*annotationCache)[m].end())
00109     cacheAnnotationFromMD(m, gv);
00110   if ((*annotationCache)[m][gv].find(prop) == (*annotationCache)[m][gv].end())
00111     return false;
00112   retval = (*annotationCache)[m][gv][prop][0];
00113   return true;
00114 }
00115 
00116 bool llvm::findAllNVVMAnnotation(const GlobalValue *gv, std::string prop,
00117                                  std::vector<unsigned> &retval) {
00118   MutexGuard Guard(Lock);
00119   const Module *m = gv->getParent();
00120   if ((*annotationCache).find(m) == (*annotationCache).end())
00121     cacheAnnotationFromMD(m, gv);
00122   else if ((*annotationCache)[m].find(gv) == (*annotationCache)[m].end())
00123     cacheAnnotationFromMD(m, gv);
00124   if ((*annotationCache)[m][gv].find(prop) == (*annotationCache)[m][gv].end())
00125     return false;
00126   retval = (*annotationCache)[m][gv][prop];
00127   return true;
00128 }
00129 
00130 bool llvm::isTexture(const llvm::Value &val) {
00131   if (const GlobalValue *gv = dyn_cast<GlobalValue>(&val)) {
00132     unsigned annot;
00133     if (llvm::findOneNVVMAnnotation(
00134             gv, llvm::PropertyAnnotationNames[llvm::PROPERTY_ISTEXTURE],
00135             annot)) {
00136       assert((annot == 1) && "Unexpected annotation on a texture symbol");
00137       return true;
00138     }
00139   }
00140   return false;
00141 }
00142 
00143 bool llvm::isSurface(const llvm::Value &val) {
00144   if (const GlobalValue *gv = dyn_cast<GlobalValue>(&val)) {
00145     unsigned annot;
00146     if (llvm::findOneNVVMAnnotation(
00147             gv, llvm::PropertyAnnotationNames[llvm::PROPERTY_ISSURFACE],
00148             annot)) {
00149       assert((annot == 1) && "Unexpected annotation on a surface symbol");
00150       return true;
00151     }
00152   }
00153   return false;
00154 }
00155 
00156 bool llvm::isSampler(const llvm::Value &val) {
00157   if (const GlobalValue *gv = dyn_cast<GlobalValue>(&val)) {
00158     unsigned annot;
00159     if (llvm::findOneNVVMAnnotation(
00160             gv, llvm::PropertyAnnotationNames[llvm::PROPERTY_ISSAMPLER],
00161             annot)) {
00162       assert((annot == 1) && "Unexpected annotation on a sampler symbol");
00163       return true;
00164     }
00165   }
00166   if (const Argument *arg = dyn_cast<Argument>(&val)) {
00167     const Function *func = arg->getParent();
00168     std::vector<unsigned> annot;
00169     if (llvm::findAllNVVMAnnotation(
00170             func, llvm::PropertyAnnotationNames[llvm::PROPERTY_ISSAMPLER],
00171             annot)) {
00172       if (std::find(annot.begin(), annot.end(), arg->getArgNo()) != annot.end())
00173         return true;
00174     }
00175   }
00176   return false;
00177 }
00178 
00179 bool llvm::isImageReadOnly(const llvm::Value &val) {
00180   if (const Argument *arg = dyn_cast<Argument>(&val)) {
00181     const Function *func = arg->getParent();
00182     std::vector<unsigned> annot;
00183     if (llvm::findAllNVVMAnnotation(func,
00184                                     llvm::PropertyAnnotationNames[
00185                                         llvm::PROPERTY_ISREADONLY_IMAGE_PARAM],
00186                                     annot)) {
00187       if (std::find(annot.begin(), annot.end(), arg->getArgNo()) != annot.end())
00188         return true;
00189     }
00190   }
00191   return false;
00192 }
00193 
00194 bool llvm::isImageWriteOnly(const llvm::Value &val) {
00195   if (const Argument *arg = dyn_cast<Argument>(&val)) {
00196     const Function *func = arg->getParent();
00197     std::vector<unsigned> annot;
00198     if (llvm::findAllNVVMAnnotation(func,
00199                                     llvm::PropertyAnnotationNames[
00200                                         llvm::PROPERTY_ISWRITEONLY_IMAGE_PARAM],
00201                                     annot)) {
00202       if (std::find(annot.begin(), annot.end(), arg->getArgNo()) != annot.end())
00203         return true;
00204     }
00205   }
00206   return false;
00207 }
00208 
00209 bool llvm::isImageReadWrite(const llvm::Value &val) {
00210   if (const Argument *arg = dyn_cast<Argument>(&val)) {
00211     const Function *func = arg->getParent();
00212     std::vector<unsigned> annot;
00213     if (llvm::findAllNVVMAnnotation(func,
00214                                     llvm::PropertyAnnotationNames[
00215                                         llvm::PROPERTY_ISREADWRITE_IMAGE_PARAM],
00216                                     annot)) {
00217       if (std::find(annot.begin(), annot.end(), arg->getArgNo()) != annot.end())
00218         return true;
00219     }
00220   }
00221   return false;
00222 }
00223 
00224 bool llvm::isImage(const llvm::Value &val) {
00225   return llvm::isImageReadOnly(val) || llvm::isImageWriteOnly(val) ||
00226          llvm::isImageReadWrite(val);
00227 }
00228 
00229 bool llvm::isManaged(const llvm::Value &val) {
00230   if(const GlobalValue *gv = dyn_cast<GlobalValue>(&val)) {
00231     unsigned annot;
00232     if(llvm::findOneNVVMAnnotation(gv,
00233                           llvm::PropertyAnnotationNames[llvm::PROPERTY_MANAGED],
00234                                    annot)) {
00235       assert((annot == 1) && "Unexpected annotation on a managed symbol");
00236       return true;
00237     }
00238   }
00239   return false;
00240 }
00241 
00242 std::string llvm::getTextureName(const llvm::Value &val) {
00243   assert(val.hasName() && "Found texture variable with no name");
00244   return val.getName();
00245 }
00246 
00247 std::string llvm::getSurfaceName(const llvm::Value &val) {
00248   assert(val.hasName() && "Found surface variable with no name");
00249   return val.getName();
00250 }
00251 
00252 std::string llvm::getSamplerName(const llvm::Value &val) {
00253   assert(val.hasName() && "Found sampler variable with no name");
00254   return val.getName();
00255 }
00256 
00257 bool llvm::getMaxNTIDx(const Function &F, unsigned &x) {
00258   return (llvm::findOneNVVMAnnotation(
00259       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_MAXNTID_X], x));
00260 }
00261 
00262 bool llvm::getMaxNTIDy(const Function &F, unsigned &y) {
00263   return (llvm::findOneNVVMAnnotation(
00264       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_MAXNTID_Y], y));
00265 }
00266 
00267 bool llvm::getMaxNTIDz(const Function &F, unsigned &z) {
00268   return (llvm::findOneNVVMAnnotation(
00269       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_MAXNTID_Z], z));
00270 }
00271 
00272 bool llvm::getReqNTIDx(const Function &F, unsigned &x) {
00273   return (llvm::findOneNVVMAnnotation(
00274       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_REQNTID_X], x));
00275 }
00276 
00277 bool llvm::getReqNTIDy(const Function &F, unsigned &y) {
00278   return (llvm::findOneNVVMAnnotation(
00279       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_REQNTID_Y], y));
00280 }
00281 
00282 bool llvm::getReqNTIDz(const Function &F, unsigned &z) {
00283   return (llvm::findOneNVVMAnnotation(
00284       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_REQNTID_Z], z));
00285 }
00286 
00287 bool llvm::getMinCTASm(const Function &F, unsigned &x) {
00288   return (llvm::findOneNVVMAnnotation(
00289       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_MINNCTAPERSM], x));
00290 }
00291 
00292 bool llvm::isKernelFunction(const Function &F) {
00293   unsigned x = 0;
00294   bool retval = llvm::findOneNVVMAnnotation(
00295       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_ISKERNEL_FUNCTION], x);
00296   if (!retval) {
00297     // There is no NVVM metadata, check the calling convention
00298     return F.getCallingConv() == llvm::CallingConv::PTX_Kernel;
00299   }
00300   return (x == 1);
00301 }
00302 
00303 bool llvm::getAlign(const Function &F, unsigned index, unsigned &align) {
00304   std::vector<unsigned> Vs;
00305   bool retval = llvm::findAllNVVMAnnotation(
00306       &F, llvm::PropertyAnnotationNames[llvm::PROPERTY_ALIGN], Vs);
00307   if (!retval)
00308     return false;
00309   for (int i = 0, e = Vs.size(); i < e; i++) {
00310     unsigned v = Vs[i];
00311     if ((v >> 16) == index) {
00312       align = v & 0xFFFF;
00313       return true;
00314     }
00315   }
00316   return false;
00317 }
00318 
00319 bool llvm::getAlign(const CallInst &I, unsigned index, unsigned &align) {
00320   if (MDNode *alignNode = I.getMetadata("callalign")) {
00321     for (int i = 0, n = alignNode->getNumOperands(); i < n; i++) {
00322       if (const ConstantInt *CI =
00323               mdconst::dyn_extract<ConstantInt>(alignNode->getOperand(i))) {
00324         unsigned v = CI->getZExtValue();
00325         if ((v >> 16) == index) {
00326           align = v & 0xFFFF;
00327           return true;
00328         }
00329         if ((v >> 16) > index) {
00330           return false;
00331         }
00332       }
00333     }
00334   }
00335   return false;
00336 }
00337 
00338 bool llvm::isBarrierIntrinsic(Intrinsic::ID id) {
00339   if ((id == Intrinsic::nvvm_barrier0) ||
00340       (id == Intrinsic::nvvm_barrier0_popc) ||
00341       (id == Intrinsic::nvvm_barrier0_and) ||
00342       (id == Intrinsic::nvvm_barrier0_or) ||
00343       (id == Intrinsic::cuda_syncthreads))
00344     return true;
00345   return false;
00346 }
00347 
00348 // Interface for checking all memory space transfer related intrinsics
00349 bool llvm::isMemorySpaceTransferIntrinsic(Intrinsic::ID id) {
00350   if (id == Intrinsic::nvvm_ptr_local_to_gen ||
00351       id == Intrinsic::nvvm_ptr_shared_to_gen ||
00352       id == Intrinsic::nvvm_ptr_global_to_gen ||
00353       id == Intrinsic::nvvm_ptr_constant_to_gen ||
00354       id == Intrinsic::nvvm_ptr_gen_to_global ||
00355       id == Intrinsic::nvvm_ptr_gen_to_shared ||
00356       id == Intrinsic::nvvm_ptr_gen_to_local ||
00357       id == Intrinsic::nvvm_ptr_gen_to_constant ||
00358       id == Intrinsic::nvvm_ptr_gen_to_param) {
00359     return true;
00360   }
00361 
00362   return false;
00363 }
00364 
00365 // consider several special intrinsics in striping pointer casts, and
00366 // provide an option to ignore GEP indicies for find out the base address only
00367 // which could be used in simple alias disambigurate.
00368 const Value *
00369 llvm::skipPointerTransfer(const Value *V, bool ignore_GEP_indices) {
00370   V = V->stripPointerCasts();
00371   while (true) {
00372     if (const IntrinsicInst *IS = dyn_cast<IntrinsicInst>(V)) {
00373       if (isMemorySpaceTransferIntrinsic(IS->getIntrinsicID())) {
00374         V = IS->getArgOperand(0)->stripPointerCasts();
00375         continue;
00376       }
00377     } else if (ignore_GEP_indices)
00378       if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00379         V = GEP->getPointerOperand()->stripPointerCasts();
00380         continue;
00381       }
00382     break;
00383   }
00384   return V;
00385 }
00386 
00387 // consider several special intrinsics in striping pointer casts, and
00388 // - ignore GEP indicies for find out the base address only, and
00389 // - tracking PHINode
00390 // which could be used in simple alias disambigurate.
00391 const Value *
00392 llvm::skipPointerTransfer(const Value *V, std::set<const Value *> &processed) {
00393   if (processed.find(V) != processed.end())
00394     return nullptr;
00395   processed.insert(V);
00396 
00397   const Value *V2 = V->stripPointerCasts();
00398   if (V2 != V && processed.find(V2) != processed.end())
00399     return nullptr;
00400   processed.insert(V2);
00401 
00402   V = V2;
00403 
00404   while (true) {
00405     if (const IntrinsicInst *IS = dyn_cast<IntrinsicInst>(V)) {
00406       if (isMemorySpaceTransferIntrinsic(IS->getIntrinsicID())) {
00407         V = IS->getArgOperand(0)->stripPointerCasts();
00408         continue;
00409       }
00410     } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00411       V = GEP->getPointerOperand()->stripPointerCasts();
00412       continue;
00413     } else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
00414       if (V != V2 && processed.find(V) != processed.end())
00415         return nullptr;
00416       processed.insert(PN);
00417       const Value *common = nullptr;
00418       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
00419         const Value *pv = PN->getIncomingValue(i);
00420         const Value *base = skipPointerTransfer(pv, processed);
00421         if (base) {
00422           if (!common)
00423             common = base;
00424           else if (common != base)
00425             return PN;
00426         }
00427       }
00428       if (!common)
00429         return PN;
00430       V = common;
00431     }
00432     break;
00433   }
00434   return V;
00435 }
00436 
00437 // The following are some useful utilities for debuggung
00438 
00439 BasicBlock *llvm::getParentBlock(Value *v) {
00440   if (BasicBlock *B = dyn_cast<BasicBlock>(v))
00441     return B;
00442 
00443   if (Instruction *I = dyn_cast<Instruction>(v))
00444     return I->getParent();
00445 
00446   return nullptr;
00447 }
00448 
00449 Function *llvm::getParentFunction(Value *v) {
00450   if (Function *F = dyn_cast<Function>(v))
00451     return F;
00452 
00453   if (Instruction *I = dyn_cast<Instruction>(v))
00454     return I->getParent()->getParent();
00455 
00456   if (BasicBlock *B = dyn_cast<BasicBlock>(v))
00457     return B->getParent();
00458 
00459   return nullptr;
00460 }
00461 
00462 // Dump a block by name
00463 void llvm::dumpBlock(Value *v, char *blockName) {
00464   Function *F = getParentFunction(v);
00465   if (!F)
00466     return;
00467 
00468   for (Function::iterator it = F->begin(), ie = F->end(); it != ie; ++it) {
00469     BasicBlock *B = it;
00470     if (strcmp(B->getName().data(), blockName) == 0) {
00471       B->dump();
00472       return;
00473     }
00474   }
00475 }
00476 
00477 // Find an instruction by name
00478 Instruction *llvm::getInst(Value *base, char *instName) {
00479   Function *F = getParentFunction(base);
00480   if (!F)
00481     return nullptr;
00482 
00483   for (inst_iterator it = inst_begin(F), ie = inst_end(F); it != ie; ++it) {
00484     Instruction *I = &*it;
00485     if (strcmp(I->getName().data(), instName) == 0) {
00486       return I;
00487     }
00488   }
00489 
00490   return nullptr;
00491 }
00492 
00493 // Dump an instruction by nane
00494 void llvm::dumpInst(Value *base, char *instName) {
00495   Instruction *I = getInst(base, instName);
00496   if (I)
00497     I->dump();
00498 }
00499 
00500 // Dump an instruction and all dependent instructions
00501 void llvm::dumpInstRec(Value *v, std::set<Instruction *> *visited) {
00502   if (Instruction *I = dyn_cast<Instruction>(v)) {
00503 
00504     if (visited->find(I) != visited->end())
00505       return;
00506 
00507     visited->insert(I);
00508 
00509     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00510       dumpInstRec(I->getOperand(i), visited);
00511 
00512     I->dump();
00513   }
00514 }
00515 
00516 // Dump an instruction and all dependent instructions
00517 void llvm::dumpInstRec(Value *v) {
00518   std::set<Instruction *> visited;
00519 
00520   //BasicBlock *B = getParentBlock(v);
00521 
00522   dumpInstRec(v, &visited);
00523 }
00524 
00525 // Dump the parent for Instruction, block or function
00526 void llvm::dumpParent(Value *v) {
00527   if (Instruction *I = dyn_cast<Instruction>(v)) {
00528     I->getParent()->dump();
00529     return;
00530   }
00531 
00532   if (BasicBlock *B = dyn_cast<BasicBlock>(v)) {
00533     B->getParent()->dump();
00534     return;
00535   }
00536 
00537   if (Function *F = dyn_cast<Function>(v)) {
00538     F->getParent()->dump();
00539     return;
00540   }
00541 }