Coverage Report

Created: 2021-09-21 08:58

/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
/// Base class for emitting a file (e.g. header or test) from OpenCLBuiltins.td
237
class OpenCLBuiltinFileEmitterBase {
238
public:
239
  OpenCLBuiltinFileEmitterBase(RecordKeeper &Records, raw_ostream &OS)
240
1
      : Records(Records), OS(OS) {}
241
1
  virtual ~OpenCLBuiltinFileEmitterBase() = default;
242
243
  // Entrypoint to generate the functions for testing all OpenCL builtin
244
  // functions.
245
  virtual void emit() = 0;
246
247
protected:
248
  struct TypeFlags {
249
21.5k
    TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
250
    bool IsConst : 1;
251
    bool IsVolatile : 1;
252
    bool IsPointer : 1;
253
    StringRef AddrSpace;
254
  };
255
256
  // Return a string representation of the given type, such that it can be
257
  // used as a type in OpenCL C code.
258
  std::string getTypeString(const Record *Type, TypeFlags Flags,
259
                            int VectorSize) const;
260
261
  // Return the type(s) and vector size(s) for the given type.  For
262
  // non-GenericTypes, the resulting vectors will contain 1 element.  For
263
  // GenericTypes, the resulting vectors typically contain multiple elements.
264
  void getTypeLists(Record *Type, TypeFlags &Flags,
265
                    std::vector<Record *> &TypeList,
266
                    std::vector<int64_t> &VectorList) const;
267
268
  // Expand the TableGen Records representing a builtin function signature into
269
  // one or more function signatures.  Return them as a vector of a vector of
270
  // strings, with each string containing an OpenCL C type and optional
271
  // qualifiers.
272
  //
273
  // The Records may contain GenericTypes, which expand into multiple
274
  // signatures.  Repeated occurrences of GenericType in a signature expand to
275
  // the same types.  For example [char, FGenType, FGenType] expands to:
276
  //   [char, float, float]
277
  //   [char, float2, float2]
278
  //   [char, float3, float3]
279
  //   ...
280
  void
281
  expandTypesInSignature(const std::vector<Record *> &Signature,
282
                         SmallVectorImpl<SmallVector<std::string, 2>> &Types);
283
284
  // Emit extension enabling pragmas.
285
  void emitExtensionSetup();
286
287
  // Emit an #if guard for a Builtin's extension.  Return the corresponding
288
  // closing #endif, or an empty string if no extension #if guard was emitted.
289
  std::string emitExtensionGuard(const Record *Builtin);
290
291
  // Emit an #if guard for a Builtin's language version.  Return the
292
  // corresponding closing #endif, or an empty string if no version #if guard
293
  // was emitted.
294
  std::string emitVersionGuard(const Record *Builtin);
295
296
  // Contains OpenCL builtin functions and related information, stored as
297
  // Record instances. They are coming from the associated TableGen file.
298
  RecordKeeper &Records;
299
300
  // The output file.
301
  raw_ostream &OS;
302
};
303
304
// OpenCL builtin test generator.  This class processes the same TableGen input
305
// as BuiltinNameEmitter, but generates a .cl file that contains a call to each
306
// builtin function described in the .td input.
307
class OpenCLBuiltinTestEmitter : public OpenCLBuiltinFileEmitterBase {
308
public:
309
  OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
310
1
      : OpenCLBuiltinFileEmitterBase(Records, OS) {}
311
312
  // Entrypoint to generate the functions for testing all OpenCL builtin
313
  // functions.
314
  void emit() override;
315
};
316
317
} // namespace
318
319
0
void BuiltinNameEmitter::Emit() {
320
0
  emitSourceFileHeader("OpenCL Builtin handling", OS);
321
322
0
  OS << "#include \"llvm/ADT/StringRef.h\"\n";
323
0
  OS << "using namespace clang;\n\n";
324
325
  // Emit enums and structs.
326
0
  EmitDeclarations();
327
328
  // Parse the Records to populate the internal lists.
329
0
  GetOverloads();
330
0
  GroupBySignature();
331
332
  // Emit tables.
333
0
  EmitExtensionTable();
334
0
  EmitTypeTable();
335
0
  EmitSignatureTable();
336
0
  EmitBuiltinTable();
337
338
  // Emit functions.
339
0
  EmitStringMatcher();
340
0
  EmitQualTypeFinder();
341
0
}
342
343
void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
344
                                          StringMap<bool> &TypesSeen,
345
                                          std::string &Output,
346
0
                                          std::vector<const Record *> &List) {
347
0
  raw_string_ostream SS(Output);
348
349
0
  for (const auto *T : Types) {
350
0
    if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
351
0
      SS << "  OCLT_" + T->getValueAsString("Name") << ",\n";
352
      // Save the type names in the same order as their enum value. Note that
353
      // the Record can be a VectorType or something else, only the name is
354
      // important.
355
0
      List.push_back(T);
356
0
      TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
357
0
    }
358
0
  }
359
0
  SS.flush();
