Function.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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 "LLVMContextImpl.h"
  14. #include "SymbolTableListTraitsImpl.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/CodeGen/ValueTypes.h"
  24. #include "llvm/IR/Argument.h"
  25. #include "llvm/IR/Attributes.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/CallSite.h"
  28. #include "llvm/IR/Constant.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Function.h"
  32. #include "llvm/IR/GlobalValue.h"
  33. #include "llvm/IR/InstIterator.h"
  34. #include "llvm/IR/Instruction.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. #include "llvm/IR/LLVMContext.h"
  39. #include "llvm/IR/MDBuilder.h"
  40. #include "llvm/IR/Metadata.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/IR/SymbolTableListTraits.h"
  43. #include "llvm/IR/Type.h"
  44. #include "llvm/IR/Use.h"
  45. #include "llvm/IR/User.h"
  46. #include "llvm/IR/Value.h"
  47. #include "llvm/IR/ValueSymbolTable.h"
  48. #include "llvm/Support/Casting.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/ErrorHandling.h"
  51. #include <algorithm>
  52. #include <cassert>
  53. #include <cstddef>
  54. #include <cstdint>
  55. #include <cstring>
  56. #include <string>
  57. using namespace llvm;
  58. // Explicit instantiations of SymbolTableListTraits since some of the methods
  59. // are not in the public header file...
  60. template class llvm::SymbolTableListTraits<BasicBlock>;
  61. //===----------------------------------------------------------------------===//
  62. // Argument Implementation
  63. //===----------------------------------------------------------------------===//
  64. void Argument::anchor() {}
  65. Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
  66. : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
  67. setName(Name);
  68. }
  69. void Argument::setParent(Function *parent) {
  70. Parent = parent;
  71. }
  72. bool Argument::hasNonNullAttr() const {
  73. if (!getType()->isPointerTy()) return false;
  74. if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
  75. return true;
  76. else if (getDereferenceableBytes() > 0 &&
  77. getType()->getPointerAddressSpace() == 0)
  78. return true;
  79. return false;
  80. }
  81. bool Argument::hasByValAttr() const {
  82. if (!getType()->isPointerTy()) return false;
  83. return hasAttribute(Attribute::ByVal);
  84. }
  85. bool Argument::hasSwiftSelfAttr() const {
  86. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
  87. }
  88. bool Argument::hasSwiftErrorAttr() const {
  89. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
  90. }
  91. bool Argument::hasInAllocaAttr() const {
  92. if (!getType()->isPointerTy()) return false;
  93. return hasAttribute(Attribute::InAlloca);
  94. }
  95. bool Argument::hasByValOrInAllocaAttr() const {
  96. if (!getType()->isPointerTy()) return false;
  97. AttributeList Attrs = getParent()->getAttributes();
  98. return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
  99. Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca);
  100. }
  101. unsigned Argument::getParamAlignment() const {
  102. assert(getType()->isPointerTy() && "Only pointers have alignments");
  103. return getParent()->getParamAlignment(getArgNo());
  104. }
  105. uint64_t Argument::getDereferenceableBytes() const {
  106. assert(getType()->isPointerTy() &&
  107. "Only pointers have dereferenceable bytes");
  108. return getParent()->getDereferenceableBytes(getArgNo() +
  109. AttributeList::FirstArgIndex);
  110. }
  111. uint64_t Argument::getDereferenceableOrNullBytes() const {
  112. assert(getType()->isPointerTy() &&
  113. "Only pointers have dereferenceable bytes");
  114. return getParent()->getDereferenceableOrNullBytes(
  115. getArgNo() + AttributeList::FirstArgIndex);
  116. }
  117. bool Argument::hasNestAttr() const {
  118. if (!getType()->isPointerTy()) return false;
  119. return hasAttribute(Attribute::Nest);
  120. }
  121. bool Argument::hasNoAliasAttr() const {
  122. if (!getType()->isPointerTy()) return false;
  123. return hasAttribute(Attribute::NoAlias);
  124. }
  125. bool Argument::hasNoCaptureAttr() const {
  126. if (!getType()->isPointerTy()) return false;
  127. return hasAttribute(Attribute::NoCapture);
  128. }
  129. bool Argument::hasStructRetAttr() const {
  130. if (!getType()->isPointerTy()) return false;
  131. return hasAttribute(Attribute::StructRet);
  132. }
  133. bool Argument::hasReturnedAttr() const {
  134. return hasAttribute(Attribute::Returned);
  135. }
  136. bool Argument::hasZExtAttr() const {
  137. return hasAttribute(Attribute::ZExt);
  138. }
  139. bool Argument::hasSExtAttr() const {
  140. return hasAttribute(Attribute::SExt);
  141. }
  142. bool Argument::onlyReadsMemory() const {
  143. AttributeList Attrs = getParent()->getAttributes();
  144. return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
  145. Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
  146. }
  147. void Argument::addAttrs(AttrBuilder &B) {
  148. AttributeList AL = getParent()->getAttributes();
  149. AL = AL.addAttributes(Parent->getContext(),
  150. getArgNo() + AttributeList::FirstArgIndex, B);
  151. getParent()->setAttributes(AL);
  152. }
  153. void Argument::addAttr(Attribute::AttrKind Kind) {
  154. getParent()->addAttribute(getArgNo() + AttributeList::FirstArgIndex, Kind);
  155. }
  156. void Argument::addAttr(Attribute Attr) {
  157. getParent()->addAttribute(getArgNo() + AttributeList::FirstArgIndex, Attr);
  158. }
  159. void Argument::removeAttr(Attribute::AttrKind Kind) {
  160. getParent()->removeAttribute(getArgNo() + AttributeList::FirstArgIndex, Kind);
  161. }
  162. bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
  163. return getParent()->hasParamAttribute(getArgNo(), Kind);
  164. }
  165. //===----------------------------------------------------------------------===//
  166. // Helper Methods in Function
  167. //===----------------------------------------------------------------------===//
  168. LLVMContext &Function::getContext() const {
  169. return getType()->getContext();
  170. }
  171. void Function::removeFromParent() {
  172. getParent()->getFunctionList().remove(getIterator());
  173. }
  174. void Function::eraseFromParent() {
  175. getParent()->getFunctionList().erase(getIterator());
  176. }
  177. //===----------------------------------------------------------------------===//
  178. // Function Implementation
  179. //===----------------------------------------------------------------------===//
  180. Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
  181. Module *ParentModule)
  182. : GlobalObject(Ty, Value::FunctionVal,
  183. OperandTraits<Function>::op_begin(this), 0, Linkage, name),
  184. NumArgs(Ty->getNumParams()) {
  185. assert(FunctionType::isValidReturnType(getReturnType()) &&
  186. "invalid return type");
  187. setGlobalObjectSubClassData(0);
  188. // We only need a symbol table for a function if the context keeps value names
  189. if (!getContext().shouldDiscardValueNames())
  190. SymTab = make_unique<ValueSymbolTable>();
  191. // If the function has arguments, mark them as lazily built.
  192. if (Ty->getNumParams())
  193. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  194. if (ParentModule)
  195. ParentModule->getFunctionList().push_back(this);
  196. HasLLVMReservedName = getName().startswith("llvm.");
  197. // Ensure intrinsics have the right parameter attributes.
  198. // Note, the IntID field will have been set in Value::setName if this function
  199. // name is a valid intrinsic ID.
  200. if (IntID)
  201. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  202. }
  203. Function::~Function() {
  204. dropAllReferences(); // After this it is safe to delete instructions.
  205. // Delete all of the method arguments and unlink from symbol table...
  206. if (Arguments)
  207. clearArguments();
  208. // Remove the function from the on-the-side GC table.
  209. clearGC();
  210. }
  211. void Function::BuildLazyArguments() const {
  212. // Create the arguments vector, all arguments start out unnamed.
  213. auto *FT = getFunctionType();
  214. if (NumArgs > 0) {
  215. Arguments = std::allocator<Argument>().allocate(NumArgs);
  216. for (unsigned i = 0, e = NumArgs; i != e; ++i) {
  217. Type *ArgTy = FT->getParamType(i);
  218. assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
  219. new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
  220. }
  221. }
  222. // Clear the lazy arguments bit.
  223. unsigned SDC = getSubclassDataFromValue();
  224. const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
  225. assert(!hasLazyArguments());
  226. }
  227. static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
  228. return MutableArrayRef<Argument>(Args, Count);
  229. }
  230. void Function::clearArguments() {
  231. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  232. A.setName("");
  233. A.~Argument();
  234. }
  235. std::allocator<Argument>().deallocate(Arguments, NumArgs);
  236. Arguments = nullptr;
  237. }
  238. void Function::stealArgumentListFrom(Function &Src) {
  239. assert(isDeclaration() && "Expected no references to current arguments");
  240. // Drop the current arguments, if any, and set the lazy argument bit.
  241. if (!hasLazyArguments()) {
  242. assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
  243. [](const Argument &A) { return A.use_empty(); }) &&
  244. "Expected arguments to be unused in declaration");
  245. clearArguments();
  246. setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
  247. }
  248. // Nothing to steal if Src has lazy arguments.
  249. if (Src.hasLazyArguments())
  250. return;
  251. // Steal arguments from Src, and fix the lazy argument bits.
  252. assert(arg_size() == Src.arg_size());
  253. Arguments = Src.Arguments;
  254. Src.Arguments = nullptr;
  255. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  256. // FIXME: This does the work of transferNodesFromList inefficiently.
  257. SmallString<128> Name;
  258. if (A.hasName())
  259. Name = A.getName();
  260. if (!Name.empty())
  261. A.setName("");
  262. A.setParent(this);
  263. if (!Name.empty())
  264. A.setName(Name);
  265. }
  266. setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
  267. assert(!hasLazyArguments());
  268. Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
  269. }
  270. // dropAllReferences() - This function causes all the subinstructions to "let
  271. // go" of all references that they are maintaining. This allows one to
  272. // 'delete' a whole class at a time, even though there may be circular
  273. // references... first all references are dropped, and all use counts go to
  274. // zero. Then everything is deleted for real. Note that no operations are
  275. // valid on an object that has "dropped all references", except operator
  276. // delete.
  277. //
  278. void Function::dropAllReferences() {
  279. setIsMaterializable(false);
  280. for (BasicBlock &BB : *this)
  281. BB.dropAllReferences();
  282. // Delete all basic blocks. They are now unused, except possibly by
  283. // blockaddresses, but BasicBlock's destructor takes care of those.
  284. while (!BasicBlocks.empty())
  285. BasicBlocks.begin()->eraseFromParent();
  286. // Drop uses of any optional data (real or placeholder).
  287. if (getNumOperands()) {
  288. User::dropAllReferences();
  289. setNumHungOffUseOperands(0);
  290. setValueSubclassData(getSubclassDataFromValue() & ~0xe);
  291. }
  292. // Metadata is stored in a side-table.
  293. clearMetadata();
  294. }
  295. void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
  296. AttributeList PAL = getAttributes();
  297. PAL = PAL.addAttribute(getContext(), i, Kind);
  298. setAttributes(PAL);
  299. }
  300. void Function::addAttribute(unsigned i, Attribute Attr) {
  301. AttributeList PAL = getAttributes();
  302. PAL = PAL.addAttribute(getContext(), i, Attr);
  303. setAttributes(PAL);
  304. }
  305. void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
  306. AttributeList PAL = getAttributes();
  307. PAL = PAL.addAttributes(getContext(), i, Attrs);
  308. setAttributes(PAL);
  309. }
  310. void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
  311. AttributeList PAL = getAttributes();
  312. PAL = PAL.removeAttribute(getContext(), i, Kind);
  313. setAttributes(PAL);
  314. }
  315. void Function::removeAttribute(unsigned i, StringRef Kind) {
  316. AttributeList PAL = getAttributes();
  317. PAL = PAL.removeAttribute(getContext(), i, Kind);
  318. setAttributes(PAL);
  319. }
  320. void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
  321. AttributeList PAL = getAttributes();
  322. PAL = PAL.removeAttributes(getContext(), i, Attrs);
  323. setAttributes(PAL);
  324. }
  325. void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  326. AttributeList PAL = getAttributes();
  327. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  328. setAttributes(PAL);
  329. }
  330. void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  331. AttributeList PAL = getAttributes();
  332. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  333. setAttributes(PAL);
  334. }
  335. const std::string &Function::getGC() const {
  336. assert(hasGC() && "Function has no collector");
  337. return getContext().getGC(*this);
  338. }
  339. void Function::setGC(std::string Str) {
  340. setValueSubclassDataBit(14, !Str.empty());
  341. getContext().setGC(*this, std::move(Str));
  342. }
  343. void Function::clearGC() {
  344. if (!hasGC())
  345. return;
  346. getContext().deleteGC(*this);
  347. setValueSubclassDataBit(14, false);
  348. }
  349. /// Copy all additional attributes (those not needed to create a Function) from
  350. /// the Function Src to this one.
  351. void Function::copyAttributesFrom(const Function *Src) {
  352. GlobalObject::copyAttributesFrom(Src);
  353. setCallingConv(Src->getCallingConv());
  354. setAttributes(Src->getAttributes());
  355. if (Src->hasGC())
  356. setGC(Src->getGC());
  357. else
  358. clearGC();
  359. if (Src->hasPersonalityFn())
  360. setPersonalityFn(Src->getPersonalityFn());
  361. if (Src->hasPrefixData())
  362. setPrefixData(Src->getPrefixData());
  363. if (Src->hasPrologueData())
  364. setPrologueData(Src->getPrologueData());
  365. }
  366. /// Table of string intrinsic names indexed by enum value.
  367. static const char * const IntrinsicNameTable[] = {
  368. "not_intrinsic",
  369. #define GET_INTRINSIC_NAME_TABLE
  370. #include "llvm/IR/Intrinsics.gen"
  371. #undef GET_INTRINSIC_NAME_TABLE
  372. };
  373. /// Table of per-target intrinsic name tables.
  374. #define GET_INTRINSIC_TARGET_DATA
  375. #include "llvm/IR/Intrinsics.gen"
  376. #undef GET_INTRINSIC_TARGET_DATA
  377. /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
  378. /// target as \c Name, or the generic table if \c Name is not target specific.
  379. ///
  380. /// Returns the relevant slice of \c IntrinsicNameTable
  381. static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
  382. assert(Name.startswith("llvm."));
  383. ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
  384. // Drop "llvm." and take the first dotted component. That will be the target
  385. // if this is target specific.
  386. StringRef Target = Name.drop_front(5).split('.').first;
  387. auto It = std::lower_bound(Targets.begin(), Targets.end(), Target,
  388. [](const IntrinsicTargetInfo &TI,
  389. StringRef Target) { return TI.Name < Target; });
  390. // We've either found the target or just fall back to the generic set, which
  391. // is always first.
  392. const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
  393. return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
  394. }
  395. /// \brief This does the actual lookup of an intrinsic ID which
  396. /// matches the given function name.
  397. Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
  398. ArrayRef<const char *> NameTable = findTargetSubtable(Name);
  399. int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
  400. if (Idx == -1)
  401. return Intrinsic::not_intrinsic;
  402. // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
  403. // an index into a sub-table.
  404. int Adjust = NameTable.data() - IntrinsicNameTable;
  405. Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
  406. // If the intrinsic is not overloaded, require an exact match. If it is
  407. // overloaded, require a prefix match.
  408. bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]);
  409. return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
  410. }
  411. void Function::recalculateIntrinsicID() {
  412. StringRef Name = getName();
  413. if (!Name.startswith("llvm.")) {
  414. HasLLVMReservedName = false;
  415. IntID = Intrinsic::not_intrinsic;
  416. return;
  417. }
  418. HasLLVMReservedName = true;
  419. IntID = lookupIntrinsicID(Name);
  420. }
  421. /// Returns a stable mangling for the type specified for use in the name
  422. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  423. /// of named types is simply their name. Manglings for unnamed types consist
  424. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  425. /// combined with the mangling of their component types. A vararg function
  426. /// type will have a suffix of 'vararg'. Since function types can contain
  427. /// other function types, we close a function type mangling with suffix 'f'
  428. /// which can't be confused with it's prefix. This ensures we don't have
  429. /// collisions between two unrelated function types. Otherwise, you might
  430. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  431. /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
  432. /// cases) fall back to the MVT codepath, where they could be mangled to
  433. /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
  434. /// everything.
  435. static std::string getMangledTypeStr(Type* Ty) {
  436. std::string Result;
  437. if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
  438. Result += "p" + utostr(PTyp->getAddressSpace()) +
  439. getMangledTypeStr(PTyp->getElementType());
  440. } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
  441. Result += "a" + utostr(ATyp->getNumElements()) +
  442. getMangledTypeStr(ATyp->getElementType());
  443. } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
  444. if (!STyp->isLiteral()) {
  445. Result += "s_";
  446. Result += STyp->getName();
  447. } else {
  448. Result += "sl_";
  449. for (auto Elem : STyp->elements())
  450. Result += getMangledTypeStr(Elem);
  451. }
  452. // Ensure nested structs are distinguishable.
  453. Result += "s";
  454. } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
  455. Result += "f_" + getMangledTypeStr(FT->getReturnType());
  456. for (size_t i = 0; i < FT->getNumParams(); i++)
  457. Result += getMangledTypeStr(FT->getParamType(i));
  458. if (FT->isVarArg())
  459. Result += "vararg";
  460. // Ensure nested function types are distinguishable.
  461. Result += "f";
  462. } else if (isa<VectorType>(Ty))
  463. Result += "v" + utostr(Ty->getVectorNumElements()) +
  464. getMangledTypeStr(Ty->getVectorElementType());
  465. else if (Ty)
  466. Result += EVT::getEVT(Ty).getEVTString();
  467. return Result;
  468. }
  469. StringRef Intrinsic::getName(ID id) {
  470. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  471. assert(!isOverloaded(id) &&
  472. "This version of getName does not support overloading");
  473. return IntrinsicNameTable[id];
  474. }
  475. std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
  476. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  477. std::string Result(IntrinsicNameTable[id]);
  478. for (Type *Ty : Tys) {
  479. Result += "." + getMangledTypeStr(Ty);
  480. }
  481. return Result;
  482. }
  483. /// IIT_Info - These are enumerators that describe the entries returned by the
  484. /// getIntrinsicInfoTableEntries function.
  485. ///
  486. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  487. enum IIT_Info {
  488. // Common values should be encoded with 0-15.
  489. IIT_Done = 0,
  490. IIT_I1 = 1,
  491. IIT_I8 = 2,
  492. IIT_I16 = 3,
  493. IIT_I32 = 4,
  494. IIT_I64 = 5,
  495. IIT_F16 = 6,
  496. IIT_F32 = 7,
  497. IIT_F64 = 8,
  498. IIT_V2 = 9,
  499. IIT_V4 = 10,
  500. IIT_V8 = 11,
  501. IIT_V16 = 12,
  502. IIT_V32 = 13,
  503. IIT_PTR = 14,
  504. IIT_ARG = 15,
  505. // Values from 16+ are only encodable with the inefficient encoding.
  506. IIT_V64 = 16,
  507. IIT_MMX = 17,
  508. IIT_TOKEN = 18,
  509. IIT_METADATA = 19,
  510. IIT_EMPTYSTRUCT = 20,
  511. IIT_STRUCT2 = 21,
  512. IIT_STRUCT3 = 22,
  513. IIT_STRUCT4 = 23,
  514. IIT_STRUCT5 = 24,
  515. IIT_EXTEND_ARG = 25,
  516. IIT_TRUNC_ARG = 26,
  517. IIT_ANYPTR = 27,
  518. IIT_V1 = 28,
  519. IIT_VARARG = 29,
  520. IIT_HALF_VEC_ARG = 30,
  521. IIT_SAME_VEC_WIDTH_ARG = 31,
  522. IIT_PTR_TO_ARG = 32,
  523. IIT_PTR_TO_ELT = 33,
  524. IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
  525. IIT_I128 = 35,
  526. IIT_V512 = 36,
  527. IIT_V1024 = 37
  528. };
  529. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  530. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  531. using namespace Intrinsic;
  532. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  533. unsigned StructElts = 2;
  534. switch (Info) {
  535. case IIT_Done:
  536. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  537. return;
  538. case IIT_VARARG:
  539. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  540. return;
  541. case IIT_MMX:
  542. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  543. return;
  544. case IIT_TOKEN:
  545. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
  546. return;
  547. case IIT_METADATA:
  548. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  549. return;
  550. case IIT_F16:
  551. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  552. return;
  553. case IIT_F32:
  554. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  555. return;
  556. case IIT_F64:
  557. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  558. return;
  559. case IIT_I1:
  560. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  561. return;
  562. case IIT_I8:
  563. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  564. return;
  565. case IIT_I16:
  566. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  567. return;
  568. case IIT_I32:
  569. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  570. return;
  571. case IIT_I64:
  572. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  573. return;
  574. case IIT_I128:
  575. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
  576. return;
  577. case IIT_V1:
  578. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
  579. DecodeIITType(NextElt, Infos, OutputTable);
  580. return;
  581. case IIT_V2:
  582. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
  583. DecodeIITType(NextElt, Infos, OutputTable);
  584. return;
  585. case IIT_V4:
  586. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
  587. DecodeIITType(NextElt, Infos, OutputTable);
  588. return;
  589. case IIT_V8:
  590. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
  591. DecodeIITType(NextElt, Infos, OutputTable);
  592. return;
  593. case IIT_V16:
  594. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
  595. DecodeIITType(NextElt, Infos, OutputTable);
  596. return;
  597. case IIT_V32:
  598. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
  599. DecodeIITType(NextElt, Infos, OutputTable);
  600. return;
  601. case IIT_V64:
  602. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
  603. DecodeIITType(NextElt, Infos, OutputTable);
  604. return;
  605. case IIT_V512:
  606. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
  607. DecodeIITType(NextElt, Infos, OutputTable);
  608. return;
  609. case IIT_V1024:
  610. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
  611. DecodeIITType(NextElt, Infos, OutputTable);
  612. return;
  613. case IIT_PTR:
  614. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  615. DecodeIITType(NextElt, Infos, OutputTable);
  616. return;
  617. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  618. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  619. Infos[NextElt++]));
  620. DecodeIITType(NextElt, Infos, OutputTable);
  621. return;
  622. }
  623. case IIT_ARG: {
  624. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  625. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  626. return;
  627. }
  628. case IIT_EXTEND_ARG: {
  629. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  630. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  631. ArgInfo));
  632. return;
  633. }
  634. case IIT_TRUNC_ARG: {
  635. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  636. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  637. ArgInfo));
  638. return;
  639. }
  640. case IIT_HALF_VEC_ARG: {
  641. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  642. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  643. ArgInfo));
  644. return;
  645. }
  646. case IIT_SAME_VEC_WIDTH_ARG: {
  647. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  648. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  649. ArgInfo));
  650. return;
  651. }
  652. case IIT_PTR_TO_ARG: {
  653. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  654. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  655. ArgInfo));
  656. return;
  657. }
  658. case IIT_PTR_TO_ELT: {
  659. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  660. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
  661. return;
  662. }
  663. case IIT_VEC_OF_ANYPTRS_TO_ELT: {
  664. unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  665. unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  666. OutputTable.push_back(
  667. IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
  668. return;
  669. }
  670. case IIT_EMPTYSTRUCT:
  671. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  672. return;
  673. case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
  674. case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
  675. case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
  676. case IIT_STRUCT2: {
  677. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  678. for (unsigned i = 0; i != StructElts; ++i)
  679. DecodeIITType(NextElt, Infos, OutputTable);
  680. return;
  681. }
  682. }
  683. llvm_unreachable("unhandled");
  684. }
  685. #define GET_INTRINSIC_GENERATOR_GLOBAL
  686. #include "llvm/IR/Intrinsics.gen"
  687. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  688. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  689. SmallVectorImpl<IITDescriptor> &T){
  690. // Check to see if the intrinsic's type was expressible by the table.
  691. unsigned TableVal = IIT_Table[id-1];
  692. // Decode the TableVal into an array of IITValues.
  693. SmallVector<unsigned char, 8> IITValues;
  694. ArrayRef<unsigned char> IITEntries;
  695. unsigned NextElt = 0;
  696. if ((TableVal >> 31) != 0) {
  697. // This is an offset into the IIT_LongEncodingTable.
  698. IITEntries = IIT_LongEncodingTable;
  699. // Strip sentinel bit.
  700. NextElt = (TableVal << 1) >> 1;
  701. } else {
  702. // Decode the TableVal into an array of IITValues. If the entry was encoded
  703. // into a single word in the table itself, decode it now.
  704. do {
  705. IITValues.push_back(TableVal & 0xF);
  706. TableVal >>= 4;
  707. } while (TableVal);
  708. IITEntries = IITValues;
  709. NextElt = 0;
  710. }
  711. // Okay, decode the table into the output vector of IITDescriptors.
  712. DecodeIITType(NextElt, IITEntries, T);
  713. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  714. DecodeIITType(NextElt, IITEntries, T);
  715. }
  716. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  717. ArrayRef<Type*> Tys, LLVMContext &Context) {
  718. using namespace Intrinsic;
  719. IITDescriptor D = Infos.front();
  720. Infos = Infos.slice(1);
  721. switch (D.Kind) {
  722. case IITDescriptor::Void: return Type::getVoidTy(Context);
  723. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  724. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  725. case IITDescriptor::Token: return Type::getTokenTy(Context);
  726. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  727. case IITDescriptor::Half: return Type::getHalfTy(Context);
  728. case IITDescriptor::Float: return Type::getFloatTy(Context);
  729. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  730. case IITDescriptor::Integer:
  731. return IntegerType::get(Context, D.Integer_Width);
  732. case IITDescriptor::Vector:
  733. return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
  734. case IITDescriptor::Pointer:
  735. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  736. D.Pointer_AddressSpace);
  737. case IITDescriptor::Struct: {
  738. Type *Elts[5];
  739. assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
  740. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  741. Elts[i] = DecodeFixedType(Infos, Tys, Context);
  742. return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
  743. }
  744. case IITDescriptor::Argument:
  745. return Tys[D.getArgumentNumber()];
  746. case IITDescriptor::ExtendArgument: {
  747. Type *Ty = Tys[D.getArgumentNumber()];
  748. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  749. return VectorType::getExtendedElementVectorType(VTy);
  750. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  751. }
  752. case IITDescriptor::TruncArgument: {
  753. Type *Ty = Tys[D.getArgumentNumber()];
  754. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  755. return VectorType::getTruncatedElementVectorType(VTy);
  756. IntegerType *ITy = cast<IntegerType>(Ty);
  757. assert(ITy->getBitWidth() % 2 == 0);
  758. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  759. }
  760. case IITDescriptor::HalfVecArgument:
  761. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  762. Tys[D.getArgumentNumber()]));
  763. case IITDescriptor::SameVecWidthArgument: {
  764. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  765. Type *Ty = Tys[D.getArgumentNumber()];
  766. if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  767. return VectorType::get(EltTy, VTy->getNumElements());
  768. }
  769. llvm_unreachable("unhandled");
  770. }
  771. case IITDescriptor::PtrToArgument: {
  772. Type *Ty = Tys[D.getArgumentNumber()];
  773. return PointerType::getUnqual(Ty);
  774. }
  775. case IITDescriptor::PtrToElt: {
  776. Type *Ty = Tys[D.getArgumentNumber()];
  777. VectorType *VTy = dyn_cast<VectorType>(Ty);
  778. if (!VTy)
  779. llvm_unreachable("Expected an argument of Vector Type");
  780. Type *EltTy = VTy->getVectorElementType();
  781. return PointerType::getUnqual(EltTy);
  782. }
  783. case IITDescriptor::VecOfAnyPtrsToElt:
  784. // Return the overloaded type (which determines the pointers address space)
  785. return Tys[D.getOverloadArgNumber()];
  786. }
  787. llvm_unreachable("unhandled");
  788. }
  789. FunctionType *Intrinsic::getType(LLVMContext &Context,
  790. ID id, ArrayRef<Type*> Tys) {
  791. SmallVector<IITDescriptor, 8> Table;
  792. getIntrinsicInfoTableEntries(id, Table);
  793. ArrayRef<IITDescriptor> TableRef = Table;
  794. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  795. SmallVector<Type*, 8> ArgTys;
  796. while (!TableRef.empty())
  797. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  798. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  799. // If we see void type as the type of the last argument, it is vararg intrinsic
  800. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  801. ArgTys.pop_back();
  802. return FunctionType::get(ResultTy, ArgTys, true);
  803. }
  804. return FunctionType::get(ResultTy, ArgTys, false);
  805. }
  806. bool Intrinsic::isOverloaded(ID id) {
  807. #define GET_INTRINSIC_OVERLOAD_TABLE
  808. #include "llvm/IR/Intrinsics.gen"
  809. #undef GET_INTRINSIC_OVERLOAD_TABLE
  810. }
  811. bool Intrinsic::isLeaf(ID id) {
  812. switch (id) {
  813. default:
  814. return true;
  815. case Intrinsic::experimental_gc_statepoint:
  816. case Intrinsic::experimental_patchpoint_void:
  817. case Intrinsic::experimental_patchpoint_i64:
  818. return false;
  819. }
  820. }
  821. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  822. #define GET_INTRINSIC_ATTRIBUTES
  823. #include "llvm/IR/Intrinsics.gen"
  824. #undef GET_INTRINSIC_ATTRIBUTES
  825. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  826. // There can never be multiple globals with the same name of different types,
  827. // because intrinsics must be a specific type.
  828. return
  829. cast<Function>(M->getOrInsertFunction(getName(id, Tys),
  830. getType(M->getContext(), id, Tys)));
  831. }
  832. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  833. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  834. #include "llvm/IR/Intrinsics.gen"
  835. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  836. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  837. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  838. #include "llvm/IR/Intrinsics.gen"
  839. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  840. bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
  841. SmallVectorImpl<Type*> &ArgTys) {
  842. using namespace Intrinsic;
  843. // If we ran out of descriptors, there are too many arguments.
  844. if (Infos.empty()) return true;
  845. IITDescriptor D = Infos.front();
  846. Infos = Infos.slice(1);
  847. switch (D.Kind) {
  848. case IITDescriptor::Void: return !Ty->isVoidTy();
  849. case IITDescriptor::VarArg: return true;
  850. case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
  851. case IITDescriptor::Token: return !Ty->isTokenTy();
  852. case IITDescriptor::Metadata: return !Ty->isMetadataTy();
  853. case IITDescriptor::Half: return !Ty->isHalfTy();
  854. case IITDescriptor::Float: return !Ty->isFloatTy();
  855. case IITDescriptor::Double: return !Ty->isDoubleTy();
  856. case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
  857. case IITDescriptor::Vector: {
  858. VectorType *VT = dyn_cast<VectorType>(Ty);
  859. return !VT || VT->getNumElements() != D.Vector_Width ||
  860. matchIntrinsicType(VT->getElementType(), Infos, ArgTys);
  861. }
  862. case IITDescriptor::Pointer: {
  863. PointerType *PT = dyn_cast<PointerType>(Ty);
  864. return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
  865. matchIntrinsicType(PT->getElementType(), Infos, ArgTys);
  866. }
  867. case IITDescriptor::Struct: {
  868. StructType *ST = dyn_cast<StructType>(Ty);
  869. if (!ST || ST->getNumElements() != D.Struct_NumElements)
  870. return true;
  871. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  872. if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys))
  873. return true;
  874. return false;
  875. }
  876. case IITDescriptor::Argument:
  877. // Two cases here - If this is the second occurrence of an argument, verify
  878. // that the later instance matches the previous instance.
  879. if (D.getArgumentNumber() < ArgTys.size())
  880. return Ty != ArgTys[D.getArgumentNumber()];
  881. // Otherwise, if this is the first instance of an argument, record it and
  882. // verify the "Any" kind.
  883. assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
  884. ArgTys.push_back(Ty);
  885. switch (D.getArgumentKind()) {
  886. case IITDescriptor::AK_Any: return false; // Success
  887. case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
  888. case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
  889. case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
  890. case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
  891. }
  892. llvm_unreachable("all argument kinds not covered");
  893. case IITDescriptor::ExtendArgument: {
  894. // This may only be used when referring to a previous vector argument.
  895. if (D.getArgumentNumber() >= ArgTys.size())
  896. return true;
  897. Type *NewTy = ArgTys[D.getArgumentNumber()];
  898. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  899. NewTy = VectorType::getExtendedElementVectorType(VTy);
  900. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  901. NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
  902. else
  903. return true;
  904. return Ty != NewTy;
  905. }
  906. case IITDescriptor::TruncArgument: {
  907. // This may only be used when referring to a previous vector argument.
  908. if (D.getArgumentNumber() >= ArgTys.size())
  909. return true;
  910. Type *NewTy = ArgTys[D.getArgumentNumber()];
  911. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  912. NewTy = VectorType::getTruncatedElementVectorType(VTy);
  913. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  914. NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
  915. else
  916. return true;
  917. return Ty != NewTy;
  918. }
  919. case IITDescriptor::HalfVecArgument:
  920. // This may only be used when referring to a previous vector argument.
  921. return D.getArgumentNumber() >= ArgTys.size() ||
  922. !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
  923. VectorType::getHalfElementsVectorType(
  924. cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
  925. case IITDescriptor::SameVecWidthArgument: {
  926. if (D.getArgumentNumber() >= ArgTys.size())
  927. return true;
  928. VectorType * ReferenceType =
  929. dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  930. VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
  931. if (!ThisArgType || !ReferenceType ||
  932. (ReferenceType->getVectorNumElements() !=
  933. ThisArgType->getVectorNumElements()))
  934. return true;
  935. return matchIntrinsicType(ThisArgType->getVectorElementType(),
  936. Infos, ArgTys);
  937. }
  938. case IITDescriptor::PtrToArgument: {
  939. if (D.getArgumentNumber() >= ArgTys.size())
  940. return true;
  941. Type * ReferenceType = ArgTys[D.getArgumentNumber()];
  942. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  943. return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
  944. }
  945. case IITDescriptor::PtrToElt: {
  946. if (D.getArgumentNumber() >= ArgTys.size())
  947. return true;
  948. VectorType * ReferenceType =
  949. dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
  950. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  951. return (!ThisArgType || !ReferenceType ||
  952. ThisArgType->getElementType() != ReferenceType->getElementType());
  953. }
  954. case IITDescriptor::VecOfAnyPtrsToElt: {
  955. unsigned RefArgNumber = D.getRefArgNumber();
  956. // This may only be used when referring to a previous argument.
  957. if (RefArgNumber >= ArgTys.size())
  958. return true;
  959. // Record the overloaded type
  960. assert(D.getOverloadArgNumber() == ArgTys.size() &&
  961. "Table consistency error");
  962. ArgTys.push_back(Ty);
  963. // Verify the overloaded type "matches" the Ref type.
  964. // i.e. Ty is a vector with the same width as Ref.
  965. // Composed of pointers to the same element type as Ref.
  966. VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
  967. VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  968. if (!ThisArgVecTy || !ReferenceType ||
  969. (ReferenceType->getVectorNumElements() !=
  970. ThisArgVecTy->getVectorNumElements()))
  971. return true;
  972. PointerType *ThisArgEltTy =
  973. dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
  974. if (!ThisArgEltTy)
  975. return true;
  976. return ThisArgEltTy->getElementType() !=
  977. ReferenceType->getVectorElementType();
  978. }
  979. }
  980. llvm_unreachable("unhandled");
  981. }
  982. bool
  983. Intrinsic::matchIntrinsicVarArg(bool isVarArg,
  984. ArrayRef<Intrinsic::IITDescriptor> &Infos) {
  985. // If there are no descriptors left, then it can't be a vararg.
  986. if (Infos.empty())
  987. return isVarArg;
  988. // There should be only one descriptor remaining at this point.
  989. if (Infos.size() != 1)
  990. return true;
  991. // Check and verify the descriptor.
  992. IITDescriptor D = Infos.front();
  993. Infos = Infos.slice(1);
  994. if (D.Kind == IITDescriptor::VarArg)
  995. return !isVarArg;
  996. return true;
  997. }
  998. Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
  999. Intrinsic::ID ID = F->getIntrinsicID();
  1000. if (!ID)
  1001. return None;
  1002. FunctionType *FTy = F->getFunctionType();
  1003. // Accumulate an array of overloaded types for the given intrinsic
  1004. SmallVector<Type *, 4> ArgTys;
  1005. {
  1006. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  1007. getIntrinsicInfoTableEntries(ID, Table);
  1008. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  1009. // If we encounter any problems matching the signature with the descriptor
  1010. // just give up remangling. It's up to verifier to report the discrepancy.
  1011. if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys))
  1012. return None;
  1013. for (auto Ty : FTy->params())
  1014. if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys))
  1015. return None;
  1016. if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
  1017. return None;
  1018. }
  1019. StringRef Name = F->getName();
  1020. if (Name == Intrinsic::getName(ID, ArgTys))
  1021. return None;
  1022. auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
  1023. NewDecl->setCallingConv(F->getCallingConv());
  1024. assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
  1025. return NewDecl;
  1026. }
  1027. /// hasAddressTaken - returns true if there are any uses of this function
  1028. /// other than direct calls or invokes to it.
  1029. bool Function::hasAddressTaken(const User* *PutOffender) const {
  1030. for (const Use &U : uses()) {
  1031. const User *FU = U.getUser();
  1032. if (isa<BlockAddress>(FU))
  1033. continue;
  1034. if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) {
  1035. if (PutOffender)
  1036. *PutOffender = FU;
  1037. return true;
  1038. }
  1039. ImmutableCallSite CS(cast<Instruction>(FU));
  1040. if (!CS.isCallee(&U)) {
  1041. if (PutOffender)
  1042. *PutOffender = FU;
  1043. return true;
  1044. }
  1045. }
  1046. return false;
  1047. }
  1048. bool Function::isDefTriviallyDead() const {
  1049. // Check the linkage
  1050. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  1051. !hasAvailableExternallyLinkage())
  1052. return false;
  1053. // Check if the function is used by anything other than a blockaddress.
  1054. for (const User *U : users())
  1055. if (!isa<BlockAddress>(U))
  1056. return false;
  1057. return true;
  1058. }
  1059. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  1060. /// setjmp or other function that gcc recognizes as "returning twice".
  1061. bool Function::callsFunctionThatReturnsTwice() const {
  1062. for (const_inst_iterator
  1063. I = inst_begin(this), E = inst_end(this); I != E; ++I) {
  1064. ImmutableCallSite CS(&*I);
  1065. if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
  1066. return true;
  1067. }
  1068. return false;
  1069. }
  1070. Constant *Function::getPersonalityFn() const {
  1071. assert(hasPersonalityFn() && getNumOperands());
  1072. return cast<Constant>(Op<0>());
  1073. }
  1074. void Function::setPersonalityFn(Constant *Fn) {
  1075. setHungoffOperand<0>(Fn);
  1076. setValueSubclassDataBit(3, Fn != nullptr);
  1077. }
  1078. Constant *Function::getPrefixData() const {
  1079. assert(hasPrefixData() && getNumOperands());
  1080. return cast<Constant>(Op<1>());
  1081. }
  1082. void Function::setPrefixData(Constant *PrefixData) {
  1083. setHungoffOperand<1>(PrefixData);
  1084. setValueSubclassDataBit(1, PrefixData != nullptr);
  1085. }
  1086. Constant *Function::getPrologueData() const {
  1087. assert(hasPrologueData() && getNumOperands());
  1088. return cast<Constant>(Op<2>());
  1089. }
  1090. void Function::setPrologueData(Constant *PrologueData) {
  1091. setHungoffOperand<2>(PrologueData);
  1092. setValueSubclassDataBit(2, PrologueData != nullptr);
  1093. }
  1094. void Function::allocHungoffUselist() {
  1095. // If we've already allocated a uselist, stop here.
  1096. if (getNumOperands())
  1097. return;
  1098. allocHungoffUses(3, /*IsPhi=*/ false);
  1099. setNumHungOffUseOperands(3);
  1100. // Initialize the uselist with placeholder operands to allow traversal.
  1101. auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
  1102. Op<0>().set(CPN);
  1103. Op<1>().set(CPN);
  1104. Op<2>().set(CPN);
  1105. }
  1106. template <int Idx>
  1107. void Function::setHungoffOperand(Constant *C) {
  1108. if (C) {
  1109. allocHungoffUselist();
  1110. Op<Idx>().set(C);
  1111. } else if (getNumOperands()) {
  1112. Op<Idx>().set(
  1113. ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
  1114. }
  1115. }
  1116. void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
  1117. assert(Bit < 16 && "SubclassData contains only 16 bits");
  1118. if (On)
  1119. setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
  1120. else
  1121. setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
  1122. }
  1123. void Function::setEntryCount(uint64_t Count,
  1124. const DenseSet<GlobalValue::GUID> *S) {
  1125. MDBuilder MDB(getContext());
  1126. setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count, S));
  1127. }
  1128. Optional<uint64_t> Function::getEntryCount() const {
  1129. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  1130. if (MD && MD->getOperand(0))
  1131. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  1132. if (MDS->getString().equals("function_entry_count")) {
  1133. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1134. uint64_t Count = CI->getValue().getZExtValue();
  1135. if (Count == 0)
  1136. return None;
  1137. return Count;
  1138. }
  1139. return None;
  1140. }
  1141. DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
  1142. DenseSet<GlobalValue::GUID> R;
  1143. if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
  1144. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  1145. if (MDS->getString().equals("function_entry_count"))
  1146. for (unsigned i = 2; i < MD->getNumOperands(); i++)
  1147. R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
  1148. ->getValue()
  1149. .getZExtValue());
  1150. return R;
  1151. }
  1152. void Function::setSectionPrefix(StringRef Prefix) {
  1153. MDBuilder MDB(getContext());
  1154. setMetadata(LLVMContext::MD_section_prefix,
  1155. MDB.createFunctionSectionPrefix(Prefix));
  1156. }
  1157. Optional<StringRef> Function::getSectionPrefix() const {
  1158. if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
  1159. assert(dyn_cast<MDString>(MD->getOperand(0))
  1160. ->getString()
  1161. .equals("function_section_prefix") &&
  1162. "Metadata not match");
  1163. return dyn_cast<MDString>(MD->getOperand(1))->getString();
  1164. }
  1165. return None;
  1166. }