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 // These backends consume the definitions of OpenCL builtin functions in
12 // clang/lib/Sema/OpenCLBuiltins.td and produce builtin handling code for
13 // inclusion in SemaLookup.cpp, or a test file that calls all declared builtins.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "TableGenBackends.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 #include "llvm/TableGen/StringMatcher.h"
30 #include "llvm/TableGen/TableGenBackend.h"
31 
32 using namespace llvm;
33 
34 namespace {
35 
36 // A list of signatures that are shared by one or more builtin functions.
37 struct BuiltinTableEntries {
38   SmallVector<StringRef, 4> Names;
39   std::vector<std::pair<const Record *, unsigned>> Signatures;
40 };
41 
42 // This tablegen backend emits code for checking whether a function is an
43 // OpenCL builtin function. If so, all overloads of this function are
44 // added to the LookupResult. The generated include file is used by
45 // SemaLookup.cpp
46 //
47 // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
48 // returns a pair <Index, Len>.
49 // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
50 // <SigIndex, SigLen> of the overloads of "cos".
51 // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
52 // one of the signatures of "cos". The SignatureTable entry can be
53 // referenced by other functions, e.g. "sin", to exploit the fact that
54 // many OpenCL builtins share the same signature.
55 //
56 // The file generated by this TableGen emitter contains the following:
57 //
58 //  * Structs and enums to represent types and function signatures.
59 //
60 //  * const char *FunctionExtensionTable[]
61 //    List of space-separated OpenCL extensions.  A builtin references an
62 //    entry in this table when the builtin requires a particular (set of)
63 //    extension(s) to be enabled.
64 //
65 //  * OpenCLTypeStruct TypeTable[]
66 //    Type information for return types and arguments.
67 //
68 //  * unsigned SignatureTable[]
69 //    A list of types representing function signatures.  Each entry is an index
70 //    into the above TypeTable.  Multiple entries following each other form a
71 //    signature, where the first entry is the return type and subsequent
72 //    entries are the argument types.
73 //
74 //  * OpenCLBuiltinStruct BuiltinTable[]
75 //    Each entry represents one overload of an OpenCL builtin function and
76 //    consists of an index into the SignatureTable and the number of arguments.
77 //
78 //  * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
79 //    Find out whether a string matches an existing OpenCL builtin function
80 //    name and return an index into BuiltinTable and the number of overloads.
81 //
82 //  * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&)
83 //    Convert an OpenCLTypeStruct type to a list of QualType instances.
84 //    One OpenCLTypeStruct can represent multiple types, primarily when using
85 //    GenTypes.
86 //
87 class BuiltinNameEmitter {
88 public:
89   BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
90       : Records(Records), OS(OS) {}
91 
92   // Entrypoint to generate the functions and structures for checking
93   // whether a function is an OpenCL builtin function.
94   void Emit();
95 
96 private:
97   // A list of indices into the builtin function table.
98   using BuiltinIndexListTy = SmallVector<unsigned, 11>;
99 
100   // Contains OpenCL builtin functions and related information, stored as
101   // Record instances. They are coming from the associated TableGen file.
102   RecordKeeper &Records;
103 
104   // The output file.
105   raw_ostream &OS;
106 
107   // Helper function for BuiltinNameEmitter::EmitDeclarations.  Generate enum
108   // definitions in the Output string parameter, and save their Record instances
109   // in the List parameter.
110   // \param Types (in) List containing the Types to extract.
111   // \param TypesSeen (inout) List containing the Types already extracted.
112   // \param Output (out) String containing the enums to emit in the output file.
113   // \param List (out) List containing the extracted Types, except the Types in
114   //        TypesSeen.
115   void ExtractEnumTypes(std::vector<Record *> &Types,
116                         StringMap<bool> &TypesSeen, std::string &Output,
117                         std::vector<const Record *> &List);
118 
119   // Emit the enum or struct used in the generated file.
120   // Populate the TypeList at the same time.
121   void EmitDeclarations();
122 
123   // Parse the Records generated by TableGen to populate the SignaturesList,
124   // FctOverloadMap and TypeMap.
125   void GetOverloads();
126 
127   // Compare two lists of signatures and check that e.g. the OpenCL version,
128   // function attributes, and extension are equal for each signature.
129   // \param Candidate (in) Entry in the SignatureListMap to check.
130   // \param SignatureList (in) List of signatures of the considered function.
131   // \returns true if the two lists of signatures are identical.
132   bool CanReuseSignature(
133       BuiltinIndexListTy *Candidate,
134       std::vector<std::pair<const Record *, unsigned>> &SignatureList);
135 
136   // Group functions with the same list of signatures by populating the
137   // SignatureListMap.
138   // Some builtin functions have the same list of signatures, for example the
139   // "sin" and "cos" functions. To save space in the BuiltinTable, the
140   // "isOpenCLBuiltin" function will have the same output for these two
141   // function names.
142   void GroupBySignature();
143 
144   // Emit the FunctionExtensionTable that lists all function extensions.
145   void EmitExtensionTable();
146 
147   // Emit the TypeTable containing all types used by OpenCL builtins.
148   void EmitTypeTable();
149 
150   // Emit the SignatureTable. This table contains all the possible signatures.
151   // A signature is stored as a list of indexes of the TypeTable.
152   // The first index references the return type (mandatory), and the followings
153   // reference its arguments.
154   // E.g.:
155   // 15, 2, 15 can represent a function with the signature:
156   // int func(float, int)
157   // The "int" type being at the index 15 in the TypeTable.
158   void EmitSignatureTable();
159 
160   // Emit the BuiltinTable table. This table contains all the overloads of
161   // each function, and is a struct OpenCLBuiltinDecl.
162   // E.g.:
163   // // 891 convert_float2_rtn
164   //   { 58, 2, 3, 100, 0 },
165   // This means that the signature of this convert_float2_rtn overload has
166   // 1 argument (+1 for the return type), stored at index 58 in
167   // the SignatureTable.  This prototype requires extension "3" in the
168   // FunctionExtensionTable.  The last two values represent the minimum (1.0)
169   // and maximum (0, meaning no max version) OpenCL version in which this
170   // overload is supported.
171   void EmitBuiltinTable();
172 
173   // Emit a StringMatcher function to check whether a function name is an
174   // OpenCL builtin function name.
175   void EmitStringMatcher();
176 
177   // Emit a function returning the clang QualType instance associated with
178   // the TableGen Record Type.
179   void EmitQualTypeFinder();
180 
181   // Contains a list of the available signatures, without the name of the
182   // function. Each pair consists of a signature and a cumulative index.
183   // E.g.:  <<float, float>, 0>,
184   //        <<float, int, int, 2>>,
185   //        <<float>, 5>,
186   //        ...
187   //        <<double, double>, 35>.
188   std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
189 
190   // Map the name of a builtin function to its prototypes (instances of the
191   // TableGen "Builtin" class).
192   // Each prototype is registered as a pair of:
193   //   <pointer to the "Builtin" instance,
194   //    cumulative index of the associated signature in the SignaturesList>
195   // E.g.:  The function cos: (float cos(float), double cos(double), ...)
196   //        <"cos", <<ptrToPrototype0, 5>,
197   //                 <ptrToPrototype1, 35>,
198   //                 <ptrToPrototype2, 79>>
199   // ptrToPrototype1 has the following signature: <double, double>
200   MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
201       FctOverloadMap;
202 
203   // Contains the map of OpenCL types to their index in the TypeTable.
204   MapVector<const Record *, unsigned> TypeMap;
205 
206   // List of OpenCL function extensions mapping extension strings to
207   // an index into the FunctionExtensionTable.
208   StringMap<unsigned> FunctionExtensionIndex;
209 
210   // List of OpenCL type names in the same order as in enum OpenCLTypeID.
211   // This list does not contain generic types.
212   std::vector<const Record *> TypeList;
213 
214   // Same as TypeList, but for generic types only.
215   std::vector<const Record *> GenTypeList;
216 
217   // Map an ordered vector of signatures to their original Record instances,
218   // and to a list of function names that share these signatures.
219   //
220   // For example, suppose the "cos" and "sin" functions have only three
221   // signatures, and these signatures are at index Ix in the SignatureTable:
222   //          cos         |         sin         |  Signature    | Index
223   //  float   cos(float)  | float   sin(float)  |  Signature1   | I1
224   //  double  cos(double) | double  sin(double) |  Signature2   | I2
225   //  half    cos(half)   | half    sin(half)   |  Signature3   | I3
226   //
227   // Then we will create a mapping of the vector of signatures:
228   // SignatureListMap[<I1, I2, I3>] = <
229   //                  <"cos", "sin">,
230   //                  <Signature1, Signature2, Signature3>>
231   // The function "tan", having the same signatures, would be mapped to the
232   // same entry (<I1, I2, I3>).
233   MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap;
234 };
235 
236 // OpenCL builtin test generator.  This class processes the same TableGen input
237 // as BuiltinNameEmitter, but generates a .cl file that contains a call to each
238 // builtin function described in the .td input.
239 class OpenCLBuiltinTestEmitter {
240 public:
241   OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
242       : Records(Records), OS(OS) {}
243 
244   // Entrypoint to generate the functions for testing all OpenCL builtin
245   // functions.
246   void emit();
247 
248 private:
249   struct TypeFlags {
250     TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
251     bool IsConst : 1;
252     bool IsVolatile : 1;
253     bool IsPointer : 1;
254     StringRef AddrSpace;
255   };
256 
257   // Return a string representation of the given type, such that it can be
258   // used as a type in OpenCL C code.
259   std::string getTypeString(const Record *Type, TypeFlags Flags,
260                             int VectorSize) const;
261 
262   // Return the type(s) and vector size(s) for the given type.  For
263   // non-GenericTypes, the resulting vectors will contain 1 element.  For
264   // GenericTypes, the resulting vectors typically contain multiple elements.
265   void getTypeLists(Record *Type, TypeFlags &Flags,
266                     std::vector<Record *> &TypeList,
267                     std::vector<int64_t> &VectorList) const;
268 
269   // Expand the TableGen Records representing a builtin function signature into
270   // one or more function signatures.  Return them as a vector of a vector of
271   // strings, with each string containing an OpenCL C type and optional
272   // qualifiers.
273   //
274   // The Records may contain GenericTypes, which expand into multiple
275   // signatures.  Repeated occurrences of GenericType in a signature expand to
276   // the same types.  For example [char, FGenType, FGenType] expands to:
277   //   [char, float, float]
278   //   [char, float2, float2]
279   //   [char, float3, float3]
280   //   ...
281   void
282   expandTypesInSignature(const std::vector<Record *> &Signature,
283                          SmallVectorImpl<SmallVector<std::string, 2>> &Types);
284 
285   // Contains OpenCL builtin functions and related information, stored as
286   // Record instances. They are coming from the associated TableGen file.
287   RecordKeeper &Records;
288 
289   // The output file.
290   raw_ostream &OS;
291 };
292 
293 } // namespace
294 
295 void BuiltinNameEmitter::Emit() {
296   emitSourceFileHeader("OpenCL Builtin handling", OS);
297 
298   OS << "#include \"llvm/ADT/StringRef.h\"\n";
299   OS << "using namespace clang;\n\n";
300 
301   // Emit enums and structs.
302   EmitDeclarations();
303 
304   // Parse the Records to populate the internal lists.
305   GetOverloads();
306   GroupBySignature();
307 
308   // Emit tables.
309   EmitExtensionTable();
310   EmitTypeTable();
311   EmitSignatureTable();
312   EmitBuiltinTable();
313 
314   // Emit functions.
315   EmitStringMatcher();
316   EmitQualTypeFinder();
317 }
318 
319 void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
320                                           StringMap<bool> &TypesSeen,
321                                           std::string &Output,
322                                           std::vector<const Record *> &List) {
323   raw_string_ostream SS(Output);
324 
325   for (const auto *T : Types) {
326     if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
327       SS << "  OCLT_" + T->getValueAsString("Name") << ",\n";
328       // Save the type names in the same order as their enum value. Note that
329       // the Record can be a VectorType or something else, only the name is
330       // important.
331       List.push_back(T);
332       TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
333     }
334   }
335   SS.flush();
336 }
337 
338 void BuiltinNameEmitter::EmitDeclarations() {
339   // Enum of scalar type names (float, int, ...) and generic type sets.
340   OS << "enum OpenCLTypeID {\n";
341 
342   StringMap<bool> TypesSeen;
343   std::string GenTypeEnums;
344   std::string TypeEnums;
345 
346   // Extract generic types and non-generic types separately, to keep
347   // gentypes at the end of the enum which simplifies the special handling
348   // for gentypes in SemaLookup.
349   std::vector<Record *> GenTypes =
350       Records.getAllDerivedDefinitions("GenericType");
351   ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
352 
353   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
354   ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
355 
356   OS << TypeEnums;
357   OS << GenTypeEnums;
358   OS << "};\n";
359 
360   // Structure definitions.
361   OS << R"(
362 // Image access qualifier.
363 enum OpenCLAccessQual : unsigned char {
364   OCLAQ_None,
365   OCLAQ_ReadOnly,
366   OCLAQ_WriteOnly,
367   OCLAQ_ReadWrite
368 };
369 
370 // Represents a return type or argument type.
371 struct OpenCLTypeStruct {
372   // A type (e.g. float, int, ...).
373   const OpenCLTypeID ID;
374   // Vector size (if applicable; 0 for scalars and generic types).
375   const unsigned VectorWidth;
376   // 0 if the type is not a pointer.
377   const bool IsPointer : 1;
378   // 0 if the type is not const.
379   const bool IsConst : 1;
380   // 0 if the type is not volatile.
381   const bool IsVolatile : 1;
382   // Access qualifier.
383   const OpenCLAccessQual AccessQualifier;
384   // Address space of the pointer (if applicable).
385   const LangAS AS;
386 };
387 
388 // One overload of an OpenCL builtin function.
389 struct OpenCLBuiltinStruct {
390   // Index of the signature in the OpenCLTypeStruct table.
391   const unsigned SigTableIndex;
392   // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
393   // the SignatureTable represent the complete signature.  The first type at
394   // index SigTableIndex is the return type.
395   const unsigned NumTypes;
396   // Function attribute __attribute__((pure))
397   const bool IsPure : 1;
398   // Function attribute __attribute__((const))
399   const bool IsConst : 1;
400   // Function attribute __attribute__((convergent))
401   const bool IsConv : 1;
402   // OpenCL extension(s) required for this overload.
403   const unsigned short Extension;
404   // OpenCL versions in which this overload is available.
405   const unsigned short Versions;
406 };
407 
408 )";
409 }
410 
411 // Verify that the combination of GenTypes in a signature is supported.
412 // To simplify the logic for creating overloads in SemaLookup, only allow
413 // a signature to contain different GenTypes if these GenTypes represent
414 // the same number of actual scalar or vector types.
415 //
416 // Exit with a fatal error if an unsupported construct is encountered.
417 static void VerifySignature(const std::vector<Record *> &Signature,
418                             const Record *BuiltinRec) {
419   unsigned GenTypeVecSizes = 1;
420   unsigned GenTypeTypes = 1;
421 
422   for (const auto *T : Signature) {
423     // Check all GenericType arguments in this signature.
424     if (T->isSubClassOf("GenericType")) {
425       // Check number of vector sizes.
426       unsigned NVecSizes =
427           T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
428       if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
429         if (GenTypeVecSizes > 1) {
430           // We already saw a gentype with a different number of vector sizes.
431           PrintFatalError(BuiltinRec->getLoc(),
432               "number of vector sizes should be equal or 1 for all gentypes "
433               "in a declaration");
434         }
435         GenTypeVecSizes = NVecSizes;
436       }
437 
438       // Check number of data types.
439       unsigned NTypes =
440           T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
441       if (NTypes != GenTypeTypes && NTypes != 1) {
442         if (GenTypeTypes > 1) {
443           // We already saw a gentype with a different number of types.
444           PrintFatalError(BuiltinRec->getLoc(),
445               "number of types should be equal or 1 for all gentypes "
446               "in a declaration");
447         }
448         GenTypeTypes = NTypes;
449       }
450     }
451   }
452 }
453 
454 void BuiltinNameEmitter::GetOverloads() {
455   // Populate the TypeMap.
456   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
457   unsigned I = 0;
458   for (const auto &T : Types) {
459     TypeMap.insert(std::make_pair(T, I++));
460   }
461 
462   // Populate the SignaturesList and the FctOverloadMap.
463   unsigned CumulativeSignIndex = 0;
464   std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
465   for (const auto *B : Builtins) {
466     StringRef BName = B->getValueAsString("Name");
467     if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
468       FctOverloadMap.insert(std::make_pair(
469           BName, std::vector<std::pair<const Record *, unsigned>>{}));
470     }
471 
472     auto Signature = B->getValueAsListOfDefs("Signature");
473     // Reuse signatures to avoid unnecessary duplicates.
474     auto it =
475         std::find_if(SignaturesList.begin(), SignaturesList.end(),
476                      [&](const std::pair<std::vector<Record *>, unsigned> &a) {
477                        return a.first == Signature;
478                      });
479     unsigned SignIndex;
480     if (it == SignaturesList.end()) {
481       VerifySignature(Signature, B);
482       SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
483       SignIndex = CumulativeSignIndex;
484       CumulativeSignIndex += Signature.size();
485     } else {
486       SignIndex = it->second;
487     }
488     FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
489   }
490 }
491 
492 void BuiltinNameEmitter::EmitExtensionTable() {
493   OS << "static const char *FunctionExtensionTable[] = {\n";
494   unsigned Index = 0;
495   std::vector<Record *> FuncExtensions =
496       Records.getAllDerivedDefinitions("FunctionExtension");
497 
498   for (const auto &FE : FuncExtensions) {
499     // Emit OpenCL extension table entry.
500     OS << "  // " << Index << ": " << FE->getName() << "\n"
501        << "  \"" << FE->getValueAsString("ExtName") << "\",\n";
502 
503     // Record index of this extension.
504     FunctionExtensionIndex[FE->getName()] = Index++;
505   }
506   OS << "};\n\n";
507 }
508 
509 void BuiltinNameEmitter::EmitTypeTable() {
510   OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
511   for (const auto &T : TypeMap) {
512     const char *AccessQual =
513         StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
514             .Case("RO", "OCLAQ_ReadOnly")
515             .Case("WO", "OCLAQ_WriteOnly")
516             .Case("RW", "OCLAQ_ReadWrite")
517             .Default("OCLAQ_None");
518 
519     OS << "  // " << T.second << "\n"
520        << "  {OCLT_" << T.first->getValueAsString("Name") << ", "
521        << T.first->getValueAsInt("VecWidth") << ", "
522        << T.first->getValueAsBit("IsPointer") << ", "
523        << T.first->getValueAsBit("IsConst") << ", "
524        << T.first->getValueAsBit("IsVolatile") << ", "
525        << AccessQual << ", "
526        << T.first->getValueAsString("AddrSpace") << "},\n";
527   }
528   OS << "};\n\n";
529 }
530 
531 void BuiltinNameEmitter::EmitSignatureTable() {
532   // Store a type (e.g. int, float, int2, ...). The type is stored as an index
533   // of a struct OpenCLType table. Multiple entries following each other form a
534   // signature.
535   OS << "static const unsigned short SignatureTable[] = {\n";
536   for (const auto &P : SignaturesList) {
537     OS << "  // " << P.second << "\n  ";
538     for (const Record *R : P.first) {
539       unsigned Entry = TypeMap.find(R)->second;
540       if (Entry > USHRT_MAX) {
541         // Report an error when seeing an entry that is too large for the
542         // current index type (unsigned short).  When hitting this, the type
543         // of SignatureTable will need to be changed.
544         PrintFatalError("Entry in SignatureTable exceeds limit.");
545       }
546       OS << Entry << ", ";
547     }
548     OS << "\n";
549   }
550   OS << "};\n\n";
551 }
552 
553 // Encode a range MinVersion..MaxVersion into a single bit mask that can be
554 // checked against LangOpts using isOpenCLVersionContainedInMask().
555 // This must be kept in sync with OpenCLVersionID in OpenCLOptions.h.
556 // (Including OpenCLOptions.h here would be a layering violation.)
557 static unsigned short EncodeVersions(unsigned int MinVersion,
558                                      unsigned int MaxVersion) {
559   unsigned short Encoded = 0;
560 
561   // A maximum version of 0 means available in all later versions.
562   if (MaxVersion == 0) {
563     MaxVersion = UINT_MAX;
564   }
565 
566   unsigned VersionIDs[] = {100, 110, 120, 200, 300};
567   for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
568     if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
569       Encoded |= 1 << I;
570     }
571   }
572 
573   return Encoded;
574 }
575 
576 void BuiltinNameEmitter::EmitBuiltinTable() {
577   unsigned Index = 0;
578 
579   OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
580   for (const auto &SLM : SignatureListMap) {
581 
582     OS << "  // " << (Index + 1) << ": ";
583     for (const auto &Name : SLM.second.Names) {
584       OS << Name << ", ";
585     }
586     OS << "\n";
587 
588     for (const auto &Overload : SLM.second.Signatures) {
589       StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
590       unsigned int MinVersion =
591           Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
592       unsigned int MaxVersion =
593           Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
594 
595       OS << "  { " << Overload.second << ", "
596          << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
597          << (Overload.first->getValueAsBit("IsPure")) << ", "
598          << (Overload.first->getValueAsBit("IsConst")) << ", "
599          << (Overload.first->getValueAsBit("IsConv")) << ", "
600          << FunctionExtensionIndex[ExtName] << ", "
601          << EncodeVersions(MinVersion, MaxVersion) << " },\n";
602       Index++;
603     }
604   }
605   OS << "};\n\n";
606 }
607 
608 bool BuiltinNameEmitter::CanReuseSignature(
609     BuiltinIndexListTy *Candidate,
610     std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
611   assert(Candidate->size() == SignatureList.size() &&
612          "signature lists should have the same size");
613 
614   auto &CandidateSigs =
615       SignatureListMap.find(Candidate)->second.Signatures;
616   for (unsigned Index = 0; Index < Candidate->size(); Index++) {
617     const Record *Rec = SignatureList[Index].first;
618     const Record *Rec2 = CandidateSigs[Index].first;
619     if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
620         Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
621         Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
622         Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
623             Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
624         Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
625             Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
626         Rec->getValueAsDef("Extension")->getName() ==
627             Rec2->getValueAsDef("Extension")->getName()) {
628       return true;
629     }
630   }
631   return false;
632 }
633 
634 void BuiltinNameEmitter::GroupBySignature() {
635   // List of signatures known to be emitted.
636   std::vector<BuiltinIndexListTy *> KnownSignatures;
637 
638   for (auto &Fct : FctOverloadMap) {
639     bool FoundReusableSig = false;
640 
641     // Gather all signatures for the current function.
642     auto *CurSignatureList = new BuiltinIndexListTy();
643     for (const auto &Signature : Fct.second) {
644       CurSignatureList->push_back(Signature.second);
645     }
646     // Sort the list to facilitate future comparisons.
647     llvm::sort(*CurSignatureList);
648 
649     // Check if we have already seen another function with the same list of
650     // signatures.  If so, just add the name of the function.
651     for (auto *Candidate : KnownSignatures) {
652       if (Candidate->size() == CurSignatureList->size() &&
653           *Candidate == *CurSignatureList) {
654         if (CanReuseSignature(Candidate, Fct.second)) {
655           SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
656           FoundReusableSig = true;
657         }
658       }
659     }
660 
661     if (FoundReusableSig) {
662       delete CurSignatureList;
663     } else {
664       // Add a new entry.
665       SignatureListMap[CurSignatureList] = {
666           SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
667       KnownSignatures.push_back(CurSignatureList);
668     }
669   }
670 
671   for (auto *I : KnownSignatures) {
672     delete I;
673   }
674 }
675 
676 void BuiltinNameEmitter::EmitStringMatcher() {
677   std::vector<StringMatcher::StringPair> ValidBuiltins;
678   unsigned CumulativeIndex = 1;
679 
680   for (const auto &SLM : SignatureListMap) {
681     const auto &Ovl = SLM.second.Signatures;
682 
683     // A single signature list may be used by different builtins.  Return the
684     // same <index, length> pair for each of those builtins.
685     for (const auto &FctName : SLM.second.Names) {
686       std::string RetStmt;
687       raw_string_ostream SS(RetStmt);
688       SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
689          << ");";
690       SS.flush();
691       ValidBuiltins.push_back(
692           StringMatcher::StringPair(std::string(FctName), RetStmt));
693     }
694     CumulativeIndex += Ovl.size();
695   }
696 
697   OS << R"(
698 // Find out whether a string matches an existing OpenCL builtin function name.
699 // Returns: A pair <0, 0> if no name matches.
700 //          A pair <Index, Len> indexing the BuiltinTable if the name is
701 //          matching an OpenCL builtin function.
702 static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
703 
704 )";
705 
706   StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
707 
708   OS << "  return std::make_pair(0, 0);\n";
709   OS << "} // isOpenCLBuiltin\n";
710 }
711 
712 void BuiltinNameEmitter::EmitQualTypeFinder() {
713   OS << R"(
714 
715 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
716 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
717 
718 // Convert an OpenCLTypeStruct type to a list of QualTypes.
719 // Generic types represent multiple types and vector sizes, thus a vector
720 // is returned. The conversion is done in two steps:
721 // Step 1: A switch statement fills a vector with scalar base types for the
722 //         Cartesian product of (vector sizes) x (types) for generic types,
723 //         or a single scalar type for non generic types.
724 // Step 2: Qualifiers and other type properties such as vector size are
725 //         applied.
726 static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
727                      llvm::SmallVectorImpl<QualType> &QT) {
728   ASTContext &Context = S.Context;
729   // Number of scalar types in the GenType.
730   unsigned GenTypeNumTypes;
731   // Pointer to the list of vector sizes for the GenType.
732   llvm::ArrayRef<unsigned> GenVectorSizes;
733 )";
734 
735   // Generate list of vector sizes for each generic type.
736   for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
737     OS << "  constexpr unsigned List"
738        << VectList->getValueAsString("Name") << "[] = {";
739     for (const auto V : VectList->getValueAsListOfInts("List")) {
740       OS << V << ", ";
741     }
742     OS << "};\n";
743   }
744 
745   // Step 1.
746   // Start of switch statement over all types.
747   OS << "\n  switch (Ty.ID) {\n";
748 
749   // Switch cases for image types (Image2d, Image3d, ...)
750   std::vector<Record *> ImageTypes =
751       Records.getAllDerivedDefinitions("ImageType");
752 
753   // Map an image type name to its 3 access-qualified types (RO, WO, RW).
754   StringMap<SmallVector<Record *, 3>> ImageTypesMap;
755   for (auto *IT : ImageTypes) {
756     auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
757     if (Entry == ImageTypesMap.end()) {
758       SmallVector<Record *, 3> ImageList;
759       ImageList.push_back(IT);
760       ImageTypesMap.insert(
761           std::make_pair(IT->getValueAsString("Name"), ImageList));
762     } else {
763       Entry->second.push_back(IT);
764     }
765   }
766 
767   // Emit the cases for the image types.  For an image type name, there are 3
768   // corresponding QualTypes ("RO", "WO", "RW").  The "AccessQualifier" field
769   // tells which one is needed.  Emit a switch statement that puts the
770   // corresponding QualType into "QT".
771   for (const auto &ITE : ImageTypesMap) {
772     OS << "    case OCLT_" << ITE.getKey() << ":\n"
773        << "      switch (Ty.AccessQualifier) {\n"
774        << "        case OCLAQ_None:\n"
775        << "          llvm_unreachable(\"Image without access qualifier\");\n";
776     for (const auto &Image : ITE.getValue()) {
777       OS << StringSwitch<const char *>(
778                 Image->getValueAsString("AccessQualifier"))
779                 .Case("RO", "        case OCLAQ_ReadOnly:\n")
780                 .Case("WO", "        case OCLAQ_WriteOnly:\n")
781                 .Case("RW", "        case OCLAQ_ReadWrite:\n")
782          << "          QT.push_back("
783          << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
784          << ");\n"
785          << "          break;\n";
786     }
787     OS << "      }\n"
788        << "      break;\n";
789   }
790 
791   // Switch cases for generic types.
792   for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
793     OS << "    case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
794 
795     // Build the Cartesian product of (vector sizes) x (types).  Only insert
796     // the plain scalar types for now; other type information such as vector
797     // size and type qualifiers will be added after the switch statement.
798     std::vector<Record *> BaseTypes =
799         GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
800 
801     // Collect all QualTypes for a single vector size into TypeList.
802     OS << "      SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
803     for (const auto *T : BaseTypes) {
804       StringRef Ext =
805           T->getValueAsDef("Extension")->getValueAsString("ExtName");
806       if (!Ext.empty()) {
807         OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
808            << "\")) {\n  ";
809       }
810       OS << "      TypeList.push_back("
811          << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
812       if (!Ext.empty()) {
813         OS << "      }\n";
814       }
815     }
816     OS << "      GenTypeNumTypes = TypeList.size();\n";
817 
818     // Duplicate the TypeList for every vector size.
819     std::vector<int64_t> VectorList =
820         GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
821     OS << "      QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
822        << "      for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
823        << "        QT.append(TypeList);\n"
824        << "      }\n";
825 
826     // GenVectorSizes is the list of vector sizes for this GenType.
827     OS << "      GenVectorSizes = List"
828        << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
829        << ";\n"
830        << "      break;\n"
831        << "    }\n";
832   }
833 
834   // Switch cases for non generic, non image types (int, int4, float, ...).
835   // Only insert the plain scalar type; vector information and type qualifiers
836   // are added in step 2.
837   std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
838   StringMap<bool> TypesSeen;
839 
840   for (const auto *T : Types) {
841     // Check this is not an image type
842     if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
843       continue;
844     // Check we have not seen this Type
845     if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
846       continue;
847     TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
848 
849     // Check the Type does not have an "abstract" QualType
850     auto QT = T->getValueAsDef("QTExpr");
851     if (QT->getValueAsBit("IsAbstract") == 1)
852       continue;
853     // Emit the cases for non generic, non image types.
854     OS << "    case OCLT_" << T->getValueAsString("Name") << ":\n";
855 
856     StringRef Ext = T->getValueAsDef("Extension")->getValueAsString("ExtName");
857     // If this type depends on an extension, ensure the extension macro is
858     // defined.
859     if (!Ext.empty()) {
860       OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
861          << "\")) {\n  ";
862     }
863     OS << "      QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
864     if (!Ext.empty()) {
865       OS << "      }\n";
866     }
867     OS << "      break;\n";
868   }
869 
870   // End of switch statement.
871   OS << "  } // end of switch (Ty.ID)\n\n";
872 
873   // Step 2.
874   // Add ExtVector types if this was a generic type, as the switch statement
875   // above only populated the list with scalar types.  This completes the
876   // construction of the Cartesian product of (vector sizes) x (types).
877   OS << "  // Construct the different vector types for each generic type.\n";
878   OS << "  if (Ty.ID >= " << TypeList.size() << ") {";
879   OS << R"(
880     for (unsigned I = 0; I < QT.size(); I++) {
881       // For scalars, size is 1.
882       if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
883         QT[I] = Context.getExtVectorType(QT[I],
884                           GenVectorSizes[I / GenTypeNumTypes]);
885       }
886     }
887   }
888 )";
889 
890   // Assign the right attributes to the types (e.g. vector size).
891   OS << R"(
892   // Set vector size for non-generic vector types.
893   if (Ty.VectorWidth > 1) {
894     for (unsigned Index = 0; Index < QT.size(); Index++) {
895       QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
896     }
897   }
898 
899   if (Ty.IsVolatile != 0) {
900     for (unsigned Index = 0; Index < QT.size(); Index++) {
901       QT[Index] = Context.getVolatileType(QT[Index]);
902     }
903   }
904 
905   if (Ty.IsConst != 0) {
906     for (unsigned Index = 0; Index < QT.size(); Index++) {
907       QT[Index] = Context.getConstType(QT[Index]);
908     }
909   }
910 
911   // Transform the type to a pointer as the last step, if necessary.
912   // Builtin functions only have pointers on [const|volatile], no
913   // [const|volatile] pointers, so this is ok to do it as a last step.
914   if (Ty.IsPointer != 0) {
915     for (unsigned Index = 0; Index < QT.size(); Index++) {
916       QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
917       QT[Index] = Context.getPointerType(QT[Index]);
918     }
919   }
920 )";
921 
922   // End of the "OCL2Qual" function.
923   OS << "\n} // OCL2Qual\n";
924 }
925 
926 std::string OpenCLBuiltinTestEmitter::getTypeString(const Record *Type,
927                                                     TypeFlags Flags,
928                                                     int VectorSize) const {
929   std::string S;
930   if (Type->getValueAsBit("IsConst") || Flags.IsConst) {
931     S += "const ";
932   }
933   if (Type->getValueAsBit("IsVolatile") || Flags.IsVolatile) {
934     S += "volatile ";
935   }
936 
937   auto PrintAddrSpace = [&S](StringRef AddrSpace) {
938     S += StringSwitch<const char *>(AddrSpace)
939              .Case("clang::LangAS::opencl_private", "__private")
940              .Case("clang::LangAS::opencl_global", "__global")
941              .Case("clang::LangAS::opencl_constant", "__constant")
942              .Case("clang::LangAS::opencl_local", "__local")
943              .Case("clang::LangAS::opencl_generic", "__generic")
944              .Default("__private");
945     S += " ";
946   };
947   if (Flags.IsPointer) {
948     PrintAddrSpace(Flags.AddrSpace);
949   } else if (Type->getValueAsBit("IsPointer")) {
950     PrintAddrSpace(Type->getValueAsString("AddrSpace"));
951   }
952 
953   StringRef Acc = Type->getValueAsString("AccessQualifier");
954   if (Acc != "") {
955     S += StringSwitch<const char *>(Acc)
956              .Case("RO", "__read_only ")
957              .Case("WO", "__write_only ")
958              .Case("RW", "__read_write ");
959   }
960 
961   S += Type->getValueAsString("Name").str();
962   if (VectorSize > 1) {
963     S += std::to_string(VectorSize);
964   }
965 
966   if (Type->getValueAsBit("IsPointer") || Flags.IsPointer) {
967     S += " *";
968   }
969 
970   return S;
971 }
972 
973 void OpenCLBuiltinTestEmitter::getTypeLists(
974     Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
975     std::vector<int64_t> &VectorList) const {
976   bool isGenType = Type->isSubClassOf("GenericType");
977   if (isGenType) {
978     TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
979     VectorList =
980         Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
981     return;
982   }
983 
984   if (Type->isSubClassOf("PointerType") || Type->isSubClassOf("ConstType") ||
985       Type->isSubClassOf("VolatileType")) {
986     StringRef SubTypeName = Type->getValueAsString("Name");
987     Record *PossibleGenType = Records.getDef(SubTypeName);
988     if (PossibleGenType && PossibleGenType->isSubClassOf("GenericType")) {
989       // When PointerType, ConstType, or VolatileType is applied to a
990       // GenericType, the flags need to be taken from the subtype, not from the
991       // GenericType.
992       Flags.IsPointer = Type->getValueAsBit("IsPointer");
993       Flags.IsConst = Type->getValueAsBit("IsConst");
994       Flags.IsVolatile = Type->getValueAsBit("IsVolatile");
995       Flags.AddrSpace = Type->getValueAsString("AddrSpace");
996       getTypeLists(PossibleGenType, Flags, TypeList, VectorList);
997       return;
998     }
999   }
1000 
1001   // Not a GenericType, so just insert the single type.
1002   TypeList.push_back(Type);
1003   VectorList.push_back(Type->getValueAsInt("VecWidth"));
1004 }
1005 
1006 void OpenCLBuiltinTestEmitter::expandTypesInSignature(
1007     const std::vector<Record *> &Signature,
1008     SmallVectorImpl<SmallVector<std::string, 2>> &Types) {
1009   // Find out if there are any GenTypes in this signature, and if so, calculate
1010   // into how many signatures they will expand.
1011   unsigned NumSignatures = 1;
1012   SmallVector<SmallVector<std::string, 4>, 4> ExpandedGenTypes;
1013   for (const auto &Arg : Signature) {
1014     SmallVector<std::string, 4> ExpandedArg;
1015     std::vector<Record *> TypeList;
1016     std::vector<int64_t> VectorList;
1017     TypeFlags Flags;
1018 
1019     getTypeLists(Arg, Flags, TypeList, VectorList);
1020 
1021     // Insert the Cartesian product of the types and vector sizes.
1022     for (const auto &Vector : VectorList) {
1023       for (const auto &Type : TypeList) {
1024         ExpandedArg.push_back(getTypeString(Type, Flags, Vector));
1025       }
1026     }
1027     NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
1028     ExpandedGenTypes.push_back(ExpandedArg);
1029   }
1030 
1031   // Now the total number of signatures is known.  Populate the return list with
1032   // all signatures.
1033   for (unsigned I = 0; I < NumSignatures; I++) {
1034     SmallVector<std::string, 2> Args;
1035 
1036     // Process a single signature.
1037     for (unsigned ArgNum = 0; ArgNum < Signature.size(); ArgNum++) {
1038       // For differently-sized GenTypes in a parameter list, the smaller
1039       // GenTypes just repeat, so index modulo the number of expanded types.
1040       size_t TypeIndex = I % ExpandedGenTypes[ArgNum].size();
1041       Args.push_back(ExpandedGenTypes[ArgNum][TypeIndex]);
1042     }
1043     Types.push_back(Args);
1044   }
1045 }
1046 
1047 void OpenCLBuiltinTestEmitter::emit() {
1048   emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
1049 
1050   // Enable some extensions for testing.
1051   OS << R"(
1052 #pragma OPENCL EXTENSION cl_khr_fp16 : enable
1053 #pragma OPENCL EXTENSION cl_khr_fp64 : enable
1054 #pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
1055 #pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
1056 #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
1057 #pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
1058 #pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
1059 
1060 )";
1061 
1062   // Ensure each test has a unique name by numbering them.
1063   unsigned TestID = 0;
1064 
1065   // Iterate over all builtins.
1066   std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
1067   for (const auto *B : Builtins) {
1068     StringRef Name = B->getValueAsString("Name");
1069 
1070     SmallVector<SmallVector<std::string, 2>, 4> FTypes;
1071     expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
1072 
1073     OS << "// Test " << Name << "\n";
1074     std::string OptionalEndif;
1075     StringRef Extensions =
1076         B->getValueAsDef("Extension")->getValueAsString("ExtName");
1077     if (!Extensions.empty()) {
1078       OS << "#if";
1079       OptionalEndif = "#endif // Extension\n";
1080 
1081       SmallVector<StringRef, 2> ExtVec;
1082       Extensions.split(ExtVec, " ");
1083       bool isFirst = true;
1084       for (StringRef Ext : ExtVec) {
1085         if (!isFirst) {
1086           OS << " &&";
1087         }
1088         OS << " defined(" << Ext << ")";
1089         isFirst = false;
1090       }
1091       OS << "\n";
1092     }
1093     auto PrintOpenCLVersion = [this](int Version) {
1094       OS << "CL_VERSION_" << (Version / 100) << "_" << ((Version % 100) / 10);
1095     };
1096     int MinVersion = B->getValueAsDef("MinVersion")->getValueAsInt("ID");
1097     if (MinVersion != 100) {
1098       // OpenCL 1.0 is the default minimum version.
1099       OS << "#if __OPENCL_C_VERSION__ >= ";
1100       PrintOpenCLVersion(MinVersion);
1101       OS << "\n";
1102       OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
1103     }
1104     int MaxVersion = B->getValueAsDef("MaxVersion")->getValueAsInt("ID");
1105     if (MaxVersion) {
1106       OS << "#if __OPENCL_C_VERSION__ < ";
1107       PrintOpenCLVersion(MaxVersion);
1108       OS << "\n";
1109       OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
1110     }
1111     for (const auto &Signature : FTypes) {
1112       // Emit function declaration.
1113       OS << Signature[0] << " test" << TestID++ << "_" << Name << "(";
1114       if (Signature.size() > 1) {
1115         for (unsigned I = 1; I < Signature.size(); I++) {
1116           if (I != 1)
1117             OS << ", ";
1118           OS << Signature[I] << " arg" << I;
1119         }
1120       }
1121       OS << ") {\n";
1122 
1123       // Emit function body.
1124       OS << "  ";
1125       if (Signature[0] != "void") {
1126         OS << "return ";
1127       }
1128       OS << Name << "(";
1129       for (unsigned I = 1; I < Signature.size(); I++) {
1130         if (I != 1)
1131           OS << ", ";
1132         OS << "arg" << I;
1133       }
1134       OS << ");\n";
1135 
1136       // End of function body.
1137       OS << "}\n";
1138     }
1139     OS << OptionalEndif << "\n";
1140   }
1141 }
1142 
1143 void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
1144   BuiltinNameEmitter NameChecker(Records, OS);
1145   NameChecker.Emit();
1146 }
1147 
1148 void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
1149                                         raw_ostream &OS) {
1150   OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
1151   TestFileGenerator.emit();
1152 }
1153