360
0
}
361
362
0
void BuiltinNameEmitter::EmitDeclarations() {
363
  // Enum of scalar type names (float, int, ...) and generic type sets.
364
0
  OS << "enum OpenCLTypeID {\n";
365
366
0
  StringMap<bool> TypesSeen;
367
0
  std::string GenTypeEnums;
368
0
  std::string TypeEnums;
369
370
  // Extract generic types and non-generic types separately, to keep
371
  // gentypes at the end of the enum which simplifies the special handling
372
  // for gentypes in SemaLookup.
373
0
  std::vector<Record *> GenTypes =
374
0
      Records.getAllDerivedDefinitions("GenericType");
375
0
  ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
376
377
0
  std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
378
0
  ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
379
380
0
  OS << TypeEnums;
381
0
  OS << GenTypeEnums;
382
0
  OS << "};\n";
383
384
  // Structure definitions.
385
0
  OS << R"(
386
0
// Image access qualifier.
387
0
enum OpenCLAccessQual : unsigned char {
388
0
  OCLAQ_None,
389
0
  OCLAQ_ReadOnly,
390
0
  OCLAQ_WriteOnly,
391
0
  OCLAQ_ReadWrite
392
0
};
393
0
394
0
// Represents a return type or argument type.
395
0
struct OpenCLTypeStruct {
396
0
  // A type (e.g. float, int, ...).
397
0
  const OpenCLTypeID ID;
398
0
  // Vector size (if applicable; 0 for scalars and generic types).
399
0
  const unsigned VectorWidth;
400
0
  // 0 if the type is not a pointer.
401
0
  const bool IsPointer : 1;
402
0
  // 0 if the type is not const.
403
0
  const bool IsConst : 1;
404
0
  // 0 if the type is not volatile.
405
0
  const bool IsVolatile : 1;
406
0
  // Access qualifier.
407
0
  const OpenCLAccessQual AccessQualifier;
408
0
  // Address space of the pointer (if applicable).
409
0
  const LangAS AS;
410
0
};
411
0
412
0
// One overload of an OpenCL builtin function.
413
0
struct OpenCLBuiltinStruct {
414
0
  // Index of the signature in the OpenCLTypeStruct table.
415
0
  const unsigned SigTableIndex;
416
0
  // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
417
0
  // the SignatureTable represent the complete signature.  The first type at
418
0
  // index SigTableIndex is the return type.
419
0
  const unsigned NumTypes;
420
0
  // Function attribute __attribute__((pure))
421
0
  const bool IsPure : 1;
422
0
  // Function attribute __attribute__((const))
423
0
  const bool IsConst : 1;
424
0
  // Function attribute __attribute__((convergent))
425
0
  const bool IsConv : 1;
426
0
  // OpenCL extension(s) required for this overload.
427
0
  const unsigned short Extension;
428
0
  // OpenCL versions in which this overload is available.
429
0
  const unsigned short Versions;
430
0
};
431
0
432
0
)";
433
0
}
434
435
// Verify that the combination of GenTypes in a signature is supported.
436
// To simplify the logic for creating overloads in SemaLookup, only allow
437
// a signature to contain different GenTypes if these GenTypes represent
438
// the same number of actual scalar or vector types.
439
//
440
// Exit with a fatal error if an unsupported construct is encountered.
441
static void VerifySignature(const std::vector<Record *> &Signature,
442
0
                            const Record *BuiltinRec) {
443
0
  unsigned GenTypeVecSizes = 1;
444
0
  unsigned GenTypeTypes = 1;
445
446
0
  for (const auto *T : Signature) {
447
    // Check all GenericType arguments in this signature.
448
0
    if (T->isSubClassOf("GenericType")) {
449
      // Check number of vector sizes.
450
0
      unsigned NVecSizes =
451
0
          T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
452
0
      if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
453
0
        if (GenTypeVecSizes > 1) {
454
          // We already saw a gentype with a different number of vector sizes.
455
0
          PrintFatalError(BuiltinRec->getLoc(),
456
0
              "number of vector sizes should be equal or 1 for all gentypes "
457
0
              "in a declaration");
458
0
        }
459
0
        GenTypeVecSizes = NVecSizes;
460
0
      }
461
462
      // Check number of data types.
463
0
      unsigned NTypes =
464
0
          T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
465
0
      if (NTypes != GenTypeTypes && NTypes != 1) {
466
0
        if (GenTypeTypes > 1) {
467
          // We already saw a gentype with a different number of types.
468
0
          PrintFatalError(BuiltinRec->getLoc(),
469
0
              "number of types should be equal or 1 for all gentypes "
470
0
              "in a declaration");
471
0
        }
472
0
        GenTypeTypes = NTypes;
473
0
      }
474
0
    }
475
0
  }
