Coverage Report

Created: 2021-06-15 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
Line
Count
Source (jump to first uncovered line)
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
0
      : 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
1
      : 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
21.3k
    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
0
void BuiltinNameEmitter::Emit() {
296
0
  emitSourceFileHeader("OpenCL Builtin handling", OS);
297
298
0
  OS << "#include \"llvm/ADT/StringRef.h\"\n";
299
0
  OS << "using namespace clang;\n\n";
300
301
  // Emit enums and structs.
302
0
  EmitDeclarations();
303
304
  // Parse the Records to populate the internal lists.
305
0
  GetOverloads();
306
0
  GroupBySignature();
307
308
  // Emit tables.
309
0
  EmitExtensionTable();
310
0
  EmitTypeTable();
311
0
  EmitSignatureTable();
312
0
  EmitBuiltinTable();
313
314
  // Emit functions.
315
0
  EmitStringMatcher();
316
0
  EmitQualTypeFinder();
317
0
}
318
319
void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
320
                                          StringMap<bool> &TypesSeen,
321
                                          std::string &Output,
322
0
                                          std::vector<const Record *> &List) {
323
0
  raw_string_ostream SS(Output);
324
325
0
  for (const auto *T : Types) {
326
0
    if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
327
0
      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
0
      List.push_back(T);
332
0
      TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
333
0
    }
334
0
  }
335
0
  SS.flush();
336
0
}
337
338
0
void BuiltinNameEmitter::EmitDeclarations() {
339
  // Enum of scalar type names (float, int, ...) and generic type sets.
340
0
  OS << "enum OpenCLTypeID {\n";
341
342
0
  StringMap<bool> TypesSeen;
343
0
  std::string GenTypeEnums;
344
0
  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
0
  std::vector<Record *> GenTypes =
350
0
      Records.getAllDerivedDefinitions("GenericType");
351
0
  ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
352
353
0
  std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
354
0
  ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
355
356
0
  OS << TypeEnums;
357
0
  OS << GenTypeEnums;
358
0
  OS << "};\n";
359
360
  // Structure definitions.
361
0
  OS << R"(
362
0
// Image access qualifier.
363
0
enum OpenCLAccessQual : unsigned char {
364
0
  OCLAQ_None,
365
0
  OCLAQ_ReadOnly,
366
0
  OCLAQ_WriteOnly,
367
0
  OCLAQ_ReadWrite
368
0
};
369
0
370
0
// Represents a return type or argument type.
371
0
struct OpenCLTypeStruct {
372
0
  // A type (e.g. float, int, ...).
373
0
  const OpenCLTypeID ID;
374
0
  // Vector size (if applicable; 0 for scalars and generic types).
375
0
  const unsigned VectorWidth;
376
0
  // 0 if the type is not a pointer.
377
0
  const bool IsPointer : 1;
378
0
  // 0 if the type is not const.
379
0
  const bool IsConst : 1;
380
0
  // 0 if the type is not volatile.
381
0
  const bool IsVolatile : 1;
382
0
  // Access qualifier.
383
0
  const OpenCLAccessQual AccessQualifier;
384
0
  // Address space of the pointer (if applicable).
385
0
  const LangAS AS;
386
0
};
387
0
388
0
// One overload of an OpenCL builtin function.
389
0
struct OpenCLBuiltinStruct {
390
0
  // Index of the signature in the OpenCLTypeStruct table.
391
0
  const unsigned SigTableIndex;
392
0
  // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
393
0
  // the SignatureTable represent the complete signature.  The first type at
394
0
  // index SigTableIndex is the return type.
395
0
  const unsigned NumTypes;
396
0
  // Function attribute __attribute__((pure))
397
0
  const bool IsPure : 1;
398
0
  // Function attribute __attribute__((const))
399
0
  const bool IsConst : 1;
400
0
  // Function attribute __attribute__((convergent))
401
0
  const bool IsConv : 1;
402
0
  // OpenCL extension(s) required for this overload.
403
0
  const unsigned short Extension;
404
0
  // OpenCL versions in which this overload is available.
405
0
  const unsigned short Versions;
406
0
};
407
0
408
0
)";
409
0
}
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
0
                            const Record *BuiltinRec) {
419
0
  unsigned GenTypeVecSizes = 1;
420
0
  unsigned GenTypeTypes = 1;
421
422
0
  for (const auto *T : Signature) {
423
    // Check all GenericType arguments in this signature.
424
0
    if (T->isSubClassOf("GenericType")) {
425
      // Check number of vector sizes.
426
0
      unsigned NVecSizes =
427
0
          T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
428
0
      if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
429
0
        if (GenTypeVecSizes > 1) {
430
          // We already saw a gentype with a different number of vector sizes.
431
0
          PrintFatalError(BuiltinRec->getLoc(),
432
0
              "number of vector sizes should be equal or 1 for all gentypes "
433
0
              "in a declaration");
434
0
        }
435
0
        GenTypeVecSizes = NVecSizes;
436
0
      }
437
438
      // Check number of data types.
439
0
      unsigned NTypes =
440
0
          T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
441
0
      if (NTypes != GenTypeTypes && NTypes != 1) {
442
0
        if (GenTypeTypes > 1) {
443
          // We already saw a gentype with a different number of types.
444
0
          PrintFatalError(BuiltinRec->getLoc(),
445
0
              "number of types should be equal or 1 for all gentypes "
446
0
              "in a declaration");
447
0
        }
448
0
        GenTypeTypes = NTypes;
449
0
      }
450
0
    }
451
0
  }
