Function.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. //===-- Function.cpp - Implement the Global object classes ----------------===//
  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 file implements the Function class for the IR library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/Function.h"
  14. #include "LLVMContextImpl.h"
  15. #include "SymbolTableListTraitsImpl.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/CodeGen/ValueTypes.h"
  20. #include "llvm/IR/CallSite.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DerivedTypes.h"
  23. #include "llvm/IR/InstIterator.h"
  24. #include "llvm/IR/IntrinsicInst.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/MDBuilder.h"
  27. #include "llvm/IR/Metadata.h"
  28. #include "llvm/IR/Module.h"
  29. #include "dxc/HLSL/HLModule.h" // HLSL Change
  30. #include "dxc/HLSL/DxilModule.h" // HLSL Change
  31. #include "llvm/Support/ManagedStatic.h"
  32. #include "llvm/Support/RWMutex.h"
  33. #include "llvm/Support/StringPool.h"
  34. #include "llvm/Support/Threading.h"
  35. using namespace llvm;
  36. // Explicit instantiations of SymbolTableListTraits since some of the methods
  37. // are not in the public header file...
  38. template class llvm::SymbolTableListTraits<Argument, Function>;
  39. template class llvm::SymbolTableListTraits<BasicBlock, Function>;
  40. //===----------------------------------------------------------------------===//
  41. // Argument Implementation
  42. //===----------------------------------------------------------------------===//
  43. void Argument::anchor() { }
  44. Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
  45. : Value(Ty, Value::ArgumentVal) {
  46. Parent = nullptr;
  47. if (Par)
  48. Par->getArgumentList().push_back(this);
  49. setName(Name);
  50. }
  51. void Argument::setParent(Function *parent) {
  52. Parent = parent;
  53. }
  54. /// getArgNo - Return the index of this formal argument in its containing
  55. /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
  56. unsigned Argument::getArgNo() const {
  57. const Function *F = getParent();
  58. assert(F && "Argument is not in a function");
  59. Function::const_arg_iterator AI = F->arg_begin();
  60. unsigned ArgIdx = 0;
  61. for (; &*AI != this; ++AI)
  62. ++ArgIdx;
  63. return ArgIdx;
  64. }
  65. /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
  66. /// it in its containing function. Also returns true if at least one byte is
  67. /// known to be dereferenceable and the pointer is in addrspace(0).
  68. bool Argument::hasNonNullAttr() const {
  69. if (!getType()->isPointerTy()) return false;
  70. if (getParent()->getAttributes().
  71. hasAttribute(getArgNo()+1, Attribute::NonNull))
  72. return true;
  73. else if (getDereferenceableBytes() > 0 &&
  74. getType()->getPointerAddressSpace() == 0)
  75. return true;
  76. return false;
  77. }
  78. /// hasByValAttr - Return true if this argument has the byval attribute on it
  79. /// in its containing function.
  80. bool Argument::hasByValAttr() const {
  81. if (!getType()->isPointerTy()) return false;
  82. return getParent()->getAttributes().
  83. hasAttribute(getArgNo()+1, Attribute::ByVal);
  84. }
  85. /// \brief Return true if this argument has the inalloca attribute on it in
  86. /// its containing function.
  87. bool Argument::hasInAllocaAttr() const {
  88. if (!getType()->isPointerTy()) return false;
  89. return getParent()->getAttributes().
  90. hasAttribute(getArgNo()+1, Attribute::InAlloca);
  91. }
  92. bool Argument::hasByValOrInAllocaAttr() const {
  93. if (!getType()->isPointerTy()) return false;
  94. AttributeSet Attrs = getParent()->getAttributes();
  95. return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
  96. Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
  97. }
  98. unsigned Argument::getParamAlignment() const {
  99. assert(getType()->isPointerTy() && "Only pointers have alignments");
  100. return getParent()->getParamAlignment(getArgNo()+1);
  101. }
  102. uint64_t Argument::getDereferenceableBytes() const {
  103. assert(getType()->isPointerTy() &&
  104. "Only pointers have dereferenceable bytes");
  105. return getParent()->getDereferenceableBytes(getArgNo()+1);
  106. }
  107. uint64_t Argument::getDereferenceableOrNullBytes() const {
  108. assert(getType()->isPointerTy() &&
  109. "Only pointers have dereferenceable bytes");
  110. return getParent()->getDereferenceableOrNullBytes(getArgNo()+1);
  111. }
  112. /// hasNestAttr - Return true if this argument has the nest attribute on
  113. /// it in its containing function.
  114. bool Argument::hasNestAttr() const {
  115. if (!getType()->isPointerTy()) return false;
  116. return getParent()->getAttributes().
  117. hasAttribute(getArgNo()+1, Attribute::Nest);
  118. }
  119. /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
  120. /// it in its containing function.
  121. bool Argument::hasNoAliasAttr() const {
  122. if (!getType()->isPointerTy()) return false;
  123. return getParent()->getAttributes().
  124. hasAttribute(getArgNo()+1, Attribute::NoAlias);
  125. }
  126. /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
  127. /// on it in its containing function.
  128. bool Argument::hasNoCaptureAttr() const {
  129. if (!getType()->isPointerTy()) return false;
  130. return getParent()->getAttributes().
  131. hasAttribute(getArgNo()+1, Attribute::NoCapture);
  132. }
  133. /// hasSRetAttr - Return true if this argument has the sret attribute on
  134. /// it in its containing function.
  135. bool Argument::hasStructRetAttr() const {
  136. if (!getType()->isPointerTy()) return false;
  137. return getParent()->getAttributes().
  138. hasAttribute(getArgNo()+1, Attribute::StructRet);
  139. }
  140. /// hasReturnedAttr - Return true if this argument has the returned attribute on
  141. /// it in its containing function.
  142. bool Argument::hasReturnedAttr() const {
  143. return getParent()->getAttributes().
  144. hasAttribute(getArgNo()+1, Attribute::Returned);
  145. }
  146. /// hasZExtAttr - Return true if this argument has the zext attribute on it in
  147. /// its containing function.
  148. bool Argument::hasZExtAttr() const {
  149. return getParent()->getAttributes().
  150. hasAttribute(getArgNo()+1, Attribute::ZExt);
  151. }
  152. /// hasSExtAttr Return true if this argument has the sext attribute on it in its
  153. /// containing function.
  154. bool Argument::hasSExtAttr() const {
  155. return getParent()->getAttributes().
  156. hasAttribute(getArgNo()+1, Attribute::SExt);
  157. }
  158. /// Return true if this argument has the readonly or readnone attribute on it
  159. /// in its containing function.
  160. bool Argument::onlyReadsMemory() const {
  161. return getParent()->getAttributes().
  162. hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
  163. getParent()->getAttributes().
  164. hasAttribute(getArgNo()+1, Attribute::ReadNone);
  165. }
  166. /// addAttr - Add attributes to an argument.
  167. void Argument::addAttr(AttributeSet AS) {
  168. assert(AS.getNumSlots() <= 1 &&
  169. "Trying to add more than one attribute set to an argument!");
  170. AttrBuilder B(AS, AS.getSlotIndex(0));
  171. getParent()->addAttributes(getArgNo() + 1,
  172. AttributeSet::get(Parent->getContext(),
  173. getArgNo() + 1, B));
  174. }
  175. /// removeAttr - Remove attributes from an argument.
  176. void Argument::removeAttr(AttributeSet AS) {
  177. assert(AS.getNumSlots() <= 1 &&
  178. "Trying to remove more than one attribute set from an argument!");
  179. AttrBuilder B(AS, AS.getSlotIndex(0));
  180. getParent()->removeAttributes(getArgNo() + 1,
  181. AttributeSet::get(Parent->getContext(),
  182. getArgNo() + 1, B));
  183. }
  184. //===----------------------------------------------------------------------===//
  185. // Helper Methods in Function
  186. //===----------------------------------------------------------------------===//
  187. bool Function::isMaterializable() const {
  188. return getGlobalObjectSubClassData() & IsMaterializableBit;
  189. }
  190. void Function::setIsMaterializable(bool V) {
  191. setGlobalObjectBit(IsMaterializableBit, V);
  192. }
  193. LLVMContext &Function::getContext() const {
  194. return getType()->getContext();
  195. }
  196. FunctionType *Function::getFunctionType() const { return Ty; }
  197. bool Function::isVarArg() const {
  198. return getFunctionType()->isVarArg();
  199. }
  200. Type *Function::getReturnType() const {
  201. return getFunctionType()->getReturnType();
  202. }
  203. void Function::removeFromParent() {
  204. if (getParent()->HasHLModule()) getParent()->GetHLModule().RemoveFunction(this); // HLSL Change
  205. if (getParent()->HasDxilModule()) getParent()->GetDxilModule().RemoveFunction(this); // HLSL Change
  206. getParent()->getFunctionList().remove(this);
  207. }
  208. void Function::eraseFromParent() {
  209. if (getParent()->HasHLModule()) getParent()->GetHLModule().RemoveFunction(this); // HLSL Change
  210. if (getParent()->HasDxilModule()) getParent()->GetDxilModule().RemoveFunction(this); // HLSL Change
  211. getParent()->getFunctionList().erase(this);
  212. }
  213. //===----------------------------------------------------------------------===//
  214. // Function Implementation
  215. //===----------------------------------------------------------------------===//
  216. Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
  217. Module *ParentModule)
  218. : GlobalObject(PointerType::getUnqual(Ty), Value::FunctionVal,
  219. OperandTraits<Function>::op_begin(this), 0, Linkage, name),
  220. Ty(Ty) {
  221. assert(FunctionType::isValidReturnType(getReturnType()) &&
  222. "invalid return type");
  223. setGlobalObjectSubClassData(0);
  224. SymTab = new ValueSymbolTable();
  225. // If the function has arguments, mark them as lazily built.
  226. if (Ty->getNumParams())
  227. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  228. if (ParentModule)
  229. ParentModule->getFunctionList().push_back(this);
  230. // Ensure intrinsics have the right parameter attributes.
  231. // Note, the IntID field will have been set in Value::setName if this function
  232. // name is a valid intrinsic ID.
  233. if (IntID)
  234. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  235. }
  236. Function::~Function() {
  237. dropAllReferences(); // After this it is safe to delete instructions.
  238. // Delete all of the method arguments and unlink from symbol table...
  239. ArgumentList.clear();
  240. delete SymTab;
  241. // Remove the function from the on-the-side GC table.
  242. clearGC();
  243. // FIXME: needed by operator delete
  244. setFunctionNumOperands(1);
  245. }
  246. void Function::BuildLazyArguments() const {
  247. // Create the arguments vector, all arguments start out unnamed.
  248. FunctionType *FT = getFunctionType();
  249. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  250. assert(!FT->getParamType(i)->isVoidTy() &&
  251. "Cannot have void typed arguments!");
  252. ArgumentList.push_back(new Argument(FT->getParamType(i)));
  253. }
  254. // Clear the lazy arguments bit.
  255. unsigned SDC = getSubclassDataFromValue();
  256. const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
  257. }
  258. size_t Function::arg_size() const {
  259. return getFunctionType()->getNumParams();
  260. }
  261. bool Function::arg_empty() const {
  262. return getFunctionType()->getNumParams() == 0;
  263. }
  264. void Function::setParent(Module *parent) {
  265. Parent = parent;
  266. }
  267. // dropAllReferences() - This function causes all the subinstructions to "let
  268. // go" of all references that they are maintaining. This allows one to
  269. // 'delete' a whole class at a time, even though there may be circular
  270. // references... first all references are dropped, and all use counts go to
  271. // zero. Then everything is deleted for real. Note that no operations are
  272. // valid on an object that has "dropped all references", except operator
  273. // delete.
  274. //
  275. void Function::dropAllReferences() {
  276. setIsMaterializable(false);
  277. for (iterator I = begin(), E = end(); I != E; ++I)
  278. I->dropAllReferences();
  279. // Delete all basic blocks. They are now unused, except possibly by
  280. // blockaddresses, but BasicBlock's destructor takes care of those.
  281. while (!BasicBlocks.empty())
  282. BasicBlocks.begin()->eraseFromParent();
  283. // Prefix and prologue data are stored in a side table.
  284. setPrefixData(nullptr);
  285. setPrologueData(nullptr);
  286. // Metadata is stored in a side-table.
  287. clearMetadata();
  288. setPersonalityFn(nullptr);
  289. }
  290. void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
  291. AttributeSet PAL = getAttributes();
  292. PAL = PAL.addAttribute(getContext(), i, attr);
  293. setAttributes(PAL);
  294. }
  295. void Function::addAttributes(unsigned i, AttributeSet attrs) {
  296. AttributeSet PAL = getAttributes();
  297. PAL = PAL.addAttributes(getContext(), i, attrs);
  298. setAttributes(PAL);
  299. }
  300. void Function::removeAttributes(unsigned i, AttributeSet attrs) {
  301. AttributeSet PAL = getAttributes();
  302. PAL = PAL.removeAttributes(getContext(), i, attrs);
  303. setAttributes(PAL);
  304. }
  305. void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  306. AttributeSet PAL = getAttributes();
  307. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  308. setAttributes(PAL);
  309. }
  310. void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  311. AttributeSet PAL = getAttributes();
  312. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  313. setAttributes(PAL);
  314. }
  315. // Maintain the GC name for each function in an on-the-side table. This saves
  316. // allocating an additional word in Function for programs which do not use GC
  317. // (i.e., most programs) at the cost of increased overhead for clients which do
  318. // use GC.
  319. static DenseMap<const Function*,PooledStringPtr> *GCNames;
  320. static StringPool *GCNamePool;
  321. static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
  322. bool Function::hasGC() const {
  323. #if 0 // HLSL Change
  324. sys::SmartScopedReader<true> Reader(*GCLock);
  325. return GCNames && GCNames->count(this);
  326. #else
  327. return false;
  328. #endif // HLSL Change Ends
  329. }
  330. const char *Function::getGC() const {
  331. #if 0 // HLSL Change
  332. assert(hasGC() && "Function has no collector");
  333. sys::SmartScopedReader<true> Reader(*GCLock);
  334. return *(*GCNames)[this];
  335. #else
  336. return nullptr;
  337. #endif // HLSL Change Ends
  338. }
  339. void Function::setGC(const char *Str) {
  340. #if 0 // HLSL Change Starts
  341. sys::SmartScopedWriter<true> Writer(*GCLock);
  342. if (!GCNamePool)
  343. GCNamePool = new StringPool();
  344. if (!GCNames)
  345. GCNames = new DenseMap<const Function*,PooledStringPtr>();
  346. (*GCNames)[this] = GCNamePool->intern(Str);
  347. #else
  348. assert(false && "GC not supported");
  349. #endif // HLSL Change Ends
  350. }
  351. void Function::clearGC() {
  352. #if 0 // HLSL Change Starts
  353. sys::SmartScopedWriter<true> Writer(*GCLock);
  354. if (GCNames) {
  355. GCNames->erase(this);
  356. if (GCNames->empty()) {
  357. delete GCNames;
  358. GCNames = nullptr;
  359. if (GCNamePool->empty()) {
  360. delete GCNamePool;
  361. GCNamePool = nullptr;
  362. }
  363. }
  364. }
  365. #endif // HLSL Change Ends
  366. }
  367. /// copyAttributesFrom - copy all additional attributes (those not needed to
  368. /// create a Function) from the Function Src to this one.
  369. void Function::copyAttributesFrom(const GlobalValue *Src) {
  370. assert(isa<Function>(Src) && "Expected a Function!");
  371. GlobalObject::copyAttributesFrom(Src);
  372. const Function *SrcF = cast<Function>(Src);
  373. setCallingConv(SrcF->getCallingConv());
  374. setAttributes(SrcF->getAttributes());
  375. if (SrcF->hasGC())
  376. setGC(SrcF->getGC());
  377. else
  378. clearGC();
  379. if (SrcF->hasPrefixData())
  380. setPrefixData(SrcF->getPrefixData());
  381. else
  382. setPrefixData(nullptr);
  383. if (SrcF->hasPrologueData())
  384. setPrologueData(SrcF->getPrologueData());
  385. else
  386. setPrologueData(nullptr);
  387. if (SrcF->hasPersonalityFn())
  388. setPersonalityFn(SrcF->getPersonalityFn());
  389. else
  390. setPersonalityFn(nullptr);
  391. }
  392. /// \brief This does the actual lookup of an intrinsic ID which
  393. /// matches the given function name.
  394. static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
  395. unsigned Len = ValName->getKeyLength();
  396. const char *Name = ValName->getKeyData();
  397. #define GET_FUNCTION_RECOGNIZER
  398. #include "llvm/IR/Intrinsics.gen"
  399. #undef GET_FUNCTION_RECOGNIZER
  400. return Intrinsic::not_intrinsic;
  401. }
  402. void Function::recalculateIntrinsicID() {
  403. const ValueName *ValName = this->getValueName();
  404. if (!ValName || !isIntrinsic()) {
  405. IntID = Intrinsic::not_intrinsic;
  406. return;
  407. }
  408. IntID = lookupIntrinsicID(ValName);
  409. }
  410. /// Returns a stable mangling for the type specified for use in the name
  411. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  412. /// of named types is simply their name. Manglings for unnamed types consist
  413. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  414. /// combined with the mangling of their component types. A vararg function
  415. /// type will have a suffix of 'vararg'. Since function types can contain
  416. /// other function types, we close a function type mangling with suffix 'f'
  417. /// which can't be confused with it's prefix. This ensures we don't have
  418. /// collisions between two unrelated function types. Otherwise, you might
  419. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  420. /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
  421. /// cases) fall back to the MVT codepath, where they could be mangled to
  422. /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
  423. /// everything.
  424. static std::string getMangledTypeStr(Type* Ty) {
  425. std::string Result;
  426. if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
  427. Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
  428. getMangledTypeStr(PTyp->getElementType());
  429. } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
  430. Result += "a" + llvm::utostr(ATyp->getNumElements()) +
  431. getMangledTypeStr(ATyp->getElementType());
  432. } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
  433. assert(!STyp->isLiteral() && "TODO: implement literal types");
  434. Result += STyp->getName();
  435. } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
  436. Result += "f_" + getMangledTypeStr(FT->getReturnType());
  437. for (size_t i = 0; i < FT->getNumParams(); i++)
  438. Result += getMangledTypeStr(FT->getParamType(i));
  439. if (FT->isVarArg())
  440. Result += "vararg";
  441. // Ensure nested function types are distinguishable.
  442. Result += "f";
  443. } else if (Ty)
  444. Result += EVT::getEVT(Ty).getEVTString();
  445. return Result;
  446. }
  447. std::string Intrinsic::getName(_In_range_(0, num_intrinsics-1) ID id, ArrayRef<Type*> Tys) {
  448. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  449. static const char * const Table[] = {
  450. "not_intrinsic",
  451. #define GET_INTRINSIC_NAME_TABLE
  452. #include "llvm/IR/Intrinsics.gen"
  453. #undef GET_INTRINSIC_NAME_TABLE
  454. };
  455. if (Tys.empty())
  456. return Table[id];
  457. std::string Result(Table[id]);
  458. for (unsigned i = 0; i < Tys.size(); ++i) {
  459. Result += "." + getMangledTypeStr(Tys[i]);
  460. }
  461. return Result;
  462. }
  463. /// IIT_Info - These are enumerators that describe the entries returned by the
  464. /// getIntrinsicInfoTableEntries function.
  465. ///
  466. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  467. enum IIT_Info {
  468. // Common values should be encoded with 0-15.
  469. IIT_Done = 0,
  470. IIT_I1 = 1,
  471. IIT_I8 = 2,
  472. IIT_I16 = 3,
  473. IIT_I32 = 4,
  474. IIT_I64 = 5,
  475. IIT_F16 = 6,
  476. IIT_F32 = 7,
  477. IIT_F64 = 8,
  478. IIT_V2 = 9,
  479. IIT_V4 = 10,
  480. IIT_V8 = 11,
  481. IIT_V16 = 12,
  482. IIT_V32 = 13,
  483. IIT_PTR = 14,
  484. IIT_ARG = 15,
  485. // Values from 16+ are only encodable with the inefficient encoding.
  486. IIT_V64 = 16,
  487. IIT_MMX = 17,
  488. IIT_METADATA = 18,
  489. IIT_EMPTYSTRUCT = 19,
  490. IIT_STRUCT2 = 20,
  491. IIT_STRUCT3 = 21,
  492. IIT_STRUCT4 = 22,
  493. IIT_STRUCT5 = 23,
  494. IIT_EXTEND_ARG = 24,
  495. IIT_TRUNC_ARG = 25,
  496. IIT_ANYPTR = 26,
  497. IIT_V1 = 27,
  498. IIT_VARARG = 28,
  499. IIT_HALF_VEC_ARG = 29,
  500. IIT_SAME_VEC_WIDTH_ARG = 30,
  501. IIT_PTR_TO_ARG = 31,
  502. IIT_VEC_OF_PTRS_TO_ELT = 32,
  503. IIT_I128 = 33
  504. };
  505. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  506. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  507. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  508. unsigned StructElts = 2;
  509. using namespace Intrinsic;
  510. switch (Info) {
  511. case IIT_Done:
  512. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  513. return;
  514. case IIT_VARARG:
  515. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  516. return;
  517. case IIT_MMX:
  518. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  519. return;
  520. case IIT_METADATA:
  521. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  522. return;
  523. case IIT_F16:
  524. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  525. return;
  526. case IIT_F32:
  527. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  528. return;
  529. case IIT_F64:
  530. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  531. return;
  532. case IIT_I1:
  533. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  534. return;
  535. case IIT_I8:
  536. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  537. return;
  538. case IIT_I16:
  539. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  540. return;
  541. case IIT_I32:
  542. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  543. return;
  544. case IIT_I64:
  545. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  546. return;
  547. case IIT_I128:
  548. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
  549. return;
  550. case IIT_V1:
  551. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
  552. DecodeIITType(NextElt, Infos, OutputTable);
  553. return;
  554. case IIT_V2:
  555. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
  556. DecodeIITType(NextElt, Infos, OutputTable);
  557. return;
  558. case IIT_V4:
  559. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
  560. DecodeIITType(NextElt, Infos, OutputTable);
  561. return;
  562. case IIT_V8:
  563. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
  564. DecodeIITType(NextElt, Infos, OutputTable);
  565. return;
  566. case IIT_V16:
  567. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
  568. DecodeIITType(NextElt, Infos, OutputTable);
  569. return;
  570. case IIT_V32:
  571. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
  572. DecodeIITType(NextElt, Infos, OutputTable);
  573. return;
  574. case IIT_V64:
  575. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
  576. DecodeIITType(NextElt, Infos, OutputTable);
  577. return;
  578. case IIT_PTR:
  579. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  580. DecodeIITType(NextElt, Infos, OutputTable);
  581. return;
  582. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  583. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  584. Infos[NextElt++]));
  585. DecodeIITType(NextElt, Infos, OutputTable);
  586. return;
  587. }
  588. case IIT_ARG: {
  589. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  590. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  591. return;
  592. }
  593. case IIT_EXTEND_ARG: {
  594. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  595. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  596. ArgInfo));
  597. return;
  598. }
  599. case IIT_TRUNC_ARG: {
  600. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  601. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  602. ArgInfo));
  603. return;
  604. }
  605. case IIT_HALF_VEC_ARG: {
  606. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  607. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  608. ArgInfo));
  609. return;
  610. }
  611. case IIT_SAME_VEC_WIDTH_ARG: {
  612. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  613. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  614. ArgInfo));
  615. return;
  616. }
  617. case IIT_PTR_TO_ARG: {
  618. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  619. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  620. ArgInfo));
  621. return;
  622. }
  623. case IIT_VEC_OF_PTRS_TO_ELT: {
  624. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  625. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
  626. ArgInfo));
  627. return;
  628. }
  629. case IIT_EMPTYSTRUCT:
  630. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  631. return;
  632. case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
  633. case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
  634. case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
  635. case IIT_STRUCT2: {
  636. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  637. for (unsigned i = 0; i != StructElts; ++i)
  638. DecodeIITType(NextElt, Infos, OutputTable);
  639. return;
  640. }
  641. }
  642. llvm_unreachable("unhandled");
  643. }
  644. #define GET_INTRINSIC_GENERATOR_GLOBAL
  645. #include "llvm/IR/Intrinsics.gen"
  646. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  647. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  648. SmallVectorImpl<IITDescriptor> &T){
  649. // Check to see if the intrinsic's type was expressible by the table.
  650. unsigned TableVal = IIT_Table[id-1];
  651. // Decode the TableVal into an array of IITValues.
  652. SmallVector<unsigned char, 8> IITValues;
  653. ArrayRef<unsigned char> IITEntries;
  654. unsigned NextElt = 0;
  655. if ((TableVal >> 31) != 0) {
  656. // This is an offset into the IIT_LongEncodingTable.
  657. IITEntries = IIT_LongEncodingTable;
  658. // Strip sentinel bit.
  659. NextElt = (TableVal << 1) >> 1;
  660. } else {
  661. // Decode the TableVal into an array of IITValues. If the entry was encoded
  662. // into a single word in the table itself, decode it now.
  663. do {
  664. IITValues.push_back(TableVal & 0xF);
  665. TableVal >>= 4;
  666. } while (TableVal);
  667. IITEntries = IITValues;
  668. NextElt = 0;
  669. }
  670. // Okay, decode the table into the output vector of IITDescriptors.
  671. DecodeIITType(NextElt, IITEntries, T);
  672. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  673. DecodeIITType(NextElt, IITEntries, T);
  674. }
  675. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  676. ArrayRef<Type*> Tys, LLVMContext &Context) {
  677. using namespace Intrinsic;
  678. IITDescriptor D = Infos.front();
  679. Infos = Infos.slice(1);
  680. switch (D.Kind) {
  681. case IITDescriptor::Void: return Type::getVoidTy(Context);
  682. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  683. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  684. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  685. case IITDescriptor::Half: return Type::getHalfTy(Context);
  686. case IITDescriptor::Float: return Type::getFloatTy(Context);
  687. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  688. case IITDescriptor::Integer:
  689. return IntegerType::get(Context, D.Integer_Width);
  690. case IITDescriptor::Vector:
  691. return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
  692. case IITDescriptor::Pointer:
  693. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  694. D.Pointer_AddressSpace);
  695. case IITDescriptor::Struct: {
  696. Type *Elts[5];
  697. assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
  698. for (unsigned i = 0, e = D.Struct_NumElements; i != e && i < _countof(Elts); ++i) // HLSL Change - add extra check to help SAL
  699. Elts[i] = DecodeFixedType(Infos, Tys, Context);
  700. return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
  701. }
  702. case IITDescriptor::Argument:
  703. return Tys[D.getArgumentNumber()];
  704. case IITDescriptor::ExtendArgument: {
  705. Type *Ty = Tys[D.getArgumentNumber()];
  706. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  707. return VectorType::getExtendedElementVectorType(VTy);
  708. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  709. }
  710. case IITDescriptor::TruncArgument: {
  711. Type *Ty = Tys[D.getArgumentNumber()];
  712. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  713. return VectorType::getTruncatedElementVectorType(VTy);
  714. IntegerType *ITy = cast<IntegerType>(Ty);
  715. assert(ITy->getBitWidth() % 2 == 0);
  716. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  717. }
  718. case IITDescriptor::HalfVecArgument:
  719. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  720. Tys[D.getArgumentNumber()]));
  721. case IITDescriptor::SameVecWidthArgument: {
  722. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  723. Type *Ty = Tys[D.getArgumentNumber()];
  724. if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  725. return VectorType::get(EltTy, VTy->getNumElements());
  726. }
  727. llvm_unreachable("unhandled");
  728. }
  729. case IITDescriptor::PtrToArgument: {
  730. Type *Ty = Tys[D.getArgumentNumber()];
  731. return PointerType::getUnqual(Ty);
  732. }
  733. case IITDescriptor::VecOfPtrsToElt: {
  734. Type *Ty = Tys[D.getArgumentNumber()];
  735. VectorType *VTy = dyn_cast<VectorType>(Ty);
  736. if (!VTy)
  737. llvm_unreachable("Expected an argument of Vector Type");
  738. Type *EltTy = VTy->getVectorElementType();
  739. return VectorType::get(PointerType::getUnqual(EltTy),
  740. VTy->getNumElements());
  741. }
  742. }
  743. llvm_unreachable("unhandled");
  744. }
  745. FunctionType *Intrinsic::getType(LLVMContext &Context,
  746. ID id, ArrayRef<Type*> Tys) {
  747. SmallVector<IITDescriptor, 8> Table;
  748. getIntrinsicInfoTableEntries(id, Table);
  749. ArrayRef<IITDescriptor> TableRef = Table;
  750. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  751. SmallVector<Type*, 8> ArgTys;
  752. while (!TableRef.empty())
  753. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  754. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  755. // If we see void type as the type of the last argument, it is vararg intrinsic
  756. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  757. ArgTys.pop_back();
  758. return FunctionType::get(ResultTy, ArgTys, true);
  759. }
  760. return FunctionType::get(ResultTy, ArgTys, false);
  761. }
  762. bool Intrinsic::isOverloaded(ID id) {
  763. #define GET_INTRINSIC_OVERLOAD_TABLE
  764. #include "llvm/IR/Intrinsics.gen"
  765. #undef GET_INTRINSIC_OVERLOAD_TABLE
  766. }
  767. bool Intrinsic::isLeaf(ID id) {
  768. switch (id) {
  769. default:
  770. return true;
  771. case Intrinsic::experimental_gc_statepoint:
  772. case Intrinsic::experimental_patchpoint_void:
  773. case Intrinsic::experimental_patchpoint_i64:
  774. return false;
  775. }
  776. }
  777. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  778. #define GET_INTRINSIC_ATTRIBUTES
  779. #include "llvm/IR/Intrinsics.gen"
  780. #undef GET_INTRINSIC_ATTRIBUTES
  781. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  782. // There can never be multiple globals with the same name of different types,
  783. // because intrinsics must be a specific type.
  784. return
  785. cast<Function>(M->getOrInsertFunction(getName(id, Tys),
  786. getType(M->getContext(), id, Tys)));
  787. }
  788. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  789. //#pragma optimize("", off) // HLSL Change - comment out pragma optimize directive
  790. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  791. #include "llvm/IR/Intrinsics.gen"
  792. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  793. //#pragma optimize("", on) // HLSL Change - comment out pragma optimize directive
  794. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  795. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  796. #include "llvm/IR/Intrinsics.gen"
  797. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  798. /// hasAddressTaken - returns true if there are any uses of this function
  799. /// other than direct calls or invokes to it.
  800. bool Function::hasAddressTaken(const User* *PutOffender) const {
  801. for (const Use &U : uses()) {
  802. const User *FU = U.getUser();
  803. if (isa<BlockAddress>(FU))
  804. continue;
  805. if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
  806. return PutOffender ? (*PutOffender = FU, true) : true;
  807. ImmutableCallSite CS(cast<Instruction>(FU));
  808. if (!CS.isCallee(&U))
  809. return PutOffender ? (*PutOffender = FU, true) : true;
  810. }
  811. return false;
  812. }
  813. bool Function::isDefTriviallyDead() const {
  814. // Check the linkage
  815. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  816. !hasAvailableExternallyLinkage())
  817. return false;
  818. // Check if the function is used by anything other than a blockaddress.
  819. for (const User *U : users())
  820. if (!isa<BlockAddress>(U))
  821. return false;
  822. return true;
  823. }
  824. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  825. /// setjmp or other function that gcc recognizes as "returning twice".
  826. bool Function::callsFunctionThatReturnsTwice() const {
  827. for (const_inst_iterator
  828. I = inst_begin(this), E = inst_end(this); I != E; ++I) {
  829. ImmutableCallSite CS(&*I);
  830. if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
  831. return true;
  832. }
  833. return false;
  834. }
  835. Constant *Function::getPrefixData() const {
  836. assert(hasPrefixData());
  837. const LLVMContextImpl::PrefixDataMapTy &PDMap =
  838. getContext().pImpl->PrefixDataMap;
  839. assert(PDMap.find(this) != PDMap.end());
  840. return cast<Constant>(PDMap.find(this)->second->getReturnValue());
  841. }
  842. void Function::setPrefixData(Constant *PrefixData) {
  843. if (!PrefixData && !hasPrefixData())
  844. return;
  845. unsigned SCData = getSubclassDataFromValue();
  846. LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
  847. ReturnInst *&PDHolder = PDMap[this];
  848. if (PrefixData) {
  849. if (PDHolder)
  850. PDHolder->setOperand(0, PrefixData);
  851. else
  852. PDHolder = ReturnInst::Create(getContext(), PrefixData);
  853. SCData |= (1<<1);
  854. } else {
  855. delete PDHolder;
  856. PDMap.erase(this);
  857. SCData &= ~(1<<1);
  858. }
  859. setValueSubclassData(SCData);
  860. }
  861. Constant *Function::getPrologueData() const {
  862. assert(hasPrologueData());
  863. const LLVMContextImpl::PrologueDataMapTy &SOMap =
  864. getContext().pImpl->PrologueDataMap;
  865. assert(SOMap.find(this) != SOMap.end());
  866. return cast<Constant>(SOMap.find(this)->second->getReturnValue());
  867. }
  868. void Function::setPrologueData(Constant *PrologueData) {
  869. if (!PrologueData && !hasPrologueData())
  870. return;
  871. unsigned PDData = getSubclassDataFromValue();
  872. LLVMContextImpl::PrologueDataMapTy &PDMap = getContext().pImpl->PrologueDataMap;
  873. ReturnInst *&PDHolder = PDMap[this];
  874. if (PrologueData) {
  875. if (PDHolder)
  876. PDHolder->setOperand(0, PrologueData);
  877. else
  878. PDHolder = ReturnInst::Create(getContext(), PrologueData);
  879. PDData |= (1<<2);
  880. } else {
  881. delete PDHolder;
  882. PDMap.erase(this);
  883. PDData &= ~(1<<2);
  884. }
  885. setValueSubclassData(PDData);
  886. }
  887. void Function::setEntryCount(uint64_t Count) {
  888. MDBuilder MDB(getContext());
  889. setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
  890. }
  891. Optional<uint64_t> Function::getEntryCount() const {
  892. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  893. if (MD && MD->getOperand(0))
  894. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  895. if (MDS->getString().equals("function_entry_count")) {
  896. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  897. return CI->getValue().getZExtValue();
  898. }
  899. return None;
  900. }
  901. void Function::setPersonalityFn(Constant *C) {
  902. if (!C) {
  903. if (hasPersonalityFn()) {
  904. // Note, the num operands is used to compute the offset of the operand, so
  905. // the order here matters. Clearing the operand then clearing the num
  906. // operands ensures we have the correct offset to the operand.
  907. Op<0>().set(nullptr);
  908. setFunctionNumOperands(0);
  909. }
  910. } else {
  911. // Note, the num operands is used to compute the offset of the operand, so
  912. // the order here matters. We need to set num operands to 1 first so that
  913. // we get the correct offset to the first operand when we set it.
  914. if (!hasPersonalityFn())
  915. setFunctionNumOperands(1);
  916. Op<0>().set(C);
  917. }
  918. }