476
0
}
477
478
0
void BuiltinNameEmitter::GetOverloads() {
479
  // Populate the TypeMap.
480
0
  std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
481
0
  unsigned I = 0;
482
0
  for (const auto &T : Types) {
483
0
    TypeMap.insert(std::make_pair(T, I++));
484
0
  }
485
486
  // Populate the SignaturesList and the FctOverloadMap.
487
0
  unsigned CumulativeSignIndex = 0;
488
0
  std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
489
0
  for (const auto *B : Builtins) {
490
0
    StringRef BName = B->getValueAsString("Name");
491
0
    if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
492
0
      FctOverloadMap.insert(std::make_pair(
493
0
          BName, std::vector<std::pair<const Record *, unsigned>>{}));
494
0
    }
495
496
0
    auto Signature = B->getValueAsListOfDefs("Signature");
497
    // Reuse signatures to avoid unnecessary duplicates.
498
0
    auto it =
499
0
        std::find_if(SignaturesList.begin(), SignaturesList.end(),
500
0
                     [&](const std::pair<std::vector<Record *>, unsigned> &a) {
501
0
                       return a.first == Signature;
502
0
                     });
503
0
    unsigned SignIndex;
504
0
    if (it == SignaturesList.end()) {
505
0
      VerifySignature(Signature, B);
506
0
      SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
507
0
      SignIndex = CumulativeSignIndex;
508
0
      CumulativeSignIndex += Signature.size();
509
0
    } else {
510
0
      SignIndex = it->second;
511
0
    }
512
0
    FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
513
0
  }
514
0
}
515
516
0
void BuiltinNameEmitter::EmitExtensionTable() {
517
0
  OS << "static const char *FunctionExtensionTable[] = {\n";
518
0
  unsigned Index = 0;
519
0
  std::vector<Record *> FuncExtensions =
520
0
      Records.getAllDerivedDefinitions("FunctionExtension");
521
522
0
  for (const auto &FE : FuncExtensions) {
523
    // Emit OpenCL extension table entry.
524
0
    OS << "  // " << Index << ": " << FE->getName() << "\n"
525
0
       << "  \"" << FE->getValueAsString("ExtName") << "\",\n";
526
527
    // Record index of this extension.
528
0
    FunctionExtensionIndex[FE->getName()] = Index++;
529
0
  }
530
0
  OS << "};\n\n";
531
0
}
532
533
0
void BuiltinNameEmitter::EmitTypeTable() {
534
0
  OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
535
0
  for (const auto &T : TypeMap) {
536
0
    const char *AccessQual =
537
0
        StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
538
0
            .Case("RO", "OCLAQ_ReadOnly")
539
0
            .Case("WO", "OCLAQ_WriteOnly")
540
0
            .Case("RW", "OCLAQ_ReadWrite")
541
0
            .Default("OCLAQ_None");
542
543
0
    OS << "  // " << T.second << "\n"
544
0
       << "  {OCLT_" << T.first->getValueAsString("Name") << ", "
545
0
       << T.first->getValueAsInt("VecWidth") << ", "
546
0
       << T.first->getValueAsBit("IsPointer") << ", "
547
0
       << T.first->getValueAsBit("IsConst") << ", "
548
0
       << T.first->getValueAsBit("IsVolatile") << ", "
549
0
       << AccessQual << ", "
550
0
       << T.first->getValueAsString("AddrSpace") << "},\n";
551
0
  }
552
0
  OS << "};\n\n";
553
0
}
554
555
0
void BuiltinNameEmitter::EmitSignatureTable() {
556
  // Store a type (e.g. int, float, int2, ...). The type is stored as an index
557
  // of a struct OpenCLType table. Multiple entries following each other form a
558
  // signature.
559
0
  OS << "static const unsigned short SignatureTable[] = {\n";
560
0
  for (const auto &P : SignaturesList) {
561
0
    OS << "  // " << P.second << "\n  ";
562
0
    for (const Record *R : P.first) {
563
0
      unsigned Entry = TypeMap.find(R)->second;
564
0
      if (Entry > USHRT_MAX) {
565
        // Report an error when seeing an entry that is too large for the
566
        // current index type (unsigned short).  When hitting this, the type
567
        // of SignatureTable will need to be changed.
568
0
        PrintFatalError("Entry in SignatureTable exceeds limit.");
569
0
      }
570
0
      OS << Entry << ", ";
571
0
    }
572
0
    OS << "\n";
573
0
  }
574
0
  OS << "};\n\n";
575
0
}
576
577
// Encode a range MinVersion..MaxVersion into a single bit mask that can be
578
// checked against LangOpts using isOpenCLVersionContainedInMask().
579
// This must be kept in sync with OpenCLVersionID in OpenCLOptions.h.
580
// (Including OpenCLOptions.h here would be a layering violation.)
581
static unsigned short EncodeVersions(unsigned int MinVersion,
582
0
                                     unsigned int MaxVersion) {
583
0
  unsigned short Encoded = 0;
584
585
  // A maximum version of 0 means available in all later versions.
586
0
  if (MaxVersion == 0) {
587
0
    MaxVersion = UINT_MAX;
588
0
  }
589
590
0
  unsigned VersionIDs[] = {100, 110, 120, 200, 300};
591
0
  for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
592
0
    if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
593
0
      Encoded |= 1 << I;
594
0
    }
595
0
  }
596
597
0
  return Encoded;
