Function.cpp 35 KB

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