452
0
}
453
454
0
void BuiltinNameEmitter::GetOverloads() {
455
  // Populate the TypeMap.
456
0
  std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
457
0
  unsigned I = 0;
458
0
  for (const auto &T : Types) {
459
0
    TypeMap.insert(std::make_pair(T, I++));
460
0
  }
461
462
  // Populate the SignaturesList and the FctOverloadMap.
463
0
  unsigned CumulativeSignIndex = 0;
464
0
  std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
465
0
  for (const auto *B : Builtins) {
466
0
    StringRef BName = B->getValueAsString("Name");
467
0
    if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
468
0
      FctOverloadMap.insert(std::make_pair(
469
0
          BName, std::vector<std::pair<const Record *, unsigned>>{}));
470
0
    }
471
472
0
    auto Signature = B->getValueAsListOfDefs("Signature");
473
    // Reuse signatures to avoid unnecessary duplicates.
474
0
    auto it =
475
0
        std::find_if(SignaturesList.begin(), SignaturesList.end(),
476
0
                     [&](const std::pair<std::vector<Record *>, unsigned> &a) {
477
0
                       return a.first == Signature;
478
0
                     });
479
0
    unsigned SignIndex;
480
0
    if (it == SignaturesList.end()) {
481
0
      VerifySignature(Signature, B);
482
0
      SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
483
0
      SignIndex = CumulativeSignIndex;
484
0
      CumulativeSignIndex += Signature.size();
485
0
    } else {
486
0
      SignIndex = it->second;
487
0
    }
488
0
    FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
489
0
  }
490
0
}
491
492
0
void BuiltinNameEmitter::EmitExtensionTable() {
493
0
  OS << "static const char *FunctionExtensionTable[] = {\n";
494
0
  unsigned Index = 0;
495
0
  std::vector<Record *> FuncExtensions =
496
0
      Records.getAllDerivedDefinitions("FunctionExtension");
497
498
0
  for (const auto &FE : FuncExtensions) {
499
    // Emit OpenCL extension table entry.
500
0
    OS << "  // " << Index << ": " << FE->getName() << "\n"
501
0
       << "  \"" << FE->getValueAsString("ExtName") << "\",\n";
502
503
    // Record index of this extension.
504
0
    FunctionExtensionIndex[FE->getName()] = Index++;
505
0
  }
506
0
  OS << "};\n\n";
507
0
}
508
509
0
void BuiltinNameEmitter::EmitTypeTable() {
510
0
  OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
511
0
  for (const auto &T : TypeMap) {
512
0
    const char *AccessQual =
513
0
        StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
514
0
            .Case("RO", "OCLAQ_ReadOnly")
515
0
            .Case("WO", "OCLAQ_WriteOnly")
516
0
            .Case("RW", "OCLAQ_ReadWrite")
517
0
            .Default("OCLAQ_None");
518
519
0
    OS << "  // " << T.second << "\n"
520
0
       << "  {OCLT_" << T.first->getValueAsString("Name") << ", "
521
0
       << T.first->getValueAsInt("VecWidth") << ", "
522
0
       << T.first->getValueAsBit("IsPointer") << ", "
523
0
       << T.first->getValueAsBit("IsConst") << ", "
524
0
       << T.first->getValueAsBit("IsVolatile") << ", "
525
0
       << AccessQual << ", "
526
0
       << T.first->getValueAsString("AddrSpace") << "},\n";
527
0
  }
528
0
  OS << "};\n\n";
529
0
}
530
531
0
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
0
  OS << "static const unsigned short SignatureTable[] = {\n";