598
0
}
599
600
0
void BuiltinNameEmitter::EmitBuiltinTable() {
601
0
  unsigned Index = 0;
602
603
0
  OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
604
0
  for (const auto &SLM : SignatureListMap) {
605
606
0
    OS << "  // " << (Index + 1) << ": ";
607
0
    for (const auto &Name : SLM.second.Names) {
608
0
      OS << Name << ", ";
609
0
    }
610
0
    OS << "\n";
611
612
0
    for (const auto &Overload : SLM.second.Signatures) {
613
0
      StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
614
0
      unsigned int MinVersion =
615
0
          Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
616
0
      unsigned int MaxVersion =
617
0
          Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
618
619
0
      OS << "  { " << Overload.second << ", "
620
0
         << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
621
0
         << (Overload.first->getValueAsBit("IsPure")) << ", "
622
0
         << (Overload.first->getValueAsBit("IsConst")) << ", "
623
0
         << (Overload.first->getValueAsBit("IsConv")) << ", "
624
0
         << FunctionExtensionIndex[ExtName] << ", "
625
0
         << EncodeVersions(MinVersion, MaxVersion) << " },\n";
626
0
      Index++;
627
0
    }
628
0
  }
629
0
  OS << "};\n\n";
630
0
}
631
632
bool BuiltinNameEmitter::CanReuseSignature(
633
    BuiltinIndexListTy *Candidate,
634
0
    std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
635
0
  assert(Candidate->size() == SignatureList.size() &&
636
0
         "signature lists should have the same size");
637
638
0
  auto &CandidateSigs =
639
0
      SignatureListMap.find(Candidate)->second.Signatures;
640
0
  for (unsigned Index = 0; Index < Candidate->size(); Index++) {
641
0
    const Record *Rec = SignatureList[Index].first;
642
0
    const Record *Rec2 = CandidateSigs[Index].first;
643
0
    if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
644
0
        Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
645
0
        Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
646
0
        Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
647
0
            Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
648
0
        Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
649
0
            Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
650
0
        Rec->getValueAsDef("Extension")->getName() ==
651
0
            Rec2->getValueAsDef("Extension")->getName()) {
652
0
      return true;
653
0
    }
654
0
  }
655
0
  return false;
656
0
}
657
658
0
void BuiltinNameEmitter::GroupBySignature() {
659
  // List of signatures known to be emitted.
660
0
  std::vector<BuiltinIndexListTy *> KnownSignatures;
661
662
0
  for (auto &Fct : FctOverloadMap) {
663
0
    bool FoundReusableSig = false;
664
665
    // Gather all signatures for the current function.
666
0
    auto *CurSignatureList = new BuiltinIndexListTy();
667
0
    for (const auto &Signature : Fct.second) {
668
0
      CurSignatureList->push_back(Signature.second);
669
0
    }
670
    // Sort the list to facilitate future comparisons.
671
0
    llvm::sort(*CurSignatureList);
672
673
    // Check if we have already seen another function with the same list of
674
    // signatures.  If so, just add the name of the function.
675
0
    for (auto *Candidate : KnownSignatures) {
676
0
      if (Candidate->size() == CurSignatureList->size() &&
677
0
          *Candidate == *CurSignatureList) {
678
0
        if (CanReuseSignature(Candidate, Fct.second)) {
679
0
          SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
680
0
          FoundReusableSig = true;
681
0
        }
682
0
      }
683
0
    }
684
685
0
    if (FoundReusableSig) {
686
0
      delete CurSignatureList;
687
0
    } else {
688
      // Add a new entry.
689
0
      SignatureListMap[CurSignatureList] = {
690
0
          SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
691
0
      KnownSignatures.push_back(CurSignatureList);
692
0
    }
693
0
  }
694
695
0
  for (auto *I : KnownSignatures) {
696
0
    delete I;
697
0
  }
698
0
}
699
700
0
void BuiltinNameEmitter::EmitStringMatcher() {
701
0
  std::vector<StringMatcher::StringPair> ValidBuiltins;
702
0
  unsigned CumulativeIndex = 1;
703
704
0
  for (const auto &SLM : SignatureListMap) {
705
0
    const auto &Ovl = SLM.second.Signatures;
706
707
    // A single signature list may be used by different builtins.  Return the
708
    // same <index, length> pair for each of those builtins.
709
0
    for (const auto &FctName : SLM.second.Names) {
710
0
      std::string RetStmt;
711
0
      raw_string_ostream SS(RetStmt);
712
0
      SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
713
0
         << ");";
714
0
      SS.flush();
715
0
      ValidBuiltins.push_back(
716
0
          StringMatcher::StringPair(std::string(FctName), RetStmt));
717
0
    }
718
0
    CumulativeIndex += Ovl.size();
719
0
  }
720
721
0
  OS << R"(
722
0
// Find out whether a string matches an existing OpenCL builtin function name.
723
0
// Returns: A pair <0, 0> if no name matches.
724
0
//          A pair <Index, Len> indexing the BuiltinTable if the name is
725
0
//          matching an OpenCL builtin function.
726
0
static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
727
0
728
0
)";
729
730
0
  StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
731
732
0
  OS << "  return std::make_pair(0, 0);\n";
733
0
  OS << "} // isOpenCLBuiltin\n";
734
0
}
735
736
0
void BuiltinNameEmitter::EmitQualTypeFinder() {
737
0
  OS << R"(
738
0
739
0
static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
740
0
static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
741
0
742
0
// Convert an OpenCLTypeStruct type to a list of QualTypes.
743
0
// Generic types represent multiple types and vector sizes, thus a vector
744
0
// is returned. The conversion is done in two steps:
745
0
// Step 1: A switch statement fills a vector with scalar base types for the
746
0
//         Cartesian product of (vector sizes) x (types) for generic types,
747
0
//         or a single scalar type for non generic types.
748
0
// Step 2: Qualifiers and other type properties such as vector size are
749
0
//         applied.
750
0
static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
751
0
                     llvm::SmallVectorImpl<QualType> &QT) {
752
0
  ASTContext &Context = S.Context;
753
0
  // Number of scalar types in the GenType.
754
0
  unsigned GenTypeNumTypes;
755
0
  // Pointer to the list of vector sizes for the GenType.
756
0
  llvm::ArrayRef<unsigned> GenVectorSizes;
757
0
)";
758
759
  // Generate list of vector sizes for each generic type.
