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