MacroInfo.cpp 8.5 KB

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