760
0
  for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
761
0
    OS << "  constexpr unsigned List"
762
0
       << VectList->getValueAsString("Name") << "[] = {";
763
0
    for (const auto V : VectList->getValueAsListOfInts("List")) {
764
0
      OS << V << ", ";
765
0
    }
766
0
    OS << "};\n";
767
0
  }
768
769
  // Step 1.
770
  // Start of switch statement over all types.
771
0
  OS << "\n  switch (Ty.ID) {\n";
772
773
  // Switch cases for image types (Image2d, Image3d, ...)
774
0
  std::vector<Record *> ImageTypes =
775
0
      Records.getAllDerivedDefinitions("ImageType");
776
777
  // Map an image type name to its 3 access-qualified types (RO, WO, RW).
778
0
  StringMap<SmallVector<Record *, 3>> ImageTypesMap;
779
0
  for (auto *IT : ImageTypes) {
780
0
    auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
781
0
    if (Entry == ImageTypesMap.end()) {
782
0
      SmallVector<Record *, 3> ImageList;
783
0
      ImageList.push_back(IT);
784
0
      ImageTypesMap.insert(
785
0
          std::make_pair(IT->getValueAsString("Name"), ImageList));
786
0
    } else {
787
0
      Entry->second.push_back(IT);
788
0
    }
789
0
  }
790
791
  // Emit the cases for the image types.  For an image type name, there are 3
792
  // corresponding QualTypes ("RO", "WO", "RW").  The "AccessQualifier" field
793
  // tells which one is needed.  Emit a switch statement that puts the
794
  // corresponding QualType into "QT".
795
0
  for (const auto &ITE : ImageTypesMap) {
796
0
    OS << "    case OCLT_" << ITE.getKey() << ":\n"
797
0
       << "      switch (Ty.AccessQualifier) {\n"
798
0
       << "        case OCLAQ_None:\n"
799
0
       << "          llvm_unreachable(\"Image without access qualifier\");\n";
800
0
    for (const auto &Image : ITE.getValue()) {
801
0
      OS << StringSwitch<const char *>(
802
0
                Image->getValueAsString("AccessQualifier"))
803
0
                .Case("RO", "        case OCLAQ_ReadOnly:\n")
804
0
                .Case("WO", "        case OCLAQ_WriteOnly:\n")
805
0
                .Case("RW", "        case OCLAQ_ReadWrite:\n")
806
0
         << "          QT.push_back("
807
0
         << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
808
0
         << ");\n"
809
0
         << "          break;\n";
810
0
    }
811
0
    OS << "      }\n"
812
0
       << "      break;\n";
813
0
  }
814
815
  // Switch cases for generic types.
816
0
  for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
817
0
    OS << "    case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
818
819
    // Build the Cartesian product of (vector sizes) x (types).  Only insert
820
    // the plain scalar types for now; other type information such as vector
821
    // size and type qualifiers will be added after the switch statement.
822
0
    std::vector<Record *> BaseTypes =
823
0
        GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
824
825
    // Collect all QualTypes for a single vector size into TypeList.
826
0
    OS << "      SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
827
0
    for (const auto *T : BaseTypes) {
828
0
      StringRef Ext =
829
0
          T->getValueAsDef("Extension")->getValueAsString("ExtName");
830
0
      if (!Ext.empty()) {
831
0
        OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
832
0
           << "\")) {\n  ";
833
0
      }
834
0
      OS << "      TypeList.push_back("
835
0
         << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
836
0
      if (!Ext.empty()) {
837
0
        OS << "      }\n";
838
0
      }
839
0
    }
840
0
    OS << "      GenTypeNumTypes = TypeList.size();\n";
841
842
    // Duplicate the TypeList for every vector size.
843
0
    std::vector<int64_t> VectorList =
844
0
        GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
845
0
    OS << "      QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
846
0
       << "      for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
847
0
       << "        QT.append(TypeList);\n"
848
0
       << "      }\n";
849
850
    // GenVectorSizes is the list of vector sizes for this GenType.
851
0
    OS << "      GenVectorSizes = List"
852
0
       << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
853
0
       << ";\n"
854
0
       << "      break;\n"
855
0
       << "    }\n";
856
0
  }