536
0
  for (const auto &P : SignaturesList) {
537
0
    OS << "  // " << P.second << "\n  ";
538
0
    for (const Record *R : P.first) {
539
0
      unsigned Entry = TypeMap.find(R)->second;
540
0
      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
0
        PrintFatalError("Entry in SignatureTable exceeds limit.");
545
0
      }
546
0
      OS << Entry << ", ";
547
0
    }
548
0
    OS << "\n";
549
0
  }
550
0
  OS << "};\n\n";
551
0
}
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
0
                                     unsigned int MaxVersion) {
559
0
  unsigned short Encoded = 0;
560
561
  // A maximum version of 0 means available in all later versions.
562
0
  if (MaxVersion == 0) {
563
0
    MaxVersion = UINT_MAX;
564
0
  }
565
566
0
  unsigned VersionIDs[] = {100, 110, 120, 200, 300};
567
0
  for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
568
0
    if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
569
0
      Encoded |= 1 << I;
570
0
    }
571
0
  }
572
573
0
  return Encoded;
574
0
}
575
576
0
void BuiltinNameEmitter::EmitBuiltinTable() {
577
0
  unsigned Index = 0;
578
579
0
  OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
580
0
  for (const auto &SLM : SignatureListMap) {
581
582
0
    OS << "  // " << (Index + 1) << ": ";
583
0
    for (const auto &Name : SLM.second.Names) {
584
0
      OS << Name << ", ";
585
0
    }
586
0
    OS << "\n";
587
588
0
    for (const auto &Overload : SLM.second.Signatures) {
589
0
      StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
590
0
      unsigned int MinVersion =
591
0
          Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
592
0
      unsigned int MaxVersion =
593
0
          Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
594
595
0
      OS << "  { " << Overload.second << ", "
596
0
         << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
597
0
         << (Overload.first->getValueAsBit("IsPure")) << ", "
598
0
         << (Overload.first->getValueAsBit("IsConst")) << ", "
599
0
         << (Overload.first->getValueAsBit("IsConv")) << ", "
600
0
         << FunctionExtensionIndex[ExtName] << ", "
601
0
         << EncodeVersions(MinVersion, MaxVersion) << " },\n";
602
0
      Index++;
603
0
    }
604
0
  }
605
0
  OS << "};\n\n";
606
0
}
607
608
bool BuiltinNameEmitter::CanReuseSignature(
609
    BuiltinIndexListTy *Candidate,
610
0
    std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
611
0
  assert(Candidate->size() == SignatureList.size() &&
612
0
         "signature lists should have the same size");
613
614
0
  auto &CandidateSigs =
615
0
      SignatureListMap.find(Candidate)->second.Signatures;
616
0
  for (unsigned Index = 0; Index < Candidate->size(); Index++) {
617
0
    const Record *Rec = SignatureList[Index].first;
618
0
    const Record *Rec2 = CandidateSigs[Index].first;
619
0
    if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
620
0
        Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
621
0
        Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
622
0
        Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
623
0
            Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
624
0
        Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
625
0
            Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
626
0
        Rec->getValueAsDef("Extension")->getName() ==
627
0
            Rec2->getValueAsDef("Extension")->getName()) {
628
0
      return true;
629
0
    }
630
0
  }
631
0
  return false;
