xref: /minix3/external/bsd/llvm/dist/clang/lib/Lex/PPMacroExpansion.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10*0a6a1f1dSLionel Sambuc // This file implements the top level handling of macro expansion for the
11f4a2713aSLionel Sambuc // preprocessor.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc 
15f4a2713aSLionel Sambuc #include "clang/Lex/Preprocessor.h"
16*0a6a1f1dSLionel Sambuc #include "clang/Basic/Attributes.h"
17f4a2713aSLionel Sambuc #include "clang/Basic/FileManager.h"
18f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
19f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
20f4a2713aSLionel Sambuc #include "clang/Lex/CodeCompletionHandler.h"
21f4a2713aSLionel Sambuc #include "clang/Lex/ExternalPreprocessorSource.h"
22f4a2713aSLionel Sambuc #include "clang/Lex/LexDiagnostic.h"
23*0a6a1f1dSLionel Sambuc #include "clang/Lex/MacroArgs.h"
24f4a2713aSLionel Sambuc #include "clang/Lex/MacroInfo.h"
25f4a2713aSLionel Sambuc #include "llvm/ADT/STLExtras.h"
26f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
27f4a2713aSLionel Sambuc #include "llvm/ADT/StringSwitch.h"
28f4a2713aSLionel Sambuc #include "llvm/Config/llvm-config.h"
29f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
30f4a2713aSLionel Sambuc #include "llvm/Support/Format.h"
31f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
32f4a2713aSLionel Sambuc #include <cstdio>
33f4a2713aSLionel Sambuc #include <ctime>
34f4a2713aSLionel Sambuc using namespace clang;
35f4a2713aSLionel Sambuc 
36f4a2713aSLionel Sambuc MacroDirective *
getMacroDirectiveHistory(const IdentifierInfo * II) const37f4a2713aSLionel Sambuc Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
38f4a2713aSLionel Sambuc   assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
39f4a2713aSLionel Sambuc 
40f4a2713aSLionel Sambuc   macro_iterator Pos = Macros.find(II);
41f4a2713aSLionel Sambuc   assert(Pos != Macros.end() && "Identifier macro info is missing!");
42f4a2713aSLionel Sambuc   return Pos->second;
43f4a2713aSLionel Sambuc }
44f4a2713aSLionel Sambuc 
appendMacroDirective(IdentifierInfo * II,MacroDirective * MD)45f4a2713aSLionel Sambuc void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
46f4a2713aSLionel Sambuc   assert(MD && "MacroDirective should be non-zero!");
47f4a2713aSLionel Sambuc   assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
48f4a2713aSLionel Sambuc 
49f4a2713aSLionel Sambuc   MacroDirective *&StoredMD = Macros[II];
50f4a2713aSLionel Sambuc   MD->setPrevious(StoredMD);
51f4a2713aSLionel Sambuc   StoredMD = MD;
52*0a6a1f1dSLionel Sambuc   // Setup the identifier as having associated macro history.
53*0a6a1f1dSLionel Sambuc   II->setHasMacroDefinition(true);
54*0a6a1f1dSLionel Sambuc   if (!MD->isDefined())
55*0a6a1f1dSLionel Sambuc     II->setHasMacroDefinition(false);
56f4a2713aSLionel Sambuc   bool isImportedMacro = isa<DefMacroDirective>(MD) &&
57f4a2713aSLionel Sambuc                          cast<DefMacroDirective>(MD)->isImported();
58f4a2713aSLionel Sambuc   if (II->isFromAST() && !isImportedMacro)
59f4a2713aSLionel Sambuc     II->setChangedSinceDeserialization();
60f4a2713aSLionel Sambuc }
61f4a2713aSLionel Sambuc 
setLoadedMacroDirective(IdentifierInfo * II,MacroDirective * MD)62f4a2713aSLionel Sambuc void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
63f4a2713aSLionel Sambuc                                            MacroDirective *MD) {
64f4a2713aSLionel Sambuc   assert(II && MD);
65f4a2713aSLionel Sambuc   MacroDirective *&StoredMD = Macros[II];
66f4a2713aSLionel Sambuc   assert(!StoredMD &&
67f4a2713aSLionel Sambuc          "the macro history was modified before initializing it from a pch");
68f4a2713aSLionel Sambuc   StoredMD = MD;
69f4a2713aSLionel Sambuc   // Setup the identifier as having associated macro history.
70f4a2713aSLionel Sambuc   II->setHasMacroDefinition(true);
71f4a2713aSLionel Sambuc   if (!MD->isDefined())
72f4a2713aSLionel Sambuc     II->setHasMacroDefinition(false);
73f4a2713aSLionel Sambuc }
74f4a2713aSLionel Sambuc 
75f4a2713aSLionel Sambuc /// RegisterBuiltinMacro - Register the specified identifier in the identifier
76f4a2713aSLionel Sambuc /// table and mark it as a builtin macro to be expanded.
RegisterBuiltinMacro(Preprocessor & PP,const char * Name)77f4a2713aSLionel Sambuc static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
78f4a2713aSLionel Sambuc   // Get the identifier.
79f4a2713aSLionel Sambuc   IdentifierInfo *Id = PP.getIdentifierInfo(Name);
80f4a2713aSLionel Sambuc 
81f4a2713aSLionel Sambuc   // Mark it as being a macro that is builtin.
82f4a2713aSLionel Sambuc   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
83f4a2713aSLionel Sambuc   MI->setIsBuiltinMacro();
84f4a2713aSLionel Sambuc   PP.appendDefMacroDirective(Id, MI);
85f4a2713aSLionel Sambuc   return Id;
86f4a2713aSLionel Sambuc }
87f4a2713aSLionel Sambuc 
88f4a2713aSLionel Sambuc 
89f4a2713aSLionel Sambuc /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
90f4a2713aSLionel Sambuc /// identifier table.
RegisterBuiltinMacros()91f4a2713aSLionel Sambuc void Preprocessor::RegisterBuiltinMacros() {
92f4a2713aSLionel Sambuc   Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
93f4a2713aSLionel Sambuc   Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
94f4a2713aSLionel Sambuc   Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
95f4a2713aSLionel Sambuc   Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
96f4a2713aSLionel Sambuc   Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
97f4a2713aSLionel Sambuc   Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
98f4a2713aSLionel Sambuc 
99*0a6a1f1dSLionel Sambuc   // C++ Standing Document Extensions.
100*0a6a1f1dSLionel Sambuc   Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute");
101*0a6a1f1dSLionel Sambuc 
102f4a2713aSLionel Sambuc   // GCC Extensions.
103f4a2713aSLionel Sambuc   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
104f4a2713aSLionel Sambuc   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
105f4a2713aSLionel Sambuc   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
106f4a2713aSLionel Sambuc 
107*0a6a1f1dSLionel Sambuc   // Microsoft Extensions.
108*0a6a1f1dSLionel Sambuc   if (LangOpts.MicrosoftExt) {
109*0a6a1f1dSLionel Sambuc     Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
110*0a6a1f1dSLionel Sambuc     Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
111*0a6a1f1dSLionel Sambuc   } else {
112*0a6a1f1dSLionel Sambuc     Ident__identifier = nullptr;
113*0a6a1f1dSLionel Sambuc     Ident__pragma = nullptr;
114*0a6a1f1dSLionel Sambuc   }
115*0a6a1f1dSLionel Sambuc 
116f4a2713aSLionel Sambuc   // Clang Extensions.
117f4a2713aSLionel Sambuc   Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
118f4a2713aSLionel Sambuc   Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
119f4a2713aSLionel Sambuc   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
120f4a2713aSLionel Sambuc   Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
121*0a6a1f1dSLionel Sambuc   Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
122f4a2713aSLionel Sambuc   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
123f4a2713aSLionel Sambuc   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
124f4a2713aSLionel Sambuc   Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
125*0a6a1f1dSLionel Sambuc   Ident__is_identifier    = RegisterBuiltinMacro(*this, "__is_identifier");
126f4a2713aSLionel Sambuc 
127f4a2713aSLionel Sambuc   // Modules.
128f4a2713aSLionel Sambuc   if (LangOpts.Modules) {
129f4a2713aSLionel Sambuc     Ident__building_module  = RegisterBuiltinMacro(*this, "__building_module");
130f4a2713aSLionel Sambuc 
131f4a2713aSLionel Sambuc     // __MODULE__
132f4a2713aSLionel Sambuc     if (!LangOpts.CurrentModule.empty())
133f4a2713aSLionel Sambuc       Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
134f4a2713aSLionel Sambuc     else
135*0a6a1f1dSLionel Sambuc       Ident__MODULE__ = nullptr;
136f4a2713aSLionel Sambuc   } else {
137*0a6a1f1dSLionel Sambuc     Ident__building_module = nullptr;
138*0a6a1f1dSLionel Sambuc     Ident__MODULE__ = nullptr;
139f4a2713aSLionel Sambuc   }
140f4a2713aSLionel Sambuc }
141f4a2713aSLionel Sambuc 
142f4a2713aSLionel Sambuc /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
143f4a2713aSLionel Sambuc /// in its expansion, currently expands to that token literally.
isTrivialSingleTokenExpansion(const MacroInfo * MI,const IdentifierInfo * MacroIdent,Preprocessor & PP)144f4a2713aSLionel Sambuc static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
145f4a2713aSLionel Sambuc                                           const IdentifierInfo *MacroIdent,
146f4a2713aSLionel Sambuc                                           Preprocessor &PP) {
147f4a2713aSLionel Sambuc   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
148f4a2713aSLionel Sambuc 
149f4a2713aSLionel Sambuc   // If the token isn't an identifier, it's always literally expanded.
150*0a6a1f1dSLionel Sambuc   if (!II) return true;
151f4a2713aSLionel Sambuc 
152f4a2713aSLionel Sambuc   // If the information about this identifier is out of date, update it from
153f4a2713aSLionel Sambuc   // the external source.
154f4a2713aSLionel Sambuc   if (II->isOutOfDate())
155f4a2713aSLionel Sambuc     PP.getExternalSource()->updateOutOfDateIdentifier(*II);
156f4a2713aSLionel Sambuc 
157f4a2713aSLionel Sambuc   // If the identifier is a macro, and if that macro is enabled, it may be
158f4a2713aSLionel Sambuc   // expanded so it's not a trivial expansion.
159f4a2713aSLionel Sambuc   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
160f4a2713aSLionel Sambuc       // Fast expanding "#define X X" is ok, because X would be disabled.
161f4a2713aSLionel Sambuc       II != MacroIdent)
162f4a2713aSLionel Sambuc     return false;
163f4a2713aSLionel Sambuc 
164f4a2713aSLionel Sambuc   // If this is an object-like macro invocation, it is safe to trivially expand
165f4a2713aSLionel Sambuc   // it.
166f4a2713aSLionel Sambuc   if (MI->isObjectLike()) return true;
167f4a2713aSLionel Sambuc 
168f4a2713aSLionel Sambuc   // If this is a function-like macro invocation, it's safe to trivially expand
169f4a2713aSLionel Sambuc   // as long as the identifier is not a macro argument.
170f4a2713aSLionel Sambuc   for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
171f4a2713aSLionel Sambuc        I != E; ++I)
172f4a2713aSLionel Sambuc     if (*I == II)
173f4a2713aSLionel Sambuc       return false;   // Identifier is a macro argument.
174f4a2713aSLionel Sambuc 
175f4a2713aSLionel Sambuc   return true;
176f4a2713aSLionel Sambuc }
177f4a2713aSLionel Sambuc 
178f4a2713aSLionel Sambuc 
179f4a2713aSLionel Sambuc /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
180f4a2713aSLionel Sambuc /// lexed is a '('.  If so, consume the token and return true, if not, this
181f4a2713aSLionel Sambuc /// method should have no observable side-effect on the lexed tokens.
isNextPPTokenLParen()182f4a2713aSLionel Sambuc bool Preprocessor::isNextPPTokenLParen() {
183f4a2713aSLionel Sambuc   // Do some quick tests for rejection cases.
184f4a2713aSLionel Sambuc   unsigned Val;
185f4a2713aSLionel Sambuc   if (CurLexer)
186f4a2713aSLionel Sambuc     Val = CurLexer->isNextPPTokenLParen();
187f4a2713aSLionel Sambuc   else if (CurPTHLexer)
188f4a2713aSLionel Sambuc     Val = CurPTHLexer->isNextPPTokenLParen();
189f4a2713aSLionel Sambuc   else
190f4a2713aSLionel Sambuc     Val = CurTokenLexer->isNextTokenLParen();
191f4a2713aSLionel Sambuc 
192f4a2713aSLionel Sambuc   if (Val == 2) {
193f4a2713aSLionel Sambuc     // We have run off the end.  If it's a source file we don't
194f4a2713aSLionel Sambuc     // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
195f4a2713aSLionel Sambuc     // macro stack.
196f4a2713aSLionel Sambuc     if (CurPPLexer)
197f4a2713aSLionel Sambuc       return false;
198f4a2713aSLionel Sambuc     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
199f4a2713aSLionel Sambuc       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
200f4a2713aSLionel Sambuc       if (Entry.TheLexer)
201f4a2713aSLionel Sambuc         Val = Entry.TheLexer->isNextPPTokenLParen();
202f4a2713aSLionel Sambuc       else if (Entry.ThePTHLexer)
203f4a2713aSLionel Sambuc         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
204f4a2713aSLionel Sambuc       else
205f4a2713aSLionel Sambuc         Val = Entry.TheTokenLexer->isNextTokenLParen();
206f4a2713aSLionel Sambuc 
207f4a2713aSLionel Sambuc       if (Val != 2)
208f4a2713aSLionel Sambuc         break;
209f4a2713aSLionel Sambuc 
210f4a2713aSLionel Sambuc       // Ran off the end of a source file?
211f4a2713aSLionel Sambuc       if (Entry.ThePPLexer)
212f4a2713aSLionel Sambuc         return false;
213f4a2713aSLionel Sambuc     }
214f4a2713aSLionel Sambuc   }
215f4a2713aSLionel Sambuc 
216f4a2713aSLionel Sambuc   // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
217f4a2713aSLionel Sambuc   // have found something that isn't a '(' or we found the end of the
218f4a2713aSLionel Sambuc   // translation unit.  In either case, return false.
219f4a2713aSLionel Sambuc   return Val == 1;
220f4a2713aSLionel Sambuc }
221f4a2713aSLionel Sambuc 
222f4a2713aSLionel Sambuc /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
223f4a2713aSLionel Sambuc /// expanded as a macro, handle it and return the next token as 'Identifier'.
HandleMacroExpandedIdentifier(Token & Identifier,MacroDirective * MD)224f4a2713aSLionel Sambuc bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
225f4a2713aSLionel Sambuc                                                  MacroDirective *MD) {
226f4a2713aSLionel Sambuc   MacroDirective::DefInfo Def = MD->getDefinition();
227f4a2713aSLionel Sambuc   assert(Def.isValid());
228f4a2713aSLionel Sambuc   MacroInfo *MI = Def.getMacroInfo();
229f4a2713aSLionel Sambuc 
230f4a2713aSLionel Sambuc   // If this is a macro expansion in the "#if !defined(x)" line for the file,
231f4a2713aSLionel Sambuc   // then the macro could expand to different things in other contexts, we need
232f4a2713aSLionel Sambuc   // to disable the optimization in this case.
233f4a2713aSLionel Sambuc   if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
234f4a2713aSLionel Sambuc 
235f4a2713aSLionel Sambuc   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
236f4a2713aSLionel Sambuc   if (MI->isBuiltinMacro()) {
237f4a2713aSLionel Sambuc     if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
238*0a6a1f1dSLionel Sambuc                                            Identifier.getLocation(),
239*0a6a1f1dSLionel Sambuc                                            /*Args=*/nullptr);
240f4a2713aSLionel Sambuc     ExpandBuiltinMacro(Identifier);
241f4a2713aSLionel Sambuc     return true;
242f4a2713aSLionel Sambuc   }
243f4a2713aSLionel Sambuc 
244f4a2713aSLionel Sambuc   /// Args - If this is a function-like macro expansion, this contains,
245f4a2713aSLionel Sambuc   /// for each macro argument, the list of tokens that were provided to the
246f4a2713aSLionel Sambuc   /// invocation.
247*0a6a1f1dSLionel Sambuc   MacroArgs *Args = nullptr;
248f4a2713aSLionel Sambuc 
249f4a2713aSLionel Sambuc   // Remember where the end of the expansion occurred.  For an object-like
250f4a2713aSLionel Sambuc   // macro, this is the identifier.  For a function-like macro, this is the ')'.
251f4a2713aSLionel Sambuc   SourceLocation ExpansionEnd = Identifier.getLocation();
252f4a2713aSLionel Sambuc 
253f4a2713aSLionel Sambuc   // If this is a function-like macro, read the arguments.
254f4a2713aSLionel Sambuc   if (MI->isFunctionLike()) {
255f4a2713aSLionel Sambuc     // Remember that we are now parsing the arguments to a macro invocation.
256f4a2713aSLionel Sambuc     // Preprocessor directives used inside macro arguments are not portable, and
257f4a2713aSLionel Sambuc     // this enables the warning.
258f4a2713aSLionel Sambuc     InMacroArgs = true;
259f4a2713aSLionel Sambuc     Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
260f4a2713aSLionel Sambuc 
261f4a2713aSLionel Sambuc     // Finished parsing args.
262f4a2713aSLionel Sambuc     InMacroArgs = false;
263f4a2713aSLionel Sambuc 
264f4a2713aSLionel Sambuc     // If there was an error parsing the arguments, bail out.
265*0a6a1f1dSLionel Sambuc     if (!Args) return true;
266f4a2713aSLionel Sambuc 
267f4a2713aSLionel Sambuc     ++NumFnMacroExpanded;
268f4a2713aSLionel Sambuc   } else {
269f4a2713aSLionel Sambuc     ++NumMacroExpanded;
270f4a2713aSLionel Sambuc   }
271f4a2713aSLionel Sambuc 
272f4a2713aSLionel Sambuc   // Notice that this macro has been used.
273f4a2713aSLionel Sambuc   markMacroAsUsed(MI);
274f4a2713aSLionel Sambuc 
275f4a2713aSLionel Sambuc   // Remember where the token is expanded.
276f4a2713aSLionel Sambuc   SourceLocation ExpandLoc = Identifier.getLocation();
277f4a2713aSLionel Sambuc   SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
278f4a2713aSLionel Sambuc 
279f4a2713aSLionel Sambuc   if (Callbacks) {
280f4a2713aSLionel Sambuc     if (InMacroArgs) {
281f4a2713aSLionel Sambuc       // We can have macro expansion inside a conditional directive while
282f4a2713aSLionel Sambuc       // reading the function macro arguments. To ensure, in that case, that
283f4a2713aSLionel Sambuc       // MacroExpands callbacks still happen in source order, queue this
284f4a2713aSLionel Sambuc       // callback to have it happen after the function macro callback.
285f4a2713aSLionel Sambuc       DelayedMacroExpandsCallbacks.push_back(
286f4a2713aSLionel Sambuc                               MacroExpandsInfo(Identifier, MD, ExpansionRange));
287f4a2713aSLionel Sambuc     } else {
288f4a2713aSLionel Sambuc       Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
289f4a2713aSLionel Sambuc       if (!DelayedMacroExpandsCallbacks.empty()) {
290f4a2713aSLionel Sambuc         for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
291f4a2713aSLionel Sambuc           MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
292f4a2713aSLionel Sambuc           // FIXME: We lose macro args info with delayed callback.
293*0a6a1f1dSLionel Sambuc           Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
294*0a6a1f1dSLionel Sambuc                                   /*Args=*/nullptr);
295f4a2713aSLionel Sambuc         }
296f4a2713aSLionel Sambuc         DelayedMacroExpandsCallbacks.clear();
297f4a2713aSLionel Sambuc       }
298f4a2713aSLionel Sambuc     }
299f4a2713aSLionel Sambuc   }
300f4a2713aSLionel Sambuc 
301f4a2713aSLionel Sambuc   // If the macro definition is ambiguous, complain.
302f4a2713aSLionel Sambuc   if (Def.getDirective()->isAmbiguous()) {
303f4a2713aSLionel Sambuc     Diag(Identifier, diag::warn_pp_ambiguous_macro)
304f4a2713aSLionel Sambuc       << Identifier.getIdentifierInfo();
305f4a2713aSLionel Sambuc     Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
306f4a2713aSLionel Sambuc       << Identifier.getIdentifierInfo();
307f4a2713aSLionel Sambuc     for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
308f4a2713aSLionel Sambuc          PrevDef && !PrevDef.isUndefined();
309f4a2713aSLionel Sambuc          PrevDef = PrevDef.getPreviousDefinition()) {
310f4a2713aSLionel Sambuc       Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
311f4a2713aSLionel Sambuc            diag::note_pp_ambiguous_macro_other)
312f4a2713aSLionel Sambuc         << Identifier.getIdentifierInfo();
313*0a6a1f1dSLionel Sambuc       if (!PrevDef.getDirective()->isAmbiguous())
314*0a6a1f1dSLionel Sambuc         break;
315f4a2713aSLionel Sambuc     }
316f4a2713aSLionel Sambuc   }
317f4a2713aSLionel Sambuc 
318f4a2713aSLionel Sambuc   // If we started lexing a macro, enter the macro expansion body.
319f4a2713aSLionel Sambuc 
320f4a2713aSLionel Sambuc   // If this macro expands to no tokens, don't bother to push it onto the
321f4a2713aSLionel Sambuc   // expansion stack, only to take it right back off.
322f4a2713aSLionel Sambuc   if (MI->getNumTokens() == 0) {
323f4a2713aSLionel Sambuc     // No need for arg info.
324f4a2713aSLionel Sambuc     if (Args) Args->destroy(*this);
325f4a2713aSLionel Sambuc 
326f4a2713aSLionel Sambuc     // Propagate whitespace info as if we had pushed, then popped,
327f4a2713aSLionel Sambuc     // a macro context.
328f4a2713aSLionel Sambuc     Identifier.setFlag(Token::LeadingEmptyMacro);
329f4a2713aSLionel Sambuc     PropagateLineStartLeadingSpaceInfo(Identifier);
330f4a2713aSLionel Sambuc     ++NumFastMacroExpanded;
331f4a2713aSLionel Sambuc     return false;
332f4a2713aSLionel Sambuc   } else if (MI->getNumTokens() == 1 &&
333f4a2713aSLionel Sambuc              isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
334f4a2713aSLionel Sambuc                                            *this)) {
335f4a2713aSLionel Sambuc     // Otherwise, if this macro expands into a single trivially-expanded
336f4a2713aSLionel Sambuc     // token: expand it now.  This handles common cases like
337f4a2713aSLionel Sambuc     // "#define VAL 42".
338f4a2713aSLionel Sambuc 
339f4a2713aSLionel Sambuc     // No need for arg info.
340f4a2713aSLionel Sambuc     if (Args) Args->destroy(*this);
341f4a2713aSLionel Sambuc 
342f4a2713aSLionel Sambuc     // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
343f4a2713aSLionel Sambuc     // identifier to the expanded token.
344f4a2713aSLionel Sambuc     bool isAtStartOfLine = Identifier.isAtStartOfLine();
345f4a2713aSLionel Sambuc     bool hasLeadingSpace = Identifier.hasLeadingSpace();
346f4a2713aSLionel Sambuc 
347f4a2713aSLionel Sambuc     // Replace the result token.
348f4a2713aSLionel Sambuc     Identifier = MI->getReplacementToken(0);
349f4a2713aSLionel Sambuc 
350f4a2713aSLionel Sambuc     // Restore the StartOfLine/LeadingSpace markers.
351f4a2713aSLionel Sambuc     Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
352f4a2713aSLionel Sambuc     Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
353f4a2713aSLionel Sambuc 
354f4a2713aSLionel Sambuc     // Update the tokens location to include both its expansion and physical
355f4a2713aSLionel Sambuc     // locations.
356f4a2713aSLionel Sambuc     SourceLocation Loc =
357f4a2713aSLionel Sambuc       SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
358f4a2713aSLionel Sambuc                                    ExpansionEnd,Identifier.getLength());
359f4a2713aSLionel Sambuc     Identifier.setLocation(Loc);
360f4a2713aSLionel Sambuc 
361f4a2713aSLionel Sambuc     // If this is a disabled macro or #define X X, we must mark the result as
362f4a2713aSLionel Sambuc     // unexpandable.
363f4a2713aSLionel Sambuc     if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
364f4a2713aSLionel Sambuc       if (MacroInfo *NewMI = getMacroInfo(NewII))
365f4a2713aSLionel Sambuc         if (!NewMI->isEnabled() || NewMI == MI) {
366f4a2713aSLionel Sambuc           Identifier.setFlag(Token::DisableExpand);
367f4a2713aSLionel Sambuc           // Don't warn for "#define X X" like "#define bool bool" from
368f4a2713aSLionel Sambuc           // stdbool.h.
369f4a2713aSLionel Sambuc           if (NewMI != MI || MI->isFunctionLike())
370f4a2713aSLionel Sambuc             Diag(Identifier, diag::pp_disabled_macro_expansion);
371f4a2713aSLionel Sambuc         }
372f4a2713aSLionel Sambuc     }
373f4a2713aSLionel Sambuc 
374f4a2713aSLionel Sambuc     // Since this is not an identifier token, it can't be macro expanded, so
375f4a2713aSLionel Sambuc     // we're done.
376f4a2713aSLionel Sambuc     ++NumFastMacroExpanded;
377f4a2713aSLionel Sambuc     return true;
378f4a2713aSLionel Sambuc   }
379f4a2713aSLionel Sambuc 
380f4a2713aSLionel Sambuc   // Start expanding the macro.
381f4a2713aSLionel Sambuc   EnterMacro(Identifier, ExpansionEnd, MI, Args);
382f4a2713aSLionel Sambuc   return false;
383f4a2713aSLionel Sambuc }
384f4a2713aSLionel Sambuc 
385f4a2713aSLionel Sambuc enum Bracket {
386f4a2713aSLionel Sambuc   Brace,
387f4a2713aSLionel Sambuc   Paren
388f4a2713aSLionel Sambuc };
389f4a2713aSLionel Sambuc 
390f4a2713aSLionel Sambuc /// CheckMatchedBrackets - Returns true if the braces and parentheses in the
391f4a2713aSLionel Sambuc /// token vector are properly nested.
CheckMatchedBrackets(const SmallVectorImpl<Token> & Tokens)392f4a2713aSLionel Sambuc static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
393f4a2713aSLionel Sambuc   SmallVector<Bracket, 8> Brackets;
394f4a2713aSLionel Sambuc   for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
395f4a2713aSLionel Sambuc                                               E = Tokens.end();
396f4a2713aSLionel Sambuc        I != E; ++I) {
397f4a2713aSLionel Sambuc     if (I->is(tok::l_paren)) {
398f4a2713aSLionel Sambuc       Brackets.push_back(Paren);
399f4a2713aSLionel Sambuc     } else if (I->is(tok::r_paren)) {
400f4a2713aSLionel Sambuc       if (Brackets.empty() || Brackets.back() == Brace)
401f4a2713aSLionel Sambuc         return false;
402f4a2713aSLionel Sambuc       Brackets.pop_back();
403f4a2713aSLionel Sambuc     } else if (I->is(tok::l_brace)) {
404f4a2713aSLionel Sambuc       Brackets.push_back(Brace);
405f4a2713aSLionel Sambuc     } else if (I->is(tok::r_brace)) {
406f4a2713aSLionel Sambuc       if (Brackets.empty() || Brackets.back() == Paren)
407f4a2713aSLionel Sambuc         return false;
408f4a2713aSLionel Sambuc       Brackets.pop_back();
409f4a2713aSLionel Sambuc     }
410f4a2713aSLionel Sambuc   }
411f4a2713aSLionel Sambuc   if (!Brackets.empty())
412f4a2713aSLionel Sambuc     return false;
413f4a2713aSLionel Sambuc   return true;
414f4a2713aSLionel Sambuc }
415f4a2713aSLionel Sambuc 
416f4a2713aSLionel Sambuc /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
417f4a2713aSLionel Sambuc /// vector of tokens in NewTokens.  The new number of arguments will be placed
418f4a2713aSLionel Sambuc /// in NumArgs and the ranges which need to surrounded in parentheses will be
419f4a2713aSLionel Sambuc /// in ParenHints.
420f4a2713aSLionel Sambuc /// Returns false if the token stream cannot be changed.  If this is because
421f4a2713aSLionel Sambuc /// of an initializer list starting a macro argument, the range of those
422f4a2713aSLionel Sambuc /// initializer lists will be place in InitLists.
GenerateNewArgTokens(Preprocessor & PP,SmallVectorImpl<Token> & OldTokens,SmallVectorImpl<Token> & NewTokens,unsigned & NumArgs,SmallVectorImpl<SourceRange> & ParenHints,SmallVectorImpl<SourceRange> & InitLists)423f4a2713aSLionel Sambuc static bool GenerateNewArgTokens(Preprocessor &PP,
424f4a2713aSLionel Sambuc                                  SmallVectorImpl<Token> &OldTokens,
425f4a2713aSLionel Sambuc                                  SmallVectorImpl<Token> &NewTokens,
426f4a2713aSLionel Sambuc                                  unsigned &NumArgs,
427f4a2713aSLionel Sambuc                                  SmallVectorImpl<SourceRange> &ParenHints,
428f4a2713aSLionel Sambuc                                  SmallVectorImpl<SourceRange> &InitLists) {
429f4a2713aSLionel Sambuc   if (!CheckMatchedBrackets(OldTokens))
430f4a2713aSLionel Sambuc     return false;
431f4a2713aSLionel Sambuc 
432f4a2713aSLionel Sambuc   // Once it is known that the brackets are matched, only a simple count of the
433f4a2713aSLionel Sambuc   // braces is needed.
434f4a2713aSLionel Sambuc   unsigned Braces = 0;
435f4a2713aSLionel Sambuc 
436f4a2713aSLionel Sambuc   // First token of a new macro argument.
437f4a2713aSLionel Sambuc   SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
438f4a2713aSLionel Sambuc 
439f4a2713aSLionel Sambuc   // First closing brace in a new macro argument.  Used to generate
440f4a2713aSLionel Sambuc   // SourceRanges for InitLists.
441f4a2713aSLionel Sambuc   SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
442f4a2713aSLionel Sambuc   NumArgs = 0;
443f4a2713aSLionel Sambuc   Token TempToken;
444f4a2713aSLionel Sambuc   // Set to true when a macro separator token is found inside a braced list.
445f4a2713aSLionel Sambuc   // If true, the fixed argument spans multiple old arguments and ParenHints
446f4a2713aSLionel Sambuc   // will be updated.
447f4a2713aSLionel Sambuc   bool FoundSeparatorToken = false;
448f4a2713aSLionel Sambuc   for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
449f4a2713aSLionel Sambuc                                         E = OldTokens.end();
450f4a2713aSLionel Sambuc        I != E; ++I) {
451f4a2713aSLionel Sambuc     if (I->is(tok::l_brace)) {
452f4a2713aSLionel Sambuc       ++Braces;
453f4a2713aSLionel Sambuc     } else if (I->is(tok::r_brace)) {
454f4a2713aSLionel Sambuc       --Braces;
455f4a2713aSLionel Sambuc       if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
456f4a2713aSLionel Sambuc         ClosingBrace = I;
457f4a2713aSLionel Sambuc     } else if (I->is(tok::eof)) {
458f4a2713aSLionel Sambuc       // EOF token is used to separate macro arguments
459f4a2713aSLionel Sambuc       if (Braces != 0) {
460f4a2713aSLionel Sambuc         // Assume comma separator is actually braced list separator and change
461f4a2713aSLionel Sambuc         // it back to a comma.
462f4a2713aSLionel Sambuc         FoundSeparatorToken = true;
463f4a2713aSLionel Sambuc         I->setKind(tok::comma);
464f4a2713aSLionel Sambuc         I->setLength(1);
465f4a2713aSLionel Sambuc       } else { // Braces == 0
466f4a2713aSLionel Sambuc         // Separator token still separates arguments.
467f4a2713aSLionel Sambuc         ++NumArgs;
468f4a2713aSLionel Sambuc 
469f4a2713aSLionel Sambuc         // If the argument starts with a brace, it can't be fixed with
470f4a2713aSLionel Sambuc         // parentheses.  A different diagnostic will be given.
471f4a2713aSLionel Sambuc         if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
472f4a2713aSLionel Sambuc           InitLists.push_back(
473f4a2713aSLionel Sambuc               SourceRange(ArgStartIterator->getLocation(),
474f4a2713aSLionel Sambuc                           PP.getLocForEndOfToken(ClosingBrace->getLocation())));
475f4a2713aSLionel Sambuc           ClosingBrace = E;
476f4a2713aSLionel Sambuc         }
477f4a2713aSLionel Sambuc 
478f4a2713aSLionel Sambuc         // Add left paren
479f4a2713aSLionel Sambuc         if (FoundSeparatorToken) {
480f4a2713aSLionel Sambuc           TempToken.startToken();
481f4a2713aSLionel Sambuc           TempToken.setKind(tok::l_paren);
482f4a2713aSLionel Sambuc           TempToken.setLocation(ArgStartIterator->getLocation());
483f4a2713aSLionel Sambuc           TempToken.setLength(0);
484f4a2713aSLionel Sambuc           NewTokens.push_back(TempToken);
485f4a2713aSLionel Sambuc         }
486f4a2713aSLionel Sambuc 
487f4a2713aSLionel Sambuc         // Copy over argument tokens
488f4a2713aSLionel Sambuc         NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
489f4a2713aSLionel Sambuc 
490f4a2713aSLionel Sambuc         // Add right paren and store the paren locations in ParenHints
491f4a2713aSLionel Sambuc         if (FoundSeparatorToken) {
492f4a2713aSLionel Sambuc           SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
493f4a2713aSLionel Sambuc           TempToken.startToken();
494f4a2713aSLionel Sambuc           TempToken.setKind(tok::r_paren);
495f4a2713aSLionel Sambuc           TempToken.setLocation(Loc);
496f4a2713aSLionel Sambuc           TempToken.setLength(0);
497f4a2713aSLionel Sambuc           NewTokens.push_back(TempToken);
498f4a2713aSLionel Sambuc           ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
499f4a2713aSLionel Sambuc                                            Loc));
500f4a2713aSLionel Sambuc         }
501f4a2713aSLionel Sambuc 
502f4a2713aSLionel Sambuc         // Copy separator token
503f4a2713aSLionel Sambuc         NewTokens.push_back(*I);
504f4a2713aSLionel Sambuc 
505f4a2713aSLionel Sambuc         // Reset values
506f4a2713aSLionel Sambuc         ArgStartIterator = I + 1;
507f4a2713aSLionel Sambuc         FoundSeparatorToken = false;
508f4a2713aSLionel Sambuc       }
509f4a2713aSLionel Sambuc     }
510f4a2713aSLionel Sambuc   }
511f4a2713aSLionel Sambuc 
512f4a2713aSLionel Sambuc   return !ParenHints.empty() && InitLists.empty();
513f4a2713aSLionel Sambuc }
514f4a2713aSLionel Sambuc 
515f4a2713aSLionel Sambuc /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
516f4a2713aSLionel Sambuc /// token is the '(' of the macro, this method is invoked to read all of the
517f4a2713aSLionel Sambuc /// actual arguments specified for the macro invocation.  This returns null on
518f4a2713aSLionel Sambuc /// error.
ReadFunctionLikeMacroArgs(Token & MacroName,MacroInfo * MI,SourceLocation & MacroEnd)519f4a2713aSLionel Sambuc MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
520f4a2713aSLionel Sambuc                                                    MacroInfo *MI,
521f4a2713aSLionel Sambuc                                                    SourceLocation &MacroEnd) {
522f4a2713aSLionel Sambuc   // The number of fixed arguments to parse.
523f4a2713aSLionel Sambuc   unsigned NumFixedArgsLeft = MI->getNumArgs();
524f4a2713aSLionel Sambuc   bool isVariadic = MI->isVariadic();
525f4a2713aSLionel Sambuc 
526f4a2713aSLionel Sambuc   // Outer loop, while there are more arguments, keep reading them.
527f4a2713aSLionel Sambuc   Token Tok;
528f4a2713aSLionel Sambuc 
529f4a2713aSLionel Sambuc   // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
530f4a2713aSLionel Sambuc   // an argument value in a macro could expand to ',' or '(' or ')'.
531f4a2713aSLionel Sambuc   LexUnexpandedToken(Tok);
532f4a2713aSLionel Sambuc   assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
533f4a2713aSLionel Sambuc 
534f4a2713aSLionel Sambuc   // ArgTokens - Build up a list of tokens that make up each argument.  Each
535f4a2713aSLionel Sambuc   // argument is separated by an EOF token.  Use a SmallVector so we can avoid
536f4a2713aSLionel Sambuc   // heap allocations in the common case.
537f4a2713aSLionel Sambuc   SmallVector<Token, 64> ArgTokens;
538f4a2713aSLionel Sambuc   bool ContainsCodeCompletionTok = false;
539f4a2713aSLionel Sambuc 
540f4a2713aSLionel Sambuc   SourceLocation TooManyArgsLoc;
541f4a2713aSLionel Sambuc 
542f4a2713aSLionel Sambuc   unsigned NumActuals = 0;
543f4a2713aSLionel Sambuc   while (Tok.isNot(tok::r_paren)) {
544f4a2713aSLionel Sambuc     if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
545f4a2713aSLionel Sambuc       break;
546f4a2713aSLionel Sambuc 
547f4a2713aSLionel Sambuc     assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
548f4a2713aSLionel Sambuc            "only expect argument separators here");
549f4a2713aSLionel Sambuc 
550f4a2713aSLionel Sambuc     unsigned ArgTokenStart = ArgTokens.size();
551f4a2713aSLionel Sambuc     SourceLocation ArgStartLoc = Tok.getLocation();
552f4a2713aSLionel Sambuc 
553f4a2713aSLionel Sambuc     // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
554f4a2713aSLionel Sambuc     // that we already consumed the first one.
555f4a2713aSLionel Sambuc     unsigned NumParens = 0;
556f4a2713aSLionel Sambuc 
557f4a2713aSLionel Sambuc     while (1) {
558f4a2713aSLionel Sambuc       // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
559f4a2713aSLionel Sambuc       // an argument value in a macro could expand to ',' or '(' or ')'.
560f4a2713aSLionel Sambuc       LexUnexpandedToken(Tok);
561f4a2713aSLionel Sambuc 
562f4a2713aSLionel Sambuc       if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
563f4a2713aSLionel Sambuc         if (!ContainsCodeCompletionTok) {
564f4a2713aSLionel Sambuc           Diag(MacroName, diag::err_unterm_macro_invoc);
565f4a2713aSLionel Sambuc           Diag(MI->getDefinitionLoc(), diag::note_macro_here)
566f4a2713aSLionel Sambuc             << MacroName.getIdentifierInfo();
567f4a2713aSLionel Sambuc           // Do not lose the EOF/EOD.  Return it to the client.
568f4a2713aSLionel Sambuc           MacroName = Tok;
569*0a6a1f1dSLionel Sambuc           return nullptr;
570f4a2713aSLionel Sambuc         } else {
571f4a2713aSLionel Sambuc           // Do not lose the EOF/EOD.
572f4a2713aSLionel Sambuc           Token *Toks = new Token[1];
573f4a2713aSLionel Sambuc           Toks[0] = Tok;
574f4a2713aSLionel Sambuc           EnterTokenStream(Toks, 1, true, true);
575f4a2713aSLionel Sambuc           break;
576f4a2713aSLionel Sambuc         }
577f4a2713aSLionel Sambuc       } else if (Tok.is(tok::r_paren)) {
578f4a2713aSLionel Sambuc         // If we found the ) token, the macro arg list is done.
579f4a2713aSLionel Sambuc         if (NumParens-- == 0) {
580f4a2713aSLionel Sambuc           MacroEnd = Tok.getLocation();
581f4a2713aSLionel Sambuc           break;
582f4a2713aSLionel Sambuc         }
583f4a2713aSLionel Sambuc       } else if (Tok.is(tok::l_paren)) {
584f4a2713aSLionel Sambuc         ++NumParens;
585f4a2713aSLionel Sambuc       } else if (Tok.is(tok::comma) && NumParens == 0 &&
586f4a2713aSLionel Sambuc                  !(Tok.getFlags() & Token::IgnoredComma)) {
587f4a2713aSLionel Sambuc         // In Microsoft-compatibility mode, single commas from nested macro
588f4a2713aSLionel Sambuc         // expansions should not be considered as argument separators. We test
589f4a2713aSLionel Sambuc         // for this with the IgnoredComma token flag above.
590f4a2713aSLionel Sambuc 
591f4a2713aSLionel Sambuc         // Comma ends this argument if there are more fixed arguments expected.
592f4a2713aSLionel Sambuc         // However, if this is a variadic macro, and this is part of the
593f4a2713aSLionel Sambuc         // variadic part, then the comma is just an argument token.
594f4a2713aSLionel Sambuc         if (!isVariadic) break;
595f4a2713aSLionel Sambuc         if (NumFixedArgsLeft > 1)
596f4a2713aSLionel Sambuc           break;
597f4a2713aSLionel Sambuc       } else if (Tok.is(tok::comment) && !KeepMacroComments) {
598f4a2713aSLionel Sambuc         // If this is a comment token in the argument list and we're just in
599f4a2713aSLionel Sambuc         // -C mode (not -CC mode), discard the comment.
600f4a2713aSLionel Sambuc         continue;
601*0a6a1f1dSLionel Sambuc       } else if (Tok.getIdentifierInfo() != nullptr) {
602f4a2713aSLionel Sambuc         // Reading macro arguments can cause macros that we are currently
603f4a2713aSLionel Sambuc         // expanding from to be popped off the expansion stack.  Doing so causes
604f4a2713aSLionel Sambuc         // them to be reenabled for expansion.  Here we record whether any
605f4a2713aSLionel Sambuc         // identifiers we lex as macro arguments correspond to disabled macros.
606f4a2713aSLionel Sambuc         // If so, we mark the token as noexpand.  This is a subtle aspect of
607f4a2713aSLionel Sambuc         // C99 6.10.3.4p2.
608f4a2713aSLionel Sambuc         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
609f4a2713aSLionel Sambuc           if (!MI->isEnabled())
610f4a2713aSLionel Sambuc             Tok.setFlag(Token::DisableExpand);
611f4a2713aSLionel Sambuc       } else if (Tok.is(tok::code_completion)) {
612f4a2713aSLionel Sambuc         ContainsCodeCompletionTok = true;
613f4a2713aSLionel Sambuc         if (CodeComplete)
614f4a2713aSLionel Sambuc           CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
615f4a2713aSLionel Sambuc                                                   MI, NumActuals);
616f4a2713aSLionel Sambuc         // Don't mark that we reached the code-completion point because the
617f4a2713aSLionel Sambuc         // parser is going to handle the token and there will be another
618f4a2713aSLionel Sambuc         // code-completion callback.
619f4a2713aSLionel Sambuc       }
620f4a2713aSLionel Sambuc 
621f4a2713aSLionel Sambuc       ArgTokens.push_back(Tok);
622f4a2713aSLionel Sambuc     }
623f4a2713aSLionel Sambuc 
624f4a2713aSLionel Sambuc     // If this was an empty argument list foo(), don't add this as an empty
625f4a2713aSLionel Sambuc     // argument.
626f4a2713aSLionel Sambuc     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
627f4a2713aSLionel Sambuc       break;
628f4a2713aSLionel Sambuc 
629f4a2713aSLionel Sambuc     // If this is not a variadic macro, and too many args were specified, emit
630f4a2713aSLionel Sambuc     // an error.
631f4a2713aSLionel Sambuc     if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
632f4a2713aSLionel Sambuc       if (ArgTokens.size() != ArgTokenStart)
633f4a2713aSLionel Sambuc         TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
634f4a2713aSLionel Sambuc       else
635f4a2713aSLionel Sambuc         TooManyArgsLoc = ArgStartLoc;
636f4a2713aSLionel Sambuc     }
637f4a2713aSLionel Sambuc 
638f4a2713aSLionel Sambuc     // Empty arguments are standard in C99 and C++0x, and are supported as an
639f4a2713aSLionel Sambuc     // extension in other modes.
640f4a2713aSLionel Sambuc     if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
641f4a2713aSLionel Sambuc       Diag(Tok, LangOpts.CPlusPlus11 ?
642f4a2713aSLionel Sambuc            diag::warn_cxx98_compat_empty_fnmacro_arg :
643f4a2713aSLionel Sambuc            diag::ext_empty_fnmacro_arg);
644f4a2713aSLionel Sambuc 
645f4a2713aSLionel Sambuc     // Add a marker EOF token to the end of the token list for this argument.
646f4a2713aSLionel Sambuc     Token EOFTok;
647f4a2713aSLionel Sambuc     EOFTok.startToken();
648f4a2713aSLionel Sambuc     EOFTok.setKind(tok::eof);
649f4a2713aSLionel Sambuc     EOFTok.setLocation(Tok.getLocation());
650f4a2713aSLionel Sambuc     EOFTok.setLength(0);
651f4a2713aSLionel Sambuc     ArgTokens.push_back(EOFTok);
652f4a2713aSLionel Sambuc     ++NumActuals;
653f4a2713aSLionel Sambuc     if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
654f4a2713aSLionel Sambuc       --NumFixedArgsLeft;
655f4a2713aSLionel Sambuc   }
656f4a2713aSLionel Sambuc 
657f4a2713aSLionel Sambuc   // Okay, we either found the r_paren.  Check to see if we parsed too few
658f4a2713aSLionel Sambuc   // arguments.
659f4a2713aSLionel Sambuc   unsigned MinArgsExpected = MI->getNumArgs();
660f4a2713aSLionel Sambuc 
661f4a2713aSLionel Sambuc   // If this is not a variadic macro, and too many args were specified, emit
662f4a2713aSLionel Sambuc   // an error.
663f4a2713aSLionel Sambuc   if (!isVariadic && NumActuals > MinArgsExpected &&
664f4a2713aSLionel Sambuc       !ContainsCodeCompletionTok) {
665f4a2713aSLionel Sambuc     // Emit the diagnostic at the macro name in case there is a missing ).
666f4a2713aSLionel Sambuc     // Emitting it at the , could be far away from the macro name.
667f4a2713aSLionel Sambuc     Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
668f4a2713aSLionel Sambuc     Diag(MI->getDefinitionLoc(), diag::note_macro_here)
669f4a2713aSLionel Sambuc       << MacroName.getIdentifierInfo();
670f4a2713aSLionel Sambuc 
671f4a2713aSLionel Sambuc     // Commas from braced initializer lists will be treated as argument
672f4a2713aSLionel Sambuc     // separators inside macros.  Attempt to correct for this with parentheses.
673f4a2713aSLionel Sambuc     // TODO: See if this can be generalized to angle brackets for templates
674f4a2713aSLionel Sambuc     // inside macro arguments.
675f4a2713aSLionel Sambuc 
676f4a2713aSLionel Sambuc     SmallVector<Token, 4> FixedArgTokens;
677f4a2713aSLionel Sambuc     unsigned FixedNumArgs = 0;
678f4a2713aSLionel Sambuc     SmallVector<SourceRange, 4> ParenHints, InitLists;
679f4a2713aSLionel Sambuc     if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
680f4a2713aSLionel Sambuc                               ParenHints, InitLists)) {
681f4a2713aSLionel Sambuc       if (!InitLists.empty()) {
682f4a2713aSLionel Sambuc         DiagnosticBuilder DB =
683f4a2713aSLionel Sambuc             Diag(MacroName,
684f4a2713aSLionel Sambuc                  diag::note_init_list_at_beginning_of_macro_argument);
685*0a6a1f1dSLionel Sambuc         for (const SourceRange &Range : InitLists)
686*0a6a1f1dSLionel Sambuc           DB << Range;
687f4a2713aSLionel Sambuc       }
688*0a6a1f1dSLionel Sambuc       return nullptr;
689f4a2713aSLionel Sambuc     }
690f4a2713aSLionel Sambuc     if (FixedNumArgs != MinArgsExpected)
691*0a6a1f1dSLionel Sambuc       return nullptr;
692f4a2713aSLionel Sambuc 
693f4a2713aSLionel Sambuc     DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
694*0a6a1f1dSLionel Sambuc     for (const SourceRange &ParenLocation : ParenHints) {
695*0a6a1f1dSLionel Sambuc       DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
696*0a6a1f1dSLionel Sambuc       DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
697f4a2713aSLionel Sambuc     }
698f4a2713aSLionel Sambuc     ArgTokens.swap(FixedArgTokens);
699f4a2713aSLionel Sambuc     NumActuals = FixedNumArgs;
700f4a2713aSLionel Sambuc   }
701f4a2713aSLionel Sambuc 
702f4a2713aSLionel Sambuc   // See MacroArgs instance var for description of this.
703f4a2713aSLionel Sambuc   bool isVarargsElided = false;
704f4a2713aSLionel Sambuc 
705f4a2713aSLionel Sambuc   if (ContainsCodeCompletionTok) {
706f4a2713aSLionel Sambuc     // Recover from not-fully-formed macro invocation during code-completion.
707f4a2713aSLionel Sambuc     Token EOFTok;
708f4a2713aSLionel Sambuc     EOFTok.startToken();
709f4a2713aSLionel Sambuc     EOFTok.setKind(tok::eof);
710f4a2713aSLionel Sambuc     EOFTok.setLocation(Tok.getLocation());
711f4a2713aSLionel Sambuc     EOFTok.setLength(0);
712f4a2713aSLionel Sambuc     for (; NumActuals < MinArgsExpected; ++NumActuals)
713f4a2713aSLionel Sambuc       ArgTokens.push_back(EOFTok);
714f4a2713aSLionel Sambuc   }
715f4a2713aSLionel Sambuc 
716f4a2713aSLionel Sambuc   if (NumActuals < MinArgsExpected) {
717f4a2713aSLionel Sambuc     // There are several cases where too few arguments is ok, handle them now.
718f4a2713aSLionel Sambuc     if (NumActuals == 0 && MinArgsExpected == 1) {
719f4a2713aSLionel Sambuc       // #define A(X)  or  #define A(...)   ---> A()
720f4a2713aSLionel Sambuc 
721f4a2713aSLionel Sambuc       // If there is exactly one argument, and that argument is missing,
722f4a2713aSLionel Sambuc       // then we have an empty "()" argument empty list.  This is fine, even if
723f4a2713aSLionel Sambuc       // the macro expects one argument (the argument is just empty).
724f4a2713aSLionel Sambuc       isVarargsElided = MI->isVariadic();
725f4a2713aSLionel Sambuc     } else if (MI->isVariadic() &&
726f4a2713aSLionel Sambuc                (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
727f4a2713aSLionel Sambuc                 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
728f4a2713aSLionel Sambuc       // Varargs where the named vararg parameter is missing: OK as extension.
729f4a2713aSLionel Sambuc       //   #define A(x, ...)
730f4a2713aSLionel Sambuc       //   A("blah")
731f4a2713aSLionel Sambuc       //
732f4a2713aSLionel Sambuc       // If the macro contains the comma pasting extension, the diagnostic
733f4a2713aSLionel Sambuc       // is suppressed; we know we'll get another diagnostic later.
734f4a2713aSLionel Sambuc       if (!MI->hasCommaPasting()) {
735f4a2713aSLionel Sambuc         Diag(Tok, diag::ext_missing_varargs_arg);
736f4a2713aSLionel Sambuc         Diag(MI->getDefinitionLoc(), diag::note_macro_here)
737f4a2713aSLionel Sambuc           << MacroName.getIdentifierInfo();
738f4a2713aSLionel Sambuc       }
739f4a2713aSLionel Sambuc 
740f4a2713aSLionel Sambuc       // Remember this occurred, allowing us to elide the comma when used for
741f4a2713aSLionel Sambuc       // cases like:
742f4a2713aSLionel Sambuc       //   #define A(x, foo...) blah(a, ## foo)
743f4a2713aSLionel Sambuc       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
744f4a2713aSLionel Sambuc       //   #define C(...) blah(a, ## __VA_ARGS__)
745f4a2713aSLionel Sambuc       //  A(x) B(x) C()
746f4a2713aSLionel Sambuc       isVarargsElided = true;
747f4a2713aSLionel Sambuc     } else if (!ContainsCodeCompletionTok) {
748f4a2713aSLionel Sambuc       // Otherwise, emit the error.
749f4a2713aSLionel Sambuc       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
750f4a2713aSLionel Sambuc       Diag(MI->getDefinitionLoc(), diag::note_macro_here)
751f4a2713aSLionel Sambuc         << MacroName.getIdentifierInfo();
752*0a6a1f1dSLionel Sambuc       return nullptr;
753f4a2713aSLionel Sambuc     }
754f4a2713aSLionel Sambuc 
755f4a2713aSLionel Sambuc     // Add a marker EOF token to the end of the token list for this argument.
756f4a2713aSLionel Sambuc     SourceLocation EndLoc = Tok.getLocation();
757f4a2713aSLionel Sambuc     Tok.startToken();
758f4a2713aSLionel Sambuc     Tok.setKind(tok::eof);
759f4a2713aSLionel Sambuc     Tok.setLocation(EndLoc);
760f4a2713aSLionel Sambuc     Tok.setLength(0);
761f4a2713aSLionel Sambuc     ArgTokens.push_back(Tok);
762f4a2713aSLionel Sambuc 
763f4a2713aSLionel Sambuc     // If we expect two arguments, add both as empty.
764f4a2713aSLionel Sambuc     if (NumActuals == 0 && MinArgsExpected == 2)
765f4a2713aSLionel Sambuc       ArgTokens.push_back(Tok);
766f4a2713aSLionel Sambuc 
767f4a2713aSLionel Sambuc   } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
768f4a2713aSLionel Sambuc              !ContainsCodeCompletionTok) {
769f4a2713aSLionel Sambuc     // Emit the diagnostic at the macro name in case there is a missing ).
770f4a2713aSLionel Sambuc     // Emitting it at the , could be far away from the macro name.
771f4a2713aSLionel Sambuc     Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
772f4a2713aSLionel Sambuc     Diag(MI->getDefinitionLoc(), diag::note_macro_here)
773f4a2713aSLionel Sambuc       << MacroName.getIdentifierInfo();
774*0a6a1f1dSLionel Sambuc     return nullptr;
775f4a2713aSLionel Sambuc   }
776f4a2713aSLionel Sambuc 
777f4a2713aSLionel Sambuc   return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
778f4a2713aSLionel Sambuc }
779f4a2713aSLionel Sambuc 
780f4a2713aSLionel Sambuc /// \brief Keeps macro expanded tokens for TokenLexers.
781f4a2713aSLionel Sambuc //
782f4a2713aSLionel Sambuc /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
783f4a2713aSLionel Sambuc /// going to lex in the cache and when it finishes the tokens are removed
784f4a2713aSLionel Sambuc /// from the end of the cache.
cacheMacroExpandedTokens(TokenLexer * tokLexer,ArrayRef<Token> tokens)785f4a2713aSLionel Sambuc Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
786f4a2713aSLionel Sambuc                                               ArrayRef<Token> tokens) {
787f4a2713aSLionel Sambuc   assert(tokLexer);
788f4a2713aSLionel Sambuc   if (tokens.empty())
789*0a6a1f1dSLionel Sambuc     return nullptr;
790f4a2713aSLionel Sambuc 
791f4a2713aSLionel Sambuc   size_t newIndex = MacroExpandedTokens.size();
792f4a2713aSLionel Sambuc   bool cacheNeedsToGrow = tokens.size() >
793f4a2713aSLionel Sambuc                       MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
794f4a2713aSLionel Sambuc   MacroExpandedTokens.append(tokens.begin(), tokens.end());
795f4a2713aSLionel Sambuc 
796f4a2713aSLionel Sambuc   if (cacheNeedsToGrow) {
797f4a2713aSLionel Sambuc     // Go through all the TokenLexers whose 'Tokens' pointer points in the
798f4a2713aSLionel Sambuc     // buffer and update the pointers to the (potential) new buffer array.
799f4a2713aSLionel Sambuc     for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
800f4a2713aSLionel Sambuc       TokenLexer *prevLexer;
801f4a2713aSLionel Sambuc       size_t tokIndex;
802*0a6a1f1dSLionel Sambuc       std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
803f4a2713aSLionel Sambuc       prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
804f4a2713aSLionel Sambuc     }
805f4a2713aSLionel Sambuc   }
806f4a2713aSLionel Sambuc 
807f4a2713aSLionel Sambuc   MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
808f4a2713aSLionel Sambuc   return MacroExpandedTokens.data() + newIndex;
809f4a2713aSLionel Sambuc }
810f4a2713aSLionel Sambuc 
removeCachedMacroExpandedTokensOfLastLexer()811f4a2713aSLionel Sambuc void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
812f4a2713aSLionel Sambuc   assert(!MacroExpandingLexersStack.empty());
813f4a2713aSLionel Sambuc   size_t tokIndex = MacroExpandingLexersStack.back().second;
814f4a2713aSLionel Sambuc   assert(tokIndex < MacroExpandedTokens.size());
815f4a2713aSLionel Sambuc   // Pop the cached macro expanded tokens from the end.
816f4a2713aSLionel Sambuc   MacroExpandedTokens.resize(tokIndex);
817f4a2713aSLionel Sambuc   MacroExpandingLexersStack.pop_back();
818f4a2713aSLionel Sambuc }
819f4a2713aSLionel Sambuc 
820f4a2713aSLionel Sambuc /// ComputeDATE_TIME - Compute the current time, enter it into the specified
821f4a2713aSLionel Sambuc /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
822f4a2713aSLionel Sambuc /// the identifier tokens inserted.
ComputeDATE_TIME(SourceLocation & DATELoc,SourceLocation & TIMELoc,Preprocessor & PP)823f4a2713aSLionel Sambuc static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
824f4a2713aSLionel Sambuc                              Preprocessor &PP) {
825*0a6a1f1dSLionel Sambuc   time_t TT = time(nullptr);
826f4a2713aSLionel Sambuc   struct tm *TM = localtime(&TT);
827f4a2713aSLionel Sambuc 
828f4a2713aSLionel Sambuc   static const char * const Months[] = {
829f4a2713aSLionel Sambuc     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
830f4a2713aSLionel Sambuc   };
831f4a2713aSLionel Sambuc 
832f4a2713aSLionel Sambuc   {
833f4a2713aSLionel Sambuc     SmallString<32> TmpBuffer;
834f4a2713aSLionel Sambuc     llvm::raw_svector_ostream TmpStream(TmpBuffer);
835f4a2713aSLionel Sambuc     TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
836f4a2713aSLionel Sambuc                               TM->tm_mday, TM->tm_year + 1900);
837f4a2713aSLionel Sambuc     Token TmpTok;
838f4a2713aSLionel Sambuc     TmpTok.startToken();
839f4a2713aSLionel Sambuc     PP.CreateString(TmpStream.str(), TmpTok);
840f4a2713aSLionel Sambuc     DATELoc = TmpTok.getLocation();
841f4a2713aSLionel Sambuc   }
842f4a2713aSLionel Sambuc 
843f4a2713aSLionel Sambuc   {
844f4a2713aSLionel Sambuc     SmallString<32> TmpBuffer;
845f4a2713aSLionel Sambuc     llvm::raw_svector_ostream TmpStream(TmpBuffer);
846f4a2713aSLionel Sambuc     TmpStream << llvm::format("\"%02d:%02d:%02d\"",
847f4a2713aSLionel Sambuc                               TM->tm_hour, TM->tm_min, TM->tm_sec);
848f4a2713aSLionel Sambuc     Token TmpTok;
849f4a2713aSLionel Sambuc     TmpTok.startToken();
850f4a2713aSLionel Sambuc     PP.CreateString(TmpStream.str(), TmpTok);
851f4a2713aSLionel Sambuc     TIMELoc = TmpTok.getLocation();
852f4a2713aSLionel Sambuc   }
853f4a2713aSLionel Sambuc }
854f4a2713aSLionel Sambuc 
855f4a2713aSLionel Sambuc 
856f4a2713aSLionel Sambuc /// HasFeature - Return true if we recognize and implement the feature
857f4a2713aSLionel Sambuc /// specified by the identifier as a standard language feature.
HasFeature(const Preprocessor & PP,const IdentifierInfo * II)858f4a2713aSLionel Sambuc static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
859f4a2713aSLionel Sambuc   const LangOptions &LangOpts = PP.getLangOpts();
860f4a2713aSLionel Sambuc   StringRef Feature = II->getName();
861f4a2713aSLionel Sambuc 
862f4a2713aSLionel Sambuc   // Normalize the feature name, __foo__ becomes foo.
863f4a2713aSLionel Sambuc   if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
864f4a2713aSLionel Sambuc     Feature = Feature.substr(2, Feature.size() - 4);
865f4a2713aSLionel Sambuc 
866f4a2713aSLionel Sambuc   return llvm::StringSwitch<bool>(Feature)
867*0a6a1f1dSLionel Sambuc       .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
868f4a2713aSLionel Sambuc       .Case("attribute_analyzer_noreturn", true)
869f4a2713aSLionel Sambuc       .Case("attribute_availability", true)
870f4a2713aSLionel Sambuc       .Case("attribute_availability_with_message", true)
871f4a2713aSLionel Sambuc       .Case("attribute_cf_returns_not_retained", true)
872f4a2713aSLionel Sambuc       .Case("attribute_cf_returns_retained", true)
873f4a2713aSLionel Sambuc       .Case("attribute_deprecated_with_message", true)
874f4a2713aSLionel Sambuc       .Case("attribute_ext_vector_type", true)
875f4a2713aSLionel Sambuc       .Case("attribute_ns_returns_not_retained", true)
876f4a2713aSLionel Sambuc       .Case("attribute_ns_returns_retained", true)
877f4a2713aSLionel Sambuc       .Case("attribute_ns_consumes_self", true)
878f4a2713aSLionel Sambuc       .Case("attribute_ns_consumed", true)
879f4a2713aSLionel Sambuc       .Case("attribute_cf_consumed", true)
880f4a2713aSLionel Sambuc       .Case("attribute_objc_ivar_unused", true)
881f4a2713aSLionel Sambuc       .Case("attribute_objc_method_family", true)
882f4a2713aSLionel Sambuc       .Case("attribute_overloadable", true)
883f4a2713aSLionel Sambuc       .Case("attribute_unavailable_with_message", true)
884f4a2713aSLionel Sambuc       .Case("attribute_unused_on_fields", true)
885f4a2713aSLionel Sambuc       .Case("blocks", LangOpts.Blocks)
886f4a2713aSLionel Sambuc       .Case("c_thread_safety_attributes", true)
887*0a6a1f1dSLionel Sambuc       .Case("cxx_exceptions", LangOpts.CXXExceptions)
888f4a2713aSLionel Sambuc       .Case("cxx_rtti", LangOpts.RTTI)
889f4a2713aSLionel Sambuc       .Case("enumerator_attributes", true)
890*0a6a1f1dSLionel Sambuc       .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
891*0a6a1f1dSLionel Sambuc       .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
892*0a6a1f1dSLionel Sambuc       .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
893f4a2713aSLionel Sambuc       // Objective-C features
894f4a2713aSLionel Sambuc       .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
895f4a2713aSLionel Sambuc       .Case("objc_arc", LangOpts.ObjCAutoRefCount)
896f4a2713aSLionel Sambuc       .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
897f4a2713aSLionel Sambuc       .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
898f4a2713aSLionel Sambuc       .Case("objc_fixed_enum", LangOpts.ObjC2)
899f4a2713aSLionel Sambuc       .Case("objc_instancetype", LangOpts.ObjC2)
900f4a2713aSLionel Sambuc       .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
901f4a2713aSLionel Sambuc       .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
902*0a6a1f1dSLionel Sambuc       .Case("objc_property_explicit_atomic",
903*0a6a1f1dSLionel Sambuc             true) // Does clang support explicit "atomic" keyword?
904f4a2713aSLionel Sambuc       .Case("objc_protocol_qualifier_mangling", true)
905f4a2713aSLionel Sambuc       .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
906f4a2713aSLionel Sambuc       .Case("ownership_holds", true)
907f4a2713aSLionel Sambuc       .Case("ownership_returns", true)
908f4a2713aSLionel Sambuc       .Case("ownership_takes", true)
909f4a2713aSLionel Sambuc       .Case("objc_bool", true)
910f4a2713aSLionel Sambuc       .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
911f4a2713aSLionel Sambuc       .Case("objc_array_literals", LangOpts.ObjC2)
912f4a2713aSLionel Sambuc       .Case("objc_dictionary_literals", LangOpts.ObjC2)
913f4a2713aSLionel Sambuc       .Case("objc_boxed_expressions", LangOpts.ObjC2)
914f4a2713aSLionel Sambuc       .Case("arc_cf_code_audited", true)
915*0a6a1f1dSLionel Sambuc       .Case("objc_bridge_id", LangOpts.ObjC2)
916f4a2713aSLionel Sambuc       // C11 features
917f4a2713aSLionel Sambuc       .Case("c_alignas", LangOpts.C11)
918*0a6a1f1dSLionel Sambuc       .Case("c_alignof", LangOpts.C11)
919f4a2713aSLionel Sambuc       .Case("c_atomic", LangOpts.C11)
920f4a2713aSLionel Sambuc       .Case("c_generic_selections", LangOpts.C11)
921f4a2713aSLionel Sambuc       .Case("c_static_assert", LangOpts.C11)
922f4a2713aSLionel Sambuc       .Case("c_thread_local",
923f4a2713aSLionel Sambuc             LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
924f4a2713aSLionel Sambuc       // C++11 features
925f4a2713aSLionel Sambuc       .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
926f4a2713aSLionel Sambuc       .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
927f4a2713aSLionel Sambuc       .Case("cxx_alignas", LangOpts.CPlusPlus11)
928*0a6a1f1dSLionel Sambuc       .Case("cxx_alignof", LangOpts.CPlusPlus11)
929f4a2713aSLionel Sambuc       .Case("cxx_atomic", LangOpts.CPlusPlus11)
930f4a2713aSLionel Sambuc       .Case("cxx_attributes", LangOpts.CPlusPlus11)
931f4a2713aSLionel Sambuc       .Case("cxx_auto_type", LangOpts.CPlusPlus11)
932f4a2713aSLionel Sambuc       .Case("cxx_constexpr", LangOpts.CPlusPlus11)
933f4a2713aSLionel Sambuc       .Case("cxx_decltype", LangOpts.CPlusPlus11)
934f4a2713aSLionel Sambuc       .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
935f4a2713aSLionel Sambuc       .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
936f4a2713aSLionel Sambuc       .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
937f4a2713aSLionel Sambuc       .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
938f4a2713aSLionel Sambuc       .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
939f4a2713aSLionel Sambuc       .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
940f4a2713aSLionel Sambuc       .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
941f4a2713aSLionel Sambuc       .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
942f4a2713aSLionel Sambuc       .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
943f4a2713aSLionel Sambuc       .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
944f4a2713aSLionel Sambuc       .Case("cxx_lambdas", LangOpts.CPlusPlus11)
945f4a2713aSLionel Sambuc       .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
946f4a2713aSLionel Sambuc       .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
947f4a2713aSLionel Sambuc       .Case("cxx_noexcept", LangOpts.CPlusPlus11)
948f4a2713aSLionel Sambuc       .Case("cxx_nullptr", LangOpts.CPlusPlus11)
949f4a2713aSLionel Sambuc       .Case("cxx_override_control", LangOpts.CPlusPlus11)
950f4a2713aSLionel Sambuc       .Case("cxx_range_for", LangOpts.CPlusPlus11)
951f4a2713aSLionel Sambuc       .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
952f4a2713aSLionel Sambuc       .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
953f4a2713aSLionel Sambuc       .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
954f4a2713aSLionel Sambuc       .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
955f4a2713aSLionel Sambuc       .Case("cxx_static_assert", LangOpts.CPlusPlus11)
956f4a2713aSLionel Sambuc       .Case("cxx_thread_local",
957f4a2713aSLionel Sambuc             LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
958f4a2713aSLionel Sambuc       .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
959f4a2713aSLionel Sambuc       .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
960f4a2713aSLionel Sambuc       .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
961f4a2713aSLionel Sambuc       .Case("cxx_user_literals", LangOpts.CPlusPlus11)
962f4a2713aSLionel Sambuc       .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
963f4a2713aSLionel Sambuc       // C++1y features
964*0a6a1f1dSLionel Sambuc       .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
965*0a6a1f1dSLionel Sambuc       .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
966*0a6a1f1dSLionel Sambuc       .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
967*0a6a1f1dSLionel Sambuc       .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
968*0a6a1f1dSLionel Sambuc       .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
969*0a6a1f1dSLionel Sambuc       .Case("cxx_init_captures", LangOpts.CPlusPlus14)
970*0a6a1f1dSLionel Sambuc       .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
971*0a6a1f1dSLionel Sambuc       .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
972*0a6a1f1dSLionel Sambuc       .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
973*0a6a1f1dSLionel Sambuc       // C++ TSes
974*0a6a1f1dSLionel Sambuc       //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
975*0a6a1f1dSLionel Sambuc       //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
976*0a6a1f1dSLionel Sambuc       // FIXME: Should this be __has_feature or __has_extension?
977*0a6a1f1dSLionel Sambuc       //.Case("raw_invocation_type", LangOpts.CPlusPlus)
978f4a2713aSLionel Sambuc       // Type traits
979f4a2713aSLionel Sambuc       .Case("has_nothrow_assign", LangOpts.CPlusPlus)
980f4a2713aSLionel Sambuc       .Case("has_nothrow_copy", LangOpts.CPlusPlus)
981f4a2713aSLionel Sambuc       .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
982f4a2713aSLionel Sambuc       .Case("has_trivial_assign", LangOpts.CPlusPlus)
983f4a2713aSLionel Sambuc       .Case("has_trivial_copy", LangOpts.CPlusPlus)
984f4a2713aSLionel Sambuc       .Case("has_trivial_constructor", LangOpts.CPlusPlus)
985f4a2713aSLionel Sambuc       .Case("has_trivial_destructor", LangOpts.CPlusPlus)
986f4a2713aSLionel Sambuc       .Case("has_virtual_destructor", LangOpts.CPlusPlus)
987f4a2713aSLionel Sambuc       .Case("is_abstract", LangOpts.CPlusPlus)
988f4a2713aSLionel Sambuc       .Case("is_base_of", LangOpts.CPlusPlus)
989f4a2713aSLionel Sambuc       .Case("is_class", LangOpts.CPlusPlus)
990*0a6a1f1dSLionel Sambuc       .Case("is_constructible", LangOpts.CPlusPlus)
991f4a2713aSLionel Sambuc       .Case("is_convertible_to", LangOpts.CPlusPlus)
992f4a2713aSLionel Sambuc       .Case("is_empty", LangOpts.CPlusPlus)
993f4a2713aSLionel Sambuc       .Case("is_enum", LangOpts.CPlusPlus)
994f4a2713aSLionel Sambuc       .Case("is_final", LangOpts.CPlusPlus)
995f4a2713aSLionel Sambuc       .Case("is_literal", LangOpts.CPlusPlus)
996f4a2713aSLionel Sambuc       .Case("is_standard_layout", LangOpts.CPlusPlus)
997f4a2713aSLionel Sambuc       .Case("is_pod", LangOpts.CPlusPlus)
998f4a2713aSLionel Sambuc       .Case("is_polymorphic", LangOpts.CPlusPlus)
999f4a2713aSLionel Sambuc       .Case("is_sealed", LangOpts.MicrosoftExt)
1000f4a2713aSLionel Sambuc       .Case("is_trivial", LangOpts.CPlusPlus)
1001f4a2713aSLionel Sambuc       .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1002f4a2713aSLionel Sambuc       .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1003f4a2713aSLionel Sambuc       .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1004f4a2713aSLionel Sambuc       .Case("is_union", LangOpts.CPlusPlus)
1005f4a2713aSLionel Sambuc       .Case("modules", LangOpts.Modules)
1006f4a2713aSLionel Sambuc       .Case("tls", PP.getTargetInfo().isTLSSupported())
1007f4a2713aSLionel Sambuc       .Case("underlying_type", LangOpts.CPlusPlus)
1008f4a2713aSLionel Sambuc       .Default(false);
1009f4a2713aSLionel Sambuc }
1010f4a2713aSLionel Sambuc 
1011f4a2713aSLionel Sambuc /// HasExtension - Return true if we recognize and implement the feature
1012f4a2713aSLionel Sambuc /// specified by the identifier, either as an extension or a standard language
1013f4a2713aSLionel Sambuc /// feature.
HasExtension(const Preprocessor & PP,const IdentifierInfo * II)1014f4a2713aSLionel Sambuc static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1015f4a2713aSLionel Sambuc   if (HasFeature(PP, II))
1016f4a2713aSLionel Sambuc     return true;
1017f4a2713aSLionel Sambuc 
1018f4a2713aSLionel Sambuc   // If the use of an extension results in an error diagnostic, extensions are
1019f4a2713aSLionel Sambuc   // effectively unavailable, so just return false here.
1020*0a6a1f1dSLionel Sambuc   if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1021*0a6a1f1dSLionel Sambuc       diag::Severity::Error)
1022f4a2713aSLionel Sambuc     return false;
1023f4a2713aSLionel Sambuc 
1024f4a2713aSLionel Sambuc   const LangOptions &LangOpts = PP.getLangOpts();
1025f4a2713aSLionel Sambuc   StringRef Extension = II->getName();
1026f4a2713aSLionel Sambuc 
1027f4a2713aSLionel Sambuc   // Normalize the extension name, __foo__ becomes foo.
1028f4a2713aSLionel Sambuc   if (Extension.startswith("__") && Extension.endswith("__") &&
1029f4a2713aSLionel Sambuc       Extension.size() >= 4)
1030f4a2713aSLionel Sambuc     Extension = Extension.substr(2, Extension.size() - 4);
1031f4a2713aSLionel Sambuc 
1032f4a2713aSLionel Sambuc   // Because we inherit the feature list from HasFeature, this string switch
1033f4a2713aSLionel Sambuc   // must be less restrictive than HasFeature's.
1034f4a2713aSLionel Sambuc   return llvm::StringSwitch<bool>(Extension)
1035f4a2713aSLionel Sambuc            // C11 features supported by other languages as extensions.
1036f4a2713aSLionel Sambuc            .Case("c_alignas", true)
1037*0a6a1f1dSLionel Sambuc            .Case("c_alignof", true)
1038f4a2713aSLionel Sambuc            .Case("c_atomic", true)
1039f4a2713aSLionel Sambuc            .Case("c_generic_selections", true)
1040f4a2713aSLionel Sambuc            .Case("c_static_assert", true)
1041f4a2713aSLionel Sambuc            .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
1042f4a2713aSLionel Sambuc            // C++11 features supported by other languages as extensions.
1043f4a2713aSLionel Sambuc            .Case("cxx_atomic", LangOpts.CPlusPlus)
1044f4a2713aSLionel Sambuc            .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1045f4a2713aSLionel Sambuc            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1046f4a2713aSLionel Sambuc            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1047f4a2713aSLionel Sambuc            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1048f4a2713aSLionel Sambuc            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1049f4a2713aSLionel Sambuc            .Case("cxx_override_control", LangOpts.CPlusPlus)
1050f4a2713aSLionel Sambuc            .Case("cxx_range_for", LangOpts.CPlusPlus)
1051f4a2713aSLionel Sambuc            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1052f4a2713aSLionel Sambuc            .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
1053f4a2713aSLionel Sambuc            // C++1y features supported by other languages as extensions.
1054f4a2713aSLionel Sambuc            .Case("cxx_binary_literals", true)
1055f4a2713aSLionel Sambuc            .Case("cxx_init_captures", LangOpts.CPlusPlus11)
1056*0a6a1f1dSLionel Sambuc            .Case("cxx_variable_templates", LangOpts.CPlusPlus)
1057f4a2713aSLionel Sambuc            .Default(false);
1058f4a2713aSLionel Sambuc }
1059f4a2713aSLionel Sambuc 
1060f4a2713aSLionel Sambuc /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1061f4a2713aSLionel Sambuc /// or '__has_include_next("path")' expression.
1062f4a2713aSLionel Sambuc /// Returns true if successful.
EvaluateHasIncludeCommon(Token & Tok,IdentifierInfo * II,Preprocessor & PP,const DirectoryLookup * LookupFrom,const FileEntry * LookupFromFile)1063f4a2713aSLionel Sambuc static bool EvaluateHasIncludeCommon(Token &Tok,
1064f4a2713aSLionel Sambuc                                      IdentifierInfo *II, Preprocessor &PP,
1065*0a6a1f1dSLionel Sambuc                                      const DirectoryLookup *LookupFrom,
1066*0a6a1f1dSLionel Sambuc                                      const FileEntry *LookupFromFile) {
1067f4a2713aSLionel Sambuc   // Save the location of the current token.  If a '(' is later found, use
1068f4a2713aSLionel Sambuc   // that location.  If not, use the end of this location instead.
1069f4a2713aSLionel Sambuc   SourceLocation LParenLoc = Tok.getLocation();
1070f4a2713aSLionel Sambuc 
1071f4a2713aSLionel Sambuc   // These expressions are only allowed within a preprocessor directive.
1072f4a2713aSLionel Sambuc   if (!PP.isParsingIfOrElifDirective()) {
1073f4a2713aSLionel Sambuc     PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1074f4a2713aSLionel Sambuc     return false;
1075f4a2713aSLionel Sambuc   }
1076f4a2713aSLionel Sambuc 
1077f4a2713aSLionel Sambuc   // Get '('.
1078f4a2713aSLionel Sambuc   PP.LexNonComment(Tok);
1079f4a2713aSLionel Sambuc 
1080f4a2713aSLionel Sambuc   // Ensure we have a '('.
1081f4a2713aSLionel Sambuc   if (Tok.isNot(tok::l_paren)) {
1082f4a2713aSLionel Sambuc     // No '(', use end of last token.
1083f4a2713aSLionel Sambuc     LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1084*0a6a1f1dSLionel Sambuc     PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1085f4a2713aSLionel Sambuc     // If the next token looks like a filename or the start of one,
1086f4a2713aSLionel Sambuc     // assume it is and process it as such.
1087f4a2713aSLionel Sambuc     if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1088f4a2713aSLionel Sambuc         !Tok.is(tok::less))
1089f4a2713aSLionel Sambuc       return false;
1090f4a2713aSLionel Sambuc   } else {
1091f4a2713aSLionel Sambuc     // Save '(' location for possible missing ')' message.
1092f4a2713aSLionel Sambuc     LParenLoc = Tok.getLocation();
1093f4a2713aSLionel Sambuc 
1094f4a2713aSLionel Sambuc     if (PP.getCurrentLexer()) {
1095f4a2713aSLionel Sambuc       // Get the file name.
1096f4a2713aSLionel Sambuc       PP.getCurrentLexer()->LexIncludeFilename(Tok);
1097f4a2713aSLionel Sambuc     } else {
1098f4a2713aSLionel Sambuc       // We're in a macro, so we can't use LexIncludeFilename; just
1099f4a2713aSLionel Sambuc       // grab the next token.
1100f4a2713aSLionel Sambuc       PP.Lex(Tok);
1101f4a2713aSLionel Sambuc     }
1102f4a2713aSLionel Sambuc   }
1103f4a2713aSLionel Sambuc 
1104f4a2713aSLionel Sambuc   // Reserve a buffer to get the spelling.
1105f4a2713aSLionel Sambuc   SmallString<128> FilenameBuffer;
1106f4a2713aSLionel Sambuc   StringRef Filename;
1107f4a2713aSLionel Sambuc   SourceLocation EndLoc;
1108f4a2713aSLionel Sambuc 
1109f4a2713aSLionel Sambuc   switch (Tok.getKind()) {
1110f4a2713aSLionel Sambuc   case tok::eod:
1111f4a2713aSLionel Sambuc     // If the token kind is EOD, the error has already been diagnosed.
1112f4a2713aSLionel Sambuc     return false;
1113f4a2713aSLionel Sambuc 
1114f4a2713aSLionel Sambuc   case tok::angle_string_literal:
1115f4a2713aSLionel Sambuc   case tok::string_literal: {
1116f4a2713aSLionel Sambuc     bool Invalid = false;
1117f4a2713aSLionel Sambuc     Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1118f4a2713aSLionel Sambuc     if (Invalid)
1119f4a2713aSLionel Sambuc       return false;
1120f4a2713aSLionel Sambuc     break;
1121f4a2713aSLionel Sambuc   }
1122f4a2713aSLionel Sambuc 
1123f4a2713aSLionel Sambuc   case tok::less:
1124f4a2713aSLionel Sambuc     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1125f4a2713aSLionel Sambuc     // case, glue the tokens together into FilenameBuffer and interpret those.
1126f4a2713aSLionel Sambuc     FilenameBuffer.push_back('<');
1127f4a2713aSLionel Sambuc     if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1128f4a2713aSLionel Sambuc       // Let the caller know a <eod> was found by changing the Token kind.
1129f4a2713aSLionel Sambuc       Tok.setKind(tok::eod);
1130f4a2713aSLionel Sambuc       return false;   // Found <eod> but no ">"?  Diagnostic already emitted.
1131f4a2713aSLionel Sambuc     }
1132f4a2713aSLionel Sambuc     Filename = FilenameBuffer.str();
1133f4a2713aSLionel Sambuc     break;
1134f4a2713aSLionel Sambuc   default:
1135f4a2713aSLionel Sambuc     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1136f4a2713aSLionel Sambuc     return false;
1137f4a2713aSLionel Sambuc   }
1138f4a2713aSLionel Sambuc 
1139f4a2713aSLionel Sambuc   SourceLocation FilenameLoc = Tok.getLocation();
1140f4a2713aSLionel Sambuc 
1141f4a2713aSLionel Sambuc   // Get ')'.
1142f4a2713aSLionel Sambuc   PP.LexNonComment(Tok);
1143f4a2713aSLionel Sambuc 
1144f4a2713aSLionel Sambuc   // Ensure we have a trailing ).
1145f4a2713aSLionel Sambuc   if (Tok.isNot(tok::r_paren)) {
1146*0a6a1f1dSLionel Sambuc     PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1147*0a6a1f1dSLionel Sambuc         << II << tok::r_paren;
1148*0a6a1f1dSLionel Sambuc     PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1149f4a2713aSLionel Sambuc     return false;
1150f4a2713aSLionel Sambuc   }
1151f4a2713aSLionel Sambuc 
1152f4a2713aSLionel Sambuc   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1153f4a2713aSLionel Sambuc   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1154f4a2713aSLionel Sambuc   // error.
1155f4a2713aSLionel Sambuc   if (Filename.empty())
1156f4a2713aSLionel Sambuc     return false;
1157f4a2713aSLionel Sambuc 
1158f4a2713aSLionel Sambuc   // Search include directories.
1159f4a2713aSLionel Sambuc   const DirectoryLookup *CurDir;
1160f4a2713aSLionel Sambuc   const FileEntry *File =
1161*0a6a1f1dSLionel Sambuc       PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1162*0a6a1f1dSLionel Sambuc                     CurDir, nullptr, nullptr, nullptr);
1163f4a2713aSLionel Sambuc 
1164f4a2713aSLionel Sambuc   // Get the result value.  A result of true means the file exists.
1165*0a6a1f1dSLionel Sambuc   return File != nullptr;
1166f4a2713aSLionel Sambuc }
1167f4a2713aSLionel Sambuc 
1168f4a2713aSLionel Sambuc /// EvaluateHasInclude - Process a '__has_include("path")' expression.
1169f4a2713aSLionel Sambuc /// Returns true if successful.
EvaluateHasInclude(Token & Tok,IdentifierInfo * II,Preprocessor & PP)1170f4a2713aSLionel Sambuc static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1171f4a2713aSLionel Sambuc                                Preprocessor &PP) {
1172*0a6a1f1dSLionel Sambuc   return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
1173f4a2713aSLionel Sambuc }
1174f4a2713aSLionel Sambuc 
1175f4a2713aSLionel Sambuc /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1176f4a2713aSLionel Sambuc /// Returns true if successful.
EvaluateHasIncludeNext(Token & Tok,IdentifierInfo * II,Preprocessor & PP)1177f4a2713aSLionel Sambuc static bool EvaluateHasIncludeNext(Token &Tok,
1178f4a2713aSLionel Sambuc                                    IdentifierInfo *II, Preprocessor &PP) {
1179f4a2713aSLionel Sambuc   // __has_include_next is like __has_include, except that we start
1180f4a2713aSLionel Sambuc   // searching after the current found directory.  If we can't do this,
1181f4a2713aSLionel Sambuc   // issue a diagnostic.
1182*0a6a1f1dSLionel Sambuc   // FIXME: Factor out duplication wiht
1183*0a6a1f1dSLionel Sambuc   // Preprocessor::HandleIncludeNextDirective.
1184f4a2713aSLionel Sambuc   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1185*0a6a1f1dSLionel Sambuc   const FileEntry *LookupFromFile = nullptr;
1186f4a2713aSLionel Sambuc   if (PP.isInPrimaryFile()) {
1187*0a6a1f1dSLionel Sambuc     Lookup = nullptr;
1188f4a2713aSLionel Sambuc     PP.Diag(Tok, diag::pp_include_next_in_primary);
1189*0a6a1f1dSLionel Sambuc   } else if (PP.getCurrentSubmodule()) {
1190*0a6a1f1dSLionel Sambuc     // Start looking up in the directory *after* the one in which the current
1191*0a6a1f1dSLionel Sambuc     // file would be found, if any.
1192*0a6a1f1dSLionel Sambuc     assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1193*0a6a1f1dSLionel Sambuc     LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1194*0a6a1f1dSLionel Sambuc     Lookup = nullptr;
1195*0a6a1f1dSLionel Sambuc   } else if (!Lookup) {
1196f4a2713aSLionel Sambuc     PP.Diag(Tok, diag::pp_include_next_absolute_path);
1197f4a2713aSLionel Sambuc   } else {
1198f4a2713aSLionel Sambuc     // Start looking up in the next directory.
1199f4a2713aSLionel Sambuc     ++Lookup;
1200f4a2713aSLionel Sambuc   }
1201f4a2713aSLionel Sambuc 
1202*0a6a1f1dSLionel Sambuc   return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
1203f4a2713aSLionel Sambuc }
1204f4a2713aSLionel Sambuc 
1205f4a2713aSLionel Sambuc /// \brief Process __building_module(identifier) expression.
1206f4a2713aSLionel Sambuc /// \returns true if we are building the named module, false otherwise.
EvaluateBuildingModule(Token & Tok,IdentifierInfo * II,Preprocessor & PP)1207f4a2713aSLionel Sambuc static bool EvaluateBuildingModule(Token &Tok,
1208f4a2713aSLionel Sambuc                                    IdentifierInfo *II, Preprocessor &PP) {
1209f4a2713aSLionel Sambuc   // Get '('.
1210f4a2713aSLionel Sambuc   PP.LexNonComment(Tok);
1211f4a2713aSLionel Sambuc 
1212f4a2713aSLionel Sambuc   // Ensure we have a '('.
1213f4a2713aSLionel Sambuc   if (Tok.isNot(tok::l_paren)) {
1214*0a6a1f1dSLionel Sambuc     PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1215*0a6a1f1dSLionel Sambuc                                                             << tok::l_paren;
1216f4a2713aSLionel Sambuc     return false;
1217f4a2713aSLionel Sambuc   }
1218f4a2713aSLionel Sambuc 
1219f4a2713aSLionel Sambuc   // Save '(' location for possible missing ')' message.
1220f4a2713aSLionel Sambuc   SourceLocation LParenLoc = Tok.getLocation();
1221f4a2713aSLionel Sambuc 
1222f4a2713aSLionel Sambuc   // Get the module name.
1223f4a2713aSLionel Sambuc   PP.LexNonComment(Tok);
1224f4a2713aSLionel Sambuc 
1225f4a2713aSLionel Sambuc   // Ensure that we have an identifier.
1226f4a2713aSLionel Sambuc   if (Tok.isNot(tok::identifier)) {
1227f4a2713aSLionel Sambuc     PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1228f4a2713aSLionel Sambuc     return false;
1229f4a2713aSLionel Sambuc   }
1230f4a2713aSLionel Sambuc 
1231f4a2713aSLionel Sambuc   bool Result
1232f4a2713aSLionel Sambuc     = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1233f4a2713aSLionel Sambuc 
1234f4a2713aSLionel Sambuc   // Get ')'.
1235f4a2713aSLionel Sambuc   PP.LexNonComment(Tok);
1236f4a2713aSLionel Sambuc 
1237f4a2713aSLionel Sambuc   // Ensure we have a trailing ).
1238f4a2713aSLionel Sambuc   if (Tok.isNot(tok::r_paren)) {
1239*0a6a1f1dSLionel Sambuc     PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1240*0a6a1f1dSLionel Sambuc                                                             << tok::r_paren;
1241*0a6a1f1dSLionel Sambuc     PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1242f4a2713aSLionel Sambuc     return false;
1243f4a2713aSLionel Sambuc   }
1244f4a2713aSLionel Sambuc 
1245f4a2713aSLionel Sambuc   return Result;
1246f4a2713aSLionel Sambuc }
1247f4a2713aSLionel Sambuc 
1248f4a2713aSLionel Sambuc /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1249f4a2713aSLionel Sambuc /// as a builtin macro, handle it and return the next token as 'Tok'.
ExpandBuiltinMacro(Token & Tok)1250f4a2713aSLionel Sambuc void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1251f4a2713aSLionel Sambuc   // Figure out which token this is.
1252f4a2713aSLionel Sambuc   IdentifierInfo *II = Tok.getIdentifierInfo();
1253f4a2713aSLionel Sambuc   assert(II && "Can't be a macro without id info!");
1254f4a2713aSLionel Sambuc 
1255f4a2713aSLionel Sambuc   // If this is an _Pragma or Microsoft __pragma directive, expand it,
1256f4a2713aSLionel Sambuc   // invoke the pragma handler, then lex the token after it.
1257f4a2713aSLionel Sambuc   if (II == Ident_Pragma)
1258f4a2713aSLionel Sambuc     return Handle_Pragma(Tok);
1259f4a2713aSLionel Sambuc   else if (II == Ident__pragma) // in non-MS mode this is null
1260f4a2713aSLionel Sambuc     return HandleMicrosoft__pragma(Tok);
1261f4a2713aSLionel Sambuc 
1262f4a2713aSLionel Sambuc   ++NumBuiltinMacroExpanded;
1263f4a2713aSLionel Sambuc 
1264f4a2713aSLionel Sambuc   SmallString<128> TmpBuffer;
1265f4a2713aSLionel Sambuc   llvm::raw_svector_ostream OS(TmpBuffer);
1266f4a2713aSLionel Sambuc 
1267f4a2713aSLionel Sambuc   // Set up the return result.
1268*0a6a1f1dSLionel Sambuc   Tok.setIdentifierInfo(nullptr);
1269f4a2713aSLionel Sambuc   Tok.clearFlag(Token::NeedsCleaning);
1270f4a2713aSLionel Sambuc 
1271f4a2713aSLionel Sambuc   if (II == Ident__LINE__) {
1272f4a2713aSLionel Sambuc     // C99 6.10.8: "__LINE__: The presumed line number (within the current
1273f4a2713aSLionel Sambuc     // source file) of the current source line (an integer constant)".  This can
1274f4a2713aSLionel Sambuc     // be affected by #line.
1275f4a2713aSLionel Sambuc     SourceLocation Loc = Tok.getLocation();
1276f4a2713aSLionel Sambuc 
1277f4a2713aSLionel Sambuc     // Advance to the location of the first _, this might not be the first byte
1278f4a2713aSLionel Sambuc     // of the token if it starts with an escaped newline.
1279f4a2713aSLionel Sambuc     Loc = AdvanceToTokenCharacter(Loc, 0);
1280f4a2713aSLionel Sambuc 
1281f4a2713aSLionel Sambuc     // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1282f4a2713aSLionel Sambuc     // a macro expansion.  This doesn't matter for object-like macros, but
1283f4a2713aSLionel Sambuc     // can matter for a function-like macro that expands to contain __LINE__.
1284f4a2713aSLionel Sambuc     // Skip down through expansion points until we find a file loc for the
1285f4a2713aSLionel Sambuc     // end of the expansion history.
1286f4a2713aSLionel Sambuc     Loc = SourceMgr.getExpansionRange(Loc).second;
1287f4a2713aSLionel Sambuc     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1288f4a2713aSLionel Sambuc 
1289f4a2713aSLionel Sambuc     // __LINE__ expands to a simple numeric value.
1290f4a2713aSLionel Sambuc     OS << (PLoc.isValid()? PLoc.getLine() : 1);
1291f4a2713aSLionel Sambuc     Tok.setKind(tok::numeric_constant);
1292f4a2713aSLionel Sambuc   } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1293f4a2713aSLionel Sambuc     // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1294f4a2713aSLionel Sambuc     // character string literal)". This can be affected by #line.
1295f4a2713aSLionel Sambuc     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1296f4a2713aSLionel Sambuc 
1297f4a2713aSLionel Sambuc     // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1298f4a2713aSLionel Sambuc     // #include stack instead of the current file.
1299f4a2713aSLionel Sambuc     if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1300f4a2713aSLionel Sambuc       SourceLocation NextLoc = PLoc.getIncludeLoc();
1301f4a2713aSLionel Sambuc       while (NextLoc.isValid()) {
1302f4a2713aSLionel Sambuc         PLoc = SourceMgr.getPresumedLoc(NextLoc);
1303f4a2713aSLionel Sambuc         if (PLoc.isInvalid())
1304f4a2713aSLionel Sambuc           break;
1305f4a2713aSLionel Sambuc 
1306f4a2713aSLionel Sambuc         NextLoc = PLoc.getIncludeLoc();
1307f4a2713aSLionel Sambuc       }
1308f4a2713aSLionel Sambuc     }
1309f4a2713aSLionel Sambuc 
1310f4a2713aSLionel Sambuc     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
1311f4a2713aSLionel Sambuc     SmallString<128> FN;
1312f4a2713aSLionel Sambuc     if (PLoc.isValid()) {
1313f4a2713aSLionel Sambuc       FN += PLoc.getFilename();
1314f4a2713aSLionel Sambuc       Lexer::Stringify(FN);
1315f4a2713aSLionel Sambuc       OS << '"' << FN.str() << '"';
1316f4a2713aSLionel Sambuc     }
1317f4a2713aSLionel Sambuc     Tok.setKind(tok::string_literal);
1318f4a2713aSLionel Sambuc   } else if (II == Ident__DATE__) {
1319*0a6a1f1dSLionel Sambuc     Diag(Tok.getLocation(), diag::warn_pp_date_time);
1320f4a2713aSLionel Sambuc     if (!DATELoc.isValid())
1321f4a2713aSLionel Sambuc       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1322f4a2713aSLionel Sambuc     Tok.setKind(tok::string_literal);
1323f4a2713aSLionel Sambuc     Tok.setLength(strlen("\"Mmm dd yyyy\""));
1324f4a2713aSLionel Sambuc     Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1325f4a2713aSLionel Sambuc                                                  Tok.getLocation(),
1326f4a2713aSLionel Sambuc                                                  Tok.getLength()));
1327f4a2713aSLionel Sambuc     return;
1328f4a2713aSLionel Sambuc   } else if (II == Ident__TIME__) {
1329*0a6a1f1dSLionel Sambuc     Diag(Tok.getLocation(), diag::warn_pp_date_time);
1330f4a2713aSLionel Sambuc     if (!TIMELoc.isValid())
1331f4a2713aSLionel Sambuc       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1332f4a2713aSLionel Sambuc     Tok.setKind(tok::string_literal);
1333f4a2713aSLionel Sambuc     Tok.setLength(strlen("\"hh:mm:ss\""));
1334f4a2713aSLionel Sambuc     Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1335f4a2713aSLionel Sambuc                                                  Tok.getLocation(),
1336f4a2713aSLionel Sambuc                                                  Tok.getLength()));
1337f4a2713aSLionel Sambuc     return;
1338f4a2713aSLionel Sambuc   } else if (II == Ident__INCLUDE_LEVEL__) {
1339f4a2713aSLionel Sambuc     // Compute the presumed include depth of this token.  This can be affected
1340f4a2713aSLionel Sambuc     // by GNU line markers.
1341f4a2713aSLionel Sambuc     unsigned Depth = 0;
1342f4a2713aSLionel Sambuc 
1343f4a2713aSLionel Sambuc     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1344f4a2713aSLionel Sambuc     if (PLoc.isValid()) {
1345f4a2713aSLionel Sambuc       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1346f4a2713aSLionel Sambuc       for (; PLoc.isValid(); ++Depth)
1347f4a2713aSLionel Sambuc         PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1348f4a2713aSLionel Sambuc     }
1349f4a2713aSLionel Sambuc 
1350f4a2713aSLionel Sambuc     // __INCLUDE_LEVEL__ expands to a simple numeric value.
1351f4a2713aSLionel Sambuc     OS << Depth;
1352f4a2713aSLionel Sambuc     Tok.setKind(tok::numeric_constant);
1353f4a2713aSLionel Sambuc   } else if (II == Ident__TIMESTAMP__) {
1354*0a6a1f1dSLionel Sambuc     Diag(Tok.getLocation(), diag::warn_pp_date_time);
1355f4a2713aSLionel Sambuc     // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
1356f4a2713aSLionel Sambuc     // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1357f4a2713aSLionel Sambuc 
1358f4a2713aSLionel Sambuc     // Get the file that we are lexing out of.  If we're currently lexing from
1359f4a2713aSLionel Sambuc     // a macro, dig into the include stack.
1360*0a6a1f1dSLionel Sambuc     const FileEntry *CurFile = nullptr;
1361f4a2713aSLionel Sambuc     PreprocessorLexer *TheLexer = getCurrentFileLexer();
1362f4a2713aSLionel Sambuc 
1363f4a2713aSLionel Sambuc     if (TheLexer)
1364f4a2713aSLionel Sambuc       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1365f4a2713aSLionel Sambuc 
1366f4a2713aSLionel Sambuc     const char *Result;
1367f4a2713aSLionel Sambuc     if (CurFile) {
1368f4a2713aSLionel Sambuc       time_t TT = CurFile->getModificationTime();
1369f4a2713aSLionel Sambuc       struct tm *TM = localtime(&TT);
1370f4a2713aSLionel Sambuc       Result = asctime(TM);
1371f4a2713aSLionel Sambuc     } else {
1372f4a2713aSLionel Sambuc       Result = "??? ??? ?? ??:??:?? ????\n";
1373f4a2713aSLionel Sambuc     }
1374f4a2713aSLionel Sambuc     // Surround the string with " and strip the trailing newline.
1375*0a6a1f1dSLionel Sambuc     OS << '"' << StringRef(Result).drop_back() << '"';
1376f4a2713aSLionel Sambuc     Tok.setKind(tok::string_literal);
1377f4a2713aSLionel Sambuc   } else if (II == Ident__COUNTER__) {
1378f4a2713aSLionel Sambuc     // __COUNTER__ expands to a simple numeric value.
1379f4a2713aSLionel Sambuc     OS << CounterValue++;
1380f4a2713aSLionel Sambuc     Tok.setKind(tok::numeric_constant);
1381f4a2713aSLionel Sambuc   } else if (II == Ident__has_feature   ||
1382f4a2713aSLionel Sambuc              II == Ident__has_extension ||
1383f4a2713aSLionel Sambuc              II == Ident__has_builtin   ||
1384*0a6a1f1dSLionel Sambuc              II == Ident__is_identifier ||
1385*0a6a1f1dSLionel Sambuc              II == Ident__has_attribute ||
1386*0a6a1f1dSLionel Sambuc              II == Ident__has_declspec  ||
1387*0a6a1f1dSLionel Sambuc              II == Ident__has_cpp_attribute) {
1388f4a2713aSLionel Sambuc     // The argument to these builtins should be a parenthesized identifier.
1389f4a2713aSLionel Sambuc     SourceLocation StartLoc = Tok.getLocation();
1390f4a2713aSLionel Sambuc 
1391f4a2713aSLionel Sambuc     bool IsValid = false;
1392*0a6a1f1dSLionel Sambuc     IdentifierInfo *FeatureII = nullptr;
1393*0a6a1f1dSLionel Sambuc     IdentifierInfo *ScopeII = nullptr;
1394f4a2713aSLionel Sambuc 
1395f4a2713aSLionel Sambuc     // Read the '('.
1396f4a2713aSLionel Sambuc     LexUnexpandedToken(Tok);
1397f4a2713aSLionel Sambuc     if (Tok.is(tok::l_paren)) {
1398f4a2713aSLionel Sambuc       // Read the identifier
1399f4a2713aSLionel Sambuc       LexUnexpandedToken(Tok);
1400f4a2713aSLionel Sambuc       if ((FeatureII = Tok.getIdentifierInfo())) {
1401*0a6a1f1dSLionel Sambuc         // If we're checking __has_cpp_attribute, it is possible to receive a
1402*0a6a1f1dSLionel Sambuc         // scope token. Read the "::", if it's available.
1403f4a2713aSLionel Sambuc         LexUnexpandedToken(Tok);
1404*0a6a1f1dSLionel Sambuc         bool IsScopeValid = true;
1405*0a6a1f1dSLionel Sambuc         if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1406*0a6a1f1dSLionel Sambuc           LexUnexpandedToken(Tok);
1407*0a6a1f1dSLionel Sambuc           // The first thing we read was not the feature, it was the scope.
1408*0a6a1f1dSLionel Sambuc           ScopeII = FeatureII;
1409*0a6a1f1dSLionel Sambuc           if ((FeatureII = Tok.getIdentifierInfo()))
1410*0a6a1f1dSLionel Sambuc             LexUnexpandedToken(Tok);
1411*0a6a1f1dSLionel Sambuc           else
1412*0a6a1f1dSLionel Sambuc             IsScopeValid = false;
1413*0a6a1f1dSLionel Sambuc         }
1414*0a6a1f1dSLionel Sambuc         // Read the closing paren.
1415*0a6a1f1dSLionel Sambuc         if (IsScopeValid && Tok.is(tok::r_paren))
1416f4a2713aSLionel Sambuc           IsValid = true;
1417f4a2713aSLionel Sambuc       }
1418*0a6a1f1dSLionel Sambuc       // Eat tokens until ')'.
1419*0a6a1f1dSLionel Sambuc       while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1420*0a6a1f1dSLionel Sambuc              Tok.isNot(tok::eof))
1421*0a6a1f1dSLionel Sambuc         LexUnexpandedToken(Tok);
1422f4a2713aSLionel Sambuc     }
1423f4a2713aSLionel Sambuc 
1424*0a6a1f1dSLionel Sambuc     int Value = 0;
1425f4a2713aSLionel Sambuc     if (!IsValid)
1426f4a2713aSLionel Sambuc       Diag(StartLoc, diag::err_feature_check_malformed);
1427*0a6a1f1dSLionel Sambuc     else if (II == Ident__is_identifier)
1428*0a6a1f1dSLionel Sambuc       Value = FeatureII->getTokenID() == tok::identifier;
1429f4a2713aSLionel Sambuc     else if (II == Ident__has_builtin) {
1430f4a2713aSLionel Sambuc       // Check for a builtin is trivial.
1431f4a2713aSLionel Sambuc       Value = FeatureII->getBuiltinID() != 0;
1432f4a2713aSLionel Sambuc     } else if (II == Ident__has_attribute)
1433*0a6a1f1dSLionel Sambuc       Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII,
1434*0a6a1f1dSLionel Sambuc                            getTargetInfo().getTriple(), getLangOpts());
1435*0a6a1f1dSLionel Sambuc     else if (II == Ident__has_cpp_attribute)
1436*0a6a1f1dSLionel Sambuc       Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1437*0a6a1f1dSLionel Sambuc                            getTargetInfo().getTriple(), getLangOpts());
1438*0a6a1f1dSLionel Sambuc     else if (II == Ident__has_declspec)
1439*0a6a1f1dSLionel Sambuc       Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
1440*0a6a1f1dSLionel Sambuc                            getTargetInfo().getTriple(), getLangOpts());
1441f4a2713aSLionel Sambuc     else if (II == Ident__has_extension)
1442f4a2713aSLionel Sambuc       Value = HasExtension(*this, FeatureII);
1443f4a2713aSLionel Sambuc     else {
1444f4a2713aSLionel Sambuc       assert(II == Ident__has_feature && "Must be feature check");
1445f4a2713aSLionel Sambuc       Value = HasFeature(*this, FeatureII);
1446f4a2713aSLionel Sambuc     }
1447f4a2713aSLionel Sambuc 
1448*0a6a1f1dSLionel Sambuc     if (!IsValid)
1449*0a6a1f1dSLionel Sambuc       return;
1450*0a6a1f1dSLionel Sambuc     OS << Value;
1451f4a2713aSLionel Sambuc     Tok.setKind(tok::numeric_constant);
1452f4a2713aSLionel Sambuc   } else if (II == Ident__has_include ||
1453f4a2713aSLionel Sambuc              II == Ident__has_include_next) {
1454f4a2713aSLionel Sambuc     // The argument to these two builtins should be a parenthesized
1455f4a2713aSLionel Sambuc     // file name string literal using angle brackets (<>) or
1456f4a2713aSLionel Sambuc     // double-quotes ("").
1457f4a2713aSLionel Sambuc     bool Value;
1458f4a2713aSLionel Sambuc     if (II == Ident__has_include)
1459f4a2713aSLionel Sambuc       Value = EvaluateHasInclude(Tok, II, *this);
1460f4a2713aSLionel Sambuc     else
1461f4a2713aSLionel Sambuc       Value = EvaluateHasIncludeNext(Tok, II, *this);
1462f4a2713aSLionel Sambuc     OS << (int)Value;
1463f4a2713aSLionel Sambuc     if (Tok.is(tok::r_paren))
1464f4a2713aSLionel Sambuc       Tok.setKind(tok::numeric_constant);
1465f4a2713aSLionel Sambuc   } else if (II == Ident__has_warning) {
1466f4a2713aSLionel Sambuc     // The argument should be a parenthesized string literal.
1467f4a2713aSLionel Sambuc     // The argument to these builtins should be a parenthesized identifier.
1468f4a2713aSLionel Sambuc     SourceLocation StartLoc = Tok.getLocation();
1469f4a2713aSLionel Sambuc     bool IsValid = false;
1470f4a2713aSLionel Sambuc     bool Value = false;
1471f4a2713aSLionel Sambuc     // Read the '('.
1472f4a2713aSLionel Sambuc     LexUnexpandedToken(Tok);
1473f4a2713aSLionel Sambuc     do {
1474f4a2713aSLionel Sambuc       if (Tok.isNot(tok::l_paren)) {
1475f4a2713aSLionel Sambuc         Diag(StartLoc, diag::err_warning_check_malformed);
1476f4a2713aSLionel Sambuc         break;
1477f4a2713aSLionel Sambuc       }
1478f4a2713aSLionel Sambuc 
1479f4a2713aSLionel Sambuc       LexUnexpandedToken(Tok);
1480f4a2713aSLionel Sambuc       std::string WarningName;
1481f4a2713aSLionel Sambuc       SourceLocation StrStartLoc = Tok.getLocation();
1482f4a2713aSLionel Sambuc       if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1483f4a2713aSLionel Sambuc                                   /*MacroExpansion=*/false)) {
1484f4a2713aSLionel Sambuc         // Eat tokens until ')'.
1485f4a2713aSLionel Sambuc         while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1486f4a2713aSLionel Sambuc                Tok.isNot(tok::eof))
1487f4a2713aSLionel Sambuc           LexUnexpandedToken(Tok);
1488f4a2713aSLionel Sambuc         break;
1489f4a2713aSLionel Sambuc       }
1490f4a2713aSLionel Sambuc 
1491f4a2713aSLionel Sambuc       // Is the end a ')'?
1492f4a2713aSLionel Sambuc       if (!(IsValid = Tok.is(tok::r_paren))) {
1493f4a2713aSLionel Sambuc         Diag(StartLoc, diag::err_warning_check_malformed);
1494f4a2713aSLionel Sambuc         break;
1495f4a2713aSLionel Sambuc       }
1496f4a2713aSLionel Sambuc 
1497*0a6a1f1dSLionel Sambuc       // FIXME: Should we accept "-R..." flags here, or should that be handled
1498*0a6a1f1dSLionel Sambuc       // by a separate __has_remark?
1499f4a2713aSLionel Sambuc       if (WarningName.size() < 3 || WarningName[0] != '-' ||
1500f4a2713aSLionel Sambuc           WarningName[1] != 'W') {
1501f4a2713aSLionel Sambuc         Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1502f4a2713aSLionel Sambuc         break;
1503f4a2713aSLionel Sambuc       }
1504f4a2713aSLionel Sambuc 
1505f4a2713aSLionel Sambuc       // Finally, check if the warning flags maps to a diagnostic group.
1506f4a2713aSLionel Sambuc       // We construct a SmallVector here to talk to getDiagnosticIDs().
1507f4a2713aSLionel Sambuc       // Although we don't use the result, this isn't a hot path, and not
1508f4a2713aSLionel Sambuc       // worth special casing.
1509f4a2713aSLionel Sambuc       SmallVector<diag::kind, 10> Diags;
1510f4a2713aSLionel Sambuc       Value = !getDiagnostics().getDiagnosticIDs()->
1511*0a6a1f1dSLionel Sambuc         getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1512*0a6a1f1dSLionel Sambuc                               WarningName.substr(2), Diags);
1513f4a2713aSLionel Sambuc     } while (false);
1514f4a2713aSLionel Sambuc 
1515*0a6a1f1dSLionel Sambuc     if (!IsValid)
1516*0a6a1f1dSLionel Sambuc       return;
1517f4a2713aSLionel Sambuc     OS << (int)Value;
1518f4a2713aSLionel Sambuc     Tok.setKind(tok::numeric_constant);
1519f4a2713aSLionel Sambuc   } else if (II == Ident__building_module) {
1520f4a2713aSLionel Sambuc     // The argument to this builtin should be an identifier. The
1521f4a2713aSLionel Sambuc     // builtin evaluates to 1 when that identifier names the module we are
1522f4a2713aSLionel Sambuc     // currently building.
1523f4a2713aSLionel Sambuc     OS << (int)EvaluateBuildingModule(Tok, II, *this);
1524f4a2713aSLionel Sambuc     Tok.setKind(tok::numeric_constant);
1525f4a2713aSLionel Sambuc   } else if (II == Ident__MODULE__) {
1526f4a2713aSLionel Sambuc     // The current module as an identifier.
1527f4a2713aSLionel Sambuc     OS << getLangOpts().CurrentModule;
1528f4a2713aSLionel Sambuc     IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1529f4a2713aSLionel Sambuc     Tok.setIdentifierInfo(ModuleII);
1530f4a2713aSLionel Sambuc     Tok.setKind(ModuleII->getTokenID());
1531*0a6a1f1dSLionel Sambuc   } else if (II == Ident__identifier) {
1532*0a6a1f1dSLionel Sambuc     SourceLocation Loc = Tok.getLocation();
1533*0a6a1f1dSLionel Sambuc 
1534*0a6a1f1dSLionel Sambuc     // We're expecting '__identifier' '(' identifier ')'. Try to recover
1535*0a6a1f1dSLionel Sambuc     // if the parens are missing.
1536*0a6a1f1dSLionel Sambuc     LexNonComment(Tok);
1537*0a6a1f1dSLionel Sambuc     if (Tok.isNot(tok::l_paren)) {
1538*0a6a1f1dSLionel Sambuc       // No '(', use end of last token.
1539*0a6a1f1dSLionel Sambuc       Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1540*0a6a1f1dSLionel Sambuc         << II << tok::l_paren;
1541*0a6a1f1dSLionel Sambuc       // If the next token isn't valid as our argument, we can't recover.
1542*0a6a1f1dSLionel Sambuc       if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1543*0a6a1f1dSLionel Sambuc         Tok.setKind(tok::identifier);
1544*0a6a1f1dSLionel Sambuc       return;
1545*0a6a1f1dSLionel Sambuc     }
1546*0a6a1f1dSLionel Sambuc 
1547*0a6a1f1dSLionel Sambuc     SourceLocation LParenLoc = Tok.getLocation();
1548*0a6a1f1dSLionel Sambuc     LexNonComment(Tok);
1549*0a6a1f1dSLionel Sambuc 
1550*0a6a1f1dSLionel Sambuc     if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1551*0a6a1f1dSLionel Sambuc       Tok.setKind(tok::identifier);
1552*0a6a1f1dSLionel Sambuc     else {
1553*0a6a1f1dSLionel Sambuc       Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1554*0a6a1f1dSLionel Sambuc         << Tok.getKind();
1555*0a6a1f1dSLionel Sambuc       // Don't walk past anything that's not a real token.
1556*0a6a1f1dSLionel Sambuc       if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1557*0a6a1f1dSLionel Sambuc         return;
1558*0a6a1f1dSLionel Sambuc     }
1559*0a6a1f1dSLionel Sambuc 
1560*0a6a1f1dSLionel Sambuc     // Discard the ')', preserving 'Tok' as our result.
1561*0a6a1f1dSLionel Sambuc     Token RParen;
1562*0a6a1f1dSLionel Sambuc     LexNonComment(RParen);
1563*0a6a1f1dSLionel Sambuc     if (RParen.isNot(tok::r_paren)) {
1564*0a6a1f1dSLionel Sambuc       Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1565*0a6a1f1dSLionel Sambuc         << Tok.getKind() << tok::r_paren;
1566*0a6a1f1dSLionel Sambuc       Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1567*0a6a1f1dSLionel Sambuc     }
1568*0a6a1f1dSLionel Sambuc     return;
1569f4a2713aSLionel Sambuc   } else {
1570f4a2713aSLionel Sambuc     llvm_unreachable("Unknown identifier!");
1571f4a2713aSLionel Sambuc   }
1572f4a2713aSLionel Sambuc   CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
1573f4a2713aSLionel Sambuc }
1574f4a2713aSLionel Sambuc 
markMacroAsUsed(MacroInfo * MI)1575f4a2713aSLionel Sambuc void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1576f4a2713aSLionel Sambuc   // If the 'used' status changed, and the macro requires 'unused' warning,
1577f4a2713aSLionel Sambuc   // remove its SourceLocation from the warn-for-unused-macro locations.
1578f4a2713aSLionel Sambuc   if (MI->isWarnIfUnused() && !MI->isUsed())
1579f4a2713aSLionel Sambuc     WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1580f4a2713aSLionel Sambuc   MI->setIsUsed(true);
1581f4a2713aSLionel Sambuc }
1582