MacroInfo.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //===- MacroInfo.cpp - Information about #defined identifiers -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the MacroInfo interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #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>
  27. using namespace clang;
  28. namespace {
  29. // MacroInfo is expected to take 40 bytes on platforms with an 8 byte pointer
  30. // and 4 byte SourceLocation.
  31. template <int> class MacroInfoSizeChecker {
  32. public:
  33. [[maybe_unused]] constexpr static bool AsExpected = true;
  34. };
  35. template <> class MacroInfoSizeChecker<8> {
  36. public:
  37. [[maybe_unused]] constexpr static bool AsExpected =
  38. sizeof(MacroInfo) == (32 + sizeof(SourceLocation) * 2);
  39. };
  40. static_assert(MacroInfoSizeChecker<sizeof(void *)>::AsExpected,
  41. "Unexpected size of MacroInfo");
  42. } // end namespace
  43. MacroInfo::MacroInfo(SourceLocation DefLoc)
  44. : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
  45. IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
  46. HasCommaPasting(false), IsDisabled(false), IsUsed(false),
  47. IsAllowRedefinitionsWithoutWarning(false), IsWarnIfUnused(false),
  48. UsedForHeaderGuard(false) {}
  49. unsigned MacroInfo::getDefinitionLengthSlow(const SourceManager &SM) const {
  50. assert(!IsDefinitionLengthCached);
  51. IsDefinitionLengthCached = true;
  52. ArrayRef<Token> ReplacementTokens = tokens();
  53. if (ReplacementTokens.empty())
  54. return (DefinitionLength = 0);
  55. const Token &firstToken = ReplacementTokens.front();
  56. const Token &lastToken = ReplacementTokens.back();
  57. SourceLocation macroStart = firstToken.getLocation();
  58. SourceLocation macroEnd = lastToken.getLocation();
  59. assert(macroStart.isValid() && macroEnd.isValid());
  60. assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
  61. "Macro defined in macro?");
  62. assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
  63. "Macro defined in macro?");
  64. std::pair<FileID, unsigned>
  65. startInfo = SM.getDecomposedExpansionLoc(macroStart);
  66. std::pair<FileID, unsigned>
  67. endInfo = SM.getDecomposedExpansionLoc(macroEnd);
  68. assert(startInfo.first == endInfo.first &&
  69. "Macro definition spanning multiple FileIDs ?");
  70. assert(startInfo.second <= endInfo.second);
  71. DefinitionLength = endInfo.second - startInfo.second;
  72. DefinitionLength += lastToken.getLength();
  73. return DefinitionLength;
  74. }
  75. /// Return true if the specified macro definition is equal to
  76. /// this macro in spelling, arguments, and whitespace.
  77. ///
  78. /// \param Syntactically if true, the macro definitions can be identical even
  79. /// if they use different identifiers for the function macro parameters.
  80. /// Otherwise the comparison is lexical and this implements the rules in
  81. /// C99 6.10.3.
  82. bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
  83. bool Syntactically) const {
  84. bool Lexically = !Syntactically;
  85. // Check # tokens in replacement, number of args, and various flags all match.
  86. if (getNumTokens() != Other.getNumTokens() ||
  87. getNumParams() != Other.getNumParams() ||
  88. isFunctionLike() != Other.isFunctionLike() ||
  89. isC99Varargs() != Other.isC99Varargs() ||
  90. isGNUVarargs() != Other.isGNUVarargs())
  91. return false;
  92. if (Lexically) {
  93. // Check arguments.
  94. for (param_iterator I = param_begin(), OI = Other.param_begin(),
  95. E = param_end();
  96. I != E; ++I, ++OI)
  97. if (*I != *OI) return false;
  98. }
  99. // Check all the tokens.
  100. for (unsigned i = 0; i != NumReplacementTokens; ++i) {
  101. const Token &A = ReplacementTokens[i];
  102. const Token &B = Other.ReplacementTokens[i];
  103. if (A.getKind() != B.getKind())
  104. return false;
  105. // If this isn't the first token, check that the whitespace and
  106. // start-of-line characteristics match.
  107. if (i != 0 &&
  108. (A.isAtStartOfLine() != B.isAtStartOfLine() ||
  109. A.hasLeadingSpace() != B.hasLeadingSpace()))
  110. return false;
  111. // If this is an identifier, it is easy.
  112. if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
  113. if (A.getIdentifierInfo() == B.getIdentifierInfo())
  114. continue;
  115. if (Lexically)
  116. return false;
  117. // With syntactic equivalence the parameter names can be different as long
  118. // as they are used in the same place.
  119. int AArgNum = getParameterNum(A.getIdentifierInfo());
  120. if (AArgNum == -1)
  121. return false;
  122. if (AArgNum != Other.getParameterNum(B.getIdentifierInfo()))
  123. return false;
  124. continue;
  125. }
  126. // Otherwise, check the spelling.
  127. if (PP.getSpelling(A) != PP.getSpelling(B))
  128. return false;
  129. }
  130. return true;
  131. }
  132. LLVM_DUMP_METHOD void MacroInfo::dump() const {
  133. llvm::raw_ostream &Out = llvm::errs();
  134. // FIXME: Dump locations.
  135. Out << "MacroInfo " << this;
  136. if (IsBuiltinMacro) Out << " builtin";
  137. if (IsDisabled) Out << " disabled";
  138. if (IsUsed) Out << " used";
  139. if (IsAllowRedefinitionsWithoutWarning)
  140. Out << " allow_redefinitions_without_warning";
  141. if (IsWarnIfUnused) Out << " warn_if_unused";
  142. if (UsedForHeaderGuard) Out << " header_guard";
  143. Out << "\n #define <macro>";
  144. if (IsFunctionLike) {
  145. Out << "(";
  146. for (unsigned I = 0; I != NumParameters; ++I) {
  147. if (I) Out << ", ";
  148. Out << ParameterList[I]->getName();
  149. }
  150. if (IsC99Varargs || IsGNUVarargs) {
  151. if (NumParameters && IsC99Varargs) Out << ", ";
  152. Out << "...";
  153. }
  154. Out << ")";
  155. }
  156. bool First = true;
  157. for (const Token &Tok : tokens()) {
  158. // Leading space is semantically meaningful in a macro definition,
  159. // so preserve it in the dump output.
  160. if (First || Tok.hasLeadingSpace())
  161. Out << " ";
  162. First = false;
  163. if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
  164. Out << Punc;
  165. else if (Tok.isLiteral() && Tok.getLiteralData())
  166. Out << StringRef(Tok.getLiteralData(), Tok.getLength());
  167. else if (auto *II = Tok.getIdentifierInfo())
  168. Out << II->getName();
  169. else
  170. Out << Tok.getName();
  171. }
  172. }
  173. MacroDirective::DefInfo MacroDirective::getDefinition() {
  174. MacroDirective *MD = this;
  175. SourceLocation UndefLoc;
  176. std::optional<bool> isPublic;
  177. for (; MD; MD = MD->getPrevious()) {
  178. if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
  179. return DefInfo(DefMD, UndefLoc, !isPublic || *isPublic);
  180. if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
  181. UndefLoc = UndefMD->getLocation();
  182. continue;
  183. }
  184. VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
  185. if (!isPublic)
  186. isPublic = VisMD->isPublic();
  187. }
  188. return DefInfo(nullptr, UndefLoc, !isPublic || *isPublic);
  189. }
  190. const MacroDirective::DefInfo
  191. MacroDirective::findDirectiveAtLoc(SourceLocation L,
  192. const SourceManager &SM) const {
  193. assert(L.isValid() && "SourceLocation is invalid.");
  194. for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
  195. if (Def.getLocation().isInvalid() || // For macros defined on the command line.
  196. SM.isBeforeInTranslationUnit(Def.getLocation(), L))
  197. return (!Def.isUndefined() ||
  198. SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
  199. ? Def : DefInfo();
  200. }
  201. return DefInfo();
  202. }
  203. LLVM_DUMP_METHOD void MacroDirective::dump() const {
  204. llvm::raw_ostream &Out = llvm::errs();
  205. switch (getKind()) {
  206. case MD_Define: Out << "DefMacroDirective"; break;
  207. case MD_Undefine: Out << "UndefMacroDirective"; break;
  208. case MD_Visibility: Out << "VisibilityMacroDirective"; break;
  209. }
  210. Out << " " << this;
  211. // FIXME: Dump SourceLocation.
  212. if (auto *Prev = getPrevious())
  213. Out << " prev " << Prev;
  214. if (IsFromPCH) Out << " from_pch";
  215. if (isa<VisibilityMacroDirective>(this))
  216. Out << (IsPublic ? " public" : " private");
  217. if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
  218. if (auto *Info = DMD->getInfo()) {
  219. Out << "\n ";
  220. Info->dump();
  221. }
  222. }
  223. Out << "\n";
  224. }
  225. ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
  226. IdentifierInfo *II, MacroInfo *Macro,
  227. ArrayRef<ModuleMacro *> Overrides) {
  228. void *Mem = PP.getPreprocessorAllocator().Allocate(
  229. sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
  230. alignof(ModuleMacro));
  231. return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);
  232. }