632
0
}
633
634
0
void BuiltinNameEmitter::GroupBySignature() {
635
  // List of signatures known to be emitted.
636
0
  std::vector<BuiltinIndexListTy *> KnownSignatures;
637
638
0
  for (auto &Fct : FctOverloadMap) {
639
0
    bool FoundReusableSig = false;
640
641
    // Gather all signatures for the current function.
642
0
    auto *CurSignatureList = new BuiltinIndexListTy();
643
0
    for (const auto &Signature : Fct.second) {
644
0
      CurSignatureList->push_back(Signature.second);
645
0
    }
646
    // Sort the list to facilitate future comparisons.
647
0
    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
0
    for (auto *Candidate : KnownSignatures) {
652
0
      if (Candidate->size() == CurSignatureList->size() &&
653
0
          *Candidate == *CurSignatureList) {
654
0
        if (CanReuseSignature(Candidate, Fct.second)) {
655
0
          SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
656
0
          FoundReusableSig = true;
657
0
        }
658
0
      }
659
0
    }
660
661
0
    if (FoundReusableSig) {
662
0
      delete CurSignatureList;
663
0
    } else {
664
      // Add a new entry.
665
0
      SignatureListMap[CurSignatureList] = {
666
0
          SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
667
0
      KnownSignatures.push_back(CurSignatureList);
668
0
    }
669
0
  }
670
671
0
  for (auto *I : KnownSignatures) {
672
0
    delete I;
673
0
  }
674
0
}
675
676
0
void BuiltinNameEmitter::EmitStringMatcher() {
677
0
  std::vector<StringMatcher::StringPair> ValidBuiltins;
678
0
  unsigned CumulativeIndex = 1;
679
680
0
  for (const auto &SLM : SignatureListMap) {
681
0
    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
0
    for (const auto &FctName : SLM.second.Names) {
686
0
      std::string RetStmt;
687
0
      raw_string_ostream SS(RetStmt);
688
0
      SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
689
0
         << ");";
690
0
      SS.flush();
691
0
      ValidBuiltins.push_back(
692
0
          StringMatcher::StringPair(std::string(FctName), RetStmt));
693
0
    }
694
0
    CumulativeIndex += Ovl.size();
695
0
  }
696
697
0
  OS << R"(
698
0
// Find out whether a string matches an existing OpenCL builtin function name.
699
0
// Returns: A pair <0, 0> if no name matches.
700
0
//          A pair <Index, Len> indexing the BuiltinTable if the name is
701
0
//          matching an OpenCL builtin function.
702
0
static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
703
0
704
0
)";
705
706
0
  StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
707
708
0
  OS << "  return std::make_pair(0, 0);\n";
709
0
  OS << "} // isOpenCLBuiltin\n";
710
0
}
711
712
0
void BuiltinNameEmitter::EmitQualTypeFinder() {
713
0
  OS << R"(
714
0
715
0
static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
716
0
static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
717
0
718
0
// Convert an OpenCLTypeStruct type to a list of QualTypes.
719
0
// Generic types represent multiple types and vector sizes, thus a vector
720
0
// is returned. The conversion is done in two steps:
721
0
// Step 1: A switch statement fills a vector with scalar base types for the
722
0
//         Cartesian product of (vector sizes) x (types) for generic types,
723
0
//         or a single scalar type for non generic types.
724
0
// Step 2: Qualifiers and other type properties such as vector size are
725
0
//         applied.
726
0
static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
727
0
                     llvm::SmallVectorImpl<QualType> &QT) {
728
0
  ASTContext &Context = S.Context;
729
0
  // Number of scalar types in the GenType.
730
0
  unsigned GenTypeNumTypes;
731
0
  // Pointer to the list of vector sizes for the GenType.
732
0
  llvm::ArrayRef<unsigned> GenVectorSizes;
733
0
)";
734
735
  // Generate list of vector sizes for each generic type.
736
0
  for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
737
0
    OS << "  constexpr unsigned List"
738
0
       << VectList->getValueAsString("Name") << "[] = {";
739
0
    for (const auto V : VectList->getValueAsListOfInts("List")) {
740
0
      OS << V << ", ";
741
0
    }
742
0
    OS << "};\n";
743
0
  }
744
745
  // Step 1.
746
  // Start of switch statement over all types.
747
0
  OS << "\n  switch (Ty.ID) {\n";
748
749
  // Switch cases for image types (Image2d, Image3d, ...)
