blob: 4042c17c5296a15b0cecc78e41308c32003cf258 [file] [log] [blame]
Sven van Haastregt79a222f2019-06-03 09:39:11 +00001//===- 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>.
Sven van Haastregtb21a3652019-08-19 11:56:03 +000018// BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
Sven van Haastregt79a222f2019-06-03 09:39:11 +000019// <SigIndex, SigLen> of the overloads of "cos".
Sven van Haastregtb21a3652019-08-19 11:56:03 +000020// 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//
Sven van Haastregt79a222f2019-06-03 09:39:11 +000051//===----------------------------------------------------------------------===//
52
John McCallc45f8d42019-10-01 23:12:57 +000053#include "TableGenBackends.h"
Sven van Haastregt79a222f2019-06-03 09:39:11 +000054#include "llvm/ADT/MapVector.h"
55#include "llvm/ADT/STLExtras.h"
56#include "llvm/ADT/SmallString.h"
57#include "llvm/ADT/StringExtras.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/StringSet.h"
Sven van Haastregt988f1e32019-09-05 10:01:24 +000060#include "llvm/ADT/StringSwitch.h"
Sven van Haastregt79a222f2019-06-03 09:39:11 +000061#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/raw_ostream.h"
63#include "llvm/TableGen/Error.h"
64#include "llvm/TableGen/Record.h"
65#include "llvm/TableGen/StringMatcher.h"
66#include "llvm/TableGen/TableGenBackend.h"
67#include <set>
68
69using namespace llvm;
70
71namespace {
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +000072
73// A list of signatures that are shared by one or more builtin functions.
74struct BuiltinTableEntries {
75 SmallVector<StringRef, 4> Names;
76 std::vector<std::pair<const Record *, unsigned>> Signatures;
77};
78
Sven van Haastregt79a222f2019-06-03 09:39:11 +000079class BuiltinNameEmitter {
80public:
81 BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
82 : Records(Records), OS(OS) {}
83
84 // Entrypoint to generate the functions and structures for checking
85 // whether a function is an OpenCL builtin function.
86 void Emit();
87
88private:
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +000089 // A list of indices into the builtin function table.
90 using BuiltinIndexListTy = SmallVector<unsigned, 11>;
91
Sven van Haastregt79a222f2019-06-03 09:39:11 +000092 // Contains OpenCL builtin functions and related information, stored as
93 // Record instances. They are coming from the associated TableGen file.
94 RecordKeeper &Records;
95
96 // The output file.
97 raw_ostream &OS;
98
Sven van Haastregtb21a3652019-08-19 11:56:03 +000099 // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum
100 // definitions in the Output string parameter, and save their Record instances
101 // in the List parameter.
102 // \param Types (in) List containing the Types to extract.
103 // \param TypesSeen (inout) List containing the Types already extracted.
104 // \param Output (out) String containing the enums to emit in the output file.
105 // \param List (out) List containing the extracted Types, except the Types in
106 // TypesSeen.
107 void ExtractEnumTypes(std::vector<Record *> &Types,
108 StringMap<bool> &TypesSeen, std::string &Output,
109 std::vector<const Record *> &List);
110
111 // Emit the enum or struct used in the generated file.
112 // Populate the TypeList at the same time.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000113 void EmitDeclarations();
114
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000115 // Parse the Records generated by TableGen to populate the SignaturesList,
116 // FctOverloadMap and TypeMap.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000117 void GetOverloads();
118
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000119 // Compare two lists of signatures and check that e.g. the OpenCL version,
120 // function attributes, and extension are equal for each signature.
121 // \param Candidate (in) Entry in the SignatureListMap to check.
122 // \param SignatureList (in) List of signatures of the considered function.
123 // \returns true if the two lists of signatures are identical.
124 bool CanReuseSignature(
125 BuiltinIndexListTy *Candidate,
126 std::vector<std::pair<const Record *, unsigned>> &SignatureList);
127
128 // Group functions with the same list of signatures by populating the
129 // SignatureListMap.
130 // Some builtin functions have the same list of signatures, for example the
131 // "sin" and "cos" functions. To save space in the BuiltinTable, the
132 // "isOpenCLBuiltin" function will have the same output for these two
133 // function names.
134 void GroupBySignature();
135
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000136 // Emit the TypeTable containing all types used by OpenCL builtins.
137 void EmitTypeTable();
138
139 // Emit the SignatureTable. This table contains all the possible signatures.
140 // A signature is stored as a list of indexes of the TypeTable.
141 // The first index references the return type (mandatory), and the followings
142 // reference its arguments.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000143 // E.g.:
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000144 // 15, 2, 15 can represent a function with the signature:
145 // int func(float, int)
146 // The "int" type being at the index 15 in the TypeTable.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000147 void EmitSignatureTable();
148
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000149 // Emit the BuiltinTable table. This table contains all the overloads of
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000150 // each function, and is a struct OpenCLBuiltinDecl.
151 // E.g.:
Sven van Haastregted69faa2019-09-19 13:41:51 +0000152 // // 891 convert_float2_rtn
153 // { 58, 2, 100, 0 },
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000154 // This means that the signature of this convert_float2_rtn overload has
155 // 1 argument (+1 for the return type), stored at index 58 in
Sven van Haastregted69faa2019-09-19 13:41:51 +0000156 // the SignatureTable. The last two values represent the minimum (1.0) and
157 // maximum (0, meaning no max version) OpenCL version in which this overload
158 // is supported.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000159 void EmitBuiltinTable();
160
161 // Emit a StringMatcher function to check whether a function name is an
162 // OpenCL builtin function name.
163 void EmitStringMatcher();
164
165 // Emit a function returning the clang QualType instance associated with
166 // the TableGen Record Type.
167 void EmitQualTypeFinder();
168
169 // Contains a list of the available signatures, without the name of the
170 // function. Each pair consists of a signature and a cumulative index.
171 // E.g.: <<float, float>, 0>,
172 // <<float, int, int, 2>>,
173 // <<float>, 5>,
174 // ...
175 // <<double, double>, 35>.
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000176 std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000177
178 // Map the name of a builtin function to its prototypes (instances of the
179 // TableGen "Builtin" class).
180 // Each prototype is registered as a pair of:
181 // <pointer to the "Builtin" instance,
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000182 // cumulative index of the associated signature in the SignaturesList>
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000183 // E.g.: The function cos: (float cos(float), double cos(double), ...)
184 // <"cos", <<ptrToPrototype0, 5>,
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000185 // <ptrToPrototype1, 35>,
186 // <ptrToPrototype2, 79>>
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000187 // ptrToPrototype1 has the following signature: <double, double>
188 MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000189 FctOverloadMap;
190
191 // Contains the map of OpenCL types to their index in the TypeTable.
192 MapVector<const Record *, unsigned> TypeMap;
193
194 // List of OpenCL type names in the same order as in enum OpenCLTypeID.
195 // This list does not contain generic types.
196 std::vector<const Record *> TypeList;
197
198 // Same as TypeList, but for generic types only.
199 std::vector<const Record *> GenTypeList;
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000200
201 // Map an ordered vector of signatures to their original Record instances,
202 // and to a list of function names that share these signatures.
203 //
204 // For example, suppose the "cos" and "sin" functions have only three
205 // signatures, and these signatures are at index Ix in the SignatureTable:
206 // cos | sin | Signature | Index
207 // float cos(float) | float sin(float) | Signature1 | I1
208 // double cos(double) | double sin(double) | Signature2 | I2
209 // half cos(half) | half sin(half) | Signature3 | I3
210 //
211 // Then we will create a mapping of the vector of signatures:
212 // SignatureListMap[<I1, I2, I3>] = <
213 // <"cos", "sin">,
214 // <Signature1, Signature2, Signature3>>
215 // The function "tan", having the same signatures, would be mapped to the
216 // same entry (<I1, I2, I3>).
217 MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000218};
219} // namespace
220
221void BuiltinNameEmitter::Emit() {
222 emitSourceFileHeader("OpenCL Builtin handling", OS);
223
224 OS << "#include \"llvm/ADT/StringRef.h\"\n";
225 OS << "using namespace clang;\n\n";
226
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000227 // Emit enums and structs.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000228 EmitDeclarations();
229
230 GetOverloads();
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000231 GroupBySignature();
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000232
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000233 // Emit tables.
234 EmitTypeTable();
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000235 EmitSignatureTable();
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000236 EmitBuiltinTable();
237
238 EmitStringMatcher();
239
240 EmitQualTypeFinder();
241}
242
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000243void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
244 StringMap<bool> &TypesSeen,
245 std::string &Output,
246 std::vector<const Record *> &List) {
247 raw_string_ostream SS(Output);
248
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000249 for (const auto *T : Types) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000250 if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
251 SS << " OCLT_" + T->getValueAsString("Name") << ",\n";
252 // Save the type names in the same order as their enum value. Note that
253 // the Record can be a VectorType or something else, only the name is
254 // important.
255 List.push_back(T);
256 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
257 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000258 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000259 SS.flush();
260}
261
262void BuiltinNameEmitter::EmitDeclarations() {
263 // Enum of scalar type names (float, int, ...) and generic type sets.
264 OS << "enum OpenCLTypeID {\n";
265
266 StringMap<bool> TypesSeen;
267 std::string GenTypeEnums;
268 std::string TypeEnums;
269
270 // Extract generic types and non-generic types separately, to keep
271 // gentypes at the end of the enum which simplifies the special handling
272 // for gentypes in SemaLookup.
273 std::vector<Record *> GenTypes =
274 Records.getAllDerivedDefinitions("GenericType");
275 ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
276
277 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
278 ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
279
280 OS << TypeEnums;
281 OS << GenTypeEnums;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000282 OS << "};\n";
283
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000284 // Structure definitions.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000285 OS << R"(
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000286// Image access qualifier.
287enum OpenCLAccessQual : unsigned char {
288 OCLAQ_None,
289 OCLAQ_ReadOnly,
290 OCLAQ_WriteOnly,
291 OCLAQ_ReadWrite
292};
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000293
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000294// Represents a return type or argument type.
295struct OpenCLTypeStruct {
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000296 // A type (e.g. float, int, ...).
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000297 const OpenCLTypeID ID;
298 // Vector size (if applicable; 0 for scalars and generic types).
299 const unsigned VectorWidth;
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000300 // 0 if the type is not a pointer.
301 const bool IsPointer;
302 // 0 if the type is not const.
303 const bool IsConst;
304 // 0 if the type is not volatile.
305 const bool IsVolatile;
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000306 // Access qualifier.
307 const OpenCLAccessQual AccessQualifier;
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000308 // Address space of the pointer (if applicable).
309 const LangAS AS;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000310};
311
312// One overload of an OpenCL builtin function.
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000313struct OpenCLBuiltinStruct {
314 // Index of the signature in the OpenCLTypeStruct table.
315 const unsigned SigTableIndex;
316 // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
317 // the SignatureTable represent the complete signature. The first type at
318 // index SigTableIndex is the return type.
319 const unsigned NumTypes;
Sven van Haastregt9a8d4772019-11-05 10:07:43 +0000320 // Function attribute __attribute__((pure))
321 const bool IsPure;
322 // Function attribute __attribute__((const))
323 const bool IsConst;
324 // Function attribute __attribute__((convergent))
325 const bool IsConv;
Sven van Haastregted69faa2019-09-19 13:41:51 +0000326 // First OpenCL version in which this overload was introduced (e.g. CL20).
327 const unsigned short MinVersion;
328 // First OpenCL version in which this overload was removed (e.g. CL20).
329 const unsigned short MaxVersion;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000330};
331
332)";
333}
334
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000335// Verify that the combination of GenTypes in a signature is supported.
336// To simplify the logic for creating overloads in SemaLookup, only allow
337// a signature to contain different GenTypes if these GenTypes represent
338// the same number of actual scalar or vector types.
339//
340// Exit with a fatal error if an unsupported construct is encountered.
341static void VerifySignature(const std::vector<Record *> &Signature,
342 const Record *BuiltinRec) {
343 unsigned GenTypeVecSizes = 1;
344 unsigned GenTypeTypes = 1;
345
346 for (const auto *T : Signature) {
347 // Check all GenericType arguments in this signature.
348 if (T->isSubClassOf("GenericType")) {
349 // Check number of vector sizes.
350 unsigned NVecSizes =
351 T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
352 if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
353 if (GenTypeVecSizes > 1) {
354 // We already saw a gentype with a different number of vector sizes.
355 PrintFatalError(BuiltinRec->getLoc(),
356 "number of vector sizes should be equal or 1 for all gentypes "
357 "in a declaration");
358 }
359 GenTypeVecSizes = NVecSizes;
360 }
361
362 // Check number of data types.
363 unsigned NTypes =
364 T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
365 if (NTypes != GenTypeTypes && NTypes != 1) {
366 if (GenTypeTypes > 1) {
367 // We already saw a gentype with a different number of types.
368 PrintFatalError(BuiltinRec->getLoc(),
369 "number of types should be equal or 1 for all gentypes "
370 "in a declaration");
371 }
372 GenTypeTypes = NTypes;
373 }
374 }
375 }
376}
377
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000378void BuiltinNameEmitter::GetOverloads() {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000379 // Populate the TypeMap.
380 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
381 unsigned I = 0;
382 for (const auto &T : Types) {
383 TypeMap.insert(std::make_pair(T, I++));
384 }
385
386 // Populate the SignaturesList and the FctOverloadMap.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000387 unsigned CumulativeSignIndex = 0;
388 std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
389 for (const auto *B : Builtins) {
390 StringRef BName = B->getValueAsString("Name");
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000391 if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
392 FctOverloadMap.insert(std::make_pair(
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000393 BName, std::vector<std::pair<const Record *, unsigned>>{}));
394 }
395
396 auto Signature = B->getValueAsListOfDefs("Signature");
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000397 // Reuse signatures to avoid unnecessary duplicates.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000398 auto it =
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000399 std::find_if(SignaturesList.begin(), SignaturesList.end(),
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000400 [&](const std::pair<std::vector<Record *>, unsigned> &a) {
401 return a.first == Signature;
402 });
403 unsigned SignIndex;
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000404 if (it == SignaturesList.end()) {
405 VerifySignature(Signature, B);
406 SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000407 SignIndex = CumulativeSignIndex;
408 CumulativeSignIndex += Signature.size();
409 } else {
410 SignIndex = it->second;
411 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000412 FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000413 }
414}
415
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000416void BuiltinNameEmitter::EmitTypeTable() {
417 OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
418 for (const auto &T : TypeMap) {
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000419 const char *AccessQual =
420 StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
421 .Case("RO", "OCLAQ_ReadOnly")
422 .Case("WO", "OCLAQ_WriteOnly")
423 .Case("RW", "OCLAQ_ReadWrite")
424 .Default("OCLAQ_None");
425
426 OS << " // " << T.second << "\n"
427 << " {OCLT_" << T.first->getValueAsString("Name") << ", "
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000428 << T.first->getValueAsInt("VecWidth") << ", "
429 << T.first->getValueAsBit("IsPointer") << ", "
430 << T.first->getValueAsBit("IsConst") << ", "
431 << T.first->getValueAsBit("IsVolatile") << ", "
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000432 << AccessQual << ", "
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000433 << T.first->getValueAsString("AddrSpace") << "},\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000434 }
435 OS << "};\n\n";
436}
437
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000438void BuiltinNameEmitter::EmitSignatureTable() {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000439 // Store a type (e.g. int, float, int2, ...). The type is stored as an index
440 // of a struct OpenCLType table. Multiple entries following each other form a
441 // signature.
442 OS << "static const unsigned SignatureTable[] = {\n";
443 for (const auto &P : SignaturesList) {
444 OS << " // " << P.second << "\n ";
445 for (const Record *R : P.first) {
446 OS << TypeMap.find(R)->second << ", ";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000447 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000448 OS << "\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000449 }
450 OS << "};\n\n";
451}
452
453void BuiltinNameEmitter::EmitBuiltinTable() {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000454 unsigned Index = 0;
455
456 OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000457 for (const auto &SLM : SignatureListMap) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000458
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000459 OS << " // " << (Index + 1) << ": ";
460 for (const auto &Name : SLM.second.Names) {
461 OS << Name << ", ";
462 }
463 OS << "\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000464
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000465 for (const auto &Overload : SLM.second.Signatures) {
Sven van Haastregted69faa2019-09-19 13:41:51 +0000466 OS << " { " << Overload.second << ", "
467 << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
Sven van Haastregt9a8d4772019-11-05 10:07:43 +0000468 << (Overload.first->getValueAsBit("IsPure")) << ", "
469 << (Overload.first->getValueAsBit("IsConst")) << ", "
470 << (Overload.first->getValueAsBit("IsConv")) << ", "
Sven van Haastregted69faa2019-09-19 13:41:51 +0000471 << Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID")
472 << ", "
473 << Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID")
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000474 << " },\n";
Sven van Haastregted69faa2019-09-19 13:41:51 +0000475 Index++;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000476 }
477 }
478 OS << "};\n\n";
479}
480
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000481bool BuiltinNameEmitter::CanReuseSignature(
482 BuiltinIndexListTy *Candidate,
483 std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
484 assert(Candidate->size() == SignatureList.size() &&
485 "signature lists should have the same size");
486
487 auto &CandidateSigs =
488 SignatureListMap.find(Candidate)->second.Signatures;
489 for (unsigned Index = 0; Index < Candidate->size(); Index++) {
490 const Record *Rec = SignatureList[Index].first;
491 const Record *Rec2 = CandidateSigs[Index].first;
492 if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
493 Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
494 Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
495 Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
496 Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
497 Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
498 Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
499 Rec->getValueAsString("Extension") ==
500 Rec2->getValueAsString("Extension")) {
501 return true;
502 }
503 }
504 return false;
505}
506
507void BuiltinNameEmitter::GroupBySignature() {
508 // List of signatures known to be emitted.
509 std::vector<BuiltinIndexListTy *> KnownSignatures;
510
511 for (auto &Fct : FctOverloadMap) {
512 bool FoundReusableSig = false;
513
514 // Gather all signatures for the current function.
515 auto *CurSignatureList = new BuiltinIndexListTy();
516 for (const auto &Signature : Fct.second) {
517 CurSignatureList->push_back(Signature.second);
518 }
519 // Sort the list to facilitate future comparisons.
520 std::sort(CurSignatureList->begin(), CurSignatureList->end());
521
522 // Check if we have already seen another function with the same list of
523 // signatures. If so, just add the name of the function.
524 for (auto *Candidate : KnownSignatures) {
525 if (Candidate->size() == CurSignatureList->size() &&
526 *Candidate == *CurSignatureList) {
527 if (CanReuseSignature(Candidate, Fct.second)) {
528 SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
529 FoundReusableSig = true;
530 }
531 }
532 }
533
534 if (FoundReusableSig) {
535 delete CurSignatureList;
536 } else {
537 // Add a new entry.
538 SignatureListMap[CurSignatureList] = {
539 SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
540 KnownSignatures.push_back(CurSignatureList);
541 }
542 }
543
544 for (auto *I : KnownSignatures) {
545 delete I;
546 }
547}
548
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000549void BuiltinNameEmitter::EmitStringMatcher() {
550 std::vector<StringMatcher::StringPair> ValidBuiltins;
551 unsigned CumulativeIndex = 1;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000552
Sven van Haastregt0e56b0f2019-11-05 10:16:45 +0000553 for (const auto &SLM : SignatureListMap) {
554 const auto &Ovl = SLM.second.Signatures;
555
556 // A single signature list may be used by different builtins. Return the
557 // same <index, length> pair for each of those builtins.
558 for (const auto &FctName : SLM.second.Names) {
559 std::string RetStmt;
560 raw_string_ostream SS(RetStmt);
561 SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
562 << ");";
563 SS.flush();
564 ValidBuiltins.push_back(StringMatcher::StringPair(FctName, RetStmt));
565 }
566 CumulativeIndex += Ovl.size();
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000567 }
568
569 OS << R"(
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000570// Find out whether a string matches an existing OpenCL builtin function name.
571// Returns: A pair <0, 0> if no name matches.
572// A pair <Index, Len> indexing the BuiltinTable if the name is
573// matching an OpenCL builtin function.
574static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000575
576)";
577
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000578 StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000579
580 OS << " return std::make_pair(0, 0);\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000581 OS << "} // isOpenCLBuiltin\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000582}
583
584void BuiltinNameEmitter::EmitQualTypeFinder() {
585 OS << R"(
586
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000587// Convert an OpenCLTypeStruct type to a list of QualTypes.
588// Generic types represent multiple types and vector sizes, thus a vector
589// is returned. The conversion is done in two steps:
590// Step 1: A switch statement fills a vector with scalar base types for the
591// Cartesian product of (vector sizes) x (types) for generic types,
592// or a single scalar type for non generic types.
593// Step 2: Qualifiers and other type properties such as vector size are
594// applied.
595static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
Benjamin Kramer19651b62019-08-24 13:04:34 +0000596 llvm::SmallVectorImpl<QualType> &QT) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000597 // Number of scalar types in the GenType.
598 unsigned GenTypeNumTypes;
599 // Pointer to the list of vector sizes for the GenType.
Benjamin Kramer19651b62019-08-24 13:04:34 +0000600 llvm::ArrayRef<unsigned> GenVectorSizes;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000601)";
602
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000603 // Generate list of vector sizes for each generic type.
604 for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
Benjamin Kramer19651b62019-08-24 13:04:34 +0000605 OS << " constexpr unsigned List"
606 << VectList->getValueAsString("Name") << "[] = {";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000607 for (const auto V : VectList->getValueAsListOfInts("List")) {
608 OS << V << ", ";
609 }
610 OS << "};\n";
611 }
612
613 // Step 1.
614 // Start of switch statement over all types.
615 OS << "\n switch (Ty.ID) {\n";
616
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000617 // Switch cases for image types (Image2d, Image3d, ...)
618 std::vector<Record *> ImageTypes =
619 Records.getAllDerivedDefinitions("ImageType");
620
621 // Map an image type name to its 3 access-qualified types (RO, WO, RW).
622 std::map<StringRef, SmallVector<Record *, 3>> ImageTypesMap;
623 for (auto *IT : ImageTypes) {
624 auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
625 if (Entry == ImageTypesMap.end()) {
626 SmallVector<Record *, 3> ImageList;
627 ImageList.push_back(IT);
628 ImageTypesMap.insert(
629 std::make_pair(IT->getValueAsString("Name"), ImageList));
630 } else {
631 Entry->second.push_back(IT);
632 }
633 }
634
635 // Emit the cases for the image types. For an image type name, there are 3
636 // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field
637 // tells which one is needed. Emit a switch statement that puts the
638 // corresponding QualType into "QT".
639 for (const auto &ITE : ImageTypesMap) {
640 OS << " case OCLT_" << ITE.first.str() << ":\n"
641 << " switch (Ty.AccessQualifier) {\n"
642 << " case OCLAQ_None:\n"
643 << " llvm_unreachable(\"Image without access qualifier\");\n";
644 for (const auto &Image : ITE.second) {
645 OS << StringSwitch<const char *>(
646 Image->getValueAsString("AccessQualifier"))
647 .Case("RO", " case OCLAQ_ReadOnly:\n")
648 .Case("WO", " case OCLAQ_WriteOnly:\n")
649 .Case("RW", " case OCLAQ_ReadWrite:\n")
650 << " QT.push_back(Context."
651 << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
652 << " break;\n";
653 }
654 OS << " }\n"
655 << " break;\n";
656 }
657
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000658 // Switch cases for generic types.
659 for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
660 OS << " case OCLT_" << GenType->getValueAsString("Name") << ":\n";
Benjamin Kramer19651b62019-08-24 13:04:34 +0000661 OS << " QT.append({";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000662
663 // Build the Cartesian product of (vector sizes) x (types). Only insert
664 // the plain scalar types for now; other type information such as vector
665 // size and type qualifiers will be added after the switch statement.
666 for (unsigned I = 0; I < GenType->getValueAsDef("VectorList")
667 ->getValueAsListOfInts("List")
668 .size();
669 I++) {
670 for (const auto *T :
671 GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
Benjamin Kramer19651b62019-08-24 13:04:34 +0000672 OS << "Context."
673 << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000674 }
675 }
Sven van Haastregt92b2be12019-09-03 11:23:24 +0000676 OS << "});\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000677 // GenTypeNumTypes is the number of types in the GenType
678 // (e.g. float/double/half).
679 OS << " GenTypeNumTypes = "
680 << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")
681 .size()
682 << ";\n";
683 // GenVectorSizes is the list of vector sizes for this GenType.
684 // QT contains GenTypeNumTypes * #GenVectorSizes elements.
Benjamin Kramer19651b62019-08-24 13:04:34 +0000685 OS << " GenVectorSizes = List"
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000686 << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
687 << ";\n";
688 OS << " break;\n";
689 }
690
691 // Switch cases for non generic, non image types (int, int4, float, ...).
692 // Only insert the plain scalar type; vector information and type qualifiers
693 // are added in step 2.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000694 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
695 StringMap<bool> TypesSeen;
696
697 for (const auto *T : Types) {
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000698 // Check this is not an image type
699 if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
700 continue;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000701 // Check we have not seen this Type
702 if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
703 continue;
704 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
705
706 // Check the Type does not have an "abstract" QualType
707 auto QT = T->getValueAsDef("QTName");
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000708 if (QT->getValueAsBit("IsAbstract") == 1)
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000709 continue;
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000710 // Emit the cases for non generic, non image types.
711 OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
712 OS << " QT.push_back(Context." << QT->getValueAsString("Name")
713 << ");\n";
714 OS << " break;\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000715 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000716
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000717 // End of switch statement.
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000718 OS << " default:\n"
719 << " llvm_unreachable(\"OpenCL builtin type not handled yet\");\n"
720 << " } // end of switch (Ty.ID)\n\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000721
722 // Step 2.
723 // Add ExtVector types if this was a generic type, as the switch statement
724 // above only populated the list with scalar types. This completes the
725 // construction of the Cartesian product of (vector sizes) x (types).
726 OS << " // Construct the different vector types for each generic type.\n";
727 OS << " if (Ty.ID >= " << TypeList.size() << ") {";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000728 OS << R"(
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000729 for (unsigned I = 0; I < QT.size(); I++) {
730 // For scalars, size is 1.
Benjamin Kramer19651b62019-08-24 13:04:34 +0000731 if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000732 QT[I] = Context.getExtVectorType(QT[I],
Benjamin Kramer19651b62019-08-24 13:04:34 +0000733 GenVectorSizes[I / GenTypeNumTypes]);
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000734 }
735 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000736 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000737)";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000738
739 // Assign the right attributes to the types (e.g. vector size).
740 OS << R"(
741 // Set vector size for non-generic vector types.
742 if (Ty.VectorWidth > 1) {
743 for (unsigned Index = 0; Index < QT.size(); Index++) {
744 QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
745 }
746 }
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000747
748 if (Ty.IsVolatile != 0) {
749 for (unsigned Index = 0; Index < QT.size(); Index++) {
750 QT[Index] = Context.getVolatileType(QT[Index]);
751 }
752 }
753
754 if (Ty.IsConst != 0) {
755 for (unsigned Index = 0; Index < QT.size(); Index++) {
756 QT[Index] = Context.getConstType(QT[Index]);
757 }
758 }
759
760 // Transform the type to a pointer as the last step, if necessary.
761 // Builtin functions only have pointers on [const|volatile], no
762 // [const|volatile] pointers, so this is ok to do it as a last step.
763 if (Ty.IsPointer != 0) {
764 for (unsigned Index = 0; Index < QT.size(); Index++) {
765 QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
766 QT[Index] = Context.getPointerType(QT[Index]);
767 }
768 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000769)";
770
771 // End of the "OCL2Qual" function.
772 OS << "\n} // OCL2Qual\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000773}
774
John McCallc45f8d42019-10-01 23:12:57 +0000775void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000776 BuiltinNameEmitter NameChecker(Records, OS);
777 NameChecker.Emit();
778}