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