ClangOpenCLBuiltinEmitter.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. //===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  6. // See https://llvm.org/LICENSE.txt for license information.
  7. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  8. //
  9. //===----------------------------------------------------------------------===//
  10. //
  11. // This tablegen backend emits code for checking whether a function is an
  12. // OpenCL builtin function. If so, all overloads of this function are
  13. // added to the LookupResult. The generated include file is used by
  14. // SemaLookup.cpp
  15. //
  16. // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
  17. // returns a pair <Index, Len>.
  18. // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
  19. // <SigIndex, SigLen> of the overloads of "cos".
  20. // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
  21. // one of the signatures of "cos". The SignatureTable entry can be
  22. // referenced by other functions, e.g. "sin", to exploit the fact that
  23. // many OpenCL builtins share the same signature.
  24. //
  25. // The file generated by this TableGen emitter contains the following:
  26. //
  27. // * Structs and enums to represent types and function signatures.
  28. //
  29. // * OpenCLTypeStruct TypeTable[]
  30. // Type information for return types and arguments.
  31. //
  32. // * unsigned SignatureTable[]
  33. // A list of types representing function signatures. Each entry is an index
  34. // into the above TypeTable. Multiple entries following each other form a
  35. // signature, where the first entry is the return type and subsequent
  36. // entries are the argument types.
  37. //
  38. // * OpenCLBuiltinStruct BuiltinTable[]
  39. // Each entry represents one overload of an OpenCL builtin function and
  40. // consists of an index into the SignatureTable and the number of arguments.
  41. //
  42. // * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
  43. // Find out whether a string matches an existing OpenCL builtin function
  44. // name and return an index into BuiltinTable and the number of overloads.
  45. //
  46. // * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector<QualType>&)
  47. // Convert an OpenCLTypeStruct type to a list of QualType instances.
  48. // One OpenCLTypeStruct can represent multiple types, primarily when using
  49. // GenTypes.
  50. //
  51. //===----------------------------------------------------------------------===//
  52. #include "TableGenBackends.h"
  53. #include "llvm/ADT/MapVector.h"
  54. #include "llvm/ADT/STLExtras.h"
  55. #include "llvm/ADT/SmallString.h"
  56. #include "llvm/ADT/StringExtras.h"
  57. #include "llvm/ADT/StringRef.h"
  58. #include "llvm/ADT/StringSet.h"
  59. #include "llvm/ADT/StringSwitch.h"
  60. #include "llvm/Support/ErrorHandling.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include "llvm/TableGen/Error.h"
  63. #include "llvm/TableGen/Record.h"
  64. #include "llvm/TableGen/StringMatcher.h"
  65. #include "llvm/TableGen/TableGenBackend.h"
  66. #include <set>
  67. using namespace llvm;
  68. namespace {
  69. class BuiltinNameEmitter {
  70. public:
  71. BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
  72. : Records(Records), OS(OS) {}
  73. // Entrypoint to generate the functions and structures for checking
  74. // whether a function is an OpenCL builtin function.
  75. void Emit();
  76. private:
  77. // Contains OpenCL builtin functions and related information, stored as
  78. // Record instances. They are coming from the associated TableGen file.
  79. RecordKeeper &Records;
  80. // The output file.
  81. raw_ostream &OS;
  82. // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum
  83. // definitions in the Output string parameter, and save their Record instances
  84. // in the List parameter.
  85. // \param Types (in) List containing the Types to extract.
  86. // \param TypesSeen (inout) List containing the Types already extracted.
  87. // \param Output (out) String containing the enums to emit in the output file.
  88. // \param List (out) List containing the extracted Types, except the Types in
  89. // TypesSeen.
  90. void ExtractEnumTypes(std::vector<Record *> &Types,
  91. StringMap<bool> &TypesSeen, std::string &Output,
  92. std::vector<const Record *> &List);
  93. // Emit the enum or struct used in the generated file.
  94. // Populate the TypeList at the same time.
  95. void EmitDeclarations();
  96. // Parse the Records generated by TableGen to populate the SignaturesList,
  97. // FctOverloadMap and TypeMap.
  98. void GetOverloads();
  99. // Emit the TypeTable containing all types used by OpenCL builtins.
  100. void EmitTypeTable();
  101. // Emit the SignatureTable. This table contains all the possible signatures.
  102. // A signature is stored as a list of indexes of the TypeTable.
  103. // The first index references the return type (mandatory), and the followings
  104. // reference its arguments.
  105. // E.g.:
  106. // 15, 2, 15 can represent a function with the signature:
  107. // int func(float, int)
  108. // The "int" type being at the index 15 in the TypeTable.
  109. void EmitSignatureTable();
  110. // Emit the BuiltinTable table. This table contains all the overloads of
  111. // each function, and is a struct OpenCLBuiltinDecl.
  112. // E.g.:
  113. // // 891 convert_float2_rtn
  114. // { 58, 2, 100, 0 },
  115. // This means that the signature of this convert_float2_rtn overload has
  116. // 1 argument (+1 for the return type), stored at index 58 in
  117. // the SignatureTable. The last two values represent the minimum (1.0) and
  118. // maximum (0, meaning no max version) OpenCL version in which this overload
  119. // is supported.
  120. void EmitBuiltinTable();
  121. // Emit a StringMatcher function to check whether a function name is an
  122. // OpenCL builtin function name.
  123. void EmitStringMatcher();
  124. // Emit a function returning the clang QualType instance associated with
  125. // the TableGen Record Type.
  126. void EmitQualTypeFinder();
  127. // Contains a list of the available signatures, without the name of the
  128. // function. Each pair consists of a signature and a cumulative index.
  129. // E.g.: <<float, float>, 0>,
  130. // <<float, int, int, 2>>,
  131. // <<float>, 5>,
  132. // ...
  133. // <<double, double>, 35>.
  134. std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
  135. // Map the name of a builtin function to its prototypes (instances of the
  136. // TableGen "Builtin" class).
  137. // Each prototype is registered as a pair of:
  138. // <pointer to the "Builtin" instance,
  139. // cumulative index of the associated signature in the SignaturesList>
  140. // E.g.: The function cos: (float cos(float), double cos(double), ...)
  141. // <"cos", <<ptrToPrototype0, 5>,
  142. // <ptrToPrototype1, 35>,
  143. // <ptrToPrototype2, 79>>
  144. // ptrToPrototype1 has the following signature: <double, double>
  145. MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
  146. FctOverloadMap;
  147. // Contains the map of OpenCL types to their index in the TypeTable.
  148. MapVector<const Record *, unsigned> TypeMap;
  149. // List of OpenCL type names in the same order as in enum OpenCLTypeID.
  150. // This list does not contain generic types.
  151. std::vector<const Record *> TypeList;
  152. // Same as TypeList, but for generic types only.
  153. std::vector<const Record *> GenTypeList;
  154. };
  155. } // namespace
  156. void BuiltinNameEmitter::Emit() {
  157. emitSourceFileHeader("OpenCL Builtin handling", OS);
  158. OS << "#include \"llvm/ADT/StringRef.h\"\n";
  159. OS << "using namespace clang;\n\n";
  160. // Emit enums and structs.
  161. EmitDeclarations();
  162. GetOverloads();
  163. // Emit tables.
  164. EmitTypeTable();
  165. EmitSignatureTable();
  166. EmitBuiltinTable();
  167. EmitStringMatcher();
  168. EmitQualTypeFinder();
  169. }
  170. void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
  171. StringMap<bool> &TypesSeen,
  172. std::string &Output,
  173. std::vector<const Record *> &List) {
  174. raw_string_ostream SS(Output);
  175. for (const auto *T : Types) {
  176. if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
  177. SS << " OCLT_" + T->getValueAsString("Name") << ",\n";
  178. // Save the type names in the same order as their enum value. Note that
  179. // the Record can be a VectorType or something else, only the name is
  180. // important.
  181. List.push_back(T);
  182. TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
  183. }
  184. }
  185. SS.flush();
  186. }
  187. void BuiltinNameEmitter::EmitDeclarations() {
  188. // Enum of scalar type names (float, int, ...) and generic type sets.
  189. OS << "enum OpenCLTypeID {\n";
  190. StringMap<bool> TypesSeen;
  191. std::string GenTypeEnums;
  192. std::string TypeEnums;
  193. // Extract generic types and non-generic types separately, to keep
  194. // gentypes at the end of the enum which simplifies the special handling
  195. // for gentypes in SemaLookup.
  196. std::vector<Record *> GenTypes =
  197. Records.getAllDerivedDefinitions("GenericType");
  198. ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
  199. std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
  200. ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
  201. OS << TypeEnums;
  202. OS << GenTypeEnums;
  203. OS << "};\n";
  204. // Structure definitions.
  205. OS << R"(
  206. // Image access qualifier.
  207. enum OpenCLAccessQual : unsigned char {
  208. OCLAQ_None,
  209. OCLAQ_ReadOnly,
  210. OCLAQ_WriteOnly,
  211. OCLAQ_ReadWrite
  212. };
  213. // Represents a return type or argument type.
  214. struct OpenCLTypeStruct {
  215. // A type (e.g. float, int, ...).
  216. const OpenCLTypeID ID;
  217. // Vector size (if applicable; 0 for scalars and generic types).
  218. const unsigned VectorWidth;
  219. // 0 if the type is not a pointer.
  220. const bool IsPointer;
  221. // 0 if the type is not const.
  222. const bool IsConst;
  223. // 0 if the type is not volatile.
  224. const bool IsVolatile;
  225. // Access qualifier.
  226. const OpenCLAccessQual AccessQualifier;
  227. // Address space of the pointer (if applicable).
  228. const LangAS AS;
  229. };
  230. // One overload of an OpenCL builtin function.
  231. struct OpenCLBuiltinStruct {
  232. // Index of the signature in the OpenCLTypeStruct table.
  233. const unsigned SigTableIndex;
  234. // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
  235. // the SignatureTable represent the complete signature. The first type at
  236. // index SigTableIndex is the return type.
  237. const unsigned NumTypes;
  238. // First OpenCL version in which this overload was introduced (e.g. CL20).
  239. const unsigned short MinVersion;
  240. // First OpenCL version in which this overload was removed (e.g. CL20).
  241. const unsigned short MaxVersion;
  242. };
  243. )";
  244. }
  245. // Verify that the combination of GenTypes in a signature is supported.
  246. // To simplify the logic for creating overloads in SemaLookup, only allow
  247. // a signature to contain different GenTypes if these GenTypes represent
  248. // the same number of actual scalar or vector types.
  249. //
  250. // Exit with a fatal error if an unsupported construct is encountered.
  251. static void VerifySignature(const std::vector<Record *> &Signature,
  252. const Record *BuiltinRec) {
  253. unsigned GenTypeVecSizes = 1;
  254. unsigned GenTypeTypes = 1;
  255. for (const auto *T : Signature) {
  256. // Check all GenericType arguments in this signature.
  257. if (T->isSubClassOf("GenericType")) {
  258. // Check number of vector sizes.
  259. unsigned NVecSizes =
  260. T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
  261. if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
  262. if (GenTypeVecSizes > 1) {
  263. // We already saw a gentype with a different number of vector sizes.
  264. PrintFatalError(BuiltinRec->getLoc(),
  265. "number of vector sizes should be equal or 1 for all gentypes "
  266. "in a declaration");
  267. }
  268. GenTypeVecSizes = NVecSizes;
  269. }
  270. // Check number of data types.
  271. unsigned NTypes =
  272. T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
  273. if (NTypes != GenTypeTypes && NTypes != 1) {
  274. if (GenTypeTypes > 1) {
  275. // We already saw a gentype with a different number of types.
  276. PrintFatalError(BuiltinRec->getLoc(),
  277. "number of types should be equal or 1 for all gentypes "
  278. "in a declaration");
  279. }
  280. GenTypeTypes = NTypes;
  281. }
  282. }
  283. }
  284. }
  285. void BuiltinNameEmitter::GetOverloads() {
  286. // Populate the TypeMap.
  287. std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
  288. unsigned I = 0;
  289. for (const auto &T : Types) {
  290. TypeMap.insert(std::make_pair(T, I++));
  291. }
  292. // Populate the SignaturesList and the FctOverloadMap.
  293. unsigned CumulativeSignIndex = 0;
  294. std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
  295. for (const auto *B : Builtins) {
  296. StringRef BName = B->getValueAsString("Name");
  297. if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
  298. FctOverloadMap.insert(std::make_pair(
  299. BName, std::vector<std::pair<const Record *, unsigned>>{}));
  300. }
  301. auto Signature = B->getValueAsListOfDefs("Signature");
  302. // Reuse signatures to avoid unnecessary duplicates.
  303. auto it =
  304. std::find_if(SignaturesList.begin(), SignaturesList.end(),
  305. [&](const std::pair<std::vector<Record *>, unsigned> &a) {
  306. return a.first == Signature;
  307. });
  308. unsigned SignIndex;
  309. if (it == SignaturesList.end()) {
  310. VerifySignature(Signature, B);
  311. SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
  312. SignIndex = CumulativeSignIndex;
  313. CumulativeSignIndex += Signature.size();
  314. } else {
  315. SignIndex = it->second;
  316. }
  317. FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
  318. }
  319. }
  320. void BuiltinNameEmitter::EmitTypeTable() {
  321. OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
  322. for (const auto &T : TypeMap) {
  323. const char *AccessQual =
  324. StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
  325. .Case("RO", "OCLAQ_ReadOnly")
  326. .Case("WO", "OCLAQ_WriteOnly")
  327. .Case("RW", "OCLAQ_ReadWrite")
  328. .Default("OCLAQ_None");
  329. OS << " // " << T.second << "\n"
  330. << " {OCLT_" << T.first->getValueAsString("Name") << ", "
  331. << T.first->getValueAsInt("VecWidth") << ", "
  332. << T.first->getValueAsBit("IsPointer") << ", "
  333. << T.first->getValueAsBit("IsConst") << ", "
  334. << T.first->getValueAsBit("IsVolatile") << ", "
  335. << AccessQual << ", "
  336. << T.first->getValueAsString("AddrSpace") << "},\n";
  337. }
  338. OS << "};\n\n";
  339. }
  340. void BuiltinNameEmitter::EmitSignatureTable() {
  341. // Store a type (e.g. int, float, int2, ...). The type is stored as an index
  342. // of a struct OpenCLType table. Multiple entries following each other form a
  343. // signature.
  344. OS << "static const unsigned SignatureTable[] = {\n";
  345. for (const auto &P : SignaturesList) {
  346. OS << " // " << P.second << "\n ";
  347. for (const Record *R : P.first) {
  348. OS << TypeMap.find(R)->second << ", ";
  349. }
  350. OS << "\n";
  351. }
  352. OS << "};\n\n";
  353. }
  354. void BuiltinNameEmitter::EmitBuiltinTable() {
  355. unsigned Index = 0;
  356. OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
  357. for (const auto &FOM : FctOverloadMap) {
  358. OS << " // " << (Index + 1) << ": " << FOM.first << "\n";
  359. for (const auto &Overload : FOM.second) {
  360. OS << " { " << Overload.second << ", "
  361. << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
  362. << Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID")
  363. << ", "
  364. << Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID")
  365. << " },\n";
  366. Index++;
  367. }
  368. }
  369. OS << "};\n\n";
  370. }
  371. void BuiltinNameEmitter::EmitStringMatcher() {
  372. std::vector<StringMatcher::StringPair> ValidBuiltins;
  373. unsigned CumulativeIndex = 1;
  374. for (auto &i : FctOverloadMap) {
  375. auto &Ov = i.second;
  376. std::string RetStmt;
  377. raw_string_ostream SS(RetStmt);
  378. SS << "return std::make_pair(" << CumulativeIndex << ", " << Ov.size()
  379. << ");";
  380. SS.flush();
  381. CumulativeIndex += Ov.size();
  382. ValidBuiltins.push_back(StringMatcher::StringPair(i.first, RetStmt));
  383. }
  384. OS << R"(
  385. // Find out whether a string matches an existing OpenCL builtin function name.
  386. // Returns: A pair <0, 0> if no name matches.
  387. // A pair <Index, Len> indexing the BuiltinTable if the name is
  388. // matching an OpenCL builtin function.
  389. static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
  390. )";
  391. StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
  392. OS << " return std::make_pair(0, 0);\n";
  393. OS << "} // isOpenCLBuiltin\n";
  394. }
  395. void BuiltinNameEmitter::EmitQualTypeFinder() {
  396. OS << R"(
  397. // Convert an OpenCLTypeStruct type to a list of QualTypes.
  398. // Generic types represent multiple types and vector sizes, thus a vector
  399. // is returned. The conversion is done in two steps:
  400. // Step 1: A switch statement fills a vector with scalar base types for the
  401. // Cartesian product of (vector sizes) x (types) for generic types,
  402. // or a single scalar type for non generic types.
  403. // Step 2: Qualifiers and other type properties such as vector size are
  404. // applied.
  405. static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
  406. llvm::SmallVectorImpl<QualType> &QT) {
  407. // Number of scalar types in the GenType.
  408. unsigned GenTypeNumTypes;
  409. // Pointer to the list of vector sizes for the GenType.
  410. llvm::ArrayRef<unsigned> GenVectorSizes;
  411. )";
  412. // Generate list of vector sizes for each generic type.
  413. for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
  414. OS << " constexpr unsigned List"
  415. << VectList->getValueAsString("Name") << "[] = {";
  416. for (const auto V : VectList->getValueAsListOfInts("List")) {
  417. OS << V << ", ";
  418. }
  419. OS << "};\n";
  420. }
  421. // Step 1.
  422. // Start of switch statement over all types.
  423. OS << "\n switch (Ty.ID) {\n";
  424. // Switch cases for image types (Image2d, Image3d, ...)
  425. std::vector<Record *> ImageTypes =
  426. Records.getAllDerivedDefinitions("ImageType");
  427. // Map an image type name to its 3 access-qualified types (RO, WO, RW).
  428. std::map<StringRef, SmallVector<Record *, 3>> ImageTypesMap;
  429. for (auto *IT : ImageTypes) {
  430. auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
  431. if (Entry == ImageTypesMap.end()) {
  432. SmallVector<Record *, 3> ImageList;
  433. ImageList.push_back(IT);
  434. ImageTypesMap.insert(
  435. std::make_pair(IT->getValueAsString("Name"), ImageList));
  436. } else {
  437. Entry->second.push_back(IT);
  438. }
  439. }
  440. // Emit the cases for the image types. For an image type name, there are 3
  441. // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field
  442. // tells which one is needed. Emit a switch statement that puts the
  443. // corresponding QualType into "QT".
  444. for (const auto &ITE : ImageTypesMap) {
  445. OS << " case OCLT_" << ITE.first.str() << ":\n"
  446. << " switch (Ty.AccessQualifier) {\n"
  447. << " case OCLAQ_None:\n"
  448. << " llvm_unreachable(\"Image without access qualifier\");\n";
  449. for (const auto &Image : ITE.second) {
  450. OS << StringSwitch<const char *>(
  451. Image->getValueAsString("AccessQualifier"))
  452. .Case("RO", " case OCLAQ_ReadOnly:\n")
  453. .Case("WO", " case OCLAQ_WriteOnly:\n")
  454. .Case("RW", " case OCLAQ_ReadWrite:\n")
  455. << " QT.push_back(Context."
  456. << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
  457. << " break;\n";
  458. }
  459. OS << " }\n"
  460. << " break;\n";
  461. }
  462. // Switch cases for generic types.
  463. for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
  464. OS << " case OCLT_" << GenType->getValueAsString("Name") << ":\n";
  465. OS << " QT.append({";
  466. // Build the Cartesian product of (vector sizes) x (types). Only insert
  467. // the plain scalar types for now; other type information such as vector
  468. // size and type qualifiers will be added after the switch statement.
  469. for (unsigned I = 0; I < GenType->getValueAsDef("VectorList")
  470. ->getValueAsListOfInts("List")
  471. .size();
  472. I++) {
  473. for (const auto *T :
  474. GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
  475. OS << "Context."
  476. << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
  477. }
  478. }
  479. OS << "});\n";
  480. // GenTypeNumTypes is the number of types in the GenType
  481. // (e.g. float/double/half).
  482. OS << " GenTypeNumTypes = "
  483. << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")
  484. .size()
  485. << ";\n";
  486. // GenVectorSizes is the list of vector sizes for this GenType.
  487. // QT contains GenTypeNumTypes * #GenVectorSizes elements.
  488. OS << " GenVectorSizes = List"
  489. << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
  490. << ";\n";
  491. OS << " break;\n";
  492. }
  493. // Switch cases for non generic, non image types (int, int4, float, ...).
  494. // Only insert the plain scalar type; vector information and type qualifiers
  495. // are added in step 2.
  496. std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
  497. StringMap<bool> TypesSeen;
  498. for (const auto *T : Types) {
  499. // Check this is not an image type
  500. if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
  501. continue;
  502. // Check we have not seen this Type
  503. if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
  504. continue;
  505. TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
  506. // Check the Type does not have an "abstract" QualType
  507. auto QT = T->getValueAsDef("QTName");
  508. if (QT->getValueAsBit("IsAbstract") == 1)
  509. continue;
  510. // Emit the cases for non generic, non image types.
  511. OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
  512. OS << " QT.push_back(Context." << QT->getValueAsString("Name")
  513. << ");\n";
  514. OS << " break;\n";
  515. }
  516. // End of switch statement.
  517. OS << " default:\n"
  518. << " llvm_unreachable(\"OpenCL builtin type not handled yet\");\n"
  519. << " } // end of switch (Ty.ID)\n\n";
  520. // Step 2.
  521. // Add ExtVector types if this was a generic type, as the switch statement
  522. // above only populated the list with scalar types. This completes the
  523. // construction of the Cartesian product of (vector sizes) x (types).
  524. OS << " // Construct the different vector types for each generic type.\n";
  525. OS << " if (Ty.ID >= " << TypeList.size() << ") {";
  526. OS << R"(
  527. for (unsigned I = 0; I < QT.size(); I++) {
  528. // For scalars, size is 1.
  529. if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
  530. QT[I] = Context.getExtVectorType(QT[I],
  531. GenVectorSizes[I / GenTypeNumTypes]);
  532. }
  533. }
  534. }
  535. )";
  536. // Assign the right attributes to the types (e.g. vector size).
  537. OS << R"(
  538. // Set vector size for non-generic vector types.
  539. if (Ty.VectorWidth > 1) {
  540. for (unsigned Index = 0; Index < QT.size(); Index++) {
  541. QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
  542. }
  543. }
  544. if (Ty.IsVolatile != 0) {
  545. for (unsigned Index = 0; Index < QT.size(); Index++) {
  546. QT[Index] = Context.getVolatileType(QT[Index]);
  547. }
  548. }
  549. if (Ty.IsConst != 0) {
  550. for (unsigned Index = 0; Index < QT.size(); Index++) {
  551. QT[Index] = Context.getConstType(QT[Index]);
  552. }
  553. }
  554. // Transform the type to a pointer as the last step, if necessary.
  555. // Builtin functions only have pointers on [const|volatile], no
  556. // [const|volatile] pointers, so this is ok to do it as a last step.
  557. if (Ty.IsPointer != 0) {
  558. for (unsigned Index = 0; Index < QT.size(); Index++) {
  559. QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
  560. QT[Index] = Context.getPointerType(QT[Index]);
  561. }
  562. }
  563. )";
  564. // End of the "OCL2Qual" function.
  565. OS << "\n} // OCL2Qual\n";
  566. }
  567. void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
  568. BuiltinNameEmitter NameChecker(Records, OS);
  569. NameChecker.Emit();
  570. }