Path: blob/main/contrib/llvm-project/clang/lib/Lex/MacroInfo.cpp
35234 views
//===- MacroInfo.cpp - Information about #defined identifiers -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the MacroInfo interface.9//10//===----------------------------------------------------------------------===//1112#include "clang/Lex/MacroInfo.h"13#include "clang/Basic/IdentifierTable.h"14#include "clang/Basic/LLVM.h"15#include "clang/Basic/SourceLocation.h"16#include "clang/Basic/SourceManager.h"17#include "clang/Basic/TokenKinds.h"18#include "clang/Lex/Preprocessor.h"19#include "clang/Lex/Token.h"20#include "llvm/ADT/StringRef.h"21#include "llvm/Support/Casting.h"22#include "llvm/Support/Compiler.h"23#include "llvm/Support/raw_ostream.h"24#include <cassert>25#include <optional>26#include <utility>2728using namespace clang;2930namespace {3132// MacroInfo is expected to take 40 bytes on platforms with an 8 byte pointer33// and 4 byte SourceLocation.34template <int> class MacroInfoSizeChecker {35public:36[[maybe_unused]] constexpr static bool AsExpected = true;37};38template <> class MacroInfoSizeChecker<8> {39public:40[[maybe_unused]] constexpr static bool AsExpected =41sizeof(MacroInfo) == (32 + sizeof(SourceLocation) * 2);42};4344static_assert(MacroInfoSizeChecker<sizeof(void *)>::AsExpected,45"Unexpected size of MacroInfo");4647} // end namespace4849MacroInfo::MacroInfo(SourceLocation DefLoc)50: Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),51IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),52HasCommaPasting(false), IsDisabled(false), IsUsed(false),53IsAllowRedefinitionsWithoutWarning(false), IsWarnIfUnused(false),54UsedForHeaderGuard(false) {}5556unsigned MacroInfo::getDefinitionLengthSlow(const SourceManager &SM) const {57assert(!IsDefinitionLengthCached);58IsDefinitionLengthCached = true;5960ArrayRef<Token> ReplacementTokens = tokens();61if (ReplacementTokens.empty())62return (DefinitionLength = 0);6364const Token &firstToken = ReplacementTokens.front();65const Token &lastToken = ReplacementTokens.back();66SourceLocation macroStart = firstToken.getLocation();67SourceLocation macroEnd = lastToken.getLocation();68assert(macroStart.isValid() && macroEnd.isValid());69assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&70"Macro defined in macro?");71assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&72"Macro defined in macro?");73std::pair<FileID, unsigned>74startInfo = SM.getDecomposedExpansionLoc(macroStart);75std::pair<FileID, unsigned>76endInfo = SM.getDecomposedExpansionLoc(macroEnd);77assert(startInfo.first == endInfo.first &&78"Macro definition spanning multiple FileIDs ?");79assert(startInfo.second <= endInfo.second);80DefinitionLength = endInfo.second - startInfo.second;81DefinitionLength += lastToken.getLength();8283return DefinitionLength;84}8586/// Return true if the specified macro definition is equal to87/// this macro in spelling, arguments, and whitespace.88///89/// \param Syntactically if true, the macro definitions can be identical even90/// if they use different identifiers for the function macro parameters.91/// Otherwise the comparison is lexical and this implements the rules in92/// C99 6.10.3.93bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,94bool Syntactically) const {95bool Lexically = !Syntactically;9697// Check # tokens in replacement, number of args, and various flags all match.98if (getNumTokens() != Other.getNumTokens() ||99getNumParams() != Other.getNumParams() ||100isFunctionLike() != Other.isFunctionLike() ||101isC99Varargs() != Other.isC99Varargs() ||102isGNUVarargs() != Other.isGNUVarargs())103return false;104105if (Lexically) {106// Check arguments.107for (param_iterator I = param_begin(), OI = Other.param_begin(),108E = param_end();109I != E; ++I, ++OI)110if (*I != *OI) return false;111}112113// Check all the tokens.114for (unsigned i = 0; i != NumReplacementTokens; ++i) {115const Token &A = ReplacementTokens[i];116const Token &B = Other.ReplacementTokens[i];117if (A.getKind() != B.getKind())118return false;119120// If this isn't the first token, check that the whitespace and121// start-of-line characteristics match.122if (i != 0 &&123(A.isAtStartOfLine() != B.isAtStartOfLine() ||124A.hasLeadingSpace() != B.hasLeadingSpace()))125return false;126127// If this is an identifier, it is easy.128if (A.getIdentifierInfo() || B.getIdentifierInfo()) {129if (A.getIdentifierInfo() == B.getIdentifierInfo())130continue;131if (Lexically)132return false;133// With syntactic equivalence the parameter names can be different as long134// as they are used in the same place.135int AArgNum = getParameterNum(A.getIdentifierInfo());136if (AArgNum == -1)137return false;138if (AArgNum != Other.getParameterNum(B.getIdentifierInfo()))139return false;140continue;141}142143// Otherwise, check the spelling.144if (PP.getSpelling(A) != PP.getSpelling(B))145return false;146}147148return true;149}150151LLVM_DUMP_METHOD void MacroInfo::dump() const {152llvm::raw_ostream &Out = llvm::errs();153154// FIXME: Dump locations.155Out << "MacroInfo " << this;156if (IsBuiltinMacro) Out << " builtin";157if (IsDisabled) Out << " disabled";158if (IsUsed) Out << " used";159if (IsAllowRedefinitionsWithoutWarning)160Out << " allow_redefinitions_without_warning";161if (IsWarnIfUnused) Out << " warn_if_unused";162if (UsedForHeaderGuard) Out << " header_guard";163164Out << "\n #define <macro>";165if (IsFunctionLike) {166Out << "(";167for (unsigned I = 0; I != NumParameters; ++I) {168if (I) Out << ", ";169Out << ParameterList[I]->getName();170}171if (IsC99Varargs || IsGNUVarargs) {172if (NumParameters && IsC99Varargs) Out << ", ";173Out << "...";174}175Out << ")";176}177178bool First = true;179for (const Token &Tok : tokens()) {180// Leading space is semantically meaningful in a macro definition,181// so preserve it in the dump output.182if (First || Tok.hasLeadingSpace())183Out << " ";184First = false;185186if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))187Out << Punc;188else if (Tok.isLiteral() && Tok.getLiteralData())189Out << StringRef(Tok.getLiteralData(), Tok.getLength());190else if (auto *II = Tok.getIdentifierInfo())191Out << II->getName();192else193Out << Tok.getName();194}195}196197MacroDirective::DefInfo MacroDirective::getDefinition() {198MacroDirective *MD = this;199SourceLocation UndefLoc;200std::optional<bool> isPublic;201for (; MD; MD = MD->getPrevious()) {202if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))203return DefInfo(DefMD, UndefLoc, !isPublic || *isPublic);204205if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {206UndefLoc = UndefMD->getLocation();207continue;208}209210VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);211if (!isPublic)212isPublic = VisMD->isPublic();213}214215return DefInfo(nullptr, UndefLoc, !isPublic || *isPublic);216}217218const MacroDirective::DefInfo219MacroDirective::findDirectiveAtLoc(SourceLocation L,220const SourceManager &SM) const {221assert(L.isValid() && "SourceLocation is invalid.");222for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {223if (Def.getLocation().isInvalid() || // For macros defined on the command line.224SM.isBeforeInTranslationUnit(Def.getLocation(), L))225return (!Def.isUndefined() ||226SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))227? Def : DefInfo();228}229return DefInfo();230}231232LLVM_DUMP_METHOD void MacroDirective::dump() const {233llvm::raw_ostream &Out = llvm::errs();234235switch (getKind()) {236case MD_Define: Out << "DefMacroDirective"; break;237case MD_Undefine: Out << "UndefMacroDirective"; break;238case MD_Visibility: Out << "VisibilityMacroDirective"; break;239}240Out << " " << this;241// FIXME: Dump SourceLocation.242if (auto *Prev = getPrevious())243Out << " prev " << Prev;244if (IsFromPCH) Out << " from_pch";245246if (isa<VisibilityMacroDirective>(this))247Out << (IsPublic ? " public" : " private");248249if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {250if (auto *Info = DMD->getInfo()) {251Out << "\n ";252Info->dump();253}254}255Out << "\n";256}257258ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,259const IdentifierInfo *II, MacroInfo *Macro,260ArrayRef<ModuleMacro *> Overrides) {261void *Mem = PP.getPreprocessorAllocator().Allocate(262sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),263alignof(ModuleMacro));264return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);265}266267268