https://github.com/jansvoboda11 created https://github.com/llvm/llvm-project/pull/243274
Every compilation used to create an identifier for each builtin of its target and language upfront, in `Builtin::Context::initializeBuiltins()`. That's ~12,000 identifiers for AArch64 (mostly NEON, SVE and SME) and ~3,400 for x86-64, for every `CompilerInstance`, including every implicit module build, while a translation unit typically uses a few dozen of them. Now the `IdentifierTable` assigns the builtin ID when it creates an identifier: it asks `Builtin::Context::lookupBuiltinID()` whether the name is a builtin that its `LangOptions` support. So the `LangOptions` must not change after `Preprocessor::Initialize()`. An empty AArch64 C file now creates 874 identifiers instead of 12,896. To answer that quickly, the new `Builtin::TargetBuiltins` holds the builtin shards of a target and an optional aux target together with a hash table from builtin name to ID. It doesn't depend on the `LangOptions`: whether a builtin is supported, which of several builtins with the same name wins, and -fno-builtin-* are checked at lookup time, which only matters for the few names that are builtins. That makes `TargetBuiltins` immutable and shareable by any compilation for the same targets. Building it takes ~0.3 ms and 256 KB for AArch64; a lookup adds ~13 ns to the creation of a new identifier. `Builtin::Context` no longer has a two-step setup: it's constructed from the targets (or from existing `TargetBuiltins`), and `InitializeTarget()` is gone, which breaks out-of-tree callers of it. `Preprocessor::Initialize()` creates it and installs the lookup in its identifier table before any AST file is read, which covers every path, including PCH consumers and preprocessors created outside of `FrontendAction`. `CompilerInstance` passes its `TargetBuiltins` to the module builds it requests, so a compilation builds them once however many modules it builds. The existing calls to `initializeBuiltins()` keep working but are now redundant. Other changes in behavior: - Typo correction used to find builtins by iterating the identifier table; it now also enumerates the supported builtin names. - Builtin IDs come from the importing compilation's target and language options, for PCHs as for modules. `ASTReader` no longer restores them from a PCH, which now only contains the builtins it used. - The `IdentifierTable` starts with space for 2K identifiers instead of 8K, saving 144 KB per compilation. A throwaway check comparing the old and new builtin IDs name by name across 29 targets, 7 aux-target choices and 9 language/flag configurations found no difference; `BuiltinsConsistencyTest` checks a subset of these. clang-scan-deps on the macOS SDK (400 translation units, 2,960 modules, -j 14), mean difference with 95% CI: - clean scan: -10.9% +- 1.7% time, -11.4% +- 0.5% CPU - incremental scan: -2.7% +- 6.0% time (n.s.), -13 MB +- 3 peak footprint Alternatives considered: - Generating the name index at Clang's build time: many shards come from `.def` files or from `NeonEmitter`/`SveEmitter`, and the index for a combination of target and aux target would still have to be merged at run time. - Applying the `LangOptions` when building the index: lookups wouldn't get measurably faster, and the index couldn't be shared between compilations with different `LangOptions`. - A process-wide cache of `TargetBuiltins` in `clang/Basic`: it needs global state and a lock in a library whose clients mostly don't run compilations concurrently. For now only the module builds of one compilation share them; sharing them between compilations is left for later. >From 6dff2d45ac8c950f01b06c610f6a1af682c6db15 Mon Sep 17 00:00:00 2001 From: Jan Svoboda <[email protected]> Date: Mon, 16 Nov 2026 11:33:49 -0800 Subject: [PATCH] [clang] Register builtin identifiers lazily Every compilation used to create an identifier for each builtin of its target and language upfront, in `Builtin::Context::initializeBuiltins()`. That's ~12,000 identifiers for AArch64 (mostly NEON, SVE and SME) and ~3,400 for x86-64, for every `CompilerInstance`, including every implicit module build, while a translation unit typically uses a few dozen of them. Now the `IdentifierTable` assigns the builtin ID when it creates an identifier: it asks `Builtin::Context::lookupBuiltinID()` whether the name is a builtin that its `LangOptions` support. So the `LangOptions` must not change after `Preprocessor::Initialize()`. An empty AArch64 C file now creates 874 identifiers instead of 12,896. To answer that quickly, the new `Builtin::TargetBuiltins` holds the builtin shards of a target and an optional aux target together with a hash table from builtin name to ID. It doesn't depend on the `LangOptions`: whether a builtin is supported, which of several builtins with the same name wins, and -fno-builtin-* are checked at lookup time, which only matters for the few names that are builtins. That makes `TargetBuiltins` immutable and shareable by any compilation for the same targets. Building it takes ~0.3 ms and 256 KB for AArch64; a lookup adds ~13 ns to the creation of a new identifier. `Builtin::Context` no longer has a two-step setup: it's constructed from the targets (or from existing `TargetBuiltins`), and `InitializeTarget()` is gone, which breaks out-of-tree callers of it. `Preprocessor::Initialize()` creates it and installs the lookup in its identifier table before any AST file is read, which covers every path, including PCH consumers and preprocessors created outside of `FrontendAction`. `CompilerInstance` passes its `TargetBuiltins` to the module builds it requests, so a compilation builds them once however many modules it builds. The existing calls to `initializeBuiltins()` keep working but are now redundant. Other changes in behavior: - Typo correction used to find builtins by iterating the identifier table; it now also enumerates the supported builtin names. - Builtin IDs come from the importing compilation's target and language options, for PCHs as for modules. `ASTReader` no longer restores them from a PCH, which now only contains the builtins it used. - The `IdentifierTable` starts with space for 2K identifiers instead of 8K, saving 144 KB per compilation. A throwaway check comparing the old and new builtin IDs name by name across 29 targets, 7 aux-target choices and 9 language/flag configurations found no difference; `BuiltinsConsistencyTest` checks a subset of these. clang-scan-deps on the macOS SDK (400 translation units, 2,960 modules, -j 14), mean difference with 95% CI: - clean scan: -10.9% +- 1.7% time, -11.4% +- 0.5% CPU - incremental scan: -2.7% +- 6.0% time (n.s.), -13 MB +- 3 peak footprint Alternatives considered: - Generating the name index at Clang's build time: many shards come from `.def` files or from `NeonEmitter`/`SveEmitter`, and the index for a combination of target and aux target would still have to be merged at run time. - Applying the `LangOptions` when building the index: lookups wouldn't get measurably faster, and the index couldn't be shared between compilations with different `LangOptions`. - A process-wide cache of `TargetBuiltins` in `clang/Basic`: it needs global state and a lock in a library whose clients mostly don't run compilations concurrently. For now only the module builds of one compilation share them; sharing them between compilations is left for later. --- clang/include/clang/Basic/Builtins.h | 100 ++++- clang/include/clang/Basic/IdentifierTable.h | 25 ++ .../include/clang/Frontend/CompilerInstance.h | 8 + clang/include/clang/Lex/Preprocessor.h | 11 +- clang/lib/Basic/Builtins.cpp | 226 +++++++----- clang/lib/Basic/IdentifierTable.cpp | 11 +- clang/lib/Frontend/ChainedIncludesSource.cpp | 6 +- clang/lib/Frontend/CompilerInstance.cpp | 10 +- clang/lib/Frontend/FrontendAction.cpp | 24 +- clang/lib/Lex/Preprocessor.cpp | 39 +- clang/lib/Sema/SemaLookup.cpp | 3 + clang/lib/Serialization/ASTReader.cpp | 18 +- clang/lib/Serialization/ASTWriter.cpp | 3 + .../test/Modules/builtins-unused-in-module.c | 29 ++ clang/test/PCH/builtins-no-builtin-flags.c | 46 +++ clang/test/PCH/builtins-unused-in-pch.c | 45 +++ .../builtins-not-in-identifier-table.c | 11 + clang/unittests/Basic/BuiltinsTest.cpp | 344 ++++++++++++++++++ clang/unittests/Basic/CMakeLists.txt | 1 + .../Clang/ClangExpressionParser.cpp | 5 - 20 files changed, 825 insertions(+), 140 deletions(-) create mode 100644 clang/test/Modules/builtins-unused-in-module.c create mode 100644 clang/test/PCH/builtins-no-builtin-flags.c create mode 100644 clang/test/PCH/builtins-unused-in-pch.c create mode 100644 clang/test/Preprocessor/builtins-not-in-identifier-table.c create mode 100644 clang/unittests/Basic/BuiltinsTest.cpp diff --git a/clang/include/clang/Basic/Builtins.h b/clang/include/clang/Basic/Builtins.h index 0420b5547a5682..08b0c4d1ae6cfa 100644 --- a/clang/include/clang/Basic/Builtins.h +++ b/clang/include/clang/Basic/Builtins.h @@ -16,12 +16,14 @@ #define LLVM_CLANG_BASIC_BUILTINS_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/STLFunctionalExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringTable.h" #include "llvm/TargetParser/Triple.h" #include <cstring> +#include <memory> // VC++ defines 'alloca' as an object-like macro, which interferes with our // builtins. @@ -29,7 +31,6 @@ namespace clang { class TargetInfo; -class IdentifierTable; class LangOptions; enum LanguageID : uint16_t { @@ -229,32 +230,99 @@ struct InfosShard { CLANG_TARGET_BUILTIN_DETAIL_STR_OFFSETS(ID, TYPE, ATTRS, FEATURE), \ HeaderDesc::HEADER, LANG}, +/// The builtins of a target and an optional aux target: their shards, and a +/// hash table from their names to their builtin IDs. +/// +/// It contains every builtin of the targets, whether or not it's supported by +/// some language options; \c Context checks that when looking a name up. It's +/// immutable, so any number of contexts for the same targets can use it, also +/// concurrently. +class TargetBuiltins { + /// Open addressing with linear probing. A slot holds the hash of the name in + /// the upper 32 bits and the builtin ID in the lower 32 bits, or zero if + /// it's empty (zero is \c NotBuiltin). + std::unique_ptr<uint64_t[]> Slots; + size_t Mask = 0; + + /// The target-independent shard, then the target's and the aux target's + /// shards: the order of their builtin IDs. + llvm::SmallVector<InfosShard, 16> Shards; + unsigned NumTargetShards = 0; + + unsigned NumTargetBuiltins = 0; + unsigned NumAuxTargetBuiltins = 0; + + /// Whether the builtin with \p ID is named \p Name. + bool hasName(unsigned ID, llvm::StringRef Name) const; + +public: + /// Collect the builtins of \p Target and \p AuxTarget, which may be null. + TargetBuiltins(const TargetInfo &Target, const TargetInfo *AuxTarget); + + /// The shards of the target's builtins. + llvm::ArrayRef<InfosShard> getTargetShards() const { + return llvm::ArrayRef(Shards).slice(1, NumTargetShards); + } + + /// The shards of the aux target's builtins. + llvm::ArrayRef<InfosShard> getAuxTargetShards() const { + return llvm::ArrayRef(Shards).drop_front(1 + NumTargetShards); + } + + unsigned getNumTargetBuiltins() const { return NumTargetBuiltins; } + unsigned getNumAuxTargetBuiltins() const { return NumAuxTargetBuiltins; } + + /// Return the shard of the builtin with \p ID and its info. + std::pair<const InfosShard &, const Info &> + getShardAndInfo(unsigned ID) const; + + /// Return the IDs of all builtins named \p Name, in no particular order. + llvm::SmallVector<unsigned, 2> lookup(llvm::StringRef Name) const; +}; + /// Holds information about both target-independent and /// target-specific builtins, allowing easy queries by clients. /// -/// Builtins from an optional auxiliary target are stored in -/// AuxTSRecords. Their IDs are shifted up by TSRecords.size() and need to -/// be translated back with getAuxBuiltinID() before use. +/// Builtins from an optional auxiliary target follow the target's builtins. +/// Their IDs are shifted up by the number of target builtins and need to be +/// translated back with getAuxBuiltinID() before use. class Context { - llvm::SmallVector<InfosShard> BuiltinShards; - - llvm::SmallVector<InfosShard> TargetShards; - llvm::SmallVector<InfosShard> AuxTargetShards; + /// The builtins of the target and the aux target. Null for a context without + /// a target, which only has the target-independent builtins. + std::shared_ptr<const TargetBuiltins> Builtins; + /// Copies of the counts in Builtins, so that the inline isAuxBuiltinID() and + /// getAuxBuiltinID() don't need to go through it. unsigned NumTargetBuiltins = 0; unsigned NumAuxTargetBuiltins = 0; public: + /// Create a context with only the target-independent builtins. It doesn't + /// know any builtin names: \c lookupBuiltinID() always returns + /// \c NotBuiltin. Context(); - /// Perform target-specific initialization - /// \param AuxTarget Target info to incorporate builtins from. May be nullptr. - void InitializeTarget(const TargetInfo &Target, const TargetInfo *AuxTarget); - - /// Mark the identifiers for all the builtins with their - /// appropriate builtin ID # and mark any non-portable builtin identifiers as - /// such. - void initializeBuiltins(IdentifierTable &Table, const LangOptions& LangOpts); + /// Create a context with the builtins of \p Target and \p AuxTarget, which + /// may be null. + Context(const TargetInfo &Target, const TargetInfo *AuxTarget); + + /// Create a context with \p Builtins, which can be shared with other + /// contexts for the same targets. + explicit Context(std::shared_ptr<const TargetBuiltins> Builtins); + + /// Return the ID of the builtin named \p Name, or \c NotBuiltin if there's + /// none, \p LangOpts doesn't support it, or -fno-builtin-* disables it. + /// \c IdentifierTable::setBuiltinInfo() makes the table call this for each + /// identifier it creates. + unsigned lookupBuiltinID(llvm::StringRef Name, + const LangOptions &LangOpts) const; + + /// Call \p Fn with the name of every builtin supported by \p LangOpts, + /// whether or not the identifier table contains an identifier for it. Does + /// nothing for a context without a target. The order is unspecified, and + /// names might repeat. + void forEachBuiltinName(const LangOptions &LangOpts, + llvm::function_ref<void(llvm::StringRef)> Fn) const; /// Return the identifier name for the specified builtin, /// e.g. "__builtin_abs". diff --git a/clang/include/clang/Basic/IdentifierTable.h b/clang/include/clang/Basic/IdentifierTable.h index ac1acb7ddac61b..a9e77001bce748 100644 --- a/clang/include/clang/Basic/IdentifierTable.h +++ b/clang/include/clang/Basic/IdentifierTable.h @@ -699,6 +699,19 @@ class IdentifierTable { IdentifierInfoLookup* ExternalLookup; + /// Assigns builtin IDs to identifiers as they get created, for the builtins + /// that BuiltinLangOpts supports. + const Builtin::Context *Builtins = nullptr; + const LangOptions *BuiltinLangOpts = nullptr; + + /// Set the builtin ID of a new identifier if it names a builtin. + void assignBuiltinID(IdentifierInfo &II) { + if (Builtins) + if (unsigned ID = + Builtins->lookupBuiltinID(II.getName(), *BuiltinLangOpts)) + II.setBuiltinID(ID); + } + public: /// Create the identifier table. explicit IdentifierTable(IdentifierInfoLookup *ExternalLookup = nullptr); @@ -718,6 +731,14 @@ class IdentifierTable { return ExternalLookup; } + /// Assign builtin IDs from \p Builtins to the identifiers in the table, and + /// to every identifier that gets created from now on, for the builtins + /// supported by \p LangOpts. This lets the table avoid creating identifiers + /// for all builtins upfront. \p Builtins and \p LangOpts must outlive the + /// table, and \p LangOpts must not change afterwards. + void setBuiltinInfo(const Builtin::Context &Builtins, + const LangOptions &LangOpts); + llvm::BumpPtrAllocator& getAllocator() { return HashTable.getAllocator(); } @@ -745,6 +766,8 @@ class IdentifierTable { // contents. II->Entry = &Entry; + assignBuiltinID(*II); + return *II; } @@ -776,6 +799,8 @@ class IdentifierTable { // contents. II->Entry = &Entry; + assignBuiltinID(*II); + // If this is the 'import' or 'module' contextual keyword, mark it as such. if (Name == "import") II->setKeywordImport(true); diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h index c001229eea7fd8..62f099d666c9c8 100644 --- a/clang/include/clang/Frontend/CompilerInstance.h +++ b/clang/include/clang/Frontend/CompilerInstance.h @@ -64,6 +64,10 @@ class SourceManager; class TargetInfo; enum class DisableValidationForModuleKind; +namespace Builtin { +class TargetBuiltins; +} // namespace Builtin + /// CompilerInstance - Helper class for managing a single instance of the Clang /// compiler. /// @@ -113,6 +117,10 @@ class CompilerInstance : public ModuleLoader { /// The cache of PCM files. std::shared_ptr<ModuleCache> ModCache; + /// The builtins of the instance's target and aux target, shared with the + /// module builds it requests, which have the same targets. + std::shared_ptr<const Builtin::TargetBuiltins> SharedBuiltins; + /// Directory dependencies from the instance that requested this module build. /// An inferred framework is built from printed module map text rather than by /// repeating the inference, so its \c Frameworks listing is only seen there. diff --git a/clang/include/clang/Lex/Preprocessor.h b/clang/include/clang/Lex/Preprocessor.h index 8d15ed7e8afd85..bd7bd08aa546dc 100644 --- a/clang/include/clang/Lex/Preprocessor.h +++ b/clang/include/clang/Lex/Preprocessor.h @@ -88,7 +88,8 @@ class NoTrivialPPDirectiveTracer; namespace Builtin { class Context; -} +class TargetBuiltins; +} // namespace Builtin /// Stores token information for comparing actual tokens with /// predefined values. Only handles simple tokens and identifiers. @@ -1252,8 +1253,12 @@ class Preprocessor { /// lifetime of the preprocessor. /// \param AuxTarget is owned by the caller and must remain valid for /// the lifetime of the preprocessor. - void Initialize(const TargetInfo &Target, - const TargetInfo *AuxTarget = nullptr); + /// \param SharedBuiltins are the builtins of \p Target and \p AuxTarget. + /// They must have been collected for exactly these targets (or targets with + /// the same builtins). If null, the preprocessor collects them. + void Initialize( + const TargetInfo &Target, const TargetInfo *AuxTarget = nullptr, + std::shared_ptr<const Builtin::TargetBuiltins> SharedBuiltins = nullptr); /// Initialize the preprocessor to parse a model file /// diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp index 7ea55b268cf8f8..7e05045046be2d 100644 --- a/clang/lib/Basic/Builtins.cpp +++ b/clang/lib/Basic/Builtins.cpp @@ -12,11 +12,14 @@ #include "clang/Basic/Builtins.h" #include "BuiltinTargetFeatures.h" -#include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TargetInfo.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/MathExtras.h" +#include "llvm/Support/xxhash.h" +#include <memory> using namespace clang; const char *HeaderDesc::getName() const { @@ -44,32 +47,16 @@ static constexpr Builtin::Info BuiltinInfos[] = { }; static_assert(std::size(BuiltinInfos) == NumBuiltins); +/// The shard of the target-independent builtins, which every context has. +static const Builtin::InfosShard TargetIndependentShards[] = { + {&BuiltinStrings, BuiltinInfos}}; + std::pair<const Builtin::InfosShard &, const Builtin::Info &> Builtin::Context::getShardAndInfo(unsigned ID) const { - assert((ID < (Builtin::FirstTSBuiltin + NumTargetBuiltins + - NumAuxTargetBuiltins)) && - "Invalid builtin ID!"); - - ArrayRef<InfosShard> Shards = BuiltinShards; - if (isAuxBuiltinID(ID)) { - Shards = AuxTargetShards; - ID = getAuxBuiltinID(ID) - Builtin::FirstTSBuiltin; - } else if (ID >= Builtin::FirstTSBuiltin) { - Shards = TargetShards; - ID -= Builtin::FirstTSBuiltin; - } - - // Loop over the shards to find the one matching this ID. We don't expect to - // have many shards and so its better to search linearly than with a binary - // search. - for (const auto &Shard : Shards) { - if (ID < Shard.Infos.size()) { - return {Shard, Shard.Infos[ID]}; - } - - ID -= Shard.Infos.size(); - } - llvm_unreachable("Invalid target builtin shard structure!"); + if (Builtins) + return Builtins->getShardAndInfo(ID); + assert(ID < Builtin::FirstTSBuiltin && "Invalid builtin ID!"); + return {TargetIndependentShards[0], BuiltinInfos[ID]}; } /// Return a non-owning StringRef of the builtin's name, reconstructed into Buf. @@ -120,25 +107,19 @@ const char *Builtin::Context::getRequiredFeatures(unsigned ID) const { return (*Shard.Strings)[I.Offsets.Features].data(); } -Builtin::Context::Context() : BuiltinShards{{&BuiltinStrings, BuiltinInfos}} {} +Builtin::Context::Context() = default; -void Builtin::Context::InitializeTarget(const TargetInfo &Target, - const TargetInfo *AuxTarget) { - assert(TargetShards.empty() && "Already initialized target?"); - assert(NumTargetBuiltins == 0 && "Already initialized target?"); - TargetShards = Target.getTargetBuiltins(); - for (const auto &Shard : TargetShards) - NumTargetBuiltins += Shard.Infos.size(); - if (AuxTarget) { - AuxTargetShards = AuxTarget->getTargetBuiltins(); - for (const auto &Shard : AuxTargetShards) - NumAuxTargetBuiltins += Shard.Infos.size(); - } -} +Builtin::Context::Context(const TargetInfo &Target, const TargetInfo *AuxTarget) + : Context(std::make_shared<const TargetBuiltins>(Target, AuxTarget)) {} + +Builtin::Context::Context(std::shared_ptr<const TargetBuiltins> Builtins) + : Builtins(std::move(Builtins)), + NumTargetBuiltins(this->Builtins->getNumTargetBuiltins()), + NumAuxTargetBuiltins(this->Builtins->getNumAuxTargetBuiltins()) {} bool Builtin::Context::isBuiltinFunc(llvm::StringRef FuncName) { bool InStdNamespace = FuncName.consume_front("std-"); - for (const auto &Shard : {InfosShard{&BuiltinStrings, BuiltinInfos}}) + for (const auto &Shard : TargetIndependentShards) if (llvm::StringRef FuncNameSuffix = FuncName; FuncNameSuffix.consume_front(Shard.NamePrefix)) for (const auto &I : Shard.Infos) @@ -309,52 +290,135 @@ bool Builtin::Context::shouldGenerateFPMathIntrinsic( return GenerateIntrinsics; } -/// initializeBuiltins - Mark the identifiers for all the builtins with their -/// appropriate builtin ID # and mark any non-portable builtin identifiers as -/// such. -void Builtin::Context::initializeBuiltins(IdentifierTable &Table, - const LangOptions &LangOpts) { - { - unsigned ID = 0; - llvm::SmallString<256> NameBuf; - // Step #1: mark all target-independent builtins with their ID's. - for (const auto &Shard : BuiltinShards) - for (const auto &I : Shard.Infos) { - // If this is a real builtin (ID != 0) and is supported, add it. - if (ID != 0 && builtinIsSupported(*Shard.Strings, I, LangOpts)) - Table.get(getBuiltinNameInto(Shard, I, NameBuf)).setBuiltinID(ID); - ++ID; - } - assert(ID == FirstTSBuiltin && "Should have added all non-target IDs!"); - - // Step #2: Register target-specific builtins. - for (const auto &Shard : TargetShards) - for (const auto &I : Shard.Infos) { - if (builtinIsSupported(*Shard.Strings, I, LangOpts)) - Table.get(getBuiltinNameInto(Shard, I, NameBuf)).setBuiltinID(ID); - ++ID; - } +static uint32_t hashBuiltinName(StringRef Name) { + return static_cast<uint32_t>(llvm::xxh3_64bits(Name)); +} - // Step #3: Register target-specific builtins for AuxTarget. - for (const auto &Shard : AuxTargetShards) - for (const auto &I : Shard.Infos) { - Table.get(getBuiltinNameInto(Shard, I, NameBuf)).setBuiltinID(ID); - ++ID; +Builtin::TargetBuiltins::TargetBuiltins(const TargetInfo &Target, + const TargetInfo *AuxTarget) { + llvm::append_range(Shards, TargetIndependentShards); + llvm::append_range(Shards, Target.getTargetBuiltins()); + NumTargetShards = Shards.size() - 1; + if (AuxTarget) + llvm::append_range(Shards, AuxTarget->getTargetBuiltins()); + for (const InfosShard &Shard : getTargetShards()) + NumTargetBuiltins += Shard.Infos.size(); + for (const InfosShard &Shard : getAuxTargetShards()) + NumAuxTargetBuiltins += Shard.Infos.size(); + + size_t NumNames = 0; + for (const InfosShard &Shard : Shards) + NumNames += Shard.Infos.size(); + // Keep the load factor at or below 1/2. + size_t NumSlots = llvm::PowerOf2Ceil(NumNames * 2); + Slots = std::make_unique<uint64_t[]>(NumSlots); + Mask = NumSlots - 1; + unsigned ID = 0; + SmallString<256> NameBuf; + for (const InfosShard &Shard : Shards) { + for (const Info &I : Shard.Infos) { + // Skip the "not a builtin" entry. + if (ID != NotBuiltin) { + uint32_t Hash = hashBuiltinName(getBuiltinNameInto(Shard, I, NameBuf)); + size_t Slot = Hash & Mask; + while (Slots[Slot]) + Slot = (Slot + 1) & Mask; + Slots[Slot] = (uint64_t(Hash) << 32) | ID; } + ++ID; + } } +} - // Step #4: Unregister any builtins specified by -fno-builtin-foo. - for (llvm::StringRef Name : LangOpts.NoBuiltinFuncs) { - bool InStdNamespace = Name.consume_front("std-"); - auto NameIt = Table.find(Name); - if (NameIt != Table.end()) { - unsigned ID = NameIt->second->getBuiltinID(); - if (ID != Builtin::NotBuiltin && isPredefinedLibFunction(ID) && - isInStdNamespace(ID) == InStdNamespace) { - NameIt->second->clearBuiltinID(); - } - } +std::pair<const Builtin::InfosShard &, const Builtin::Info &> +Builtin::TargetBuiltins::getShardAndInfo(unsigned ID) const { + assert(ID < FirstTSBuiltin + NumTargetBuiltins + NumAuxTargetBuiltins && + "Invalid builtin ID!"); + // Find the group of shards from the ID, then loop over the shards of the + // group to find the one matching this ID. We don't expect to have many + // shards and so its better to search linearly than with a binary search. + ArrayRef<InfosShard> Group = ArrayRef(Shards).take_front(1); + if (ID >= FirstTSBuiltin + NumTargetBuiltins) { + Group = getAuxTargetShards(); + ID -= FirstTSBuiltin + NumTargetBuiltins; + } else if (ID >= FirstTSBuiltin) { + Group = getTargetShards(); + ID -= FirstTSBuiltin; + } + for (const InfosShard &Shard : Group) { + if (ID < Shard.Infos.size()) + return {Shard, Shard.Infos[ID]}; + ID -= Shard.Infos.size(); + } + llvm_unreachable("Invalid target builtin shard structure!"); +} + +bool Builtin::TargetBuiltins::hasName(unsigned ID, StringRef Name) const { + const auto &[Shard, I] = getShardAndInfo(ID); + return Name.consume_front(Shard.NamePrefix) && + Name == (*Shard.Strings)[I.Offsets.Name]; +} + +SmallVector<unsigned, 2> Builtin::TargetBuiltins::lookup(StringRef Name) const { + SmallVector<unsigned, 2> IDs; + uint32_t Hash = hashBuiltinName(Name); + for (size_t Slot = Hash & Mask; uint64_t Entry = Slots[Slot]; + Slot = (Slot + 1) & Mask) { + unsigned ID = static_cast<uint32_t>(Entry); + if (Entry >> 32 == Hash && hasName(ID, Name)) + IDs.push_back(ID); + } + return IDs; +} + +unsigned Builtin::Context::lookupBuiltinID(StringRef Name, + const LangOptions &LangOpts) const { + // This needs to behave as if the builtins were registered in the order of + // their IDs, with later registrations overriding earlier ones: aux target + // builtins win over target builtins, which win over target-independent + // ones. Aux target builtins are registered even if unsupported. + if (!Builtins) + return NotBuiltin; + unsigned Result = NotBuiltin; + for (unsigned ID : Builtins->lookup(Name)) { + if (ID <= Result) + continue; + const auto &[Shard, I] = getShardAndInfo(ID); + if (isAuxBuiltinID(ID) || builtinIsSupported(*Shard.Strings, I, LangOpts)) + Result = ID; } + if (Result == NotBuiltin) + return NotBuiltin; + + // Library builtins can be disabled with -fno-builtin-foo, or with + // -fno-builtin-std-foo for those in namespace std. + if (isPredefinedLibFunction(Result)) { + bool InStdNamespace = isInStdNamespace(Result); + for (StringRef NoBuiltin : LangOpts.NoBuiltinFuncs) + if (NoBuiltin.consume_front("std-") == InStdNamespace && + NoBuiltin == Name) + return NotBuiltin; + } + return Result; +} + +void Builtin::Context::forEachBuiltinName( + const LangOptions &LangOpts, llvm::function_ref<void(StringRef)> Fn) const { + if (!Builtins) + return; + llvm::SmallString<256> NameBuf; + // Skip the "not a builtin" entry. + for (const auto &Shard : TargetIndependentShards) + for (const auto &I : Shard.Infos.drop_front()) + if (builtinIsSupported(*Shard.Strings, I, LangOpts)) + Fn(getBuiltinNameInto(Shard, I, NameBuf)); + for (const auto &Shard : Builtins->getTargetShards()) + for (const auto &I : Shard.Infos) + if (builtinIsSupported(*Shard.Strings, I, LangOpts)) + Fn(getBuiltinNameInto(Shard, I, NameBuf)); + for (const auto &Shard : Builtins->getAuxTargetShards()) + for (const auto &I : Shard.Infos) + Fn(getBuiltinNameInto(Shard, I, NameBuf)); } unsigned Builtin::Context::getRequiredVectorWidth(unsigned ID) const { diff --git a/clang/lib/Basic/IdentifierTable.cpp b/clang/lib/Basic/IdentifierTable.cpp index aadf224211508c..369ec9199c4ffe 100644 --- a/clang/lib/Basic/IdentifierTable.cpp +++ b/clang/lib/Basic/IdentifierTable.cpp @@ -63,7 +63,7 @@ IdentifierIterator *IdentifierInfoLookup::getIdentifiers() { } IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup) - : HashTable(8192), // Start with space for 8K identifiers. + : HashTable(2048), // Start with space for 2K identifiers. ExternalLookup(ExternalLookup) {} IdentifierTable::IdentifierTable(const LangOptions &LangOpts, @@ -74,6 +74,15 @@ IdentifierTable::IdentifierTable(const LangOptions &LangOpts, AddKeywords(LangOpts); } +void IdentifierTable::setBuiltinInfo(const Builtin::Context &Builtins, + const LangOptions &LangOpts) { + this->Builtins = &Builtins; + BuiltinLangOpts = &LangOpts; + for (auto &Entry : HashTable) + if (Entry.second) + assignBuiltinID(*Entry.second); +} + //===----------------------------------------------------------------------===// // Language Keyword Implementation //===----------------------------------------------------------------------===// diff --git a/clang/lib/Frontend/ChainedIncludesSource.cpp b/clang/lib/Frontend/ChainedIncludesSource.cpp index 7a552a572ca78d..60085c701b645a 100644 --- a/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -152,11 +152,7 @@ clang::createChainedIncludesSource(CompilerInstance &CI, Clang->setASTConsumer(std::move(consumer)); Clang->createSema(TU_Prefix, nullptr); - if (firstInclude) { - Preprocessor &PP = Clang->getPreprocessor(); - PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), - PP.getLangOpts()); - } else { + if (!firstInclude) { assert(!SerialBufs.empty()); SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs; // TODO: Pass through the existing MemoryBuffer instances instead of diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index 0b42e03d1320ef..ad4a3a4ba5d135 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -11,6 +11,7 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/Basic/AtomicLineLogger.h" +#include "clang/Basic/Builtins.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticFrontend.h" @@ -482,7 +483,10 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { /*IdentifierInfoLookup=*/nullptr, /*OwnsHeaderSearch=*/true, TUKind); getTarget().adjust(getDiagnostics(), getLangOpts(), getAuxTarget()); - PP->Initialize(getTarget(), getAuxTarget()); + if (!SharedBuiltins) + SharedBuiltins = std::make_shared<const Builtin::TargetBuiltins>( + getTarget(), getAuxTarget()); + PP->Initialize(getTarget(), getAuxTarget(), SharedBuiltins); if (PPOpts.DetailedRecord) PP->createPreprocessingRecord(); @@ -1236,6 +1240,10 @@ std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl( std::move(Invocation), getPCHContainerOperations(), std::move(ModCache)); auto &Instance = *InstancePtr; + // The module build has the same targets as this instance, so it can use + // the same builtins. + Instance.SharedBuiltins = SharedBuiltins; + auto &Inv = Instance.getInvocation(); if (ThreadSafeConfig) { diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index 001ad1fd1e654c..1e9bbdeec5e187 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -987,9 +987,6 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, CI.setFileManager(AST->getFileManagerPtr()); CI.setSourceManager(AST->getSourceManagerPtr()); CI.setPreprocessor(AST->getPreprocessorPtr()); - Preprocessor &PP = CI.getPreprocessor(); - PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), - PP.getLangOpts()); CI.setASTContext(AST->getASTContextPtr()); setCurrentInput(Input, std::move(AST)); @@ -1294,9 +1291,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, if (!CI.getASTContext().getExternalSource()) return false; } - // If modules are enabled, create the AST reader before creating - // any builtins, so that all declarations know that they might be - // extended by an external source. + // If modules are enabled, create the AST reader before Sema creates + // any builtin declarations, so that all declarations know that they + // might be extended by an external source. if (CI.getLangOpts().Modules || !CI.hasASTContext() || !CI.getASTContext().getExternalSource()) { CI.createASTReader(); @@ -1310,21 +1307,6 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, return false; } - // Initialize built-in info as long as we aren't using an external AST - // source. - if (CI.getLangOpts().Modules || !CI.hasASTContext() || - !CI.getASTContext().getExternalSource()) { - Preprocessor &PP = CI.getPreprocessor(); - PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), - PP.getLangOpts()); - } else { - // FIXME: If this is a problem, recover from it by creating a multiplex - // source. - assert((!CI.getLangOpts().Modules || CI.getASTReader()) && - "modules enabled but created an external source that " - "doesn't support modules"); - } - // If we were asked to load any module files, do so now. for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles) { serialization::ModuleFile *Loaded = nullptr; diff --git a/clang/lib/Lex/Preprocessor.cpp b/clang/lib/Lex/Preprocessor.cpp index d3a56f726b7b85..32c06f84a93902 100644 --- a/clang/lib/Lex/Preprocessor.cpp +++ b/clang/lib/Lex/Preprocessor.cpp @@ -200,8 +200,29 @@ Preprocessor::~Preprocessor() { delete &HeaderInfo; } -void Preprocessor::Initialize(const TargetInfo &Target, - const TargetInfo *AuxTarget) { +#ifndef NDEBUG +/// Whether \p Builtins were collected for \p Target and \p AuxTarget. +static bool areBuiltinsFor(const Builtin::TargetBuiltins &Builtins, + const TargetInfo &Target, + const TargetInfo *AuxTarget) { + auto SameShards = [](ArrayRef<Builtin::InfosShard> A, + ArrayRef<Builtin::InfosShard> B) { + return llvm::equal( + A, B, [](const Builtin::InfosShard &X, const Builtin::InfosShard &Y) { + return X.Infos.data() == Y.Infos.data() && + X.Infos.size() == Y.Infos.size(); + }); + }; + return SameShards(Builtins.getTargetShards(), Target.getTargetBuiltins()) && + SameShards(Builtins.getAuxTargetShards(), + AuxTarget ? AuxTarget->getTargetBuiltins() + : SmallVector<Builtin::InfosShard>()); +} +#endif + +void Preprocessor::Initialize( + const TargetInfo &Target, const TargetInfo *AuxTarget, + std::shared_ptr<const Builtin::TargetBuiltins> SharedBuiltins) { assert((!this->Target || this->Target == &Target) && "Invalid override of target information"); this->Target = &Target; @@ -210,13 +231,23 @@ void Preprocessor::Initialize(const TargetInfo &Target, "Invalid override of aux target information."); this->AuxTarget = AuxTarget; - // Initialize information about built-ins. - BuiltinInfo->InitializeTarget(Target, AuxTarget); + // Initialize information about built-ins. The context is replaced rather + // than created here because an ASTContext may already refer to it. + assert( + (!SharedBuiltins || areBuiltinsFor(*SharedBuiltins, Target, AuxTarget)) && + "Builtins collected for other targets"); + *BuiltinInfo = SharedBuiltins ? Builtin::Context(std::move(SharedBuiltins)) + : Builtin::Context(Target, AuxTarget); HeaderInfo.setTarget(Target); // Populate the identifier table with info about keywords for the current language. Identifiers.AddKeywords(LangOpts); + // Make the identifier table assign builtin IDs. This is done before any AST + // file gets loaded, so that the identifiers read from AST files get their + // builtin IDs from this compilation rather than from the AST file. + Identifiers.setBuiltinInfo(*BuiltinInfo, LangOpts); + // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo. setTUFPEvalMethod(getTargetInfo().getFPEvalMethod()); diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp index 5e061103437670..fc94b3cc55cd8d 100644 --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -5449,6 +5449,9 @@ std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer( // FIXME: Re-add the ability to skip very unlikely potential corrections. for (const auto &I : Context.Idents) Consumer->FoundName(I.getKey()); + // Builtins only get added to the identifier table once used. + Context.BuiltinInfo.forEachBuiltinName( + getLangOpts(), [&](StringRef Name) { Consumer->FoundName(Name); }); // Walk through identifiers in external identifier sources. // FIXME: Re-add the ability to skip very unlikely potential corrections. diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index db04c06f3cee73..ecdd18ddb6c9db 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -1284,8 +1284,20 @@ IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, // Token IDs are read-only. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) II->revertTokenIDToIdentifier(); - if (!F.isModule()) + if (!F.isModule()) { + // Restore the Objective-C keyword or notable identifier ID, but not the + // builtin ID: the identifier table assigns builtin IDs based on this + // compilation's target and language options, which may disable builtins + // differently from the AST file's (-fno-builtin-foo isn't validated). + // TODO: Simplify this to: if the identifier has no builtin ID, restore + // ObjCOrBuiltinID, then clear it if it's a builtin ID. + unsigned BuiltinID = II->getBuiltinID(); II->setObjCOrBuiltinID(ObjCOrBuiltinID); + if (BuiltinID != Builtin::NotBuiltin) + II->setBuiltinID(BuiltinID); + else if (II->getBuiltinID() != Builtin::NotBuiltin) + II->clearBuiltinID(); + } assert(II->isExtensionToken() == ExtensionToken && "Incorrect extension token flag"); (void)ExtensionToken; @@ -5256,8 +5268,8 @@ ASTReader::ASTReadResult ASTReader::ReadAST(ModuleFileName FileName, } } - // Builtins and library builtins have already been initialized. Mark all - // identifiers as out-of-date, so that they are deserialized on first use. + // Mark all identifiers as out-of-date, so that they are deserialized on + // first use. if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile) for (auto &Id : PP.getIdentifierTable()) Id.second->setOutOfDate(true); diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp index 3ae7ac0e8c9fa0..f59d42e36f824d 100644 --- a/clang/lib/Serialization/ASTWriter.cpp +++ b/clang/lib/Serialization/ASTWriter.cpp @@ -3929,6 +3929,9 @@ bool IsInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset, bool IsModule, bool IsCPlusPlus) { bool NeedDecls = !IsModule || !IsCPlusPlus; + // TODO: The reader no longer restores builtin IDs from a PCH (they come + // from the importing compilation), so a builtin ID no longer makes an + // identifier interesting. Dropping it changes which identifiers get written. bool IsInteresting = II->getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable || II->getBuiltinID() != Builtin::ID::NotBuiltin || diff --git a/clang/test/Modules/builtins-unused-in-module.c b/clang/test/Modules/builtins-unused-in-module.c new file mode 100644 index 00000000000000..e5f887ade0b86c --- /dev/null +++ b/clang/test/Modules/builtins-unused-in-module.c @@ -0,0 +1,29 @@ +// Builtins are only stored in a module if it uses them. Check that importers +// can use builtins that the module doesn't know about, and builtins that the +// module uses. Identifiers from the module are deserialized differently in C +// and C++. + +// RUN: rm -rf %t +// RUN: split-file %s %t +// RUN: %clang_cc1 -triple arm64-apple-macosx -fmodules -fimplicit-module-maps \ +// RUN: -fmodules-cache-path=%t/cache -I %t -fsyntax-only -verify %t/tu.c +// RUN: %clang_cc1 -triple arm64-apple-macosx -fmodules -fimplicit-module-maps \ +// RUN: -fmodules-cache-path=%t/cache -I %t -fsyntax-only -verify \ +// RUN: -x c++ %t/tu.c + +//--- module.modulemap +module M { header "M.h" } + +//--- M.h +static inline int m_popcount(unsigned x) { return __builtin_popcount(x); } +#define M_CTZ(x) __builtin_ctz(x) + +//--- tu.c +// expected-no-diagnostics +#include "M.h" +_Static_assert(__builtin_popcount(7) == 3, ""); +_Static_assert(M_CTZ(8) == 3, ""); +_Static_assert(__builtin_clz(1) == 31, ""); +#if !__has_builtin(__builtin_arm_rbit) +#error "missing target builtin" +#endif diff --git a/clang/test/PCH/builtins-no-builtin-flags.c b/clang/test/PCH/builtins-no-builtin-flags.c new file mode 100644 index 00000000000000..e6507b99c321cc --- /dev/null +++ b/clang/test/PCH/builtins-no-builtin-flags.c @@ -0,0 +1,46 @@ +// Whether an identifier names a builtin follows the -fno-builtin-* options of +// the compilation that imports a PCH, as for modules, even if the PCH records +// the identifier. A function declared by the PCH keeps whether it was declared +// as a builtin, though. + +// RUN: rm -rf %t +// RUN: split-file %s %t + +// The PCH only mentions strlen in a macro. +// RUN: %clang_cc1 -triple arm64-apple-macosx -emit-pch -o %t/mentions.pch \ +// RUN: %t/mentions.h +// RUN: %clang_cc1 -triple arm64-apple-macosx -emit-pch \ +// RUN: -o %t/mentions-no-strlen.pch -fno-builtin-strlen %t/mentions.h +// RUN: %clang_cc1 -triple arm64-apple-macosx -include-pch %t/mentions.pch \ +// RUN: -fsyntax-only -verify=builtin %t/tu.c +// RUN: %clang_cc1 -triple arm64-apple-macosx -include-pch %t/mentions.pch \ +// RUN: -fno-builtin-strlen -fsyntax-only -verify=no-builtin %t/tu.c +// RUN: %clang_cc1 -triple arm64-apple-macosx \ +// RUN: -include-pch %t/mentions-no-strlen.pch -fsyntax-only -verify=builtin \ +// RUN: %t/tu.c + +// The PCH declares strlen. +// RUN: %clang_cc1 -triple arm64-apple-macosx -emit-pch -o %t/declares.pch \ +// RUN: %t/declares.h +// RUN: %clang_cc1 -triple arm64-apple-macosx -emit-pch \ +// RUN: -o %t/declares-no-strlen.pch -fno-builtin-strlen %t/declares.h +// RUN: %clang_cc1 -triple arm64-apple-macosx -include-pch %t/declares.pch \ +// RUN: -fsyntax-only -verify=builtin -DDECLARED %t/tu.c +// RUN: %clang_cc1 -triple arm64-apple-macosx \ +// RUN: -include-pch %t/declares-no-strlen.pch -fsyntax-only \ +// RUN: -verify=no-builtin -DDECLARED %t/tu.c + +//--- mentions.h +#define LEN(S) strlen(S) + +//--- declares.h +#define LEN(S) strlen(S) +unsigned long strlen(const char *); + +//--- tu.c +// builtin-no-diagnostics +#ifndef DECLARED +unsigned long strlen(const char *); +#endif +// no-builtin-error@+1 {{static assertion expression is not an integral constant expression}} +_Static_assert(LEN("abc") == 3, ""); diff --git a/clang/test/PCH/builtins-unused-in-pch.c b/clang/test/PCH/builtins-unused-in-pch.c new file mode 100644 index 00000000000000..91e29d61e47bbf --- /dev/null +++ b/clang/test/PCH/builtins-unused-in-pch.c @@ -0,0 +1,45 @@ +// Builtins are only stored in a PCH if it uses them. Check that the importer +// can use builtins the PCH doesn't know about, including target builtins, and +// that it applies its own -fno-builtin-* to those. + +// RUN: rm -rf %t +// RUN: split-file %s %t + +// RUN: %clang_cc1 -triple arm64-apple-macosx -target-feature +neon \ +// RUN: -emit-pch -o %t/prefix.pch %t/prefix.h +// RUN: %clang_cc1 -triple arm64-apple-macosx -target-feature +neon \ +// RUN: -include-pch %t/prefix.pch -fsyntax-only -verify %t/tu.c +// RUN: %clang_cc1 -triple arm64-apple-macosx -target-feature +neon \ +// RUN: -include-pch %t/prefix.pch -fsyntax-only -verify=no-strlen \ +// RUN: -fno-builtin-strlen %t/tu.c + +// Same with chained PCHs. +// RUN: %clang_cc1 -triple arm64-apple-macosx -target-feature +neon \ +// RUN: -chain-include %t/prefix.h -chain-include %t/chained.h \ +// RUN: -fsyntax-only -verify -DCHAINED %t/tu.c + +//--- prefix.h +int uses_one_builtin(unsigned x) { return __builtin_popcount(x); } + +//--- chained.h +_Static_assert(__builtin_ctz(8) == 3, ""); +#if !__has_builtin(__builtin_arm_rbit) +#error "missing target builtin" +#endif + +//--- tu.c +// expected-no-diagnostics +_Static_assert(__builtin_popcount(7) == 3, ""); +_Static_assert(__builtin_clz(1) == 31, ""); + +#if !__has_builtin(__builtin_neon_vaddq_v) || !__has_builtin(__builtin_arm_rbit) +#error "missing target builtins" +#endif + +#if !__has_builtin(__builtin_strlen) +#error "missing __builtin_strlen" +#endif + +unsigned long strlen(const char *); +// no-strlen-error@+1 {{static assertion expression is not an integral constant expression}} +_Static_assert(strlen("abc") == 3, ""); diff --git a/clang/test/Preprocessor/builtins-not-in-identifier-table.c b/clang/test/Preprocessor/builtins-not-in-identifier-table.c new file mode 100644 index 00000000000000..f310eecbcec92c --- /dev/null +++ b/clang/test/Preprocessor/builtins-not-in-identifier-table.c @@ -0,0 +1,11 @@ +// The identifier table only contains the builtins that get used, not all of +// the ~12,000 builtins of an AArch64 target. An empty file needs fewer than +// 2,000 identifiers (keywords and the like). + +// RUN: %clang_cc1 -triple arm64-apple-macosx -fsyntax-only -print-stats %s \ +// RUN: 2>&1 | FileCheck %s +// RUN: %clang_cc1 -triple arm64-apple-macosx -fsyntax-only -print-stats \ +// RUN: -x c++ %s 2>&1 | FileCheck %s + +// CHECK: *** Identifier Table Stats: +// CHECK-NEXT: # Identifiers: {{ *1?[0-9]{1,3}$}} diff --git a/clang/unittests/Basic/BuiltinsTest.cpp b/clang/unittests/Basic/BuiltinsTest.cpp new file mode 100644 index 00000000000000..1df41a8648d3ff --- /dev/null +++ b/clang/unittests/Basic/BuiltinsTest.cpp @@ -0,0 +1,344 @@ +//===- unittests/Basic/BuiltinsTest.cpp - Builtin::Context tests ----------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "clang/Basic/Builtins.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticOptions.h" +#include "clang/Basic/IdentifierTable.h" +#include "clang/Basic/LangOptions.h" +#include "clang/Basic/TargetInfo.h" +#include "clang/Basic/TargetOptions.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringSet.h" +#include "gtest/gtest.h" +#include <thread> +#include <vector> + +using namespace clang; + +namespace { + +class BuiltinsTest : public ::testing::Test { +protected: + DiagnosticOptions DiagOpts; + DiagnosticsEngine Diags{DiagnosticIDs::create(), DiagOpts, + new IgnoringDiagConsumer()}; + LangOptions LangOpts; + TargetOptions TargetOpts, AuxTargetOpts; + IntrusiveRefCntPtr<TargetInfo> Target, AuxTarget; + Builtin::Context Builtins; + std::unique_ptr<IdentifierTable> Idents; + + void initializeTarget(StringRef Triple, StringRef AuxTriple = "") { + TargetOpts.Triple = Triple.str(); + Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts); + ASSERT_TRUE(Target); + if (!AuxTriple.empty()) { + AuxTargetOpts.Triple = AuxTriple.str(); + AuxTarget = TargetInfo::CreateTargetInfo(Diags, AuxTargetOpts); + ASSERT_TRUE(AuxTarget); + } + Builtins = Builtin::Context(*Target, AuxTarget.get()); + Idents = std::make_unique<IdentifierTable>(LangOpts); + } + + void initialize(StringRef Triple, StringRef AuxTriple = "") { + initializeTarget(Triple, AuxTriple); + Idents->setBuiltinInfo(Builtins, LangOpts); + } + + unsigned getBuiltinID(StringRef Name) { + return Idents->get(Name).getBuiltinID(); + } + + bool contains(StringRef Name) const { + return Idents->find(Name) != Idents->end(); + } + + unsigned getNumBuiltins() const { + unsigned Num = Builtin::FirstTSBuiltin; + for (const TargetInfo *T : {Target.get(), AuxTarget.get()}) + if (T) + for (const Builtin::InfosShard &Shard : T->getTargetBuiltins()) + Num += Shard.Infos.size(); + return Num; + } +}; + +TEST_F(BuiltinsTest, IdentifiersAreCreatedOnDemand) { + initialize("arm64-apple-macosx"); + // Registering every builtin upfront would create ~12,000 identifiers. + EXPECT_LT(Idents->size(), 2000u); + EXPECT_FALSE(contains("__builtin_abs")); + EXPECT_FALSE(contains("__builtin_neon_vaddq_v")); + + EXPECT_EQ(getBuiltinID("__builtin_abs"), Builtin::BI__builtin_abs); + EXPECT_EQ(Idents->getOwn("__builtin_expect").getBuiltinID(), + Builtin::BI__builtin_expect); + EXPECT_EQ(getBuiltinID("not_a_builtin"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("__builtin_"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("__builtin_neon_"), Builtin::NotBuiltin); +} + +TEST_F(BuiltinsTest, ExistingIdentifiersAreResolved) { + initializeTarget("x86_64-linux-gnu"); + EXPECT_EQ(getBuiltinID("__builtin_abs"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("__builtin_ia32_pause"), Builtin::NotBuiltin); + + Idents->setBuiltinInfo(Builtins, LangOpts); + EXPECT_EQ(getBuiltinID("__builtin_abs"), Builtin::BI__builtin_abs); + unsigned ID = getBuiltinID("__builtin_ia32_pause"); + EXPECT_TRUE(Builtins.isTSBuiltin(ID)); + EXPECT_EQ(Builtins.getName(ID), "__builtin_ia32_pause"); +} + +TEST_F(BuiltinsTest, TargetBuiltins) { + initialize("arm64-apple-macosx"); + // Builtins in a shard without and with a name prefix. + for (StringRef Name : {"__builtin_arm_rbit", "__builtin_neon_vaddq_v", + "__builtin_sve_svadd_s8_x"}) { + unsigned ID = getBuiltinID(Name); + EXPECT_TRUE(Builtins.isTSBuiltin(ID)) << Name; + EXPECT_FALSE(Builtins.isAuxBuiltinID(ID)) << Name; + EXPECT_EQ(Builtins.getName(ID), Name); + } + EXPECT_EQ(getBuiltinID("__builtin_ia32_pause"), Builtin::NotBuiltin); +} + +TEST_F(BuiltinsTest, AuxTargetBuiltins) { + LangOpts.CUDA = true; + LangOpts.CPlusPlus = true; + initialize("nvptx64-nvidia-cuda", "x86_64-linux-gnu"); + unsigned ID = getBuiltinID("__builtin_ia32_pause"); + EXPECT_TRUE(Builtins.isAuxBuiltinID(ID)); + EXPECT_EQ(Builtins.getName(ID), "__builtin_ia32_pause"); + + ID = getBuiltinID("__nvvm_read_ptx_sreg_tid_x"); + EXPECT_TRUE(Builtins.isTSBuiltin(ID)); + EXPECT_FALSE(Builtins.isAuxBuiltinID(ID)); +} + +TEST_F(BuiltinsTest, UnsupportedBuiltins) { + initialize("x86_64-linux-gnu"); + EXPECT_EQ(getBuiltinID("__noop"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("objc_msgSend"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("move"), Builtin::NotBuiltin); +} + +TEST_F(BuiltinsTest, LanguageSpecificBuiltins) { + LangOpts.MicrosoftExt = true; + LangOpts.ObjC = true; + LangOpts.CPlusPlus = true; + initialize("x86_64-linux-gnu"); + EXPECT_EQ(getBuiltinID("__noop"), Builtin::BI__noop); + EXPECT_EQ(getBuiltinID("objc_msgSend"), Builtin::BIobjc_msgSend); + EXPECT_EQ(getBuiltinID("move"), Builtin::BImove); +} + +TEST_F(BuiltinsTest, NoBuiltinFuncs) { + LangOpts.NoBuiltinFuncs = {"malloc", "std-forward", "move"}; + LangOpts.CPlusPlus = true; + initialize("x86_64-linux-gnu"); + EXPECT_EQ(getBuiltinID("malloc"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("__builtin_malloc"), Builtin::BI__builtin_malloc); + EXPECT_EQ(getBuiltinID("free"), Builtin::BIfree); + // -fno-builtin-std-foo only applies to builtins in namespace std, and + // -fno-builtin-foo only to those outside of it. + EXPECT_EQ(getBuiltinID("forward"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("move"), Builtin::BImove); +} + +TEST_F(BuiltinsTest, NoBuiltin) { + LangOpts.NoBuiltin = true; + initialize("x86_64-linux-gnu"); + EXPECT_EQ(getBuiltinID("malloc"), Builtin::NotBuiltin); + EXPECT_EQ(getBuiltinID("__builtin_malloc"), Builtin::BI__builtin_malloc); +} + +TEST_F(BuiltinsTest, AuxTargetBuiltinsWinOverTargetBuiltins) { + // __mulh is a builtin of both x86-64 and AArch64. + LangOpts.MicrosoftExt = true; + initialize("x86_64-windows-msvc", "aarch64-windows-msvc"); + unsigned ID = getBuiltinID("__mulh"); + EXPECT_TRUE(Builtins.isAuxBuiltinID(ID)); + EXPECT_EQ(Builtins.getName(ID), "__mulh"); +} + +TEST_F(BuiltinsTest, ConcurrentContexts) { + // Contexts for different targets on several threads at once, each building + // its own index. + std::vector<std::thread> Threads; + std::vector<unsigned> IDs(8); + for (unsigned I = 0; I != IDs.size(); ++I) { + Threads.emplace_back([&, I] { + DiagnosticOptions DiagOpts; + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, + new IgnoringDiagConsumer()); + TargetOptions Opts; + Opts.Triple = I % 2 ? "riscv32-unknown-elf" : "mipsel-linux-gnu"; + IntrusiveRefCntPtr<TargetInfo> T = + TargetInfo::CreateTargetInfo(Diags, Opts); + LangOptions LO; + Builtin::Context Ctx(*T, nullptr); + IdentifierTable Table(LO); + Table.setBuiltinInfo(Ctx, LO); + IDs[I] = Table.get("__builtin_abs").getBuiltinID(); + }); + } + for (std::thread &Thread : Threads) + Thread.join(); + for (unsigned ID : IDs) + EXPECT_EQ(ID, Builtin::BI__builtin_abs); +} + +TEST_F(BuiltinsTest, SharedTargetBuiltins) { + initializeTarget("arm64-apple-macosx"); + // Contexts with different language options can share the builtins, which + // stay valid as long as any context uses them. + auto Shared = + std::make_shared<const Builtin::TargetBuiltins>(*Target, nullptr); + auto MSContext = std::make_unique<Builtin::Context>(Shared); + Builtin::Context Ctx(std::move(Shared)); + LangOptions MS; + MS.MicrosoftExt = true; + EXPECT_EQ(MSContext->lookupBuiltinID("__noop", MS), Builtin::BI__noop); + MSContext.reset(); + EXPECT_EQ(Ctx.lookupBuiltinID("__noop", LangOpts), Builtin::NotBuiltin); + EXPECT_EQ(Ctx.lookupBuiltinID("__builtin_abs", LangOpts), + Builtin::BI__builtin_abs); + EXPECT_TRUE( + Ctx.isTSBuiltin(Ctx.lookupBuiltinID("__builtin_neon_vaddq_v", LangOpts))); +} + +TEST_F(BuiltinsTest, ContextWithoutTarget) { + Builtin::Context Ctx; + EXPECT_EQ(Ctx.lookupBuiltinID("__builtin_abs", LangOpts), + Builtin::NotBuiltin); + EXPECT_EQ(Ctx.getName(Builtin::BI__builtin_abs), "__builtin_abs"); + unsigned NumNames = 0; + Ctx.forEachBuiltinName(LangOpts, [&](StringRef) { ++NumNames; }); + EXPECT_EQ(NumNames, 0u); +} + +TEST_F(BuiltinsTest, TargetBuiltinsLookup) { + // __mulh is a builtin of both x86-64 and AArch64. + initializeTarget("x86_64-windows-msvc", "aarch64-windows-msvc"); + Builtin::TargetBuiltins Index(*Target, AuxTarget.get()); + EXPECT_EQ(Index.lookup("__builtin_abs"), + SmallVector<unsigned>({Builtin::BI__builtin_abs})); + SmallVector<unsigned, 2> Mulh = Index.lookup("__mulh"); + ASSERT_EQ(Mulh.size(), 2u); + EXPECT_NE(Builtins.isAuxBuiltinID(Mulh[0]), Builtins.isAuxBuiltinID(Mulh[1])); + for (unsigned ID : Mulh) + EXPECT_EQ(Builtins.getName(ID), "__mulh"); + EXPECT_TRUE(Index.lookup("not_a_builtin").empty()); + EXPECT_TRUE(Index.lookup("").empty()); + EXPECT_TRUE(Index.lookup("__builtin_neon_").empty()); +} + +struct BuiltinsConfig { + const char *Triple; + const char *AuxTriple; + void (*Configure)(LangOptions &); +}; + +class BuiltinsConsistencyTest + : public BuiltinsTest, + public ::testing::WithParamInterface<BuiltinsConfig> {}; + +/// The lookup through the name indices agrees with the enumeration of all +/// supported builtins, which checks every builtin directly: every enumerated +/// name resolves to a builtin with that name, and no other builtin name +/// resolves. +TEST_P(BuiltinsConsistencyTest, LookupMatchesEnumeration) { + GetParam().Configure(LangOpts); + initialize(GetParam().Triple, GetParam().AuxTriple); + llvm::StringSet<> Supported; + Builtins.forEachBuiltinName(LangOpts, + [&](StringRef Name) { Supported.insert(Name); }); + ASSERT_FALSE(Supported.empty()); + + llvm::StringMap<unsigned> LastAuxID; + for (unsigned ID = 1, E = getNumBuiltins(); ID != E; ++ID) + if (Builtins.isAuxBuiltinID(ID)) + LastAuxID[Builtins.getName(ID)] = ID; + + unsigned NumResolved = 0; + for (unsigned ID = 1, E = getNumBuiltins(); ID != E; ++ID) { + std::string Name = Builtins.getName(ID); + unsigned Resolved = getBuiltinID(Name); + if (Supported.contains(Name)) { + ASSERT_NE(Resolved, Builtin::NotBuiltin) << Name; + EXPECT_EQ(Builtins.getName(Resolved), Name); + ++NumResolved; + } else { + EXPECT_EQ(Resolved, Builtin::NotBuiltin) << Name; + } + if (auto It = LastAuxID.find(Name); It != LastAuxID.end()) + EXPECT_EQ(Resolved, It->second) << Name; + } + EXPECT_GT(NumResolved, 1000u); +} + +static void c17(LangOptions &) {} +static void cxx20(LangOptions &LO) { + LO.CPlusPlus = LO.CPlusPlus11 = LO.CPlusPlus14 = LO.CPlusPlus17 = + LO.CPlusPlus20 = true; +} +static void objcMS(LangOptions &LO) { + LO.ObjC = LO.Blocks = LO.MicrosoftExt = LO.GNUMode = true; +} +static void noBuiltin(LangOptions &LO) { + LO.NoBuiltin = LO.NoMathBuiltin = true; +} +static void cuda(LangOptions &LO) { + cxx20(LO); + LO.CUDA = true; +} +static void openCL(LangOptions &LO) { + LO.OpenCL = true; + LO.OpenCLVersion = 200; +} + +INSTANTIATE_TEST_SUITE_P( + Targets, BuiltinsConsistencyTest, + ::testing::Values( + BuiltinsConfig{"arm64-apple-macosx", "", c17}, + BuiltinsConfig{"arm64-apple-macosx", "", cxx20}, + BuiltinsConfig{"arm64-apple-macosx", "", objcMS}, + BuiltinsConfig{"arm64-apple-macosx", "", noBuiltin}, + BuiltinsConfig{"x86_64-windows-msvc", "aarch64-windows-msvc", objcMS}, + BuiltinsConfig{"armv7-linux-gnueabihf", "", c17}, + BuiltinsConfig{"riscv64-linux-gnu", "", c17}, + BuiltinsConfig{"ppc64le-linux-gnu", "", cxx20}, + BuiltinsConfig{"mips64-linux-gnu", "", c17}, + BuiltinsConfig{"wasm32", "", c17}, + BuiltinsConfig{"loongarch64-linux-gnu", "", c17}, + BuiltinsConfig{"hexagon-unknown-elf", "", c17}, + BuiltinsConfig{"systemz-linux-gnu", "", c17}, + BuiltinsConfig{"amdgcn-amd-amdhsa", "x86_64-linux-gnu", cuda}, + BuiltinsConfig{"nvptx64-nvidia-cuda", "aarch64-linux-gnu", cuda}, + BuiltinsConfig{"x86_64-linux-gnu", "nvptx64-nvidia-cuda", cuda}, + BuiltinsConfig{"spir64", "", openCL})); + +TEST_F(BuiltinsTest, ForEachBuiltinName) { + initialize("arm64-apple-macosx"); + llvm::StringSet<> Names; + Builtins.forEachBuiltinName(LangOpts, + [&](StringRef Name) { Names.insert(Name); }); + EXPECT_TRUE(Names.contains("__builtin_abs")); + EXPECT_TRUE(Names.contains("__builtin_neon_vaddq_v")); + EXPECT_TRUE(Names.contains("__builtin_arm_rbit")); + EXPECT_FALSE(Names.contains("__noop")); + EXPECT_FALSE(Names.contains("__builtin_ia32_pause")); + EXPECT_FALSE(Names.contains("")); + // Enumerating names doesn't create identifiers. + EXPECT_FALSE(contains("__builtin_abs")); +} + +} // namespace diff --git a/clang/unittests/Basic/CMakeLists.txt b/clang/unittests/Basic/CMakeLists.txt index 32dce09866892b..35fc85e50222ff 100644 --- a/clang/unittests/Basic/CMakeLists.txt +++ b/clang/unittests/Basic/CMakeLists.txt @@ -2,6 +2,7 @@ # distinct target enables faster iteration times at low cost. add_distinct_clang_unittest(BasicTests AtomicLineLoggerTest.cpp + BuiltinsTest.cpp CharInfoTest.cpp DarwinSDKInfoTest.cpp DiagnosticTest.cpp diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp index b6b81aee1b6727..922260e17e6ac7 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp @@ -903,11 +903,6 @@ ClangExpressionParser::ClangExpressionParser( // 7. Most of this we get from the CompilerInstance, but we also want to give // the context an ExternalASTSource. - auto &PP = m_compiler->getPreprocessor(); - auto &builtin_context = PP.getBuiltinInfo(); - builtin_context.initializeBuiltins(PP.getIdentifierTable(), - m_compiler->getLangOpts()); - m_compiler->createASTContext(); clang::ASTContext &ast_context = m_compiler->getASTContext(); _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
