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