750
0
  std::vector<Record *> ImageTypes =
751
0
      Records.getAllDerivedDefinitions("ImageType");
752
753
  // Map an image type name to its 3 access-qualified types (RO, WO, RW).
754
0
  StringMap<SmallVector<Record *, 3>> ImageTypesMap;
755
0
  for (auto *IT : ImageTypes) {
756
0
    auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
757
0
    if (Entry == ImageTypesMap.end()) {
758
0
      SmallVector<Record *, 3> ImageList;
759
0
      ImageList.push_back(IT);
760
0
      ImageTypesMap.insert(
761
0
          std::make_pair(IT->getValueAsString("Name"), ImageList));
762
0
    } else {
763
0
      Entry->second.push_back(IT);
764
0
    }
765
0
  }
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
0
  for (const auto &ITE : ImageTypesMap) {
772
0
    OS << "    case OCLT_" << ITE.getKey() << ":\n"
773
0
       << "      switch (Ty.AccessQualifier) {\n"
774
0
       << "        case OCLAQ_None:\n"
775
0
       << "          llvm_unreachable(\"Image without access qualifier\");\n";
776
0
    for (const auto &Image : ITE.getValue()) {
777
0
      OS << StringSwitch<const char *>(
778
0
                Image->getValueAsString("AccessQualifier"))
779
0
                .Case("RO", "        case OCLAQ_ReadOnly:\n")
780
0
                .Case("WO", "        case OCLAQ_WriteOnly:\n")
781
0
                .Case("RW", "        case OCLAQ_ReadWrite:\n")
782
0
         << "          QT.push_back("
783
0
         << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
784
0
         << ");\n"
785
0
         << "          break;\n";
786
0
    }
787
0
    OS << "      }\n"
788
0
       << "      break;\n";
789
0
  }
790
791
  // Switch cases for generic types.
792
0
  for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
793
0
    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
0
    std::vector<Record *> BaseTypes =
799
0
        GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
800
801
    // Collect all QualTypes for a single vector size into TypeList.
802
0
    OS << "      SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
803
0
    for (const auto *T : BaseTypes) {
804
0
      StringRef Ext =
805
0
          T->getValueAsDef("Extension")->getValueAsString("ExtName");
806
0
      if (!Ext.empty()) {
807
0
        OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
808
0
           << "\")) {\n  ";
809
0
      }
810
0
      OS << "      TypeList.push_back("
811
0
         << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
812
0
      if (!Ext.empty()) {
813
0
        OS << "      }\n";
814
0
      }
815
0
    }
816
0
    OS << "      GenTypeNumTypes = TypeList.size();\n";
817
818
    // Duplicate the TypeList for every vector size.
819
0
    std::vector<int64_t> VectorList =
820
0
        GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
821
0
    OS << "      QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
822
0
       << "      for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
823
0
       << "        QT.append(TypeList);\n"
824
0
       << "      }\n";
825
826
    // GenVectorSizes is the list of vector sizes for this GenType.
827
0
    OS << "      GenVectorSizes = List"
828
0
       << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
829
0
       << ";\n"
830
0
       << "      break;\n"
831
0
       << "    }\n";
832
0
  }
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
0
  std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
838
0
  StringMap<bool> TypesSeen;
839
840
0
  for (const auto *T : Types) {
841
    // Check this is not an image type
842
0
    if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
843
0
      continue;
844
    // Check we have not seen this Type
845
0
    if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
846
0
      continue;
847
0
    TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
848
849
    // Check the Type does not have an "abstract" QualType
850
0
    auto QT = T->getValueAsDef("QTExpr");
851
0
    if (QT->getValueAsBit("IsAbstract") == 1)
852
0
      continue;
853
    // Emit the cases for non generic, non image types.
854
0
    OS << "    case OCLT_" << T->getValueAsString("Name") << ":\n";
855
856
0
    StringRef Ext = T->getValueAsDef("Extension")->getValueAsString("ExtName");
857
    // If this type depends on an extension, ensure the extension macro is
858
    // defined.
859
0
    if (!Ext.empty()) {
860
0
      OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
861
0
         << "\")) {\n  ";
862
0
    }
863
0
    OS << "      QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
864
0
    if (!Ext.empty()) {
865
0
      OS << "      }\n";
866
0
    }
867
0
    OS << "      break;\n";
868
0
  }