857
858
  // Switch cases for non generic, non image types (int, int4, float, ...).
859
  // Only insert the plain scalar type; vector information and type qualifiers
860
  // are added in step 2.
861
0
  std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
862
0
  StringMap<bool> TypesSeen;
863
864
0
  for (const auto *T : Types) {
865
    // Check this is not an image type
866
0
    if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
867
0
      continue;
868
    // Check we have not seen this Type
869
0
    if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
870
0
      continue;
871
0
    TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
872
873
    // Check the Type does not have an "abstract" QualType
874
0
    auto QT = T->getValueAsDef("QTExpr");
875
0
    if (QT->getValueAsBit("IsAbstract") == 1)
876
0
      continue;
877
    // Emit the cases for non generic, non image types.
878
0
    OS << "    case OCLT_" << T->getValueAsString("Name") << ":\n";
879
880
0
    StringRef Ext = T->getValueAsDef("Extension")->getValueAsString("ExtName");
881
    // If this type depends on an extension, ensure the extension macro is
882
    // defined.
883
0
    if (!Ext.empty()) {
884
0
      OS << "      if (S.getPreprocessor().isMacroDefined(\"" << Ext
885
0
         << "\")) {\n  ";
886
0
    }
887
0
    OS << "      QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
888
0
    if (!Ext.empty()) {
889
0
      OS << "      }\n";
890
0
    }
891
0
    OS << "      break;\n";
892
0
  }
893
894
  // End of switch statement.
895
0
  OS << "  } // end of switch (Ty.ID)\n\n";
896
897
  // Step 2.
898
  // Add ExtVector types if this was a generic type, as the switch statement
899
  // above only populated the list with scalar types.  This completes the
900
  // construction of the Cartesian product of (vector sizes) x (types).
901
0
  OS << "  // Construct the different vector types for each generic type.\n";
902
0
  OS << "  if (Ty.ID >= " << TypeList.size() << ") {";
903
0
  OS << R"(
904
0
    for (unsigned I = 0; I < QT.size(); I++) {
905
0
      // For scalars, size is 1.
906
0
      if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
907
0
        QT[I] = Context.getExtVectorType(QT[I],
908
0
                          GenVectorSizes[I / GenTypeNumTypes]);
909
0
      }
910
0
    }
911
0
  }
912
0
)";
913
914
  // Assign the right attributes to the types (e.g. vector size).
915
0
  OS << R"(
916
0
  // Set vector size for non-generic vector types.
917
0
  if (Ty.VectorWidth > 1) {
918
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
919
0
      QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
920
0
    }
921
0
  }
922
0
923
0
  if (Ty.IsVolatile != 0) {
924
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
925
0
      QT[Index] = Context.getVolatileType(QT[Index]);
926
0
    }
927
0
  }
928
0
929
0
  if (Ty.IsConst != 0) {
930
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
931
0
      QT[Index] = Context.getConstType(QT[Index]);
932
0
    }
933
0
  }
934
0
935
0
  // Transform the type to a pointer as the last step, if necessary.
936
0
  // Builtin functions only have pointers on [const|volatile], no
937
0
  // [const|volatile] pointers, so this is ok to do it as a last step.
938
0
  if (Ty.IsPointer != 0) {
939
0
    for (unsigned Index = 0; Index < QT.size(); Index++) {
940
0
      QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
941
0
      QT[Index] = Context.getPointerType(QT[Index]);
942
0
    }
943
0
  }
944
0
)";
945
946
  // End of the "OCL2Qual" function.
947
0
  OS << "\n} // OCL2Qual\n";
