1 //===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 6 // See https://llvm.org/LICENSE.txt for license information. 7 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 8 // 9 //===----------------------------------------------------------------------===// 10 // 11 // This tablegen backend emits code for checking whether a function is an 12 // OpenCL builtin function. If so, all overloads of this function are 13 // added to the LookupResult. The generated include file is used by 14 // SemaLookup.cpp 15 // 16 // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos") 17 // returns a pair <Index, Len>. 18 // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs 19 // <SigIndex, SigLen> of the overloads of "cos". 20 // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains 21 // one of the signatures of "cos". The SignatureTable entry can be 22 // referenced by other functions, e.g. "sin", to exploit the fact that 23 // many OpenCL builtins share the same signature. 24 // 25 // The file generated by this TableGen emitter contains the following: 26 // 27 // * Structs and enums to represent types and function signatures. 28 // 29 // * const char *FunctionExtensionTable[] 30 // List of space-separated OpenCL extensions. A builtin references an 31 // entry in this table when the builtin requires a particular (set of) 32 // extension(s) to be enabled. 33 // 34 // * OpenCLTypeStruct TypeTable[] 35 // Type information for return types and arguments. 36 // 37 // * unsigned SignatureTable[] 38 // A list of types representing function signatures. Each entry is an index 39 // into the above TypeTable. Multiple entries following each other form a 40 // signature, where the first entry is the return type and subsequent 41 // entries are the argument types. 42 // 43 // * OpenCLBuiltinStruct BuiltinTable[] 44 // Each entry represents one overload of an OpenCL builtin function and 45 // consists of an index into the SignatureTable and the number of arguments. 46 // 47 // * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) 48 // Find out whether a string matches an existing OpenCL builtin function 49 // name and return an index into BuiltinTable and the number of overloads. 50 // 51 // * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&) 52 // Convert an OpenCLTypeStruct type to a list of QualType instances. 53 // One OpenCLTypeStruct can represent multiple types, primarily when using 54 // GenTypes. 55 // 56 //===----------------------------------------------------------------------===// 57 58 #include "TableGenBackends.h" 59 #include "llvm/ADT/MapVector.h" 60 #include "llvm/ADT/STLExtras.h" 61 #include "llvm/ADT/SmallString.h" 62 #include "llvm/ADT/StringExtras.h" 63 #include "llvm/ADT/StringMap.h" 64 #include "llvm/ADT/StringRef.h" 65 #include "llvm/ADT/StringSwitch.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/TableGen/Error.h" 69 #include "llvm/TableGen/Record.h" 70 #include "llvm/TableGen/StringMatcher.h" 71 #include "llvm/TableGen/TableGenBackend.h" 72 73 using namespace llvm; 74 75 namespace { 76 77 // A list of signatures that are shared by one or more builtin functions. 78 struct BuiltinTableEntries { 79 SmallVector<StringRef, 4> Names; 80 std::vector<std::pair<const Record *, unsigned>> Signatures; 81 }; 82 83 class BuiltinNameEmitter { 84 public: 85 BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS) 86 : Records(Records), OS(OS) {} 87 88 // Entrypoint to generate the functions and structures for checking 89 // whether a function is an OpenCL builtin function. 90 void Emit(); 91 92 private: 93 // A list of indices into the builtin function table. 94 using BuiltinIndexListTy = SmallVector<unsigned, 11>; 95 96 // Contains OpenCL builtin functions and related information, stored as 97 // Record instances. They are coming from the associated TableGen file. 98 RecordKeeper &Records; 99 100 // The output file. 101 raw_ostream &OS; 102 103 // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum 104 // definitions in the Output string parameter, and save their Record instances 105 // in the List parameter. 106 // \param Types (in) List containing the Types to extract. 107 // \param TypesSeen (inout) List containing the Types already extracted. 108 // \param Output (out) String containing the enums to emit in the output file. 109 // \param List (out) List containing the extracted Types, except the Types in 110 // TypesSeen. 111 void ExtractEnumTypes(std::vector<Record *> &Types, 112 StringMap<bool> &TypesSeen, std::string &Output, 113 std::vector<const Record *> &List); 114 115 // Emit the enum or struct used in the generated file. 116 // Populate the TypeList at the same time. 117 void EmitDeclarations(); 118 119 // Parse the Records generated by TableGen to populate the SignaturesList, 120 // FctOverloadMap and TypeMap. 121 void GetOverloads(); 122 123 // Compare two lists of signatures and check that e.g. the OpenCL version, 124 // function attributes, and extension are equal for each signature. 125 // \param Candidate (in) Entry in the SignatureListMap to check. 126 // \param SignatureList (in) List of signatures of the considered function. 127 // \returns true if the two lists of signatures are identical. 128 bool CanReuseSignature( 129 BuiltinIndexListTy *Candidate, 130 std::vector<std::pair<const Record *, unsigned>> &SignatureList); 131 132 // Group functions with the same list of signatures by populating the 133 // SignatureListMap. 134 // Some builtin functions have the same list of signatures, for example the 135 // "sin" and "cos" functions. To save space in the BuiltinTable, the 136 // "isOpenCLBuiltin" function will have the same output for these two 137 // function names. 138 void GroupBySignature(); 139 140 // Emit the FunctionExtensionTable that lists all function extensions. 141 void EmitExtensionTable(); 142 143 // Emit the TypeTable containing all types used by OpenCL builtins. 144 void EmitTypeTable(); 145 146 // Emit the SignatureTable. This table contains all the possible signatures. 147 // A signature is stored as a list of indexes of the TypeTable. 148 // The first index references the return type (mandatory), and the followings 149 // reference its arguments. 150 // E.g.: 151 // 15, 2, 15 can represent a function with the signature: 152 // int func(float, int) 153 // The "int" type being at the index 15 in the TypeTable. 154 void EmitSignatureTable(); 155 156 // Emit the BuiltinTable table. This table contains all the overloads of 157 // each function, and is a struct OpenCLBuiltinDecl. 158 // E.g.: 159 // // 891 convert_float2_rtn 160 // { 58, 2, 3, 100, 0 }, 161 // This means that the signature of this convert_float2_rtn overload has 162 // 1 argument (+1 for the return type), stored at index 58 in 163 // the SignatureTable. This prototype requires extension "3" in the 164 // FunctionExtensionTable. The last two values represent the minimum (1.0) 165 // and maximum (0, meaning no max version) OpenCL version in which this 166 // overload is supported. 167 void EmitBuiltinTable(); 168 169 // Emit a StringMatcher function to check whether a function name is an 170 // OpenCL builtin function name. 171 void EmitStringMatcher(); 172 173 // Emit a function returning the clang QualType instance associated with 174 // the TableGen Record Type. 175 void EmitQualTypeFinder(); 176 177 // Contains a list of the available signatures, without the name of the 178 // function. Each pair consists of a signature and a cumulative index. 179 // E.g.: <<float, float>, 0>, 180 // <<float, int, int, 2>>, 181 // <<float>, 5>, 182 // ... 183 // <<double, double>, 35>. 184 std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList; 185 186 // Map the name of a builtin function to its prototypes (instances of the 187 // TableGen "Builtin" class). 188 // Each prototype is registered as a pair of: 189 // <pointer to the "Builtin" instance, 190 // cumulative index of the associated signature in the SignaturesList> 191 // E.g.: The function cos: (float cos(float), double cos(double), ...) 192 // <"cos", <<ptrToPrototype0, 5>, 193 // <ptrToPrototype1, 35>, 194 // <ptrToPrototype2, 79>> 195 // ptrToPrototype1 has the following signature: <double, double> 196 MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>> 197 FctOverloadMap; 198 199 // Contains the map of OpenCL types to their index in the TypeTable. 200 MapVector<const Record *, unsigned> TypeMap; 201 202 // List of OpenCL function extensions mapping extension strings to 203 // an index into the FunctionExtensionTable. 204 StringMap<unsigned> FunctionExtensionIndex; 205 206 // List of OpenCL type names in the same order as in enum OpenCLTypeID. 207 // This list does not contain generic types. 208 std::vector<const Record *> TypeList; 209 210 // Same as TypeList, but for generic types only. 211 std::vector<const Record *> GenTypeList; 212 213 // Map an ordered vector of signatures to their original Record instances, 214 // and to a list of function names that share these signatures. 215 // 216 // For example, suppose the "cos" and "sin" functions have only three 217 // signatures, and these signatures are at index Ix in the SignatureTable: 218 // cos | sin | Signature | Index 219 // float cos(float) | float sin(float) | Signature1 | I1 220 // double cos(double) | double sin(double) | Signature2 | I2 221 // half cos(half) | half sin(half) | Signature3 | I3 222 // 223 // Then we will create a mapping of the vector of signatures: 224 // SignatureListMap[<I1, I2, I3>] = < 225 // <"cos", "sin">, 226 // <Signature1, Signature2, Signature3>> 227 // The function "tan", having the same signatures, would be mapped to the 228 // same entry (<I1, I2, I3>). 229 MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap; 230 }; 231 } // namespace 232 233 void BuiltinNameEmitter::Emit() { 234 emitSourceFileHeader("OpenCL Builtin handling", OS); 235 236 OS << "#include \"llvm/ADT/StringRef.h\"\n"; 237 OS << "using namespace clang;\n\n"; 238 239 // Emit enums and structs. 240 EmitDeclarations(); 241 242 // Parse the Records to populate the internal lists. 243 GetOverloads(); 244 GroupBySignature(); 245 246 // Emit tables. 247 EmitExtensionTable(); 248 EmitTypeTable(); 249 EmitSignatureTable(); 250 EmitBuiltinTable(); 251 252 // Emit functions. 253 EmitStringMatcher(); 254 EmitQualTypeFinder(); 255 } 256 257 void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types, 258 StringMap<bool> &TypesSeen, 259 std::string &Output, 260 std::vector<const Record *> &List) { 261 raw_string_ostream SS(Output); 262 263 for (const auto *T : Types) { 264 if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) { 265 SS << " OCLT_" + T->getValueAsString("Name") << ",\n"; 266 // Save the type names in the same order as their enum value. Note that 267 // the Record can be a VectorType or something else, only the name is 268 // important. 269 List.push_back(T); 270 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true)); 271 } 272 } 273 SS.flush(); 274 } 275 276 void BuiltinNameEmitter::EmitDeclarations() { 277 // Enum of scalar type names (float, int, ...) and generic type sets. 278 OS << "enum OpenCLTypeID {\n"; 279 280 StringMap<bool> TypesSeen; 281 std::string GenTypeEnums; 282 std::string TypeEnums; 283 284 // Extract generic types and non-generic types separately, to keep 285 // gentypes at the end of the enum which simplifies the special handling 286 // for gentypes in SemaLookup. 287 std::vector<Record *> GenTypes = 288 Records.getAllDerivedDefinitions("GenericType"); 289 ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList); 290 291 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type"); 292 ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList); 293 294 OS << TypeEnums; 295 OS << GenTypeEnums; 296 OS << "};\n"; 297 298 // Structure definitions. 299 OS << R"( 300 // Image access qualifier. 301 enum OpenCLAccessQual : unsigned char { 302 OCLAQ_None, 303 OCLAQ_ReadOnly, 304 OCLAQ_WriteOnly, 305 OCLAQ_ReadWrite 306 }; 307 308 // Represents a return type or argument type. 309 struct OpenCLTypeStruct { 310 // A type (e.g. float, int, ...). 311 const OpenCLTypeID ID; 312 // Vector size (if applicable; 0 for scalars and generic types). 313 const unsigned VectorWidth; 314 // 0 if the type is not a pointer. 315 const bool IsPointer : 1; 316 // 0 if the type is not const. 317 const bool IsConst : 1; 318 // 0 if the type is not volatile. 319 const bool IsVolatile : 1; 320 // Access qualifier. 321 const OpenCLAccessQual AccessQualifier; 322 // Address space of the pointer (if applicable). 323 const LangAS AS; 324 }; 325 326 // One overload of an OpenCL builtin function. 327 struct OpenCLBuiltinStruct { 328 // Index of the signature in the OpenCLTypeStruct table. 329 const unsigned SigTableIndex; 330 // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in 331 // the SignatureTable represent the complete signature. The first type at 332 // index SigTableIndex is the return type. 333 const unsigned NumTypes; 334 // Function attribute __attribute__((pure)) 335 const bool IsPure : 1; 336 // Function attribute __attribute__((const)) 337 const bool IsConst : 1; 338 // Function attribute __attribute__((convergent)) 339 const bool IsConv : 1; 340 // OpenCL extension(s) required for this overload. 341 const unsigned short Extension; 342 // OpenCL versions in which this overload is available. 343 const unsigned short Versions; 344 }; 345 346 )"; 347 } 348 349 // Verify that the combination of GenTypes in a signature is supported. 350 // To simplify the logic for creating overloads in SemaLookup, only allow 351 // a signature to contain different GenTypes if these GenTypes represent 352 // the same number of actual scalar or vector types. 353 // 354 // Exit with a fatal error if an unsupported construct is encountered. 355 static void VerifySignature(const std::vector<Record *> &Signature, 356 const Record *BuiltinRec) { 357 unsigned GenTypeVecSizes = 1; 358 unsigned GenTypeTypes = 1; 359 360 for (const auto *T : Signature) { 361 // Check all GenericType arguments in this signature. 362 if (T->isSubClassOf("GenericType")) { 363 // Check number of vector sizes. 364 unsigned NVecSizes = 365 T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size(); 366 if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) { 367 if (GenTypeVecSizes > 1) { 368 // We already saw a gentype with a different number of vector sizes. 369 PrintFatalError(BuiltinRec->getLoc(), 370 "number of vector sizes should be equal or 1 for all gentypes " 371 "in a declaration"); 372 } 373 GenTypeVecSizes = NVecSizes; 374 } 375 376 // Check number of data types. 377 unsigned NTypes = 378 T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size(); 379 if (NTypes != GenTypeTypes && NTypes != 1) { 380 if (GenTypeTypes > 1) { 381 // We already saw a gentype with a different number of types. 382 PrintFatalError(BuiltinRec->getLoc(), 383 "number of types should be equal or 1 for all gentypes " 384 "in a declaration"); 385 } 386 GenTypeTypes = NTypes; 387 } 388 } 389 } 390 } 391 392 void BuiltinNameEmitter::GetOverloads() { 393 // Populate the TypeMap. 394 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type"); 395 unsigned I = 0; 396 for (const auto &T : Types) { 397 TypeMap.insert(std::make_pair(T, I++)); 398 } 399 400 // Populate the SignaturesList and the FctOverloadMap. 401 unsigned CumulativeSignIndex = 0; 402 std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin"); 403 for (const auto *B : Builtins) { 404 StringRef BName = B->getValueAsString("Name"); 405 if (FctOverloadMap.find(BName) == FctOverloadMap.end()) { 406 FctOverloadMap.insert(std::make_pair( 407 BName, std::vector<std::pair<const Record *, unsigned>>{})); 408 } 409 410 auto Signature = B->getValueAsListOfDefs("Signature"); 411 // Reuse signatures to avoid unnecessary duplicates. 412 auto it = 413 std::find_if(SignaturesList.begin(), SignaturesList.end(), 414 [&](const std::pair<std::vector<Record *>, unsigned> &a) { 415 return a.first == Signature; 416 }); 417 unsigned SignIndex; 418 if (it == SignaturesList.end()) { 419 VerifySignature(Signature, B); 420 SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex)); 421 SignIndex = CumulativeSignIndex; 422 CumulativeSignIndex += Signature.size(); 423 } else { 424 SignIndex = it->second; 425 } 426 FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex)); 427 } 428 } 429 430 void BuiltinNameEmitter::EmitExtensionTable() { 431 OS << "static const char *FunctionExtensionTable[] = {\n"; 432 unsigned Index = 0; 433 std::vector<Record *> FuncExtensions = 434 Records.getAllDerivedDefinitions("FunctionExtension"); 435 436 for (const auto &FE : FuncExtensions) { 437 // Emit OpenCL extension table entry. 438 OS << " // " << Index << ": " << FE->getName() << "\n" 439 << " \"" << FE->getValueAsString("ExtName") << "\",\n"; 440 441 // Record index of this extension. 442 FunctionExtensionIndex[FE->getName()] = Index++; 443 } 444 OS << "};\n\n"; 445 } 446 447 void BuiltinNameEmitter::EmitTypeTable() { 448 OS << "static const OpenCLTypeStruct TypeTable[] = {\n"; 449 for (const auto &T : TypeMap) { 450 const char *AccessQual = 451 StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier")) 452 .Case("RO", "OCLAQ_ReadOnly") 453 .Case("WO", "OCLAQ_WriteOnly") 454 .Case("RW", "OCLAQ_ReadWrite") 455 .Default("OCLAQ_None"); 456 457 OS << " // " << T.second << "\n" 458 << " {OCLT_" << T.first->getValueAsString("Name") << ", " 459 << T.first->getValueAsInt("VecWidth") << ", " 460 << T.first->getValueAsBit("IsPointer") << ", " 461 << T.first->getValueAsBit("IsConst") << ", " 462 << T.first->getValueAsBit("IsVolatile") << ", " 463 << AccessQual << ", " 464 << T.first->getValueAsString("AddrSpace") << "},\n"; 465 } 466 OS << "};\n\n"; 467 } 468 469 void BuiltinNameEmitter::EmitSignatureTable() { 470 // Store a type (e.g. int, float, int2, ...). The type is stored as an index 471 // of a struct OpenCLType table. Multiple entries following each other form a 472 // signature. 473 OS << "static const unsigned short SignatureTable[] = {\n"; 474 for (const auto &P : SignaturesList) { 475 OS << " // " << P.second << "\n "; 476 for (const Record *R : P.first) { 477 unsigned Entry = TypeMap.find(R)->second; 478 if (Entry > USHRT_MAX) { 479 // Report an error when seeing an entry that is too large for the 480 // current index type (unsigned short). When hitting this, the type 481 // of SignatureTable will need to be changed. 482 PrintFatalError("Entry in SignatureTable exceeds limit."); 483 } 484 OS << Entry << ", "; 485 } 486 OS << "\n"; 487 } 488 OS << "};\n\n"; 489 } 490 491 // Encode a range MinVersion..MaxVersion into a single bit mask that can be 492 // checked against LangOpts using isOpenCLVersionContainedInMask(). 493 // This must be kept in sync with OpenCLVersionID in OpenCLOptions.h. 494 // (Including OpenCLOptions.h here would be a layering violation.) 495 static unsigned short EncodeVersions(unsigned int MinVersion, 496 unsigned int MaxVersion) { 497 unsigned short Encoded = 0; 498 499 // A maximum version of 0 means available in all later versions. 500 if (MaxVersion == 0) { 501 MaxVersion = UINT_MAX; 502 } 503 504 unsigned VersionIDs[] = {100, 110, 120, 200, 300}; 505 for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) { 506 if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) { 507 Encoded |= 1 << I; 508 } 509 } 510 511 return Encoded; 512 } 513 514 void BuiltinNameEmitter::EmitBuiltinTable() { 515 unsigned Index = 0; 516 517 OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n"; 518 for (const auto &SLM : SignatureListMap) { 519 520 OS << " // " << (Index + 1) << ": "; 521 for (const auto &Name : SLM.second.Names) { 522 OS << Name << ", "; 523 } 524 OS << "\n"; 525 526 for (const auto &Overload : SLM.second.Signatures) { 527 StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName(); 528 OS << " { " << Overload.second << ", " 529 << Overload.first->getValueAsListOfDefs("Signature").size() << ", " 530 << (Overload.first->getValueAsBit("IsPure")) << ", " 531 << (Overload.first->getValueAsBit("IsConst")) << ", " 532 << (Overload.first->getValueAsBit("IsConv")) << ", " 533 << FunctionExtensionIndex[ExtName] << ", " 534 << EncodeVersions(Overload.first->getValueAsDef("MinVersion") 535 ->getValueAsInt("ID"), 536 Overload.first->getValueAsDef("MaxVersion") 537 ->getValueAsInt("ID")) 538 << " },\n"; 539 Index++; 540 } 541 } 542 OS << "};\n\n"; 543 } 544 545 bool BuiltinNameEmitter::CanReuseSignature( 546 BuiltinIndexListTy *Candidate, 547 std::vector<std::pair<const Record *, unsigned>> &SignatureList) { 548 assert(Candidate->size() == SignatureList.size() && 549 "signature lists should have the same size"); 550 551 auto &CandidateSigs = 552 SignatureListMap.find(Candidate)->second.Signatures; 553 for (unsigned Index = 0; Index < Candidate->size(); Index++) { 554 const Record *Rec = SignatureList[Index].first; 555 const Record *Rec2 = CandidateSigs[Index].first; 556 if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") && 557 Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") && 558 Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") && 559 Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") == 560 Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") && 561 Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") == 562 Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") && 563 Rec->getValueAsDef("Extension")->getName() == 564 Rec2->getValueAsDef("Extension")->getName()) { 565 return true; 566 } 567 } 568 return false; 569 } 570 571 void BuiltinNameEmitter::GroupBySignature() { 572 // List of signatures known to be emitted. 573 std::vector<BuiltinIndexListTy *> KnownSignatures; 574 575 for (auto &Fct : FctOverloadMap) { 576 bool FoundReusableSig = false; 577 578 // Gather all signatures for the current function. 579 auto *CurSignatureList = new BuiltinIndexListTy(); 580 for (const auto &Signature : Fct.second) { 581 CurSignatureList->push_back(Signature.second); 582 } 583 // Sort the list to facilitate future comparisons. 584 llvm::sort(*CurSignatureList); 585 586 // Check if we have already seen another function with the same list of 587 // signatures. If so, just add the name of the function. 588 for (auto *Candidate : KnownSignatures) { 589 if (Candidate->size() == CurSignatureList->size() && 590 *Candidate == *CurSignatureList) { 591 if (CanReuseSignature(Candidate, Fct.second)) { 592 SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first); 593 FoundReusableSig = true; 594 } 595 } 596 } 597 598 if (FoundReusableSig) { 599 delete CurSignatureList; 600 } else { 601 // Add a new entry. 602 SignatureListMap[CurSignatureList] = { 603 SmallVector<StringRef, 4>(1, Fct.first), Fct.second}; 604 KnownSignatures.push_back(CurSignatureList); 605 } 606 } 607 608 for (auto *I : KnownSignatures) { 609 delete I; 610 } 611 } 612 613 void BuiltinNameEmitter::EmitStringMatcher() { 614 std::vector<StringMatcher::StringPair> ValidBuiltins; 615 unsigned CumulativeIndex = 1; 616 617 for (const auto &SLM : SignatureListMap) { 618 const auto &Ovl = SLM.second.Signatures; 619 620 // A single signature list may be used by different builtins. Return the 621 // same <index, length> pair for each of those builtins. 622 for (const auto &FctName : SLM.second.Names) { 623 std::string RetStmt; 624 raw_string_ostream SS(RetStmt); 625 SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size() 626 << ");"; 627 SS.flush(); 628 ValidBuiltins.push_back( 629 StringMatcher::StringPair(std::string(FctName), RetStmt)); 630 } 631 CumulativeIndex += Ovl.size(); 632 } 633 634 OS << R"( 635 // Find out whether a string matches an existing OpenCL builtin function name. 636 // Returns: A pair <0, 0> if no name matches. 637 // A pair <Index, Len> indexing the BuiltinTable if the name is 638 // matching an OpenCL builtin function. 639 static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) { 640 641 )"; 642 643 StringMatcher("Name", ValidBuiltins, OS).Emit(0, true); 644 645 OS << " return std::make_pair(0, 0);\n"; 646 OS << "} // isOpenCLBuiltin\n"; 647 } 648 649 void BuiltinNameEmitter::EmitQualTypeFinder() { 650 OS << R"( 651 652 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name); 653 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name); 654 655 // Convert an OpenCLTypeStruct type to a list of QualTypes. 656 // Generic types represent multiple types and vector sizes, thus a vector 657 // is returned. The conversion is done in two steps: 658 // Step 1: A switch statement fills a vector with scalar base types for the 659 // Cartesian product of (vector sizes) x (types) for generic types, 660 // or a single scalar type for non generic types. 661 // Step 2: Qualifiers and other type properties such as vector size are 662 // applied. 663 static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty, 664 llvm::SmallVectorImpl<QualType> &QT) { 665 ASTContext &Context = S.Context; 666 // Number of scalar types in the GenType. 667 unsigned GenTypeNumTypes; 668 // Pointer to the list of vector sizes for the GenType. 669 llvm::ArrayRef<unsigned> GenVectorSizes; 670 )"; 671 672 // Generate list of vector sizes for each generic type. 673 for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) { 674 OS << " constexpr unsigned List" 675 << VectList->getValueAsString("Name") << "[] = {"; 676 for (const auto V : VectList->getValueAsListOfInts("List")) { 677 OS << V << ", "; 678 } 679 OS << "};\n"; 680 } 681 682 // Step 1. 683 // Start of switch statement over all types. 684 OS << "\n switch (Ty.ID) {\n"; 685 686 // Switch cases for image types (Image2d, Image3d, ...) 687 std::vector<Record *> ImageTypes = 688 Records.getAllDerivedDefinitions("ImageType"); 689 690 // Map an image type name to its 3 access-qualified types (RO, WO, RW). 691 StringMap<SmallVector<Record *, 3>> ImageTypesMap; 692 for (auto *IT : ImageTypes) { 693 auto Entry = ImageTypesMap.find(IT->getValueAsString("Name")); 694 if (Entry == ImageTypesMap.end()) { 695 SmallVector<Record *, 3> ImageList; 696 ImageList.push_back(IT); 697 ImageTypesMap.insert( 698 std::make_pair(IT->getValueAsString("Name"), ImageList)); 699 } else { 700 Entry->second.push_back(IT); 701 } 702 } 703 704 // Emit the cases for the image types. For an image type name, there are 3 705 // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field 706 // tells which one is needed. Emit a switch statement that puts the 707 // corresponding QualType into "QT". 708 for (const auto &ITE : ImageTypesMap) { 709 OS << " case OCLT_" << ITE.getKey() << ":\n" 710 << " switch (Ty.AccessQualifier) {\n" 711 << " case OCLAQ_None:\n" 712 << " llvm_unreachable(\"Image without access qualifier\");\n"; 713 for (const auto &Image : ITE.getValue()) { 714 OS << StringSwitch<const char *>( 715 Image->getValueAsString("AccessQualifier")) 716 .Case("RO", " case OCLAQ_ReadOnly:\n") 717 .Case("WO", " case OCLAQ_WriteOnly:\n") 718 .Case("RW", " case OCLAQ_ReadWrite:\n") 719 << " QT.push_back(" 720 << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") 721 << ");\n" 722 << " break;\n"; 723 } 724 OS << " }\n" 725 << " break;\n"; 726 } 727 728 // Switch cases for generic types. 729 for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) { 730 OS << " case OCLT_" << GenType->getValueAsString("Name") << ":\n"; 731 OS << " QT.append({"; 732 733 // Build the Cartesian product of (vector sizes) x (types). Only insert 734 // the plain scalar types for now; other type information such as vector 735 // size and type qualifiers will be added after the switch statement. 736 for (unsigned I = 0; I < GenType->getValueAsDef("VectorList") 737 ->getValueAsListOfInts("List") 738 .size(); 739 I++) { 740 for (const auto *T : 741 GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) { 742 OS << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ", "; 743 } 744 } 745 OS << "});\n"; 746 // GenTypeNumTypes is the number of types in the GenType 747 // (e.g. float/double/half). 748 OS << " GenTypeNumTypes = " 749 << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List") 750 .size() 751 << ";\n"; 752 // GenVectorSizes is the list of vector sizes for this GenType. 753 // QT contains GenTypeNumTypes * #GenVectorSizes elements. 754 OS << " GenVectorSizes = List" 755 << GenType->getValueAsDef("VectorList")->getValueAsString("Name") 756 << ";\n"; 757 OS << " break;\n"; 758 } 759 760 // Switch cases for non generic, non image types (int, int4, float, ...). 761 // Only insert the plain scalar type; vector information and type qualifiers 762 // are added in step 2. 763 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type"); 764 StringMap<bool> TypesSeen; 765 766 for (const auto *T : Types) { 767 // Check this is not an image type 768 if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end()) 769 continue; 770 // Check we have not seen this Type 771 if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end()) 772 continue; 773 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true)); 774 775 // Check the Type does not have an "abstract" QualType 776 auto QT = T->getValueAsDef("QTExpr"); 777 if (QT->getValueAsBit("IsAbstract") == 1) 778 continue; 779 // Emit the cases for non generic, non image types. 780 OS << " case OCLT_" << T->getValueAsString("Name") << ":\n" 781 << " QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n" 782 << " break;\n"; 783 } 784 785 // End of switch statement. 786 OS << " } // end of switch (Ty.ID)\n\n"; 787 788 // Step 2. 789 // Add ExtVector types if this was a generic type, as the switch statement 790 // above only populated the list with scalar types. This completes the 791 // construction of the Cartesian product of (vector sizes) x (types). 792 OS << " // Construct the different vector types for each generic type.\n"; 793 OS << " if (Ty.ID >= " << TypeList.size() << ") {"; 794 OS << R"( 795 for (unsigned I = 0; I < QT.size(); I++) { 796 // For scalars, size is 1. 797 if (GenVectorSizes[I / GenTypeNumTypes] != 1) { 798 QT[I] = Context.getExtVectorType(QT[I], 799 GenVectorSizes[I / GenTypeNumTypes]); 800 } 801 } 802 } 803 )"; 804 805 // Assign the right attributes to the types (e.g. vector size). 806 OS << R"( 807 // Set vector size for non-generic vector types. 808 if (Ty.VectorWidth > 1) { 809 for (unsigned Index = 0; Index < QT.size(); Index++) { 810 QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth); 811 } 812 } 813 814 if (Ty.IsVolatile != 0) { 815 for (unsigned Index = 0; Index < QT.size(); Index++) { 816 QT[Index] = Context.getVolatileType(QT[Index]); 817 } 818 } 819 820 if (Ty.IsConst != 0) { 821 for (unsigned Index = 0; Index < QT.size(); Index++) { 822 QT[Index] = Context.getConstType(QT[Index]); 823 } 824 } 825 826 // Transform the type to a pointer as the last step, if necessary. 827 // Builtin functions only have pointers on [const|volatile], no 828 // [const|volatile] pointers, so this is ok to do it as a last step. 829 if (Ty.IsPointer != 0) { 830 for (unsigned Index = 0; Index < QT.size(); Index++) { 831 QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS); 832 QT[Index] = Context.getPointerType(QT[Index]); 833 } 834 } 835 )"; 836 837 // End of the "OCL2Qual" function. 838 OS << "\n} // OCL2Qual\n"; 839 } 840 841 void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) { 842 BuiltinNameEmitter NameChecker(Records, OS); 843 NameChecker.Emit(); 844 } 845