]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Lex / MacroInfo.cpp
1 //===--- MacroInfo.cpp - Information about #defined identifiers -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MacroInfo interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Lex/MacroInfo.h"
15 #include "clang/Lex/Preprocessor.h"
16 using namespace clang;
17
18 MacroInfo::MacroInfo(SourceLocation DefLoc)
19   : Location(DefLoc),
20     ArgumentList(nullptr),
21     NumArguments(0),
22     IsDefinitionLengthCached(false),
23     IsFunctionLike(false),
24     IsC99Varargs(false),
25     IsGNUVarargs(false),
26     IsBuiltinMacro(false),
27     HasCommaPasting(false),
28     IsDisabled(false),
29     IsUsed(false),
30     IsAllowRedefinitionsWithoutWarning(false),
31     IsWarnIfUnused(false),
32     UsedForHeaderGuard(false) {
33 }
34
35 unsigned MacroInfo::getDefinitionLengthSlow(const SourceManager &SM) const {
36   assert(!IsDefinitionLengthCached);
37   IsDefinitionLengthCached = true;
38
39   if (ReplacementTokens.empty())
40     return (DefinitionLength = 0);
41
42   const Token &firstToken = ReplacementTokens.front();
43   const Token &lastToken = ReplacementTokens.back();
44   SourceLocation macroStart = firstToken.getLocation();
45   SourceLocation macroEnd = lastToken.getLocation();
46   assert(macroStart.isValid() && macroEnd.isValid());
47   assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
48          "Macro defined in macro?");
49   assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
50          "Macro defined in macro?");
51   std::pair<FileID, unsigned>
52       startInfo = SM.getDecomposedExpansionLoc(macroStart);
53   std::pair<FileID, unsigned>
54       endInfo = SM.getDecomposedExpansionLoc(macroEnd);
55   assert(startInfo.first == endInfo.first &&
56          "Macro definition spanning multiple FileIDs ?");
57   assert(startInfo.second <= endInfo.second);
58   DefinitionLength = endInfo.second - startInfo.second;
59   DefinitionLength += lastToken.getLength();
60
61   return DefinitionLength;
62 }
63
64 /// \brief Return true if the specified macro definition is equal to
65 /// this macro in spelling, arguments, and whitespace.
66 ///
67 /// \param Syntactically if true, the macro definitions can be identical even
68 /// if they use different identifiers for the function macro parameters.
69 /// Otherwise the comparison is lexical and this implements the rules in
70 /// C99 6.10.3.
71 bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
72                               bool Syntactically) const {
73   bool Lexically = !Syntactically;
74
75   // Check # tokens in replacement, number of args, and various flags all match.
76   if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
77       getNumArgs() != Other.getNumArgs() ||
78       isFunctionLike() != Other.isFunctionLike() ||
79       isC99Varargs() != Other.isC99Varargs() ||
80       isGNUVarargs() != Other.isGNUVarargs())
81     return false;
82
83   if (Lexically) {
84     // Check arguments.
85     for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
86          I != E; ++I, ++OI)
87       if (*I != *OI) return false;
88   }
89
90   // Check all the tokens.
91   for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
92     const Token &A = ReplacementTokens[i];
93     const Token &B = Other.ReplacementTokens[i];
94     if (A.getKind() != B.getKind())
95       return false;
96
97     // If this isn't the first first token, check that the whitespace and
98     // start-of-line characteristics match.
99     if (i != 0 &&
100         (A.isAtStartOfLine() != B.isAtStartOfLine() ||
101          A.hasLeadingSpace() != B.hasLeadingSpace()))
102       return false;
103
104     // If this is an identifier, it is easy.
105     if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
106       if (A.getIdentifierInfo() == B.getIdentifierInfo())
107         continue;
108       if (Lexically)
109         return false;
110       // With syntactic equivalence the parameter names can be different as long
111       // as they are used in the same place.
112       int AArgNum = getArgumentNum(A.getIdentifierInfo());
113       if (AArgNum == -1)
114         return false;
115       if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo()))
116         return false;
117       continue;
118     }
119
120     // Otherwise, check the spelling.
121     if (PP.getSpelling(A) != PP.getSpelling(B))
122       return false;
123   }
124
125   return true;
126 }
127
128 LLVM_DUMP_METHOD void MacroInfo::dump() const {
129   llvm::raw_ostream &Out = llvm::errs();
130
131   // FIXME: Dump locations.
132   Out << "MacroInfo " << this;
133   if (IsBuiltinMacro) Out << " builtin";
134   if (IsDisabled) Out << " disabled";
135   if (IsUsed) Out << " used";
136   if (IsAllowRedefinitionsWithoutWarning)
137     Out << " allow_redefinitions_without_warning";
138   if (IsWarnIfUnused) Out << " warn_if_unused";
139   if (UsedForHeaderGuard) Out << " header_guard";
140
141   Out << "\n    #define <macro>";
142   if (IsFunctionLike) {
143     Out << "(";
144     for (unsigned I = 0; I != NumArguments; ++I) {
145       if (I) Out << ", ";
146       Out << ArgumentList[I]->getName();
147     }
148     if (IsC99Varargs || IsGNUVarargs) {
149       if (NumArguments && IsC99Varargs) Out << ", ";
150       Out << "...";
151     }
152     Out << ")";
153   }
154
155   bool First = true;
156   for (const Token &Tok : ReplacementTokens) {
157     // Leading space is semantically meaningful in a macro definition,
158     // so preserve it in the dump output.
159     if (First || Tok.hasLeadingSpace())
160       Out << " ";
161     First = false;
162
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
174 MacroDirective::DefInfo MacroDirective::getDefinition() {
175   MacroDirective *MD = this;
176   SourceLocation UndefLoc;
177   Optional<bool> isPublic;
178   for (; MD; MD = MD->getPrevious()) {
179     if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
180       return DefInfo(DefMD, UndefLoc,
181                      !isPublic.hasValue() || isPublic.getValue());
182
183     if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
184       UndefLoc = UndefMD->getLocation();
185       continue;
186     }
187
188     VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
189     if (!isPublic.hasValue())
190       isPublic = VisMD->isPublic();
191   }
192
193   return DefInfo(nullptr, UndefLoc,
194                  !isPublic.hasValue() || isPublic.getValue());
195 }
196
197 const MacroDirective::DefInfo
198 MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const {
199   assert(L.isValid() && "SourceLocation is invalid.");
200   for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
201     if (Def.getLocation().isInvalid() ||  // For macros defined on the command line.
202         SM.isBeforeInTranslationUnit(Def.getLocation(), L))
203       return (!Def.isUndefined() ||
204               SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
205                   ? Def : DefInfo();
206   }
207   return DefInfo();
208 }
209
210 LLVM_DUMP_METHOD void MacroDirective::dump() const {
211   llvm::raw_ostream &Out = llvm::errs();
212
213   switch (getKind()) {
214   case MD_Define: Out << "DefMacroDirective"; break;
215   case MD_Undefine: Out << "UndefMacroDirective"; break;
216   case MD_Visibility: Out << "VisibilityMacroDirective"; break;
217   }
218   Out << " " << this;
219   // FIXME: Dump SourceLocation.
220   if (auto *Prev = getPrevious())
221     Out << " prev " << Prev;
222   if (IsFromPCH) Out << " from_pch";
223
224   if (isa<VisibilityMacroDirective>(this))
225     Out << (IsPublic ? " public" : " private");
226
227   if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
228     if (auto *Info = DMD->getInfo()) {
229       Out << "\n  ";
230       Info->dump();
231     }
232   }
233   Out << "\n";
234 }
235
236 ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
237                                  IdentifierInfo *II, MacroInfo *Macro,
238                                  ArrayRef<ModuleMacro *> Overrides) {
239   void *Mem = PP.getPreprocessorAllocator().Allocate(
240       sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
241       alignof(ModuleMacro));
242   return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);
243 }