IntrinsicEmitter.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This tablegen backend emits information about intrinsic functions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenIntrinsics.h"
  13. #include "CodeGenTarget.h"
  14. #include "SequenceToOffsetTable.h"
  15. #include "TableGenBackends.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/Support/CommandLine.h"
  18. #include "llvm/TableGen/Error.h"
  19. #include "llvm/TableGen/Record.h"
  20. #include "llvm/TableGen/StringToOffsetTable.h"
  21. #include "llvm/TableGen/TableGenBackend.h"
  22. #include <algorithm>
  23. using namespace llvm;
  24. cl::OptionCategory GenIntrinsicCat("Options for -gen-intrinsic-enums");
  25. cl::opt<std::string>
  26. IntrinsicPrefix("intrinsic-prefix",
  27. cl::desc("Generate intrinsics with this target prefix"),
  28. cl::value_desc("target prefix"), cl::cat(GenIntrinsicCat));
  29. namespace {
  30. class IntrinsicEmitter {
  31. RecordKeeper &Records;
  32. public:
  33. IntrinsicEmitter(RecordKeeper &R) : Records(R) {}
  34. void run(raw_ostream &OS, bool Enums);
  35. void EmitEnumInfo(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
  36. void EmitTargetInfo(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
  37. void EmitIntrinsicToNameTable(const CodeGenIntrinsicTable &Ints,
  38. raw_ostream &OS);
  39. void EmitIntrinsicToOverloadTable(const CodeGenIntrinsicTable &Ints,
  40. raw_ostream &OS);
  41. void EmitGenerator(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
  42. void EmitAttributes(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
  43. void EmitIntrinsicToBuiltinMap(const CodeGenIntrinsicTable &Ints, bool IsClang,
  44. raw_ostream &OS);
  45. };
  46. } // End anonymous namespace
  47. //===----------------------------------------------------------------------===//
  48. // IntrinsicEmitter Implementation
  49. //===----------------------------------------------------------------------===//
  50. void IntrinsicEmitter::run(raw_ostream &OS, bool Enums) {
  51. emitSourceFileHeader("Intrinsic Function Source Fragment", OS);
  52. CodeGenIntrinsicTable Ints(Records);
  53. if (Enums) {
  54. // Emit the enum information.
  55. EmitEnumInfo(Ints, OS);
  56. } else {
  57. // Emit the target metadata.
  58. EmitTargetInfo(Ints, OS);
  59. // Emit the intrinsic ID -> name table.
  60. EmitIntrinsicToNameTable(Ints, OS);
  61. // Emit the intrinsic ID -> overload table.
  62. EmitIntrinsicToOverloadTable(Ints, OS);
  63. // Emit the intrinsic declaration generator.
  64. EmitGenerator(Ints, OS);
  65. // Emit the intrinsic parameter attributes.
  66. EmitAttributes(Ints, OS);
  67. // Emit code to translate GCC builtins into LLVM intrinsics.
  68. EmitIntrinsicToBuiltinMap(Ints, true, OS);
  69. // Emit code to translate MS builtins into LLVM intrinsics.
  70. EmitIntrinsicToBuiltinMap(Ints, false, OS);
  71. }
  72. }
  73. void IntrinsicEmitter::EmitEnumInfo(const CodeGenIntrinsicTable &Ints,
  74. raw_ostream &OS) {
  75. // Find the TargetSet for which to generate enums. There will be an initial
  76. // set with an empty target prefix which will include target independent
  77. // intrinsics like dbg.value.
  78. const CodeGenIntrinsicTable::TargetSet *Set = nullptr;
  79. for (const auto &Target : Ints.Targets) {
  80. if (Target.Name == IntrinsicPrefix) {
  81. Set = &Target;
  82. break;
  83. }
  84. }
  85. if (!Set) {
  86. std::vector<std::string> KnownTargets;
  87. for (const auto &Target : Ints.Targets)
  88. if (!Target.Name.empty())
  89. KnownTargets.push_back(Target.Name);
  90. PrintFatalError("tried to generate intrinsics for unknown target " +
  91. IntrinsicPrefix +
  92. "\nKnown targets are: " + join(KnownTargets, ", ") + "\n");
  93. }
  94. // Generate a complete header for target specific intrinsics.
  95. if (!IntrinsicPrefix.empty()) {
  96. std::string UpperPrefix = StringRef(IntrinsicPrefix).upper();
  97. OS << "#ifndef LLVM_IR_INTRINSIC_" << UpperPrefix << "_ENUMS_H\n";
  98. OS << "#define LLVM_IR_INTRINSIC_" << UpperPrefix << "_ENUMS_H\n\n";
  99. OS << "namespace llvm {\n";
  100. OS << "namespace Intrinsic {\n";
  101. OS << "enum " << UpperPrefix << "Intrinsics : unsigned {\n";
  102. }
  103. OS << "// Enum values for intrinsics\n";
  104. for (unsigned i = Set->Offset, e = Set->Offset + Set->Count; i != e; ++i) {
  105. OS << " " << Ints[i].EnumName;
  106. // Assign a value to the first intrinsic in this target set so that all
  107. // intrinsic ids are distinct.
  108. if (i == Set->Offset)
  109. OS << " = " << (Set->Offset + 1);
  110. OS << ", ";
  111. if (Ints[i].EnumName.size() < 40)
  112. OS.indent(40 - Ints[i].EnumName.size());
  113. OS << " // " << Ints[i].Name << "\n";
  114. }
  115. // Emit num_intrinsics into the target neutral enum.
  116. if (IntrinsicPrefix.empty()) {
  117. OS << " num_intrinsics = " << (Ints.size() + 1) << "\n";
  118. } else {
  119. OS << "}; // enum\n";
  120. OS << "} // namespace Intrinsic\n";
  121. OS << "} // namespace llvm\n\n";
  122. OS << "#endif\n";
  123. }
  124. }
  125. void IntrinsicEmitter::EmitTargetInfo(const CodeGenIntrinsicTable &Ints,
  126. raw_ostream &OS) {
  127. OS << "// Target mapping\n";
  128. OS << "#ifdef GET_INTRINSIC_TARGET_DATA\n";
  129. OS << "struct IntrinsicTargetInfo {\n"
  130. << " llvm::StringLiteral Name;\n"
  131. << " size_t Offset;\n"
  132. << " size_t Count;\n"
  133. << "};\n";
  134. OS << "static constexpr IntrinsicTargetInfo TargetInfos[] = {\n";
  135. for (auto Target : Ints.Targets)
  136. OS << " {llvm::StringLiteral(\"" << Target.Name << "\"), " << Target.Offset
  137. << ", " << Target.Count << "},\n";
  138. OS << "};\n";
  139. OS << "#endif\n\n";
  140. }
  141. void IntrinsicEmitter::EmitIntrinsicToNameTable(
  142. const CodeGenIntrinsicTable &Ints, raw_ostream &OS) {
  143. OS << "// Intrinsic ID to name table\n";
  144. OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
  145. OS << " // Note that entry #0 is the invalid intrinsic!\n";
  146. for (unsigned i = 0, e = Ints.size(); i != e; ++i)
  147. OS << " \"" << Ints[i].Name << "\",\n";
  148. OS << "#endif\n\n";
  149. }
  150. void IntrinsicEmitter::EmitIntrinsicToOverloadTable(
  151. const CodeGenIntrinsicTable &Ints, raw_ostream &OS) {
  152. OS << "// Intrinsic ID to overload bitset\n";
  153. OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
  154. OS << "static const uint8_t OTable[] = {\n";
  155. OS << " 0";
  156. for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
  157. // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
  158. if ((i+1)%8 == 0)
  159. OS << ",\n 0";
  160. if (Ints[i].isOverloaded)
  161. OS << " | (1<<" << (i+1)%8 << ')';
  162. }
  163. OS << "\n};\n\n";
  164. // OTable contains a true bit at the position if the intrinsic is overloaded.
  165. OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
  166. OS << "#endif\n\n";
  167. }
  168. // NOTE: This must be kept in synch with the copy in lib/IR/Function.cpp!
  169. enum IIT_Info {
  170. // Common values should be encoded with 0-15.
  171. IIT_Done = 0,
  172. IIT_I1 = 1,
  173. IIT_I8 = 2,
  174. IIT_I16 = 3,
  175. IIT_I32 = 4,
  176. IIT_I64 = 5,
  177. IIT_F16 = 6,
  178. IIT_F32 = 7,
  179. IIT_F64 = 8,
  180. IIT_V2 = 9,
  181. IIT_V4 = 10,
  182. IIT_V8 = 11,
  183. IIT_V16 = 12,
  184. IIT_V32 = 13,
  185. IIT_PTR = 14,
  186. IIT_ARG = 15,
  187. // Values from 16+ are only encodable with the inefficient encoding.
  188. IIT_V64 = 16,
  189. IIT_MMX = 17,
  190. IIT_TOKEN = 18,
  191. IIT_METADATA = 19,
  192. IIT_EMPTYSTRUCT = 20,
  193. IIT_STRUCT2 = 21,
  194. IIT_STRUCT3 = 22,
  195. IIT_STRUCT4 = 23,
  196. IIT_STRUCT5 = 24,
  197. IIT_EXTEND_ARG = 25,
  198. IIT_TRUNC_ARG = 26,
  199. IIT_ANYPTR = 27,
  200. IIT_V1 = 28,
  201. IIT_VARARG = 29,
  202. IIT_HALF_VEC_ARG = 30,
  203. IIT_SAME_VEC_WIDTH_ARG = 31,
  204. IIT_PTR_TO_ARG = 32,
  205. IIT_PTR_TO_ELT = 33,
  206. IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
  207. IIT_I128 = 35,
  208. IIT_V512 = 36,
  209. IIT_V1024 = 37,
  210. IIT_STRUCT6 = 38,
  211. IIT_STRUCT7 = 39,
  212. IIT_STRUCT8 = 40,
  213. IIT_F128 = 41,
  214. IIT_VEC_ELEMENT = 42,
  215. IIT_SCALABLE_VEC = 43,
  216. IIT_SUBDIVIDE2_ARG = 44,
  217. IIT_SUBDIVIDE4_ARG = 45,
  218. IIT_VEC_OF_BITCASTS_TO_INT = 46,
  219. IIT_V128 = 47,
  220. IIT_BF16 = 48,
  221. IIT_STRUCT9 = 49,
  222. IIT_V256 = 50,
  223. IIT_AMX = 51,
  224. IIT_PPCF128 = 52,
  225. IIT_V3 = 53,
  226. IIT_EXTERNREF = 54,
  227. IIT_FUNCREF = 55,
  228. IIT_ANYPTR_TO_ELT = 56,
  229. IIT_I2 = 57,
  230. IIT_I4 = 58,
  231. };
  232. static void EncodeFixedValueType(MVT::SimpleValueType VT,
  233. std::vector<unsigned char> &Sig) {
  234. // clang-format off
  235. if (MVT(VT).isInteger()) {
  236. unsigned BitWidth = MVT(VT).getFixedSizeInBits();
  237. switch (BitWidth) {
  238. default: PrintFatalError("unhandled integer type width in intrinsic!");
  239. case 1: return Sig.push_back(IIT_I1);
  240. case 2: return Sig.push_back(IIT_I2);
  241. case 4: return Sig.push_back(IIT_I4);
  242. case 8: return Sig.push_back(IIT_I8);
  243. case 16: return Sig.push_back(IIT_I16);
  244. case 32: return Sig.push_back(IIT_I32);
  245. case 64: return Sig.push_back(IIT_I64);
  246. case 128: return Sig.push_back(IIT_I128);
  247. }
  248. }
  249. switch (VT) {
  250. default: PrintFatalError("unhandled MVT in intrinsic!");
  251. case MVT::f16: return Sig.push_back(IIT_F16);
  252. case MVT::bf16: return Sig.push_back(IIT_BF16);
  253. case MVT::f32: return Sig.push_back(IIT_F32);
  254. case MVT::f64: return Sig.push_back(IIT_F64);
  255. case MVT::f128: return Sig.push_back(IIT_F128);
  256. case MVT::ppcf128: return Sig.push_back(IIT_PPCF128);
  257. case MVT::token: return Sig.push_back(IIT_TOKEN);
  258. case MVT::Metadata: return Sig.push_back(IIT_METADATA);
  259. case MVT::x86mmx: return Sig.push_back(IIT_MMX);
  260. case MVT::x86amx: return Sig.push_back(IIT_AMX);
  261. // MVT::OtherVT is used to mean the empty struct type here.
  262. case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
  263. // MVT::isVoid is used to represent varargs here.
  264. case MVT::isVoid: return Sig.push_back(IIT_VARARG);
  265. case MVT::externref:
  266. return Sig.push_back(IIT_EXTERNREF);
  267. case MVT::funcref:
  268. return Sig.push_back(IIT_FUNCREF);
  269. }
  270. // clang-format on
  271. }
  272. #if defined(_MSC_VER) && !defined(__clang__)
  273. #pragma optimize("",off) // MSVC 2015 optimizer can't deal with this function.
  274. #endif
  275. static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
  276. unsigned &NextArgCode,
  277. std::vector<unsigned char> &Sig,
  278. ArrayRef<unsigned char> Mapping) {
  279. if (R->isSubClassOf("LLVMMatchType")) {
  280. unsigned Number = Mapping[R->getValueAsInt("Number")];
  281. assert(Number < ArgCodes.size() && "Invalid matching number!");
  282. if (R->isSubClassOf("LLVMExtendedType"))
  283. Sig.push_back(IIT_EXTEND_ARG);
  284. else if (R->isSubClassOf("LLVMTruncatedType"))
  285. Sig.push_back(IIT_TRUNC_ARG);
  286. else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
  287. Sig.push_back(IIT_HALF_VEC_ARG);
  288. else if (R->isSubClassOf("LLVMScalarOrSameVectorWidth")) {
  289. Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
  290. Sig.push_back((Number << 3) | ArgCodes[Number]);
  291. MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
  292. EncodeFixedValueType(VT, Sig);
  293. return;
  294. }
  295. else if (R->isSubClassOf("LLVMPointerTo"))
  296. Sig.push_back(IIT_PTR_TO_ARG);
  297. else if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
  298. Sig.push_back(IIT_VEC_OF_ANYPTRS_TO_ELT);
  299. // Encode overloaded ArgNo
  300. Sig.push_back(NextArgCode++);
  301. // Encode LLVMMatchType<Number> ArgNo
  302. Sig.push_back(Number);
  303. return;
  304. } else if (R->isSubClassOf("LLVMAnyPointerToElt")) {
  305. Sig.push_back(IIT_ANYPTR_TO_ELT);
  306. // Encode overloaded ArgNo
  307. Sig.push_back(NextArgCode++);
  308. // Encode LLVMMatchType<Number> ArgNo
  309. Sig.push_back(Number);
  310. return;
  311. } else if (R->isSubClassOf("LLVMPointerToElt"))
  312. Sig.push_back(IIT_PTR_TO_ELT);
  313. else if (R->isSubClassOf("LLVMVectorElementType"))
  314. Sig.push_back(IIT_VEC_ELEMENT);
  315. else if (R->isSubClassOf("LLVMSubdivide2VectorType"))
  316. Sig.push_back(IIT_SUBDIVIDE2_ARG);
  317. else if (R->isSubClassOf("LLVMSubdivide4VectorType"))
  318. Sig.push_back(IIT_SUBDIVIDE4_ARG);
  319. else if (R->isSubClassOf("LLVMVectorOfBitcastsToInt"))
  320. Sig.push_back(IIT_VEC_OF_BITCASTS_TO_INT);
  321. else
  322. Sig.push_back(IIT_ARG);
  323. return Sig.push_back((Number << 3) | 7 /*IITDescriptor::AK_MatchType*/);
  324. }
  325. MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
  326. unsigned Tmp = 0;
  327. switch (VT) {
  328. default: break;
  329. case MVT::iPTRAny: ++Tmp; [[fallthrough]];
  330. case MVT::vAny: ++Tmp; [[fallthrough]];
  331. case MVT::fAny: ++Tmp; [[fallthrough]];
  332. case MVT::iAny: ++Tmp; [[fallthrough]];
  333. case MVT::Any: {
  334. // If this is an "any" valuetype, then the type is the type of the next
  335. // type in the list specified to getIntrinsic().
  336. Sig.push_back(IIT_ARG);
  337. // Figure out what arg # this is consuming, and remember what kind it was.
  338. assert(NextArgCode < ArgCodes.size() && ArgCodes[NextArgCode] == Tmp &&
  339. "Invalid or no ArgCode associated with overloaded VT!");
  340. unsigned ArgNo = NextArgCode++;
  341. // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
  342. return Sig.push_back((ArgNo << 3) | Tmp);
  343. }
  344. case MVT::iPTR: {
  345. unsigned AddrSpace = 0;
  346. if (R->isSubClassOf("LLVMQualPointerType")) {
  347. AddrSpace = R->getValueAsInt("AddrSpace");
  348. assert(AddrSpace < 256 && "Address space exceeds 255");
  349. }
  350. if (AddrSpace) {
  351. Sig.push_back(IIT_ANYPTR);
  352. Sig.push_back(AddrSpace);
  353. } else {
  354. Sig.push_back(IIT_PTR);
  355. }
  356. return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, NextArgCode, Sig,
  357. Mapping);
  358. }
  359. }
  360. if (MVT(VT).isVector()) {
  361. MVT VVT = VT;
  362. if (VVT.isScalableVector())
  363. Sig.push_back(IIT_SCALABLE_VEC);
  364. switch (VVT.getVectorMinNumElements()) {
  365. default: PrintFatalError("unhandled vector type width in intrinsic!");
  366. case 1: Sig.push_back(IIT_V1); break;
  367. case 2: Sig.push_back(IIT_V2); break;
  368. case 3: Sig.push_back(IIT_V3); break;
  369. case 4: Sig.push_back(IIT_V4); break;
  370. case 8: Sig.push_back(IIT_V8); break;
  371. case 16: Sig.push_back(IIT_V16); break;
  372. case 32: Sig.push_back(IIT_V32); break;
  373. case 64: Sig.push_back(IIT_V64); break;
  374. case 128: Sig.push_back(IIT_V128); break;
  375. case 256: Sig.push_back(IIT_V256); break;
  376. case 512: Sig.push_back(IIT_V512); break;
  377. case 1024: Sig.push_back(IIT_V1024); break;
  378. }
  379. return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
  380. }
  381. EncodeFixedValueType(VT, Sig);
  382. }
  383. static void UpdateArgCodes(Record *R, std::vector<unsigned char> &ArgCodes,
  384. unsigned int &NumInserted,
  385. SmallVectorImpl<unsigned char> &Mapping) {
  386. if (R->isSubClassOf("LLVMMatchType")) {
  387. if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
  388. ArgCodes.push_back(3 /*vAny*/);
  389. ++NumInserted;
  390. } else if (R->isSubClassOf("LLVMAnyPointerToElt")) {
  391. ArgCodes.push_back(4 /*iPTRAny*/);
  392. ++NumInserted;
  393. }
  394. return;
  395. }
  396. unsigned Tmp = 0;
  397. switch (getValueType(R->getValueAsDef("VT"))) {
  398. default: break;
  399. case MVT::iPTR:
  400. UpdateArgCodes(R->getValueAsDef("ElTy"), ArgCodes, NumInserted, Mapping);
  401. break;
  402. case MVT::iPTRAny:
  403. ++Tmp;
  404. [[fallthrough]];
  405. case MVT::vAny:
  406. ++Tmp;
  407. [[fallthrough]];
  408. case MVT::fAny:
  409. ++Tmp;
  410. [[fallthrough]];
  411. case MVT::iAny:
  412. ++Tmp;
  413. [[fallthrough]];
  414. case MVT::Any:
  415. unsigned OriginalIdx = ArgCodes.size() - NumInserted;
  416. assert(OriginalIdx >= Mapping.size());
  417. Mapping.resize(OriginalIdx+1);
  418. Mapping[OriginalIdx] = ArgCodes.size();
  419. ArgCodes.push_back(Tmp);
  420. break;
  421. }
  422. }
  423. #if defined(_MSC_VER) && !defined(__clang__)
  424. #pragma optimize("",on)
  425. #endif
  426. /// ComputeFixedEncoding - If we can encode the type signature for this
  427. /// intrinsic into 32 bits, return it. If not, return ~0U.
  428. static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
  429. std::vector<unsigned char> &TypeSig) {
  430. std::vector<unsigned char> ArgCodes;
  431. // Add codes for any overloaded result VTs.
  432. unsigned int NumInserted = 0;
  433. SmallVector<unsigned char, 8> ArgMapping;
  434. for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
  435. UpdateArgCodes(Int.IS.RetTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
  436. // Add codes for any overloaded operand VTs.
  437. for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
  438. UpdateArgCodes(Int.IS.ParamTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
  439. unsigned NextArgCode = 0;
  440. if (Int.IS.RetVTs.empty())
  441. TypeSig.push_back(IIT_Done);
  442. else if (Int.IS.RetVTs.size() == 1 &&
  443. Int.IS.RetVTs[0] == MVT::isVoid)
  444. TypeSig.push_back(IIT_Done);
  445. else {
  446. switch (Int.IS.RetVTs.size()) {
  447. case 1: break;
  448. case 2: TypeSig.push_back(IIT_STRUCT2); break;
  449. case 3: TypeSig.push_back(IIT_STRUCT3); break;
  450. case 4: TypeSig.push_back(IIT_STRUCT4); break;
  451. case 5: TypeSig.push_back(IIT_STRUCT5); break;
  452. case 6: TypeSig.push_back(IIT_STRUCT6); break;
  453. case 7: TypeSig.push_back(IIT_STRUCT7); break;
  454. case 8: TypeSig.push_back(IIT_STRUCT8); break;
  455. case 9: TypeSig.push_back(IIT_STRUCT9); break;
  456. default: llvm_unreachable("Unhandled case in struct");
  457. }
  458. for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
  459. EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
  460. ArgMapping);
  461. }
  462. for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
  463. EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
  464. ArgMapping);
  465. }
  466. static void printIITEntry(raw_ostream &OS, unsigned char X) {
  467. OS << (unsigned)X;
  468. }
  469. void IntrinsicEmitter::EmitGenerator(const CodeGenIntrinsicTable &Ints,
  470. raw_ostream &OS) {
  471. // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
  472. // capture it in this vector, otherwise store a ~0U.
  473. std::vector<unsigned> FixedEncodings;
  474. SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
  475. std::vector<unsigned char> TypeSig;
  476. // Compute the unique argument type info.
  477. for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
  478. // Get the signature for the intrinsic.
  479. TypeSig.clear();
  480. ComputeFixedEncoding(Ints[i], TypeSig);
  481. // Check to see if we can encode it into a 32-bit word. We can only encode
  482. // 8 nibbles into a 32-bit word.
  483. if (TypeSig.size() <= 8) {
  484. bool Failed = false;
  485. unsigned Result = 0;
  486. for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
  487. // If we had an unencodable argument, bail out.
  488. if (TypeSig[i] > 15) {
  489. Failed = true;
  490. break;
  491. }
  492. Result = (Result << 4) | TypeSig[e-i-1];
  493. }
  494. // If this could be encoded into a 31-bit word, return it.
  495. if (!Failed && (Result >> 31) == 0) {
  496. FixedEncodings.push_back(Result);
  497. continue;
  498. }
  499. }
  500. // Otherwise, we're going to unique the sequence into the
  501. // LongEncodingTable, and use its offset in the 32-bit table instead.
  502. LongEncodingTable.add(TypeSig);
  503. // This is a placehold that we'll replace after the table is laid out.
  504. FixedEncodings.push_back(~0U);
  505. }
  506. LongEncodingTable.layout();
  507. OS << "// Global intrinsic function declaration type table.\n";
  508. OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
  509. OS << "static const unsigned IIT_Table[] = {\n ";
  510. for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
  511. if ((i & 7) == 7)
  512. OS << "\n ";
  513. // If the entry fit in the table, just emit it.
  514. if (FixedEncodings[i] != ~0U) {
  515. OS << "0x" << Twine::utohexstr(FixedEncodings[i]) << ", ";
  516. continue;
  517. }
  518. TypeSig.clear();
  519. ComputeFixedEncoding(Ints[i], TypeSig);
  520. // Otherwise, emit the offset into the long encoding table. We emit it this
  521. // way so that it is easier to read the offset in the .def file.
  522. OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
  523. }
  524. OS << "0\n};\n\n";
  525. // Emit the shared table of register lists.
  526. OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
  527. if (!LongEncodingTable.empty())
  528. LongEncodingTable.emit(OS, printIITEntry);
  529. OS << " 255\n};\n\n";
  530. OS << "#endif\n\n"; // End of GET_INTRINSIC_GENERATOR_GLOBAL
  531. }
  532. namespace {
  533. std::optional<bool> compareFnAttributes(const CodeGenIntrinsic *L,
  534. const CodeGenIntrinsic *R) {
  535. // Sort throwing intrinsics after non-throwing intrinsics.
  536. if (L->canThrow != R->canThrow)
  537. return R->canThrow;
  538. if (L->isNoDuplicate != R->isNoDuplicate)
  539. return R->isNoDuplicate;
  540. if (L->isNoMerge != R->isNoMerge)
  541. return R->isNoMerge;
  542. if (L->isNoReturn != R->isNoReturn)
  543. return R->isNoReturn;
  544. if (L->isNoCallback != R->isNoCallback)
  545. return R->isNoCallback;
  546. if (L->isNoSync != R->isNoSync)
  547. return R->isNoSync;
  548. if (L->isNoFree != R->isNoFree)
  549. return R->isNoFree;
  550. if (L->isWillReturn != R->isWillReturn)
  551. return R->isWillReturn;
  552. if (L->isCold != R->isCold)
  553. return R->isCold;
  554. if (L->isConvergent != R->isConvergent)
  555. return R->isConvergent;
  556. if (L->isSpeculatable != R->isSpeculatable)
  557. return R->isSpeculatable;
  558. if (L->hasSideEffects != R->hasSideEffects)
  559. return R->hasSideEffects;
  560. // Try to order by readonly/readnone attribute.
  561. uint32_t LK = L->ME.toIntValue();
  562. uint32_t RK = R->ME.toIntValue();
  563. if (LK != RK) return (LK > RK);
  564. return std::nullopt;
  565. }
  566. struct FnAttributeComparator {
  567. bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
  568. return compareFnAttributes(L, R).value_or(false);
  569. }
  570. };
  571. struct AttributeComparator {
  572. bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
  573. if (std::optional<bool> Res = compareFnAttributes(L, R))
  574. return *Res;
  575. // Order by argument attributes.
  576. // This is reliable because each side is already sorted internally.
  577. return (L->ArgumentAttributes < R->ArgumentAttributes);
  578. }
  579. };
  580. } // End anonymous namespace
  581. /// EmitAttributes - This emits the Intrinsic::getAttributes method.
  582. void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints,
  583. raw_ostream &OS) {
  584. OS << "// Add parameter attributes that are not common to all intrinsics.\n";
  585. OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
  586. // Compute unique argument attribute sets.
  587. std::map<SmallVector<CodeGenIntrinsic::ArgAttribute, 0>, unsigned>
  588. UniqArgAttributes;
  589. OS << "static AttributeSet getIntrinsicArgAttributeSet("
  590. << "LLVMContext &C, unsigned ID) {\n"
  591. << " switch (ID) {\n"
  592. << " default: llvm_unreachable(\"Invalid attribute set number\");\n";
  593. for (const CodeGenIntrinsic &Int : Ints) {
  594. for (auto &Attrs : Int.ArgumentAttributes) {
  595. if (Attrs.empty())
  596. continue;
  597. unsigned ID = UniqArgAttributes.size();
  598. if (!UniqArgAttributes.try_emplace(Attrs, ID).second)
  599. continue;
  600. assert(is_sorted(Attrs) &&
  601. "Argument attributes are not sorted");
  602. OS << " case " << ID << ":\n";
  603. OS << " return AttributeSet::get(C, {\n";
  604. for (const CodeGenIntrinsic::ArgAttribute &Attr : Attrs) {
  605. switch (Attr.Kind) {
  606. case CodeGenIntrinsic::NoCapture:
  607. OS << " Attribute::get(C, Attribute::NoCapture),\n";
  608. break;
  609. case CodeGenIntrinsic::NoAlias:
  610. OS << " Attribute::get(C, Attribute::NoAlias),\n";
  611. break;
  612. case CodeGenIntrinsic::NoUndef:
  613. OS << " Attribute::get(C, Attribute::NoUndef),\n";
  614. break;
  615. case CodeGenIntrinsic::NonNull:
  616. OS << " Attribute::get(C, Attribute::NonNull),\n";
  617. break;
  618. case CodeGenIntrinsic::Returned:
  619. OS << " Attribute::get(C, Attribute::Returned),\n";
  620. break;
  621. case CodeGenIntrinsic::ReadOnly:
  622. OS << " Attribute::get(C, Attribute::ReadOnly),\n";
  623. break;
  624. case CodeGenIntrinsic::WriteOnly:
  625. OS << " Attribute::get(C, Attribute::WriteOnly),\n";
  626. break;
  627. case CodeGenIntrinsic::ReadNone:
  628. OS << " Attribute::get(C, Attribute::ReadNone),\n";
  629. break;
  630. case CodeGenIntrinsic::ImmArg:
  631. OS << " Attribute::get(C, Attribute::ImmArg),\n";
  632. break;
  633. case CodeGenIntrinsic::Alignment:
  634. OS << " Attribute::get(C, Attribute::Alignment, "
  635. << Attr.Value << "),\n";
  636. break;
  637. }
  638. }
  639. OS << " });\n";
  640. }
  641. }
  642. OS << " }\n";
  643. OS << "}\n\n";
  644. // Compute unique function attribute sets.
  645. std::map<const CodeGenIntrinsic*, unsigned, FnAttributeComparator>
  646. UniqFnAttributes;
  647. OS << "static AttributeSet getIntrinsicFnAttributeSet("
  648. << "LLVMContext &C, unsigned ID) {\n"
  649. << " switch (ID) {\n"
  650. << " default: llvm_unreachable(\"Invalid attribute set number\");\n";
  651. for (const CodeGenIntrinsic &Intrinsic : Ints) {
  652. unsigned ID = UniqFnAttributes.size();
  653. if (!UniqFnAttributes.try_emplace(&Intrinsic, ID).second)
  654. continue;
  655. OS << " case " << ID << ":\n"
  656. << " return AttributeSet::get(C, {\n";
  657. if (!Intrinsic.canThrow)
  658. OS << " Attribute::get(C, Attribute::NoUnwind),\n";
  659. if (Intrinsic.isNoReturn)
  660. OS << " Attribute::get(C, Attribute::NoReturn),\n";
  661. if (Intrinsic.isNoCallback)
  662. OS << " Attribute::get(C, Attribute::NoCallback),\n";
  663. if (Intrinsic.isNoSync)
  664. OS << " Attribute::get(C, Attribute::NoSync),\n";
  665. if (Intrinsic.isNoFree)
  666. OS << " Attribute::get(C, Attribute::NoFree),\n";
  667. if (Intrinsic.isWillReturn)
  668. OS << " Attribute::get(C, Attribute::WillReturn),\n";
  669. if (Intrinsic.isCold)
  670. OS << " Attribute::get(C, Attribute::Cold),\n";
  671. if (Intrinsic.isNoDuplicate)
  672. OS << " Attribute::get(C, Attribute::NoDuplicate),\n";
  673. if (Intrinsic.isNoMerge)
  674. OS << " Attribute::get(C, Attribute::NoMerge),\n";
  675. if (Intrinsic.isConvergent)
  676. OS << " Attribute::get(C, Attribute::Convergent),\n";
  677. if (Intrinsic.isSpeculatable)
  678. OS << " Attribute::get(C, Attribute::Speculatable),\n";
  679. MemoryEffects ME = Intrinsic.ME;
  680. // TODO: IntrHasSideEffects should affect not only readnone intrinsics.
  681. if (ME.doesNotAccessMemory() && Intrinsic.hasSideEffects)
  682. ME = MemoryEffects::unknown();
  683. if (ME != MemoryEffects::unknown()) {
  684. OS << " Attribute::getWithMemoryEffects(C, "
  685. << "MemoryEffects::createFromIntValue(" << ME.toIntValue() << ")),\n";
  686. }
  687. OS << " });\n";
  688. }
  689. OS << " }\n";
  690. OS << "}\n\n";
  691. OS << "AttributeList Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
  692. // Compute the maximum number of attribute arguments and the map
  693. typedef std::map<const CodeGenIntrinsic*, unsigned,
  694. AttributeComparator> UniqAttrMapTy;
  695. UniqAttrMapTy UniqAttributes;
  696. unsigned maxArgAttrs = 0;
  697. unsigned AttrNum = 0;
  698. for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
  699. const CodeGenIntrinsic &intrinsic = Ints[i];
  700. maxArgAttrs =
  701. std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
  702. unsigned &N = UniqAttributes[&intrinsic];
  703. if (N) continue;
  704. N = ++AttrNum;
  705. assert(N < 65536 && "Too many unique attributes for table!");
  706. }
  707. // Emit an array of AttributeList. Most intrinsics will have at least one
  708. // entry, for the function itself (index ~1), which is usually nounwind.
  709. OS << " static const uint16_t IntrinsicsToAttributesMap[] = {\n";
  710. for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
  711. const CodeGenIntrinsic &intrinsic = Ints[i];
  712. OS << " " << UniqAttributes[&intrinsic] << ", // "
  713. << intrinsic.Name << "\n";
  714. }
  715. OS << " };\n\n";
  716. OS << " std::pair<unsigned, AttributeSet> AS[" << maxArgAttrs + 1 << "];\n";
  717. OS << " unsigned NumAttrs = 0;\n";
  718. OS << " if (id != 0) {\n";
  719. OS << " switch(IntrinsicsToAttributesMap[id - 1]) {\n";
  720. OS << " default: llvm_unreachable(\"Invalid attribute number\");\n";
  721. for (auto UniqAttribute : UniqAttributes) {
  722. OS << " case " << UniqAttribute.second << ": {\n";
  723. const CodeGenIntrinsic &Intrinsic = *(UniqAttribute.first);
  724. // Keep track of the number of attributes we're writing out.
  725. unsigned numAttrs = 0;
  726. for (const auto &[AttrIdx, Attrs] :
  727. enumerate(Intrinsic.ArgumentAttributes)) {
  728. if (Attrs.empty())
  729. continue;
  730. unsigned ID = UniqArgAttributes.find(Attrs)->second;
  731. OS << " AS[" << numAttrs++ << "] = {" << AttrIdx
  732. << ", getIntrinsicArgAttributeSet(C, " << ID << ")};\n";
  733. }
  734. if (!Intrinsic.canThrow ||
  735. (Intrinsic.ME != MemoryEffects::unknown() &&
  736. !Intrinsic.hasSideEffects) ||
  737. Intrinsic.isNoReturn || Intrinsic.isNoCallback || Intrinsic.isNoSync ||
  738. Intrinsic.isNoFree || Intrinsic.isWillReturn || Intrinsic.isCold ||
  739. Intrinsic.isNoDuplicate || Intrinsic.isNoMerge ||
  740. Intrinsic.isConvergent || Intrinsic.isSpeculatable) {
  741. unsigned ID = UniqFnAttributes.find(&Intrinsic)->second;
  742. OS << " AS[" << numAttrs++ << "] = {AttributeList::FunctionIndex, "
  743. << "getIntrinsicFnAttributeSet(C, " << ID << ")};\n";
  744. }
  745. if (numAttrs) {
  746. OS << " NumAttrs = " << numAttrs << ";\n";
  747. OS << " break;\n";
  748. OS << " }\n";
  749. } else {
  750. OS << " return AttributeList();\n";
  751. OS << " }\n";
  752. }
  753. }
  754. OS << " }\n";
  755. OS << " }\n";
  756. OS << " return AttributeList::get(C, ArrayRef(AS, NumAttrs));\n";
  757. OS << "}\n";
  758. OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
  759. }
  760. void IntrinsicEmitter::EmitIntrinsicToBuiltinMap(
  761. const CodeGenIntrinsicTable &Ints, bool IsClang, raw_ostream &OS) {
  762. StringRef CompilerName = (IsClang ? "Clang" : "MS");
  763. StringRef UpperCompilerName = (IsClang ? "CLANG" : "MS");
  764. typedef std::map<std::string, std::map<std::string, std::string>> BIMTy;
  765. BIMTy BuiltinMap;
  766. StringToOffsetTable Table;
  767. for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
  768. const std::string &BuiltinName =
  769. IsClang ? Ints[i].ClangBuiltinName : Ints[i].MSBuiltinName;
  770. if (!BuiltinName.empty()) {
  771. // Get the map for this target prefix.
  772. std::map<std::string, std::string> &BIM =
  773. BuiltinMap[Ints[i].TargetPrefix];
  774. if (!BIM.insert(std::make_pair(BuiltinName, Ints[i].EnumName)).second)
  775. PrintFatalError(Ints[i].TheDef->getLoc(),
  776. "Intrinsic '" + Ints[i].TheDef->getName() +
  777. "': duplicate " + CompilerName + " builtin name!");
  778. Table.GetOrAddStringOffset(BuiltinName);
  779. }
  780. }
  781. OS << "// Get the LLVM intrinsic that corresponds to a builtin.\n";
  782. OS << "// This is used by the C front-end. The builtin name is passed\n";
  783. OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
  784. OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n";
  785. OS << "#ifdef GET_LLVM_INTRINSIC_FOR_" << UpperCompilerName << "_BUILTIN\n";
  786. OS << "Intrinsic::ID Intrinsic::getIntrinsicFor" << CompilerName
  787. << "Builtin(const char "
  788. << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n";
  789. if (Table.Empty()) {
  790. OS << " return Intrinsic::not_intrinsic;\n";
  791. OS << "}\n";
  792. OS << "#endif\n\n";
  793. return;
  794. }
  795. OS << " static const char BuiltinNames[] = {\n";
  796. Table.EmitCharArray(OS);
  797. OS << " };\n\n";
  798. OS << " struct BuiltinEntry {\n";
  799. OS << " Intrinsic::ID IntrinID;\n";
  800. OS << " unsigned StrTabOffset;\n";
  801. OS << " const char *getName() const {\n";
  802. OS << " return &BuiltinNames[StrTabOffset];\n";
  803. OS << " }\n";
  804. OS << " bool operator<(StringRef RHS) const {\n";
  805. OS << " return strncmp(getName(), RHS.data(), RHS.size()) < 0;\n";
  806. OS << " }\n";
  807. OS << " };\n";
  808. OS << " StringRef TargetPrefix(TargetPrefixStr);\n\n";
  809. // Note: this could emit significantly better code if we cared.
  810. for (auto &I : BuiltinMap) {
  811. OS << " ";
  812. if (!I.first.empty())
  813. OS << "if (TargetPrefix == \"" << I.first << "\") ";
  814. else
  815. OS << "/* Target Independent Builtins */ ";
  816. OS << "{\n";
  817. // Emit the comparisons for this target prefix.
  818. OS << " static const BuiltinEntry " << I.first << "Names[] = {\n";
  819. for (const auto &P : I.second) {
  820. OS << " {Intrinsic::" << P.second << ", "
  821. << Table.GetOrAddStringOffset(P.first) << "}, // " << P.first << "\n";
  822. }
  823. OS << " };\n";
  824. OS << " auto I = std::lower_bound(std::begin(" << I.first << "Names),\n";
  825. OS << " std::end(" << I.first << "Names),\n";
  826. OS << " BuiltinNameStr);\n";
  827. OS << " if (I != std::end(" << I.first << "Names) &&\n";
  828. OS << " I->getName() == BuiltinNameStr)\n";
  829. OS << " return I->IntrinID;\n";
  830. OS << " }\n";
  831. }
  832. OS << " return ";
  833. OS << "Intrinsic::not_intrinsic;\n";
  834. OS << "}\n";
  835. OS << "#endif\n\n";
  836. }
  837. void llvm::EmitIntrinsicEnums(RecordKeeper &RK, raw_ostream &OS) {
  838. IntrinsicEmitter(RK).run(OS, /*Enums=*/true);
  839. }
  840. void llvm::EmitIntrinsicImpl(RecordKeeper &RK, raw_ostream &OS) {
  841. IntrinsicEmitter(RK).run(OS, /*Enums=*/false);
  842. }