948
0
}
949
950
std::string OpenCLBuiltinFileEmitterBase::getTypeString(const Record *Type,
951
                                                        TypeFlags Flags,
952
32.3k
                                                        int VectorSize) const {
953
32.3k
  std::string S;
954
32.3k
  if (Type->getValueAsBit("IsConst") || 
Flags.IsConst31.9k
) {
955
674
    S += "const ";
956
674
  }
957
32.3k
  if (Type->getValueAsBit("IsVolatile") || 
Flags.IsVolatile31.9k
) {
958
420
    S += "volatile ";
959
420
  }
960
961
32.3k
  auto PrintAddrSpace = [&S](StringRef AddrSpace) {
962
2.49k
    S += StringSwitch<const char *>(AddrSpace)
963
2.49k
             .Case("clang::LangAS::opencl_private", "__private")
964
2.49k
             .Case("clang::LangAS::opencl_global", "__global")
965
2.49k
             .Case("clang::LangAS::opencl_constant", "__constant")
966
2.49k
             .Case("clang::LangAS::opencl_local", "__local")
967
2.49k
             .Case("clang::LangAS::opencl_generic", "__generic")
968
2.49k
             .Default("__private");
969
2.49k
    S += " ";
970
2.49k
  };
971
32.3k
  if (Flags.IsPointer) {
972
1.02k
    PrintAddrSpace(Flags.AddrSpace);
973
31.3k
  } else if (Type->getValueAsBit("IsPointer")) {
974
1.46k
    PrintAddrSpace(Type->getValueAsString("AddrSpace"));
975
1.46k
  }
976
977
32.3k
  StringRef Acc = Type->getValueAsString("AccessQualifier");
978
32.3k
  if (Acc != "") {
979
428
    S += StringSwitch<const char *>(Acc)
980
428
             .Case("RO", "__read_only ")
981
428
             .Case("WO", "__write_only ")
982
428
             .Case("RW", "__read_write ");
983
428
  }
984
985
32.3k
  S += Type->getValueAsString("Name").str();
986
32.3k
  if (VectorSize > 1) {
987
22.0k
    S += std::to_string(VectorSize);
988
22.0k
  }
989
990
32.3k
  if (Type->getValueAsBit("IsPointer") || 
Flags.IsPointer30.8k
) {
991
2.49k
    S += " *";
992
2.49k
  }
993
994
32.3k
  return S;
995
32.3k
}
996
997
void OpenCLBuiltinFileEmitterBase::getTypeLists(
998
    Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
999
21.6k
    std::vector<int64_t> &VectorList) const {
1000
21.6k
  bool isGenType = Type->isSubClassOf("GenericType");
1001
21.6k
  if (isGenType) {
1002
898
    TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
1003
898
    VectorList =
1004
898
        Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
1005
898
    return;
1006
898
  }
1007
1008
20.7k
  if (Type->isSubClassOf("PointerType") || 
Type->isSubClassOf("ConstType")19.2k
||
1009
20.7k
      
Type->isSubClassOf("VolatileType")19.2k
) {
1010
1.52k
    StringRef SubTypeName = Type->getValueAsString("Name");
1011
1.52k
    Record *PossibleGenType = Records.getDef(SubTypeName);
1012
1.52k
    if (PossibleGenType && 
PossibleGenType->isSubClassOf("GenericType")57
) {
1013
      // When PointerType, ConstType, or VolatileType is applied to a
1014
      // GenericType, the flags need to be taken from the subtype, not from the
1015
      // GenericType.
1016
57
      Flags.IsPointer = Type->getValueAsBit("IsPointer");
1017
57
      Flags.IsConst = Type->getValueAsBit("IsConst");
1018
57
      Flags.IsVolatile = Type->getValueAsBit("IsVolatile");
1019
57
      Flags.AddrSpace = Type->getValueAsString("AddrSpace");
1020
57
      getTypeLists(PossibleGenType, Flags, TypeList, VectorList);
1021
57
      return;
1022
57
    }
1023
1.52k
  }
1024
1025
  // Not a GenericType, so just insert the single type.
1026
20.6k
  TypeList.push_back(Type);
1027
20.6k
  VectorList.push_back(Type->getValueAsInt("VecWidth"));
1028
20.6k
}
1029
1030
void OpenCLBuiltinFileEmitterBase::expandTypesInSignature(
1031
    const std::vector<Record *> &Signature,
1032
8.95k
    SmallVectorImpl<SmallVector<std::string, 2>> &Types) {
1033
  // Find out if there are any GenTypes in this signature, and if so, calculate
1034
  // into how many signatures they will expand.
1035
8.95k
  unsigned NumSignatures = 1;
1036
8.95k
  SmallVector<SmallVector<std::string, 4>, 4> ExpandedGenTypes;
1037
21.5k
  for (const auto &Arg : Signature) {
1038
21.5k
    SmallVector<std::string, 4> ExpandedArg;
1039
21.5k
    std::vector<Record *> TypeList;
1040
21.5k
    std::vector<int64_t> VectorList;
1041
21.5k
    TypeFlags Flags;
1042
1043
21.5k
    getTypeLists(Arg, Flags, TypeList, VectorList);
1044
1045
    // Insert the Cartesian product of the types and vector sizes.
1046
25.2k
    for (const auto &Vector : VectorList) {
1047
32.3k
      for (const auto &Type : TypeList) {
1048
32.3k
        ExpandedArg.push_back(getTypeString(Type, Flags, Vector));
1049
32.3k
      }
1050
25.2k
    }
1051
21.5k
    NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
1052
21.5k
    ExpandedGenTypes.push_back(ExpandedArg);
1053
21.5k
  }
1054
1055
  // Now the total number of signatures is known.  Populate the return list with
1056
  // all signatures.
1057
22.2k
  for (unsigned I = 0; I < NumSignatures; 
I++13.2k
) {
1058
13.2k
    SmallVector<std::string, 2> Args;
1059
1060
    // Process a single signature.
1061
47.5k
    for (unsigned ArgNum = 0; ArgNum < Signature.size(); 
ArgNum++34.2k
) {
1062
      // For differently-sized GenTypes in a parameter list, the smaller
1063
      // GenTypes just repeat, so index modulo the number of expanded types.
1064
34.2k
      size_t TypeIndex = I % ExpandedGenTypes[ArgNum].size();
1065
34.2k
      Args.push_back(ExpandedGenTypes[ArgNum][TypeIndex]);
1066
34.2k
    }
1067
13.2k
    Types.push_back(Args);
1068
13.2k
  }
1069
8.95k
}
1070
1071
1
void OpenCLBuiltinFileEmitterBase::emitExtensionSetup() {
1072
1
  OS << R"(
1073
1
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
1074
1
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
1075
1
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
1076
1
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
1077
1
#pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
1078
1
#pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
1079
1
#pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
1080
1
1081
1
)";
1082
1
}
1083
1084
std::string
1085
8.95k
OpenCLBuiltinFileEmitterBase::emitExtensionGuard(const Record *Builtin) {
1086
8.95k
  StringRef Extensions =
1087
8.95k
      Builtin->getValueAsDef("Extension")->getValueAsString("ExtName");
1088
8.95k
  if (Extensions.empty())
1089
8.47k
    return "";
1090
1091
487
  OS << "#if";
1092
1093
487
  SmallVector<StringRef, 2> ExtVec;
1094
487
  Extensions.split(ExtVec, " ");
1095
487
  bool isFirst = true;
1096
586
  for (StringRef Ext : ExtVec) {
1097
586
    if (!isFirst) {
1098
99
      OS << " &&";
1099
99
    }
1100
586
    OS << " defined(" << Ext << ")";
1101
586
    isFirst = false;
1102
586
  }
1103
487
  OS << "\n";
1104
1105
487
  return "#endif // Extension\n";
1106
8.95k
}
1107
1108
std::string
1109
8.95k
OpenCLBuiltinFileEmitterBase::emitVersionGuard(const Record *Builtin) {
1110
8.95k
  std::string OptionalEndif;
1111
8.95k
  auto PrintOpenCLVersion = [this](int Version) {
1112
1.31k
    OS << "CL_VERSION_" << (Version / 100) << "_" << ((Version % 100) / 10);
1113
1.31k
  };
1114
8.95k
  int MinVersion = Builtin->getValueAsDef("MinVersion")->getValueAsInt("ID");
1115
8.95k
  if (MinVersion != 100) {
1116
    // OpenCL 1.0 is the default minimum version.
1117
587
    OS << "#if __OPENCL_C_VERSION__ >= ";
1118
587
    PrintOpenCLVersion(MinVersion);
1119
587
    OS << "\n";
1120
587
    OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
1121
587
  }
1122
8.95k
  int MaxVersion = Builtin->getValueAsDef("MaxVersion")->getValueAsInt("ID");
1123
8.95k
  if (MaxVersion) {
1124
729
    OS << "#if __OPENCL_C_VERSION__ < ";
1125
729
    PrintOpenCLVersion(MaxVersion);
1126
729
    OS << "\n";
1127
729
    OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
1128
729
  }
1129
8.95k
  return OptionalEndif;
1130
8.95k
}
1131
1132
1
void OpenCLBuiltinTestEmitter::emit() {
1133
1
  emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
1134
1135
1
  emitExtensionSetup();
1136
1137
  // Ensure each test has a unique name by numbering them.
1138
1
  unsigned TestID = 0;
1139
1140
  // Iterate over all builtins.
1141
1
  std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
1142
8.95k
  for (const auto *B : Builtins) {
1143
8.95k
    StringRef Name = B->getValueAsString("Name");
1144
1145
8.95k
    SmallVector<SmallVector<std::string, 2>, 4> FTypes;
1146
8.95k
    expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
1147
1148
8.95k
    OS << "// Test " << Name << "\n";
1149
1150
8.95k
    std::string OptionalExtensionEndif = emitExtensionGuard(B);
1151
8.95k
    std::string OptionalVersionEndif = emitVersionGuard(B);
1152
1153
13.2k
    for (const auto &Signature : FTypes) {
1154
      // Emit function declaration.
1155
13.2k
      OS << Signature[0] << " test" << TestID++ << "_" << Name << "(";
1156
13.2k
      if (Signature.size() > 1) {
1157
34.2k
        for (unsigned I = 1; I < Signature.size(); 
I++21.0k
) {
1158
21.0k
          if (I != 1)
1159
7.79k
            OS << ", ";
1160
21.0k
          OS << Signature[I] << " arg" << I;
1161
21.0k
        }
1162
13.2k
      }
1163
13.2k
      OS << ") {\n";
1164
1165
      // Emit function body.
1166
13.2k
      OS << "  ";
1167
13.2k
      if (Signature[0] != "void") {
1168
12.4k
        OS << "return ";
1169
12.4k
      }
1170
13.2k
      OS << Name << "(";
1171
34.2k
      for (unsigned I = 1; I < Signature.size(); 
I++21.0k
) {
1172
21.0k
        if (I != 1)
1173
7.79k
          OS << ", ";
1174
21.0k
        OS << "arg" << I;
1175
21.0k
      }
1176
13.2k
      OS << ");\n";
1177
1178
      // End of function body.
1179
13.2k
      OS << "}\n";
1180
13.2k
    }
1181
1182
8.95k
    OS << OptionalVersionEndif;
1183
8.95k
    OS << OptionalExtensionEndif;
1184
8.95k
  }
1185
1
}
1186
1187
0
void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
1188
0
  BuiltinNameEmitter NameChecker(Records, OS);
1189
0
  NameChecker.Emit();
1190
0
}
1191
1192
void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
1193
1
                                        raw_ostream &OS) {
1194
1
  OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
1195
1
  TestFileGenerator.emit();
1196
1
}