869
870
  // End of switch statement.
871
0
  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
0
  OS << "  // Construct the different vector types for each generic type.\n";
878
0
  OS << "  if (Ty.ID >= " << TypeList.size() << ") {";
879
0
  OS << R"(
880
0
    for (unsigned I = 0; I < QT.size(); I++) {
881
0
      // For scalars, size is 1.
882
0
      if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
883
0
        QT[I] = Context.getExtVectorType(QT[I],
884
0
                          GenVectorSizes[I / GenTypeNumTypes]);
885
0
      }
886
0
    }
887
0
  }
888
0
)";
889
890
  // Assign the right attributes to the types (e.g. vector size).
891
0
  OS << R"(
892
0
  // Set vector size for non-generic vector types.
893
0
  if (Ty.VectorWidth > 1) {
894
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
895
0
      QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
896
0
    }
897
0
  }
898
0
899
0
  if (Ty.IsVolatile != 0) {
900
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
901
0
      QT[Index] = Context.getVolatileType(QT[Index]);
902
0
    }
903
0
  }
904
0
905
0
  if (Ty.IsConst != 0) {
906
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
907
0
      QT[Index] = Context.getConstType(QT[Index]);
908
0
    }
909
0
  }
910
0
911
0
  // Transform the type to a pointer as the last step, if necessary.
912
0
  // Builtin functions only have pointers on [const|volatile], no
913
0
  // [const|volatile] pointers, so this is ok to do it as a last step.
914
0
  if (Ty.IsPointer != 0) {
915
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
916
0
      QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
917
0
      QT[Index] = Context.getPointerType(QT[Index]);
918
0
    }
919
0
  }
920
0
)";
921
922
  // End of the "OCL2Qual" function.
923
0
  OS << "\n} // OCL2Qual\n";
