1351280Sdim//===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling 2351280Sdim// 3351280Sdim// The LLVM Compiler Infrastructure 4351280Sdim// 5351280Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 6351280Sdim// See https://llvm.org/LICENSE.txt for license information. 7351280Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 8351280Sdim// 9351280Sdim//===----------------------------------------------------------------------===// 10351280Sdim// 11351280Sdim// This tablegen backend emits code for checking whether a function is an 12351280Sdim// OpenCL builtin function. If so, all overloads of this function are 13351280Sdim// added to the LookupResult. The generated include file is used by 14351280Sdim// SemaLookup.cpp 15351280Sdim// 16351280Sdim// For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos") 17351280Sdim// returns a pair <Index, Len>. 18360784Sdim// BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs 19351280Sdim// <SigIndex, SigLen> of the overloads of "cos". 20360784Sdim// SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains 21360784Sdim// one of the signatures of "cos". The SignatureTable entry can be 22360784Sdim// referenced by other functions, e.g. "sin", to exploit the fact that 23360784Sdim// many OpenCL builtins share the same signature. 24360784Sdim// 25360784Sdim// The file generated by this TableGen emitter contains the following: 26360784Sdim// 27360784Sdim// * Structs and enums to represent types and function signatures. 28360784Sdim// 29360784Sdim// * const char *FunctionExtensionTable[] 30360784Sdim// List of space-separated OpenCL extensions. A builtin references an 31360784Sdim// entry in this table when the builtin requires a particular (set of) 32360784Sdim// extension(s) to be enabled. 33360784Sdim// 34360784Sdim// * OpenCLTypeStruct TypeTable[] 35360784Sdim// Type information for return types and arguments. 36360784Sdim// 37360784Sdim// * unsigned SignatureTable[] 38360784Sdim// A list of types representing function signatures. Each entry is an index 39360784Sdim// into the above TypeTable. Multiple entries following each other form a 40360784Sdim// signature, where the first entry is the return type and subsequent 41360784Sdim// entries are the argument types. 42360784Sdim// 43360784Sdim// * OpenCLBuiltinStruct BuiltinTable[] 44360784Sdim// Each entry represents one overload of an OpenCL builtin function and 45360784Sdim// consists of an index into the SignatureTable and the number of arguments. 46360784Sdim// 47360784Sdim// * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) 48360784Sdim// Find out whether a string matches an existing OpenCL builtin function 49360784Sdim// name and return an index into BuiltinTable and the number of overloads. 50360784Sdim// 51360784Sdim// * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector<QualType>&) 52360784Sdim// Convert an OpenCLTypeStruct type to a list of QualType instances. 53360784Sdim// One OpenCLTypeStruct can represent multiple types, primarily when using 54360784Sdim// GenTypes. 55360784Sdim// 56351280Sdim//===----------------------------------------------------------------------===// 57351280Sdim 58360784Sdim#include "TableGenBackends.h" 59351280Sdim#include "llvm/ADT/MapVector.h" 60351280Sdim#include "llvm/ADT/STLExtras.h" 61351280Sdim#include "llvm/ADT/SmallString.h" 62351280Sdim#include "llvm/ADT/StringExtras.h" 63351280Sdim#include "llvm/ADT/StringRef.h" 64351280Sdim#include "llvm/ADT/StringSet.h" 65360784Sdim#include "llvm/ADT/StringSwitch.h" 66351280Sdim#include "llvm/Support/ErrorHandling.h" 67351280Sdim#include "llvm/Support/raw_ostream.h" 68351280Sdim#include "llvm/TableGen/Error.h" 69351280Sdim#include "llvm/TableGen/Record.h" 70351280Sdim#include "llvm/TableGen/StringMatcher.h" 71351280Sdim#include "llvm/TableGen/TableGenBackend.h" 72351280Sdim#include <set> 73351280Sdim 74351280Sdimusing namespace llvm; 75351280Sdim 76351280Sdimnamespace { 77360784Sdim 78360784Sdim// A list of signatures that are shared by one or more builtin functions. 79360784Sdimstruct BuiltinTableEntries { 80360784Sdim SmallVector<StringRef, 4> Names; 81360784Sdim std::vector<std::pair<const Record *, unsigned>> Signatures; 82360784Sdim}; 83360784Sdim 84351280Sdimclass BuiltinNameEmitter { 85351280Sdimpublic: 86351280Sdim BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS) 87351280Sdim : Records(Records), OS(OS) {} 88351280Sdim 89351280Sdim // Entrypoint to generate the functions and structures for checking 90351280Sdim // whether a function is an OpenCL builtin function. 91351280Sdim void Emit(); 92351280Sdim 93351280Sdimprivate: 94360784Sdim // A list of indices into the builtin function table. 95360784Sdim using BuiltinIndexListTy = SmallVector<unsigned, 11>; 96360784Sdim 97351280Sdim // Contains OpenCL builtin functions and related information, stored as 98351280Sdim // Record instances. They are coming from the associated TableGen file. 99351280Sdim RecordKeeper &Records; 100351280Sdim 101351280Sdim // The output file. 102351280Sdim raw_ostream &OS; 103351280Sdim 104360784Sdim // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum 105360784Sdim // definitions in the Output string parameter, and save their Record instances 106360784Sdim // in the List parameter. 107360784Sdim // \param Types (in) List containing the Types to extract. 108360784Sdim // \param TypesSeen (inout) List containing the Types already extracted. 109360784Sdim // \param Output (out) String containing the enums to emit in the output file. 110360784Sdim // \param List (out) List containing the extracted Types, except the Types in 111360784Sdim // TypesSeen. 112360784Sdim void ExtractEnumTypes(std::vector<Record *> &Types, 113360784Sdim StringMap<bool> &TypesSeen, std::string &Output, 114360784Sdim std::vector<const Record *> &List); 115360784Sdim 116360784Sdim // Emit the enum or struct used in the generated file. 117360784Sdim // Populate the TypeList at the same time. 118351280Sdim void EmitDeclarations(); 119351280Sdim 120360784Sdim // Parse the Records generated by TableGen to populate the SignaturesList, 121360784Sdim // FctOverloadMap and TypeMap. 122351280Sdim void GetOverloads(); 123351280Sdim 124360784Sdim // Compare two lists of signatures and check that e.g. the OpenCL version, 125360784Sdim // function attributes, and extension are equal for each signature. 126360784Sdim // \param Candidate (in) Entry in the SignatureListMap to check. 127360784Sdim // \param SignatureList (in) List of signatures of the considered function. 128360784Sdim // \returns true if the two lists of signatures are identical. 129360784Sdim bool CanReuseSignature( 130360784Sdim BuiltinIndexListTy *Candidate, 131360784Sdim std::vector<std::pair<const Record *, unsigned>> &SignatureList); 132360784Sdim 133360784Sdim // Group functions with the same list of signatures by populating the 134360784Sdim // SignatureListMap. 135360784Sdim // Some builtin functions have the same list of signatures, for example the 136360784Sdim // "sin" and "cos" functions. To save space in the BuiltinTable, the 137360784Sdim // "isOpenCLBuiltin" function will have the same output for these two 138360784Sdim // function names. 139360784Sdim void GroupBySignature(); 140360784Sdim 141360784Sdim // Emit the FunctionExtensionTable that lists all function extensions. 142360784Sdim void EmitExtensionTable(); 143360784Sdim 144360784Sdim // Emit the TypeTable containing all types used by OpenCL builtins. 145360784Sdim void EmitTypeTable(); 146360784Sdim 147360784Sdim // Emit the SignatureTable. This table contains all the possible signatures. 148360784Sdim // A signature is stored as a list of indexes of the TypeTable. 149360784Sdim // The first index references the return type (mandatory), and the followings 150360784Sdim // reference its arguments. 151351280Sdim // E.g.: 152360784Sdim // 15, 2, 15 can represent a function with the signature: 153360784Sdim // int func(float, int) 154360784Sdim // The "int" type being at the index 15 in the TypeTable. 155351280Sdim void EmitSignatureTable(); 156351280Sdim 157360784Sdim // Emit the BuiltinTable table. This table contains all the overloads of 158351280Sdim // each function, and is a struct OpenCLBuiltinDecl. 159351280Sdim // E.g.: 160360784Sdim // // 891 convert_float2_rtn 161360784Sdim // { 58, 2, 3, 100, 0 }, 162360784Sdim // This means that the signature of this convert_float2_rtn overload has 163360784Sdim // 1 argument (+1 for the return type), stored at index 58 in 164360784Sdim // the SignatureTable. This prototype requires extension "3" in the 165360784Sdim // FunctionExtensionTable. The last two values represent the minimum (1.0) 166360784Sdim // and maximum (0, meaning no max version) OpenCL version in which this 167360784Sdim // overload is supported. 168351280Sdim void EmitBuiltinTable(); 169351280Sdim 170351280Sdim // Emit a StringMatcher function to check whether a function name is an 171351280Sdim // OpenCL builtin function name. 172351280Sdim void EmitStringMatcher(); 173351280Sdim 174351280Sdim // Emit a function returning the clang QualType instance associated with 175351280Sdim // the TableGen Record Type. 176351280Sdim void EmitQualTypeFinder(); 177351280Sdim 178351280Sdim // Contains a list of the available signatures, without the name of the 179351280Sdim // function. Each pair consists of a signature and a cumulative index. 180351280Sdim // E.g.: <<float, float>, 0>, 181351280Sdim // <<float, int, int, 2>>, 182351280Sdim // <<float>, 5>, 183351280Sdim // ... 184351280Sdim // <<double, double>, 35>. 185360784Sdim std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList; 186351280Sdim 187351280Sdim // Map the name of a builtin function to its prototypes (instances of the 188351280Sdim // TableGen "Builtin" class). 189351280Sdim // Each prototype is registered as a pair of: 190351280Sdim // <pointer to the "Builtin" instance, 191360784Sdim // cumulative index of the associated signature in the SignaturesList> 192351280Sdim // E.g.: The function cos: (float cos(float), double cos(double), ...) 193351280Sdim // <"cos", <<ptrToPrototype0, 5>, 194360784Sdim // <ptrToPrototype1, 35>, 195360784Sdim // <ptrToPrototype2, 79>> 196351280Sdim // ptrToPrototype1 has the following signature: <double, double> 197351280Sdim MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>> 198360784Sdim FctOverloadMap; 199360784Sdim 200360784Sdim // Contains the map of OpenCL types to their index in the TypeTable. 201360784Sdim MapVector<const Record *, unsigned> TypeMap; 202360784Sdim 203360784Sdim // List of OpenCL function extensions mapping extension strings to 204360784Sdim // an index into the FunctionExtensionTable. 205360784Sdim StringMap<unsigned> FunctionExtensionIndex; 206360784Sdim 207360784Sdim // List of OpenCL type names in the same order as in enum OpenCLTypeID. 208360784Sdim // This list does not contain generic types. 209360784Sdim std::vector<const Record *> TypeList; 210360784Sdim 211360784Sdim // Same as TypeList, but for generic types only. 212360784Sdim std::vector<const Record *> GenTypeList; 213360784Sdim 214360784Sdim // Map an ordered vector of signatures to their original Record instances, 215360784Sdim // and to a list of function names that share these signatures. 216360784Sdim // 217360784Sdim // For example, suppose the "cos" and "sin" functions have only three 218360784Sdim // signatures, and these signatures are at index Ix in the SignatureTable: 219360784Sdim // cos | sin | Signature | Index 220360784Sdim // float cos(float) | float sin(float) | Signature1 | I1 221360784Sdim // double cos(double) | double sin(double) | Signature2 | I2 222360784Sdim // half cos(half) | half sin(half) | Signature3 | I3 223360784Sdim // 224360784Sdim // Then we will create a mapping of the vector of signatures: 225360784Sdim // SignatureListMap[<I1, I2, I3>] = < 226360784Sdim // <"cos", "sin">, 227360784Sdim // <Signature1, Signature2, Signature3>> 228360784Sdim // The function "tan", having the same signatures, would be mapped to the 229360784Sdim // same entry (<I1, I2, I3>). 230360784Sdim MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap; 231351280Sdim}; 232351280Sdim} // namespace 233351280Sdim 234351280Sdimvoid BuiltinNameEmitter::Emit() { 235351280Sdim emitSourceFileHeader("OpenCL Builtin handling", OS); 236351280Sdim 237351280Sdim OS << "#include \"llvm/ADT/StringRef.h\"\n"; 238351280Sdim OS << "using namespace clang;\n\n"; 239351280Sdim 240360784Sdim // Emit enums and structs. 241351280Sdim EmitDeclarations(); 242351280Sdim 243360784Sdim // Parse the Records to populate the internal lists. 244351280Sdim GetOverloads(); 245360784Sdim GroupBySignature(); 246351280Sdim 247360784Sdim // Emit tables. 248360784Sdim EmitExtensionTable(); 249360784Sdim EmitTypeTable(); 250351280Sdim EmitSignatureTable(); 251351280Sdim EmitBuiltinTable(); 252351280Sdim 253360784Sdim // Emit functions. 254351280Sdim EmitStringMatcher(); 255351280Sdim EmitQualTypeFinder(); 256351280Sdim} 257351280Sdim 258360784Sdimvoid BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types, 259360784Sdim StringMap<bool> &TypesSeen, 260360784Sdim std::string &Output, 261360784Sdim std::vector<const Record *> &List) { 262360784Sdim raw_string_ostream SS(Output); 263360784Sdim 264360784Sdim for (const auto *T : Types) { 265360784Sdim if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) { 266360784Sdim SS << " OCLT_" + T->getValueAsString("Name") << ",\n"; 267360784Sdim // Save the type names in the same order as their enum value. Note that 268360784Sdim // the Record can be a VectorType or something else, only the name is 269360784Sdim // important. 270360784Sdim List.push_back(T); 271360784Sdim TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true)); 272360784Sdim } 273360784Sdim } 274360784Sdim SS.flush(); 275360784Sdim} 276360784Sdim 277351280Sdimvoid BuiltinNameEmitter::EmitDeclarations() { 278360784Sdim // Enum of scalar type names (float, int, ...) and generic type sets. 279351280Sdim OS << "enum OpenCLTypeID {\n"; 280360784Sdim 281360784Sdim StringMap<bool> TypesSeen; 282360784Sdim std::string GenTypeEnums; 283360784Sdim std::string TypeEnums; 284360784Sdim 285360784Sdim // Extract generic types and non-generic types separately, to keep 286360784Sdim // gentypes at the end of the enum which simplifies the special handling 287360784Sdim // for gentypes in SemaLookup. 288360784Sdim std::vector<Record *> GenTypes = 289360784Sdim Records.getAllDerivedDefinitions("GenericType"); 290360784Sdim ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList); 291360784Sdim 292351280Sdim std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type"); 293360784Sdim ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList); 294360784Sdim 295360784Sdim OS << TypeEnums; 296360784Sdim OS << GenTypeEnums; 297351280Sdim OS << "};\n"; 298351280Sdim 299360784Sdim // Structure definitions. 300351280Sdim OS << R"( 301360784Sdim// Image access qualifier. 302360784Sdimenum OpenCLAccessQual : unsigned char { 303360784Sdim OCLAQ_None, 304360784Sdim OCLAQ_ReadOnly, 305360784Sdim OCLAQ_WriteOnly, 306360784Sdim OCLAQ_ReadWrite 307360784Sdim}; 308351280Sdim 309360784Sdim// Represents a return type or argument type. 310360784Sdimstruct OpenCLTypeStruct { 311360784Sdim // A type (e.g. float, int, ...). 312360784Sdim const OpenCLTypeID ID; 313360784Sdim // Vector size (if applicable; 0 for scalars and generic types). 314360784Sdim const unsigned VectorWidth; 315360784Sdim // 0 if the type is not a pointer. 316360784Sdim const bool IsPointer; 317360784Sdim // 0 if the type is not const. 318360784Sdim const bool IsConst; 319360784Sdim // 0 if the type is not volatile. 320360784Sdim const bool IsVolatile; 321360784Sdim // Access qualifier. 322360784Sdim const OpenCLAccessQual AccessQualifier; 323360784Sdim // Address space of the pointer (if applicable). 324360784Sdim const LangAS AS; 325351280Sdim}; 326351280Sdim 327351280Sdim// One overload of an OpenCL builtin function. 328360784Sdimstruct OpenCLBuiltinStruct { 329360784Sdim // Index of the signature in the OpenCLTypeStruct table. 330360784Sdim const unsigned SigTableIndex; 331360784Sdim // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in 332360784Sdim // the SignatureTable represent the complete signature. The first type at 333360784Sdim // index SigTableIndex is the return type. 334360784Sdim const unsigned NumTypes; 335360784Sdim // Function attribute __attribute__((pure)) 336360784Sdim const bool IsPure; 337360784Sdim // Function attribute __attribute__((const)) 338360784Sdim const bool IsConst; 339360784Sdim // Function attribute __attribute__((convergent)) 340360784Sdim const bool IsConv; 341360784Sdim // OpenCL extension(s) required for this overload. 342360784Sdim const unsigned short Extension; 343360784Sdim // First OpenCL version in which this overload was introduced (e.g. CL20). 344360784Sdim const unsigned short MinVersion; 345360784Sdim // First OpenCL version in which this overload was removed (e.g. CL20). 346360784Sdim const unsigned short MaxVersion; 347351280Sdim}; 348351280Sdim 349351280Sdim)"; 350351280Sdim} 351351280Sdim 352360784Sdim// Verify that the combination of GenTypes in a signature is supported. 353360784Sdim// To simplify the logic for creating overloads in SemaLookup, only allow 354360784Sdim// a signature to contain different GenTypes if these GenTypes represent 355360784Sdim// the same number of actual scalar or vector types. 356360784Sdim// 357360784Sdim// Exit with a fatal error if an unsupported construct is encountered. 358360784Sdimstatic void VerifySignature(const std::vector<Record *> &Signature, 359360784Sdim const Record *BuiltinRec) { 360360784Sdim unsigned GenTypeVecSizes = 1; 361360784Sdim unsigned GenTypeTypes = 1; 362360784Sdim 363360784Sdim for (const auto *T : Signature) { 364360784Sdim // Check all GenericType arguments in this signature. 365360784Sdim if (T->isSubClassOf("GenericType")) { 366360784Sdim // Check number of vector sizes. 367360784Sdim unsigned NVecSizes = 368360784Sdim T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size(); 369360784Sdim if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) { 370360784Sdim if (GenTypeVecSizes > 1) { 371360784Sdim // We already saw a gentype with a different number of vector sizes. 372360784Sdim PrintFatalError(BuiltinRec->getLoc(), 373360784Sdim "number of vector sizes should be equal or 1 for all gentypes " 374360784Sdim "in a declaration"); 375360784Sdim } 376360784Sdim GenTypeVecSizes = NVecSizes; 377360784Sdim } 378360784Sdim 379360784Sdim // Check number of data types. 380360784Sdim unsigned NTypes = 381360784Sdim T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size(); 382360784Sdim if (NTypes != GenTypeTypes && NTypes != 1) { 383360784Sdim if (GenTypeTypes > 1) { 384360784Sdim // We already saw a gentype with a different number of types. 385360784Sdim PrintFatalError(BuiltinRec->getLoc(), 386360784Sdim "number of types should be equal or 1 for all gentypes " 387360784Sdim "in a declaration"); 388360784Sdim } 389360784Sdim GenTypeTypes = NTypes; 390360784Sdim } 391360784Sdim } 392360784Sdim } 393360784Sdim} 394360784Sdim 395351280Sdimvoid BuiltinNameEmitter::GetOverloads() { 396360784Sdim // Populate the TypeMap. 397360784Sdim std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type"); 398360784Sdim unsigned I = 0; 399360784Sdim for (const auto &T : Types) { 400360784Sdim TypeMap.insert(std::make_pair(T, I++)); 401360784Sdim } 402360784Sdim 403360784Sdim // Populate the SignaturesList and the FctOverloadMap. 404351280Sdim unsigned CumulativeSignIndex = 0; 405351280Sdim std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin"); 406351280Sdim for (const auto *B : Builtins) { 407351280Sdim StringRef BName = B->getValueAsString("Name"); 408360784Sdim if (FctOverloadMap.find(BName) == FctOverloadMap.end()) { 409360784Sdim FctOverloadMap.insert(std::make_pair( 410351280Sdim BName, std::vector<std::pair<const Record *, unsigned>>{})); 411351280Sdim } 412351280Sdim 413351280Sdim auto Signature = B->getValueAsListOfDefs("Signature"); 414360784Sdim // Reuse signatures to avoid unnecessary duplicates. 415351280Sdim auto it = 416360784Sdim std::find_if(SignaturesList.begin(), SignaturesList.end(), 417351280Sdim [&](const std::pair<std::vector<Record *>, unsigned> &a) { 418351280Sdim return a.first == Signature; 419351280Sdim }); 420351280Sdim unsigned SignIndex; 421360784Sdim if (it == SignaturesList.end()) { 422360784Sdim VerifySignature(Signature, B); 423360784Sdim SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex)); 424351280Sdim SignIndex = CumulativeSignIndex; 425351280Sdim CumulativeSignIndex += Signature.size(); 426351280Sdim } else { 427351280Sdim SignIndex = it->second; 428351280Sdim } 429360784Sdim FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex)); 430351280Sdim } 431351280Sdim} 432351280Sdim 433360784Sdimvoid BuiltinNameEmitter::EmitExtensionTable() { 434360784Sdim OS << "static const char *FunctionExtensionTable[] = {\n"; 435360784Sdim unsigned Index = 0; 436360784Sdim std::vector<Record *> FuncExtensions = 437360784Sdim Records.getAllDerivedDefinitions("FunctionExtension"); 438360784Sdim 439360784Sdim for (const auto &FE : FuncExtensions) { 440360784Sdim // Emit OpenCL extension table entry. 441360784Sdim OS << " // " << Index << ": " << FE->getName() << "\n" 442360784Sdim << " \"" << FE->getValueAsString("ExtName") << "\",\n"; 443360784Sdim 444360784Sdim // Record index of this extension. 445360784Sdim FunctionExtensionIndex[FE->getName()] = Index++; 446360784Sdim } 447360784Sdim OS << "};\n\n"; 448360784Sdim} 449360784Sdim 450360784Sdimvoid BuiltinNameEmitter::EmitTypeTable() { 451360784Sdim OS << "static const OpenCLTypeStruct TypeTable[] = {\n"; 452360784Sdim for (const auto &T : TypeMap) { 453360784Sdim const char *AccessQual = 454360784Sdim StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier")) 455360784Sdim .Case("RO", "OCLAQ_ReadOnly") 456360784Sdim .Case("WO", "OCLAQ_WriteOnly") 457360784Sdim .Case("RW", "OCLAQ_ReadWrite") 458360784Sdim .Default("OCLAQ_None"); 459360784Sdim 460360784Sdim OS << " // " << T.second << "\n" 461360784Sdim << " {OCLT_" << T.first->getValueAsString("Name") << ", " 462360784Sdim << T.first->getValueAsInt("VecWidth") << ", " 463360784Sdim << T.first->getValueAsBit("IsPointer") << ", " 464360784Sdim << T.first->getValueAsBit("IsConst") << ", " 465360784Sdim << T.first->getValueAsBit("IsVolatile") << ", " 466360784Sdim << AccessQual << ", " 467360784Sdim << T.first->getValueAsString("AddrSpace") << "},\n"; 468360784Sdim } 469360784Sdim OS << "};\n\n"; 470360784Sdim} 471360784Sdim 472351280Sdimvoid BuiltinNameEmitter::EmitSignatureTable() { 473360784Sdim // Store a type (e.g. int, float, int2, ...). The type is stored as an index 474360784Sdim // of a struct OpenCLType table. Multiple entries following each other form a 475360784Sdim // signature. 476360784Sdim OS << "static const unsigned SignatureTable[] = {\n"; 477360784Sdim for (const auto &P : SignaturesList) { 478360784Sdim OS << " // " << P.second << "\n "; 479360784Sdim for (const Record *R : P.first) { 480360784Sdim OS << TypeMap.find(R)->second << ", "; 481351280Sdim } 482360784Sdim OS << "\n"; 483351280Sdim } 484351280Sdim OS << "};\n\n"; 485351280Sdim} 486351280Sdim 487351280Sdimvoid BuiltinNameEmitter::EmitBuiltinTable() { 488360784Sdim unsigned Index = 0; 489360784Sdim 490360784Sdim OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n"; 491360784Sdim for (const auto &SLM : SignatureListMap) { 492360784Sdim 493360784Sdim OS << " // " << (Index + 1) << ": "; 494360784Sdim for (const auto &Name : SLM.second.Names) { 495360784Sdim OS << Name << ", "; 496360784Sdim } 497360784Sdim OS << "\n"; 498360784Sdim 499360784Sdim for (const auto &Overload : SLM.second.Signatures) { 500360784Sdim StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName(); 501360784Sdim OS << " { " << Overload.second << ", " 502360784Sdim << Overload.first->getValueAsListOfDefs("Signature").size() << ", " 503360784Sdim << (Overload.first->getValueAsBit("IsPure")) << ", " 504360784Sdim << (Overload.first->getValueAsBit("IsConst")) << ", " 505360784Sdim << (Overload.first->getValueAsBit("IsConv")) << ", " 506360784Sdim << FunctionExtensionIndex[ExtName] << ", " 507360784Sdim << Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID") 508360784Sdim << ", " 509360784Sdim << Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID") 510351280Sdim << " },\n"; 511360784Sdim Index++; 512351280Sdim } 513351280Sdim } 514351280Sdim OS << "};\n\n"; 515351280Sdim} 516351280Sdim 517360784Sdimbool BuiltinNameEmitter::CanReuseSignature( 518360784Sdim BuiltinIndexListTy *Candidate, 519360784Sdim std::vector<std::pair<const Record *, unsigned>> &SignatureList) { 520360784Sdim assert(Candidate->size() == SignatureList.size() && 521360784Sdim "signature lists should have the same size"); 522360784Sdim 523360784Sdim auto &CandidateSigs = 524360784Sdim SignatureListMap.find(Candidate)->second.Signatures; 525360784Sdim for (unsigned Index = 0; Index < Candidate->size(); Index++) { 526360784Sdim const Record *Rec = SignatureList[Index].first; 527360784Sdim const Record *Rec2 = CandidateSigs[Index].first; 528360784Sdim if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") && 529360784Sdim Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") && 530360784Sdim Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") && 531360784Sdim Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") == 532360784Sdim Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") && 533360784Sdim Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") == 534360784Sdim Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") && 535360784Sdim Rec->getValueAsDef("Extension")->getName() == 536360784Sdim Rec2->getValueAsDef("Extension")->getName()) { 537360784Sdim return true; 538360784Sdim } 539360784Sdim } 540360784Sdim return false; 541360784Sdim} 542360784Sdim 543360784Sdimvoid BuiltinNameEmitter::GroupBySignature() { 544360784Sdim // List of signatures known to be emitted. 545360784Sdim std::vector<BuiltinIndexListTy *> KnownSignatures; 546360784Sdim 547360784Sdim for (auto &Fct : FctOverloadMap) { 548360784Sdim bool FoundReusableSig = false; 549360784Sdim 550360784Sdim // Gather all signatures for the current function. 551360784Sdim auto *CurSignatureList = new BuiltinIndexListTy(); 552360784Sdim for (const auto &Signature : Fct.second) { 553360784Sdim CurSignatureList->push_back(Signature.second); 554360784Sdim } 555360784Sdim // Sort the list to facilitate future comparisons. 556360784Sdim std::sort(CurSignatureList->begin(), CurSignatureList->end()); 557360784Sdim 558360784Sdim // Check if we have already seen another function with the same list of 559360784Sdim // signatures. If so, just add the name of the function. 560360784Sdim for (auto *Candidate : KnownSignatures) { 561360784Sdim if (Candidate->size() == CurSignatureList->size() && 562360784Sdim *Candidate == *CurSignatureList) { 563360784Sdim if (CanReuseSignature(Candidate, Fct.second)) { 564360784Sdim SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first); 565360784Sdim FoundReusableSig = true; 566360784Sdim } 567360784Sdim } 568360784Sdim } 569360784Sdim 570360784Sdim if (FoundReusableSig) { 571360784Sdim delete CurSignatureList; 572360784Sdim } else { 573360784Sdim // Add a new entry. 574360784Sdim SignatureListMap[CurSignatureList] = { 575360784Sdim SmallVector<StringRef, 4>(1, Fct.first), Fct.second}; 576360784Sdim KnownSignatures.push_back(CurSignatureList); 577360784Sdim } 578360784Sdim } 579360784Sdim 580360784Sdim for (auto *I : KnownSignatures) { 581360784Sdim delete I; 582360784Sdim } 583360784Sdim} 584360784Sdim 585351280Sdimvoid BuiltinNameEmitter::EmitStringMatcher() { 586351280Sdim std::vector<StringMatcher::StringPair> ValidBuiltins; 587351280Sdim unsigned CumulativeIndex = 1; 588351280Sdim 589360784Sdim for (const auto &SLM : SignatureListMap) { 590360784Sdim const auto &Ovl = SLM.second.Signatures; 591360784Sdim 592360784Sdim // A single signature list may be used by different builtins. Return the 593360784Sdim // same <index, length> pair for each of those builtins. 594360784Sdim for (const auto &FctName : SLM.second.Names) { 595360784Sdim std::string RetStmt; 596360784Sdim raw_string_ostream SS(RetStmt); 597360784Sdim SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size() 598360784Sdim << ");"; 599360784Sdim SS.flush(); 600360784Sdim ValidBuiltins.push_back(StringMatcher::StringPair(FctName, RetStmt)); 601360784Sdim } 602360784Sdim CumulativeIndex += Ovl.size(); 603351280Sdim } 604351280Sdim 605351280Sdim OS << R"( 606360784Sdim// Find out whether a string matches an existing OpenCL builtin function name. 607360784Sdim// Returns: A pair <0, 0> if no name matches. 608360784Sdim// A pair <Index, Len> indexing the BuiltinTable if the name is 609360784Sdim// matching an OpenCL builtin function. 610360784Sdimstatic std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) { 611351280Sdim 612351280Sdim)"; 613351280Sdim 614360784Sdim StringMatcher("Name", ValidBuiltins, OS).Emit(0, true); 615351280Sdim 616351280Sdim OS << " return std::make_pair(0, 0);\n"; 617360784Sdim OS << "} // isOpenCLBuiltin\n"; 618351280Sdim} 619351280Sdim 620351280Sdimvoid BuiltinNameEmitter::EmitQualTypeFinder() { 621351280Sdim OS << R"( 622351280Sdim 623360784Sdim// Convert an OpenCLTypeStruct type to a list of QualTypes. 624360784Sdim// Generic types represent multiple types and vector sizes, thus a vector 625360784Sdim// is returned. The conversion is done in two steps: 626360784Sdim// Step 1: A switch statement fills a vector with scalar base types for the 627360784Sdim// Cartesian product of (vector sizes) x (types) for generic types, 628360784Sdim// or a single scalar type for non generic types. 629360784Sdim// Step 2: Qualifiers and other type properties such as vector size are 630360784Sdim// applied. 631360784Sdimstatic void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty, 632360784Sdim llvm::SmallVectorImpl<QualType> &QT) { 633360784Sdim // Number of scalar types in the GenType. 634360784Sdim unsigned GenTypeNumTypes; 635360784Sdim // Pointer to the list of vector sizes for the GenType. 636360784Sdim llvm::ArrayRef<unsigned> GenVectorSizes; 637351280Sdim)"; 638351280Sdim 639360784Sdim // Generate list of vector sizes for each generic type. 640360784Sdim for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) { 641360784Sdim OS << " constexpr unsigned List" 642360784Sdim << VectList->getValueAsString("Name") << "[] = {"; 643360784Sdim for (const auto V : VectList->getValueAsListOfInts("List")) { 644360784Sdim OS << V << ", "; 645360784Sdim } 646360784Sdim OS << "};\n"; 647360784Sdim } 648360784Sdim 649360784Sdim // Step 1. 650360784Sdim // Start of switch statement over all types. 651360784Sdim OS << "\n switch (Ty.ID) {\n"; 652360784Sdim 653360784Sdim // Switch cases for image types (Image2d, Image3d, ...) 654360784Sdim std::vector<Record *> ImageTypes = 655360784Sdim Records.getAllDerivedDefinitions("ImageType"); 656360784Sdim 657360784Sdim // Map an image type name to its 3 access-qualified types (RO, WO, RW). 658360784Sdim std::map<StringRef, SmallVector<Record *, 3>> ImageTypesMap; 659360784Sdim for (auto *IT : ImageTypes) { 660360784Sdim auto Entry = ImageTypesMap.find(IT->getValueAsString("Name")); 661360784Sdim if (Entry == ImageTypesMap.end()) { 662360784Sdim SmallVector<Record *, 3> ImageList; 663360784Sdim ImageList.push_back(IT); 664360784Sdim ImageTypesMap.insert( 665360784Sdim std::make_pair(IT->getValueAsString("Name"), ImageList)); 666360784Sdim } else { 667360784Sdim Entry->second.push_back(IT); 668360784Sdim } 669360784Sdim } 670360784Sdim 671360784Sdim // Emit the cases for the image types. For an image type name, there are 3 672360784Sdim // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field 673360784Sdim // tells which one is needed. Emit a switch statement that puts the 674360784Sdim // corresponding QualType into "QT". 675360784Sdim for (const auto &ITE : ImageTypesMap) { 676360784Sdim OS << " case OCLT_" << ITE.first.str() << ":\n" 677360784Sdim << " switch (Ty.AccessQualifier) {\n" 678360784Sdim << " case OCLAQ_None:\n" 679360784Sdim << " llvm_unreachable(\"Image without access qualifier\");\n"; 680360784Sdim for (const auto &Image : ITE.second) { 681360784Sdim OS << StringSwitch<const char *>( 682360784Sdim Image->getValueAsString("AccessQualifier")) 683360784Sdim .Case("RO", " case OCLAQ_ReadOnly:\n") 684360784Sdim .Case("WO", " case OCLAQ_WriteOnly:\n") 685360784Sdim .Case("RW", " case OCLAQ_ReadWrite:\n") 686360784Sdim << " QT.push_back(Context." 687360784Sdim << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n" 688360784Sdim << " break;\n"; 689360784Sdim } 690360784Sdim OS << " }\n" 691360784Sdim << " break;\n"; 692360784Sdim } 693360784Sdim 694360784Sdim // Switch cases for generic types. 695360784Sdim for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) { 696360784Sdim OS << " case OCLT_" << GenType->getValueAsString("Name") << ":\n"; 697360784Sdim OS << " QT.append({"; 698360784Sdim 699360784Sdim // Build the Cartesian product of (vector sizes) x (types). Only insert 700360784Sdim // the plain scalar types for now; other type information such as vector 701360784Sdim // size and type qualifiers will be added after the switch statement. 702360784Sdim for (unsigned I = 0; I < GenType->getValueAsDef("VectorList") 703360784Sdim ->getValueAsListOfInts("List") 704360784Sdim .size(); 705360784Sdim I++) { 706360784Sdim for (const auto *T : 707360784Sdim GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) { 708360784Sdim OS << "Context." 709360784Sdim << T->getValueAsDef("QTName")->getValueAsString("Name") << ", "; 710360784Sdim } 711360784Sdim } 712360784Sdim OS << "});\n"; 713360784Sdim // GenTypeNumTypes is the number of types in the GenType 714360784Sdim // (e.g. float/double/half). 715360784Sdim OS << " GenTypeNumTypes = " 716360784Sdim << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List") 717360784Sdim .size() 718360784Sdim << ";\n"; 719360784Sdim // GenVectorSizes is the list of vector sizes for this GenType. 720360784Sdim // QT contains GenTypeNumTypes * #GenVectorSizes elements. 721360784Sdim OS << " GenVectorSizes = List" 722360784Sdim << GenType->getValueAsDef("VectorList")->getValueAsString("Name") 723360784Sdim << ";\n"; 724360784Sdim OS << " break;\n"; 725360784Sdim } 726360784Sdim 727360784Sdim // Switch cases for non generic, non image types (int, int4, float, ...). 728360784Sdim // Only insert the plain scalar type; vector information and type qualifiers 729360784Sdim // are added in step 2. 730351280Sdim std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type"); 731351280Sdim StringMap<bool> TypesSeen; 732351280Sdim 733351280Sdim for (const auto *T : Types) { 734360784Sdim // Check this is not an image type 735360784Sdim if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end()) 736360784Sdim continue; 737351280Sdim // Check we have not seen this Type 738351280Sdim if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end()) 739351280Sdim continue; 740351280Sdim TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true)); 741351280Sdim 742351280Sdim // Check the Type does not have an "abstract" QualType 743351280Sdim auto QT = T->getValueAsDef("QTName"); 744360784Sdim if (QT->getValueAsBit("IsAbstract") == 1) 745351280Sdim continue; 746360784Sdim // Emit the cases for non generic, non image types. 747360784Sdim OS << " case OCLT_" << T->getValueAsString("Name") << ":\n"; 748360784Sdim OS << " QT.push_back(Context." << QT->getValueAsString("Name") 749360784Sdim << ");\n"; 750360784Sdim OS << " break;\n"; 751360784Sdim } 752351280Sdim 753360784Sdim // End of switch statement. 754360784Sdim OS << " } // end of switch (Ty.ID)\n\n"; 755360784Sdim 756360784Sdim // Step 2. 757360784Sdim // Add ExtVector types if this was a generic type, as the switch statement 758360784Sdim // above only populated the list with scalar types. This completes the 759360784Sdim // construction of the Cartesian product of (vector sizes) x (types). 760360784Sdim OS << " // Construct the different vector types for each generic type.\n"; 761360784Sdim OS << " if (Ty.ID >= " << TypeList.size() << ") {"; 762360784Sdim OS << R"( 763360784Sdim for (unsigned I = 0; I < QT.size(); I++) { 764360784Sdim // For scalars, size is 1. 765360784Sdim if (GenVectorSizes[I / GenTypeNumTypes] != 1) { 766360784Sdim QT[I] = Context.getExtVectorType(QT[I], 767360784Sdim GenVectorSizes[I / GenTypeNumTypes]); 768360784Sdim } 769360784Sdim } 770351280Sdim } 771360784Sdim)"; 772351280Sdim 773360784Sdim // Assign the right attributes to the types (e.g. vector size). 774351280Sdim OS << R"( 775360784Sdim // Set vector size for non-generic vector types. 776360784Sdim if (Ty.VectorWidth > 1) { 777360784Sdim for (unsigned Index = 0; Index < QT.size(); Index++) { 778360784Sdim QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth); 779360784Sdim } 780360784Sdim } 781351280Sdim 782360784Sdim if (Ty.IsVolatile != 0) { 783360784Sdim for (unsigned Index = 0; Index < QT.size(); Index++) { 784360784Sdim QT[Index] = Context.getVolatileType(QT[Index]); 785360784Sdim } 786351280Sdim } 787351280Sdim 788360784Sdim if (Ty.IsConst != 0) { 789360784Sdim for (unsigned Index = 0; Index < QT.size(); Index++) { 790360784Sdim QT[Index] = Context.getConstType(QT[Index]); 791360784Sdim } 792360784Sdim } 793360784Sdim 794360784Sdim // Transform the type to a pointer as the last step, if necessary. 795360784Sdim // Builtin functions only have pointers on [const|volatile], no 796360784Sdim // [const|volatile] pointers, so this is ok to do it as a last step. 797360784Sdim if (Ty.IsPointer != 0) { 798360784Sdim for (unsigned Index = 0; Index < QT.size(); Index++) { 799360784Sdim QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS); 800360784Sdim QT[Index] = Context.getPointerType(QT[Index]); 801360784Sdim } 802360784Sdim } 803351280Sdim)"; 804360784Sdim 805360784Sdim // End of the "OCL2Qual" function. 806360784Sdim OS << "\n} // OCL2Qual\n"; 807351280Sdim} 808351280Sdim 809360784Sdimvoid clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) { 810351280Sdim BuiltinNameEmitter NameChecker(Records, OS); 811351280Sdim NameChecker.Emit(); 812351280Sdim} 813