924
0
}
925
926
std::string OpenCLBuiltinTestEmitter::getTypeString(const Record *Type,
927
                                                    TypeFlags Flags,
928
31.7k
                                                    int VectorSize) const {
929
31.7k
  std::string S;
930
31.7k
  if (Type->getValueAsBit("IsConst") || 
Flags.IsConst31.3k
) {
931
679
    S += "const ";
932
679
  }
933
31.7k
  if (Type->getValueAsBit("IsVolatile") || 
Flags.IsVolatile31.3k
) {
934
348
    S += "volatile ";
935
348
  }
936
937
31.7k
  auto PrintAddrSpace = [&S](StringRef AddrSpace) {
938
2.46k
    S += StringSwitch<const char *>(AddrSpace)
939
2.46k
             .Case("clang::LangAS::opencl_private", "__private")
940
2.46k
             .Case("clang::LangAS::opencl_global", "__global")
941
2.46k
             .Case("clang::LangAS::opencl_constant", "__constant")
942
2.46k
             .Case("clang::LangAS::opencl_local", "__local")
943
2.46k
             .Case("clang::LangAS::opencl_generic", "__generic")
944
2.46k
             .Default("__private");
945
2.46k
    S += " ";
946
2.46k
  };
947
31.7k
  if (Flags.IsPointer) {
948
1.02k
    PrintAddrSpace(Flags.AddrSpace);
949
30.6k
  } else if (Type->getValueAsBit("IsPointer")) {
950
1.43k
    PrintAddrSpace(Type->getValueAsString("AddrSpace"));
951
1.43k
  }
952
953
31.7k
  StringRef Acc = Type->getValueAsString("AccessQualifier");
954
31.7k
  if (Acc != "") {
955
428
    S += StringSwitch<const char *>(Acc)
956
428
             .Case("RO", "__read_only ")
957
428
             .Case("WO", "__write_only ")
958
428
             .Case("RW", "__read_write ");
959
428
  }
960
961
31.7k
  S += Type->getValueAsString("Name").str();
962
31.7k
  if (VectorSize > 1) {
963
21.6k
    S += std::to_string(VectorSize);
964
21.6k
  }
965
966
31.7k
  if (Type->getValueAsBit("IsPointer") || 
Flags.IsPointer30.2k
) {
967
2.46k
    S += " *";
968
2.46k
  }
969
970
31.7k
  return S;
971
31.7k
}
972
973
void OpenCLBuiltinTestEmitter::getTypeLists(
974
    Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
975
21.4k
    std::vector<int64_t> &VectorList) const {
976
21.4k
  bool isGenType = Type->isSubClassOf("GenericType");
977
21.4k
  if (isGenType) {
978
885
    TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
979
885
    VectorList =
980
885
        Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
981
885
    return;
982
885
  }
983
984
20.5k
  if (Type->isSubClassOf("PointerType") || 
Type->isSubClassOf("ConstType")19.0k
||
985
20.5k
      
Type->isSubClassOf("VolatileType")19.0k
) {
986
1.49k
    StringRef SubTypeName = Type->getValueAsString("Name");
987
1.49k
    Record *PossibleGenType = Records.getDef(SubTypeName);
988
1.49k
    if (PossibleGenType && 
PossibleGenType->isSubClassOf("GenericType")57
) {
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
57
      Flags.IsPointer = Type->getValueAsBit("IsPointer");
993
57
      Flags.IsConst = Type->getValueAsBit("IsConst");
994
57
      Flags.IsVolatile = Type->getValueAsBit("IsVolatile");
995
57
      Flags.AddrSpace = Type->getValueAsString("AddrSpace");
996
57
      getTypeLists(PossibleGenType, Flags, TypeList, VectorList);
997
57
      return;
998
57
    }
999
1.49k
  }
1000
1001
  // Not a GenericType, so just insert the single type.
1002
20.5k
  TypeList.push_back(Type);
1003
20.5k
  VectorList.push_back(Type->getValueAsInt("VecWidth"));
1004
20.5k
}
1005
1006
void OpenCLBuiltinTestEmitter::expandTypesInSignature(
1007
    const std::vector<Record *> &Signature,
1008
8.90k
    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
8.90k
  unsigned NumSignatures = 1;
1012
8.90k
  SmallVector<SmallVector<std::string, 4>, 4> ExpandedGenTypes;
1013
21.3k
  for (const auto &Arg : Signature) {
1014
21.3k
    SmallVector<std::string, 4> ExpandedArg;
1015
21.3k
    std::vector<Record *> TypeList;
1016
21.3k
    std::vector<int64_t> VectorList;
1017
21.3k
    TypeFlags Flags;
1018
1019
21.3k
    getTypeLists(Arg, Flags, TypeList, VectorList);
1020
1021
    // Insert the Cartesian product of the types and vector sizes.
1022
24.9k
    for (const auto &Vector : VectorList) {
1023
31.7k
      for (const auto &Type : TypeList) {
1024
31.7k
        ExpandedArg.push_back(getTypeString(Type, Flags, Vector));
1025
31.7k
      }
1026
24.9k
    }
1027
21.3k
    NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
1028
21.3k
    ExpandedGenTypes.push_back(ExpandedArg);
1029
21.3k
  }
1030
1031
  // Now the total number of signatures is known.  Populate the return list with
1032
  // all signatures.
1033
21.9k
  for (unsigned I = 0; I < NumSignatures; 
I++13.0k
) {
1034
13.0k
    SmallVector<std::string, 2> Args;
1035
1036
    // Process a single signature.
1037
46.3k
    for (unsigned ArgNum = 0; ArgNum < Signature.size(); 
ArgNum++33.3k
) {
1038
      // For differently-sized GenTypes in a parameter list, the smaller
1039
      // GenTypes just repeat, so index modulo the number of expanded types.
1040
33.3k
      size_t TypeIndex = I % ExpandedGenTypes[ArgNum].size();
1041
33.3k
      Args.push_back(ExpandedGenTypes[ArgNum][TypeIndex]);
1042
33.3k
    }
1043
13.0k
    Types.push_back(Args);
1044
13.0k
  }
1045
8.90k
}
1046
1047
1
void OpenCLBuiltinTestEmitter::emit() {
1048
1
  emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
1049
1050
  // Enable some extensions for testing.
1051
1
  OS << R"(
1052
1
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
1053
1
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
1054
1
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
1055
1
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
1056
1
#pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
1057
1
#pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
1058
1
#pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
1059
1
1060
1
)";
1061
1062
  // Ensure each test has a unique name by numbering them.
1063
1
  unsigned TestID = 0;
1064
1065
  // Iterate over all builtins.
1066
1
  std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
1067
8.90k
  for (const auto *B : Builtins) {
1068
8.90k
    StringRef Name = B->getValueAsString("Name");
1069
1070
8.90k
    SmallVector<SmallVector<std::string, 2>, 4> FTypes;
1071
8.90k
    expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
1072
1073
8.90k
    OS << "// Test " << Name << "\n";
1074
8.90k
    std::string OptionalEndif;
1075
8.90k
    StringRef Extensions =
1076
8.90k
        B->getValueAsDef("Extension")->getValueAsString("ExtName");
1077
8.90k
    if (!Extensions.empty()) {
1078
378
      OS << "#if";
1079
378
      OptionalEndif = "#endif // Extension\n";
1080
1081
378
      SmallVector<StringRef, 2> ExtVec;
1082
378
      Extensions.split(ExtVec, " ");
1083
378
      bool isFirst = true;
1084
381
      for (StringRef Ext : ExtVec) {
1085
381
        if (!isFirst) {
1086
3
          OS << " &&";
1087
3
        }
1088
381
        OS << " defined(" << Ext << ")";
1089
381
        isFirst = false;
1090
381
      }
1091
378
      OS << "\n";
1092
378
    }
1093
8.90k
    auto PrintOpenCLVersion = [this](int Version) {
1094
1.30k
      OS << "CL_VERSION_" << (Version / 100) << "_" << ((Version % 100) / 10);
1095
1.30k
    };
1096
8.90k
    int MinVersion = B->getValueAsDef("MinVersion")->getValueAsInt("ID");
1097
8.90k
    if (MinVersion != 100) {
1098
      // OpenCL 1.0 is the default minimum version.
1099
540
      OS << "#if __OPENCL_C_VERSION__ >= ";
1100
540
      PrintOpenCLVersion(MinVersion);
1101
540
      OS << "\n";
1102
540
      OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
1103
540
    }
1104
8.90k
    int MaxVersion = B->getValueAsDef("MaxVersion")->getValueAsInt("ID");
1105
8.90k
    if (MaxVersion) {
1106
762
      OS << "#if __OPENCL_C_VERSION__ < ";
1107
762
      PrintOpenCLVersion(MaxVersion);
1108
762
      OS << "\n";
1109
762
      OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
1110
762
    }
1111
13.0k
    for (const auto &Signature : FTypes) {
1112
      // Emit function declaration.
1113
13.0k
      OS << Signature[0] << " test" << TestID++ << "_" << Name << "(";
1114
13.0k
      if (Signature.size() > 1) {
1115
33.3k
        for (unsigned I = 1; I < Signature.size(); 
I++20.3k
) {
1116
20.3k
          if (I != 1)
1117
7.37k
            OS << ", ";
1118
20.3k
          OS << Signature[I] << " arg" << I;
1119
20.3k
        }
1120
12.9k
      }
1121
13.0k
      OS << ") {\n";
1122
1123
      // Emit function body.
1124
13.0k
      OS << "  ";
1125
13.0k
      if (Signature[0] != "void") {
1126
12.1k
        OS << "return ";
1127
12.1k
      }
1128
13.0k
      OS << Name << "(";
1129
33.3k
      for (unsigned I = 1; I < Signature.size(); 
I++20.3k
) {
1130
20.3k
        if (I != 1)
1131
7.37k
          OS << ", ";
1132
20.3k
        OS << "arg" << I;
1133
20.3k
      }
1134
13.0k
      OS << ");\n";
1135
1136
      // End of function body.
1137
13.0k
      OS << "}\n";
1138
13.0k
    }
1139
8.90k
    OS << OptionalEndif << "\n";
1140
8.90k
  }
1141
1
}
1142
1143
0
void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
1144
0
  BuiltinNameEmitter NameChecker(Records, OS);
1145
0
  NameChecker.Emit();
1146
0
}
1147
1148
void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
1149
1
                                        raw_ostream &OS) {
1150
1
  OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
1151
1
  TestFileGenerator.emit();
1152
1
}