blob: 868820b400b42edc1da5b653e4dcbceb8c6953d6 [file] [log] [blame]
Joao Matos3e1ec722012-08-31 21:34:27 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
23#include "clang/Lex/MacroInfo.h"
24#include "llvm/ADT/STLExtras.h"
Andy Gibbs02a17682012-11-17 19:15:38 +000025#include "llvm/ADT/SmallString.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000026#include "llvm/ADT/StringSwitch.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000027#include "llvm/Config/llvm-config.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000028#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko33d054b2012-09-24 20:56:28 +000029#include "llvm/Support/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "llvm/Support/raw_ostream.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000031#include <cstdio>
32#include <ctime>
33using namespace clang;
34
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000035MacroDirective *
36Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +000037 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matos3e1ec722012-08-31 21:34:27 +000038
39 macro_iterator Pos = Macros.find(II);
Joao Matos3e1ec722012-08-31 21:34:27 +000040 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matos3e1ec722012-08-31 21:34:27 +000041 return Pos->second;
42}
43
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +000044/// \brief Specify a macro for this identifier.
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000045void Preprocessor::setMacroDirective(IdentifierInfo *II, MacroDirective *MD) {
46 assert(MD && "MacroDirective should be non-zero!");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000047
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000048 MacroDirective *&StoredMD = Macros[II];
49 MD->setPrevious(StoredMD);
50 StoredMD = MD;
51 II->setHasMacroDefinition(true);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000052 if (II->isFromAST())
Joao Matos3e1ec722012-08-31 21:34:27 +000053 II->setChangedSinceDeserialization();
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000054}
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +000055
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000056void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
57 MacroDirective *MD) {
58 assert(II && MD);
59 MacroDirective *&StoredMD = Macros[II];
60 assert(!StoredMD &&
61 "the macro history was modified before initializing it from a pch");
62 StoredMD = MD;
63 // Setup the identifier as having associated macro history.
64 II->setHasMacroDefinition(true);
65 if (!MD->isDefined())
66 II->setHasMacroDefinition(false);
Joao Matos3e1ec722012-08-31 21:34:27 +000067}
68
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000069void Preprocessor::addLoadedMacroInfo(IdentifierInfo *II, MacroDirective *MD,
70 MacroDirective *Hint) {
71 assert(MD && "Missing macro?");
72 assert(MD->isImported() && "Macro is not from an AST?");
73 assert(!MD->getPrevious() && "Macro already in chain?");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000074
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000075 MacroDirective *&StoredMD = Macros[II];
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000076
77 // Easy case: this is the first macro definition for this macro.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000078 if (!StoredMD) {
79 StoredMD = MD;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000080
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000081 if (MD->isDefined())
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000082 II->setHasMacroDefinition(true);
83 return;
84 }
85
86 // If this macro is a definition and this identifier has been neither
87 // defined nor undef'd in the current translation unit, add this macro
88 // to the end of the chain of definitions.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000089 if (MD->isDefined() && StoredMD->isImported()) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000090 // Simple case: if this is the first actual definition, just put it at
91 // th beginning.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000092 if (!StoredMD->isDefined()) {
93 MD->setPrevious(StoredMD);
94 StoredMD = MD;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000095
96 II->setHasMacroDefinition(true);
97 return;
98 }
99
100 // Find the end of the definition chain.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000101 MacroDirective *Prev;
102 MacroDirective *PrevPrev = StoredMD;
103 bool Ambiguous = StoredMD->isAmbiguous();
Douglas Gregore8219a62012-10-11 21:07:39 +0000104 bool MatchedOther = false;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000105 do {
Douglas Gregor54c8a402012-10-12 00:16:50 +0000106 Prev = PrevPrev;
107
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000108 // If the macros are not identical, we have an ambiguity.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000109 if (!Prev->getInfo()->isIdenticalTo(*MD->getInfo(), *this)) {
Douglas Gregore8219a62012-10-11 21:07:39 +0000110 if (!Ambiguous) {
111 Ambiguous = true;
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000112 StoredMD->setAmbiguous(true);
Douglas Gregore8219a62012-10-11 21:07:39 +0000113 }
114 } else {
115 MatchedOther = true;
116 }
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000117 } while ((PrevPrev = Prev->getPrevious()) &&
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000118 PrevPrev->isDefined());
119
Douglas Gregore8219a62012-10-11 21:07:39 +0000120 // If there are ambiguous definitions, and we didn't match any other
121 // definition, then mark us as ambiguous.
122 if (Ambiguous && !MatchedOther)
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000123 MD->setAmbiguous(true);
Douglas Gregor7097be92012-10-11 00:48:48 +0000124
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000125 // Wire this macro information into the chain.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000126 MD->setPrevious(Prev->getPrevious());
127 Prev->setPrevious(MD);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000128 return;
129 }
130
131 // The macro is not a definition; put it at the end of the list.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000132 MacroDirective *Prev = Hint? Hint : StoredMD;
133 while (Prev->getPrevious())
134 Prev = Prev->getPrevious();
135 Prev->setPrevious(MD);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000136}
137
138void Preprocessor::makeLoadedMacroInfoVisible(IdentifierInfo *II,
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000139 MacroDirective *MD) {
140 assert(MD->isImported() && "Macro must be from the AST");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000141
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000142 MacroDirective *&StoredMD = Macros[II];
143 if (StoredMD == MD) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000144 // Easy case: this is the first macro anyway.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000145 II->setHasMacroDefinition(MD->isDefined());
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000146 return;
147 }
148
149 // Go find the macro and pull it out of the list.
Douglas Gregor54c8a402012-10-12 00:16:50 +0000150 // FIXME: Yes, this is O(N), and making a pile of macros visible or hidden
151 // would be quadratic, but it's extremely rare.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000152 MacroDirective *Prev = StoredMD;
153 while (Prev->getPrevious() != MD)
154 Prev = Prev->getPrevious();
155 Prev->setPrevious(MD->getPrevious());
156 MD->setPrevious(0);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000157
158 // Add the macro back to the list.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000159 addLoadedMacroInfo(II, MD);
Douglas Gregor54c8a402012-10-12 00:16:50 +0000160
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000161 II->setHasMacroDefinition(StoredMD->isDefined());
Douglas Gregor54c8a402012-10-12 00:16:50 +0000162 if (II->isFromAST())
163 II->setChangedSinceDeserialization();
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000164}
165
Joao Matos3e1ec722012-08-31 21:34:27 +0000166/// \brief Undefine a macro for this identifier.
167void Preprocessor::clearMacroInfo(IdentifierInfo *II) {
168 assert(II->hasMacroDefinition() && "Macro is not defined!");
169 assert(Macros[II]->getUndefLoc().isValid() && "Macro is still defined!");
170 II->setHasMacroDefinition(false);
171 if (II->isFromAST())
172 II->setChangedSinceDeserialization();
173}
174
175/// RegisterBuiltinMacro - Register the specified identifier in the identifier
176/// table and mark it as a builtin macro to be expanded.
177static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
178 // Get the identifier.
179 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
180
181 // Mark it as being a macro that is builtin.
182 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
183 MI->setIsBuiltinMacro();
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000184 PP.setMacroDirective(Id, MI);
Joao Matos3e1ec722012-08-31 21:34:27 +0000185 return Id;
186}
187
188
189/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
190/// identifier table.
191void Preprocessor::RegisterBuiltinMacros() {
192 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
193 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
194 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
195 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
196 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
197 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
198
199 // GCC Extensions.
200 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
201 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
202 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
203
204 // Clang Extensions.
205 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
206 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
207 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
208 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
209 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
210 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
211 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
212
Douglas Gregorb09de512012-09-25 15:44:52 +0000213 // Modules.
214 if (LangOpts.Modules) {
215 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
216
217 // __MODULE__
218 if (!LangOpts.CurrentModule.empty())
219 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
220 else
221 Ident__MODULE__ = 0;
222 } else {
223 Ident__building_module = 0;
224 Ident__MODULE__ = 0;
225 }
226
Joao Matos3e1ec722012-08-31 21:34:27 +0000227 // Microsoft Extensions.
228 if (LangOpts.MicrosoftExt)
229 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
230 else
231 Ident__pragma = 0;
232}
233
234/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
235/// in its expansion, currently expands to that token literally.
236static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
237 const IdentifierInfo *MacroIdent,
238 Preprocessor &PP) {
239 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
240
241 // If the token isn't an identifier, it's always literally expanded.
242 if (II == 0) return true;
243
244 // If the information about this identifier is out of date, update it from
245 // the external source.
246 if (II->isOutOfDate())
247 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
248
249 // If the identifier is a macro, and if that macro is enabled, it may be
250 // expanded so it's not a trivial expansion.
251 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
252 // Fast expanding "#define X X" is ok, because X would be disabled.
253 II != MacroIdent)
254 return false;
255
256 // If this is an object-like macro invocation, it is safe to trivially expand
257 // it.
258 if (MI->isObjectLike()) return true;
259
260 // If this is a function-like macro invocation, it's safe to trivially expand
261 // as long as the identifier is not a macro argument.
262 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
263 I != E; ++I)
264 if (*I == II)
265 return false; // Identifier is a macro argument.
266
267 return true;
268}
269
270
271/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
272/// lexed is a '('. If so, consume the token and return true, if not, this
273/// method should have no observable side-effect on the lexed tokens.
274bool Preprocessor::isNextPPTokenLParen() {
275 // Do some quick tests for rejection cases.
276 unsigned Val;
277 if (CurLexer)
278 Val = CurLexer->isNextPPTokenLParen();
279 else if (CurPTHLexer)
280 Val = CurPTHLexer->isNextPPTokenLParen();
281 else
282 Val = CurTokenLexer->isNextTokenLParen();
283
284 if (Val == 2) {
285 // We have run off the end. If it's a source file we don't
286 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
287 // macro stack.
288 if (CurPPLexer)
289 return false;
290 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
291 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
292 if (Entry.TheLexer)
293 Val = Entry.TheLexer->isNextPPTokenLParen();
294 else if (Entry.ThePTHLexer)
295 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
296 else
297 Val = Entry.TheTokenLexer->isNextTokenLParen();
298
299 if (Val != 2)
300 break;
301
302 // Ran off the end of a source file?
303 if (Entry.ThePPLexer)
304 return false;
305 }
306 }
307
308 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
309 // have found something that isn't a '(' or we found the end of the
310 // translation unit. In either case, return false.
311 return Val == 1;
312}
313
314/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
315/// expanded as a macro, handle it and return the next token as 'Identifier'.
316bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000317 MacroDirective *MD) {
318 MacroInfo *MI = MD->getInfo();
319
Joao Matos3e1ec722012-08-31 21:34:27 +0000320 // If this is a macro expansion in the "#if !defined(x)" line for the file,
321 // then the macro could expand to different things in other contexts, we need
322 // to disable the optimization in this case.
323 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
324
325 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
326 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000327 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Joao Matos3e1ec722012-08-31 21:34:27 +0000328 Identifier.getLocation());
329 ExpandBuiltinMacro(Identifier);
330 return false;
331 }
332
333 /// Args - If this is a function-like macro expansion, this contains,
334 /// for each macro argument, the list of tokens that were provided to the
335 /// invocation.
336 MacroArgs *Args = 0;
337
338 // Remember where the end of the expansion occurred. For an object-like
339 // macro, this is the identifier. For a function-like macro, this is the ')'.
340 SourceLocation ExpansionEnd = Identifier.getLocation();
341
342 // If this is a function-like macro, read the arguments.
343 if (MI->isFunctionLike()) {
344 // C99 6.10.3p10: If the preprocessing token immediately after the macro
345 // name isn't a '(', this macro should not be expanded.
346 if (!isNextPPTokenLParen())
347 return true;
348
349 // Remember that we are now parsing the arguments to a macro invocation.
350 // Preprocessor directives used inside macro arguments are not portable, and
351 // this enables the warning.
352 InMacroArgs = true;
353 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
354
355 // Finished parsing args.
356 InMacroArgs = false;
357
358 // If there was an error parsing the arguments, bail out.
359 if (Args == 0) return false;
360
361 ++NumFnMacroExpanded;
362 } else {
363 ++NumMacroExpanded;
364 }
365
366 // Notice that this macro has been used.
367 markMacroAsUsed(MI);
368
369 // Remember where the token is expanded.
370 SourceLocation ExpandLoc = Identifier.getLocation();
371 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
372
373 if (Callbacks) {
374 if (InMacroArgs) {
375 // We can have macro expansion inside a conditional directive while
376 // reading the function macro arguments. To ensure, in that case, that
377 // MacroExpands callbacks still happen in source order, queue this
378 // callback to have it happen after the function macro callback.
379 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000380 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matos3e1ec722012-08-31 21:34:27 +0000381 } else {
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000382 Callbacks->MacroExpands(Identifier, MD, ExpansionRange);
Joao Matos3e1ec722012-08-31 21:34:27 +0000383 if (!DelayedMacroExpandsCallbacks.empty()) {
384 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
385 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000386 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range);
Joao Matos3e1ec722012-08-31 21:34:27 +0000387 }
388 DelayedMacroExpandsCallbacks.clear();
389 }
390 }
391 }
Douglas Gregore8219a62012-10-11 21:07:39 +0000392
Argyrios Kyrtzidis0c06cbc2013-01-23 18:21:56 +0000393 // FIXME: Temporarily disable this warning that is currently bogus with a PCH
394 // that redefined a macro without undef'ing it first (test/PCH/macro-redef.c).
395#if 0
Douglas Gregore8219a62012-10-11 21:07:39 +0000396 // If the macro definition is ambiguous, complain.
397 if (MI->isAmbiguous()) {
398 Diag(Identifier, diag::warn_pp_ambiguous_macro)
399 << Identifier.getIdentifierInfo();
400 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
401 << Identifier.getIdentifierInfo();
402 for (MacroInfo *PrevMI = MI->getPreviousDefinition();
403 PrevMI && PrevMI->isDefined();
404 PrevMI = PrevMI->getPreviousDefinition()) {
405 if (PrevMI->isAmbiguous()) {
406 Diag(PrevMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
407 << Identifier.getIdentifierInfo();
408 }
409 }
410 }
Argyrios Kyrtzidis0c06cbc2013-01-23 18:21:56 +0000411#endif
Douglas Gregore8219a62012-10-11 21:07:39 +0000412
Joao Matos3e1ec722012-08-31 21:34:27 +0000413 // If we started lexing a macro, enter the macro expansion body.
414
415 // If this macro expands to no tokens, don't bother to push it onto the
416 // expansion stack, only to take it right back off.
417 if (MI->getNumTokens() == 0) {
418 // No need for arg info.
419 if (Args) Args->destroy(*this);
420
421 // Ignore this macro use, just return the next token in the current
422 // buffer.
423 bool HadLeadingSpace = Identifier.hasLeadingSpace();
424 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
425
426 Lex(Identifier);
427
428 // If the identifier isn't on some OTHER line, inherit the leading
429 // whitespace/first-on-a-line property of this token. This handles
430 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
431 // empty.
432 if (!Identifier.isAtStartOfLine()) {
433 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
434 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
435 }
436 Identifier.setFlag(Token::LeadingEmptyMacro);
437 ++NumFastMacroExpanded;
438 return false;
439
440 } else if (MI->getNumTokens() == 1 &&
441 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
442 *this)) {
443 // Otherwise, if this macro expands into a single trivially-expanded
444 // token: expand it now. This handles common cases like
445 // "#define VAL 42".
446
447 // No need for arg info.
448 if (Args) Args->destroy(*this);
449
450 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
451 // identifier to the expanded token.
452 bool isAtStartOfLine = Identifier.isAtStartOfLine();
453 bool hasLeadingSpace = Identifier.hasLeadingSpace();
454
455 // Replace the result token.
456 Identifier = MI->getReplacementToken(0);
457
458 // Restore the StartOfLine/LeadingSpace markers.
459 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
460 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
461
462 // Update the tokens location to include both its expansion and physical
463 // locations.
464 SourceLocation Loc =
465 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
466 ExpansionEnd,Identifier.getLength());
467 Identifier.setLocation(Loc);
468
469 // If this is a disabled macro or #define X X, we must mark the result as
470 // unexpandable.
471 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
472 if (MacroInfo *NewMI = getMacroInfo(NewII))
473 if (!NewMI->isEnabled() || NewMI == MI) {
474 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor40f56e52013-01-30 23:10:17 +0000475 // Don't warn for "#define X X" like "#define bool bool" from
476 // stdbool.h.
477 if (NewMI != MI || MI->isFunctionLike())
478 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matos3e1ec722012-08-31 21:34:27 +0000479 }
480 }
481
482 // Since this is not an identifier token, it can't be macro expanded, so
483 // we're done.
484 ++NumFastMacroExpanded;
485 return false;
486 }
487
488 // Start expanding the macro.
489 EnterMacro(Identifier, ExpansionEnd, MI, Args);
490
491 // Now that the macro is at the top of the include stack, ask the
492 // preprocessor to read the next token from it.
493 Lex(Identifier);
494 return false;
495}
496
497/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
498/// token is the '(' of the macro, this method is invoked to read all of the
499/// actual arguments specified for the macro invocation. This returns null on
500/// error.
501MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
502 MacroInfo *MI,
503 SourceLocation &MacroEnd) {
504 // The number of fixed arguments to parse.
505 unsigned NumFixedArgsLeft = MI->getNumArgs();
506 bool isVariadic = MI->isVariadic();
507
508 // Outer loop, while there are more arguments, keep reading them.
509 Token Tok;
510
511 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
512 // an argument value in a macro could expand to ',' or '(' or ')'.
513 LexUnexpandedToken(Tok);
514 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
515
516 // ArgTokens - Build up a list of tokens that make up each argument. Each
517 // argument is separated by an EOF token. Use a SmallVector so we can avoid
518 // heap allocations in the common case.
519 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000520 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000521
522 unsigned NumActuals = 0;
523 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000524 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
525 break;
526
Joao Matos3e1ec722012-08-31 21:34:27 +0000527 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
528 "only expect argument separators here");
529
530 unsigned ArgTokenStart = ArgTokens.size();
531 SourceLocation ArgStartLoc = Tok.getLocation();
532
533 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
534 // that we already consumed the first one.
535 unsigned NumParens = 0;
536
537 while (1) {
538 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
539 // an argument value in a macro could expand to ',' or '(' or ')'.
540 LexUnexpandedToken(Tok);
541
542 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000543 if (!ContainsCodeCompletionTok) {
544 Diag(MacroName, diag::err_unterm_macro_invoc);
545 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
546 << MacroName.getIdentifierInfo();
547 // Do not lose the EOF/EOD. Return it to the client.
548 MacroName = Tok;
549 return 0;
550 } else {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000551 // Do not lose the EOF/EOD.
552 Token *Toks = new Token[1];
553 Toks[0] = Tok;
554 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000555 break;
556 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000557 } else if (Tok.is(tok::r_paren)) {
558 // If we found the ) token, the macro arg list is done.
559 if (NumParens-- == 0) {
560 MacroEnd = Tok.getLocation();
561 break;
562 }
563 } else if (Tok.is(tok::l_paren)) {
564 ++NumParens;
Nico Weber93dec512012-09-26 08:19:01 +0000565 } else if (Tok.is(tok::comma) && NumParens == 0) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000566 // Comma ends this argument if there are more fixed arguments expected.
567 // However, if this is a variadic macro, and this is part of the
568 // variadic part, then the comma is just an argument token.
569 if (!isVariadic) break;
570 if (NumFixedArgsLeft > 1)
571 break;
572 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
573 // If this is a comment token in the argument list and we're just in
574 // -C mode (not -CC mode), discard the comment.
575 continue;
576 } else if (Tok.getIdentifierInfo() != 0) {
577 // Reading macro arguments can cause macros that we are currently
578 // expanding from to be popped off the expansion stack. Doing so causes
579 // them to be reenabled for expansion. Here we record whether any
580 // identifiers we lex as macro arguments correspond to disabled macros.
581 // If so, we mark the token as noexpand. This is a subtle aspect of
582 // C99 6.10.3.4p2.
583 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
584 if (!MI->isEnabled())
585 Tok.setFlag(Token::DisableExpand);
586 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000587 ContainsCodeCompletionTok = true;
Joao Matos3e1ec722012-08-31 21:34:27 +0000588 if (CodeComplete)
589 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
590 MI, NumActuals);
591 // Don't mark that we reached the code-completion point because the
592 // parser is going to handle the token and there will be another
593 // code-completion callback.
594 }
595
596 ArgTokens.push_back(Tok);
597 }
598
599 // If this was an empty argument list foo(), don't add this as an empty
600 // argument.
601 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
602 break;
603
604 // If this is not a variadic macro, and too many args were specified, emit
605 // an error.
606 if (!isVariadic && NumFixedArgsLeft == 0) {
607 if (ArgTokens.size() != ArgTokenStart)
608 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
609
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000610 if (!ContainsCodeCompletionTok) {
611 // Emit the diagnostic at the macro name in case there is a missing ).
612 // Emitting it at the , could be far away from the macro name.
613 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
614 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
615 << MacroName.getIdentifierInfo();
616 return 0;
617 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000618 }
619
620 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
621 // other modes.
622 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +0000623 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matos3e1ec722012-08-31 21:34:27 +0000624 diag::warn_cxx98_compat_empty_fnmacro_arg :
625 diag::ext_empty_fnmacro_arg);
626
627 // Add a marker EOF token to the end of the token list for this argument.
628 Token EOFTok;
629 EOFTok.startToken();
630 EOFTok.setKind(tok::eof);
631 EOFTok.setLocation(Tok.getLocation());
632 EOFTok.setLength(0);
633 ArgTokens.push_back(EOFTok);
634 ++NumActuals;
Argyrios Kyrtzidisfdf57062013-02-22 22:28:58 +0000635 if (!ContainsCodeCompletionTok || NumFixedArgsLeft != 0) {
636 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
637 --NumFixedArgsLeft;
638 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000639 }
640
641 // Okay, we either found the r_paren. Check to see if we parsed too few
642 // arguments.
643 unsigned MinArgsExpected = MI->getNumArgs();
644
645 // See MacroArgs instance var for description of this.
646 bool isVarargsElided = false;
647
Argyrios Kyrtzidisf1e5b152012-12-21 01:51:12 +0000648 if (ContainsCodeCompletionTok) {
649 // Recover from not-fully-formed macro invocation during code-completion.
650 Token EOFTok;
651 EOFTok.startToken();
652 EOFTok.setKind(tok::eof);
653 EOFTok.setLocation(Tok.getLocation());
654 EOFTok.setLength(0);
655 for (; NumActuals < MinArgsExpected; ++NumActuals)
656 ArgTokens.push_back(EOFTok);
657 }
658
Joao Matos3e1ec722012-08-31 21:34:27 +0000659 if (NumActuals < MinArgsExpected) {
660 // There are several cases where too few arguments is ok, handle them now.
661 if (NumActuals == 0 && MinArgsExpected == 1) {
662 // #define A(X) or #define A(...) ---> A()
663
664 // If there is exactly one argument, and that argument is missing,
665 // then we have an empty "()" argument empty list. This is fine, even if
666 // the macro expects one argument (the argument is just empty).
667 isVarargsElided = MI->isVariadic();
668 } else if (MI->isVariadic() &&
669 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
670 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
671 // Varargs where the named vararg parameter is missing: OK as extension.
672 // #define A(x, ...)
673 // A("blah")
Eli Friedman4fa4b482012-11-14 02:18:46 +0000674 //
675 // If the macro contains the comma pasting extension, the diagnostic
676 // is suppressed; we know we'll get another diagnostic later.
677 if (!MI->hasCommaPasting()) {
678 Diag(Tok, diag::ext_missing_varargs_arg);
679 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
680 << MacroName.getIdentifierInfo();
681 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000682
683 // Remember this occurred, allowing us to elide the comma when used for
684 // cases like:
685 // #define A(x, foo...) blah(a, ## foo)
686 // #define B(x, ...) blah(a, ## __VA_ARGS__)
687 // #define C(...) blah(a, ## __VA_ARGS__)
688 // A(x) B(x) C()
689 isVarargsElided = true;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000690 } else if (!ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000691 // Otherwise, emit the error.
692 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000693 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
694 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000695 return 0;
696 }
697
698 // Add a marker EOF token to the end of the token list for this argument.
699 SourceLocation EndLoc = Tok.getLocation();
700 Tok.startToken();
701 Tok.setKind(tok::eof);
702 Tok.setLocation(EndLoc);
703 Tok.setLength(0);
704 ArgTokens.push_back(Tok);
705
706 // If we expect two arguments, add both as empty.
707 if (NumActuals == 0 && MinArgsExpected == 2)
708 ArgTokens.push_back(Tok);
709
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000710 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
711 !ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000712 // Emit the diagnostic at the macro name in case there is a missing ).
713 // Emitting it at the , could be far away from the macro name.
714 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000715 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
716 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000717 return 0;
718 }
719
720 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
721}
722
723/// \brief Keeps macro expanded tokens for TokenLexers.
724//
725/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
726/// going to lex in the cache and when it finishes the tokens are removed
727/// from the end of the cache.
728Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
729 ArrayRef<Token> tokens) {
730 assert(tokLexer);
731 if (tokens.empty())
732 return 0;
733
734 size_t newIndex = MacroExpandedTokens.size();
735 bool cacheNeedsToGrow = tokens.size() >
736 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
737 MacroExpandedTokens.append(tokens.begin(), tokens.end());
738
739 if (cacheNeedsToGrow) {
740 // Go through all the TokenLexers whose 'Tokens' pointer points in the
741 // buffer and update the pointers to the (potential) new buffer array.
742 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
743 TokenLexer *prevLexer;
744 size_t tokIndex;
745 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
746 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
747 }
748 }
749
750 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
751 return MacroExpandedTokens.data() + newIndex;
752}
753
754void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
755 assert(!MacroExpandingLexersStack.empty());
756 size_t tokIndex = MacroExpandingLexersStack.back().second;
757 assert(tokIndex < MacroExpandedTokens.size());
758 // Pop the cached macro expanded tokens from the end.
759 MacroExpandedTokens.resize(tokIndex);
760 MacroExpandingLexersStack.pop_back();
761}
762
763/// ComputeDATE_TIME - Compute the current time, enter it into the specified
764/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
765/// the identifier tokens inserted.
766static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
767 Preprocessor &PP) {
768 time_t TT = time(0);
769 struct tm *TM = localtime(&TT);
770
771 static const char * const Months[] = {
772 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
773 };
774
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000775 {
776 SmallString<32> TmpBuffer;
777 llvm::raw_svector_ostream TmpStream(TmpBuffer);
778 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
779 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000780 Token TmpTok;
781 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000782 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000783 DATELoc = TmpTok.getLocation();
784 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000785
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000786 {
787 SmallString<32> TmpBuffer;
788 llvm::raw_svector_ostream TmpStream(TmpBuffer);
789 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
790 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000791 Token TmpTok;
792 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000793 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000794 TIMELoc = TmpTok.getLocation();
795 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000796}
797
798
799/// HasFeature - Return true if we recognize and implement the feature
800/// specified by the identifier as a standard language feature.
801static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
802 const LangOptions &LangOpts = PP.getLangOpts();
803 StringRef Feature = II->getName();
804
805 // Normalize the feature name, __foo__ becomes foo.
806 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
807 Feature = Feature.substr(2, Feature.size() - 4);
808
809 return llvm::StringSwitch<bool>(Feature)
Will Dietz4f45bc02013-01-18 11:30:38 +0000810 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matos3e1ec722012-08-31 21:34:27 +0000811 .Case("attribute_analyzer_noreturn", true)
812 .Case("attribute_availability", true)
813 .Case("attribute_availability_with_message", true)
814 .Case("attribute_cf_returns_not_retained", true)
815 .Case("attribute_cf_returns_retained", true)
816 .Case("attribute_deprecated_with_message", true)
817 .Case("attribute_ext_vector_type", true)
818 .Case("attribute_ns_returns_not_retained", true)
819 .Case("attribute_ns_returns_retained", true)
820 .Case("attribute_ns_consumes_self", true)
821 .Case("attribute_ns_consumed", true)
822 .Case("attribute_cf_consumed", true)
823 .Case("attribute_objc_ivar_unused", true)
824 .Case("attribute_objc_method_family", true)
825 .Case("attribute_overloadable", true)
826 .Case("attribute_unavailable_with_message", true)
827 .Case("attribute_unused_on_fields", true)
828 .Case("blocks", LangOpts.Blocks)
829 .Case("cxx_exceptions", LangOpts.Exceptions)
830 .Case("cxx_rtti", LangOpts.RTTI)
831 .Case("enumerator_attributes", true)
Will Dietz4f45bc02013-01-18 11:30:38 +0000832 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
833 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Joao Matos3e1ec722012-08-31 21:34:27 +0000834 // Objective-C features
835 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
836 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
837 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
838 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
839 .Case("objc_fixed_enum", LangOpts.ObjC2)
840 .Case("objc_instancetype", LangOpts.ObjC2)
841 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
842 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremeneke4057c22013-01-04 19:04:44 +0000843 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Joao Matos3e1ec722012-08-31 21:34:27 +0000844 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
845 .Case("ownership_holds", true)
846 .Case("ownership_returns", true)
847 .Case("ownership_takes", true)
848 .Case("objc_bool", true)
849 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
850 .Case("objc_array_literals", LangOpts.ObjC2)
851 .Case("objc_dictionary_literals", LangOpts.ObjC2)
852 .Case("objc_boxed_expressions", LangOpts.ObjC2)
853 .Case("arc_cf_code_audited", true)
854 // C11 features
855 .Case("c_alignas", LangOpts.C11)
856 .Case("c_atomic", LangOpts.C11)
857 .Case("c_generic_selections", LangOpts.C11)
858 .Case("c_static_assert", LangOpts.C11)
859 // C++11 features
Richard Smith80ad52f2013-01-02 11:42:31 +0000860 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
861 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
862 .Case("cxx_alignas", LangOpts.CPlusPlus11)
863 .Case("cxx_atomic", LangOpts.CPlusPlus11)
864 .Case("cxx_attributes", LangOpts.CPlusPlus11)
865 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
866 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
867 .Case("cxx_decltype", LangOpts.CPlusPlus11)
868 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
869 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
870 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
871 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
872 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
873 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
874 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
875 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000876 //.Case("cxx_inheriting_constructors", false)
Richard Smith80ad52f2013-01-02 11:42:31 +0000877 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
878 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
879 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
880 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
881 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
882 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
883 .Case("cxx_override_control", LangOpts.CPlusPlus11)
884 .Case("cxx_range_for", LangOpts.CPlusPlus11)
885 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
886 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
887 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
888 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
889 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
890 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
891 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
892 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
893 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
894 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000895 // Type traits
896 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
897 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
898 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
899 .Case("has_trivial_assign", LangOpts.CPlusPlus)
900 .Case("has_trivial_copy", LangOpts.CPlusPlus)
901 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
902 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
903 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
904 .Case("is_abstract", LangOpts.CPlusPlus)
905 .Case("is_base_of", LangOpts.CPlusPlus)
906 .Case("is_class", LangOpts.CPlusPlus)
907 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000908 .Case("is_empty", LangOpts.CPlusPlus)
909 .Case("is_enum", LangOpts.CPlusPlus)
910 .Case("is_final", LangOpts.CPlusPlus)
911 .Case("is_literal", LangOpts.CPlusPlus)
912 .Case("is_standard_layout", LangOpts.CPlusPlus)
913 .Case("is_pod", LangOpts.CPlusPlus)
914 .Case("is_polymorphic", LangOpts.CPlusPlus)
915 .Case("is_trivial", LangOpts.CPlusPlus)
916 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
917 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
918 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
919 .Case("is_union", LangOpts.CPlusPlus)
920 .Case("modules", LangOpts.Modules)
921 .Case("tls", PP.getTargetInfo().isTLSSupported())
922 .Case("underlying_type", LangOpts.CPlusPlus)
923 .Default(false);
924}
925
926/// HasExtension - Return true if we recognize and implement the feature
927/// specified by the identifier, either as an extension or a standard language
928/// feature.
929static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
930 if (HasFeature(PP, II))
931 return true;
932
933 // If the use of an extension results in an error diagnostic, extensions are
934 // effectively unavailable, so just return false here.
935 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
936 DiagnosticsEngine::Ext_Error)
937 return false;
938
939 const LangOptions &LangOpts = PP.getLangOpts();
940 StringRef Extension = II->getName();
941
942 // Normalize the extension name, __foo__ becomes foo.
943 if (Extension.startswith("__") && Extension.endswith("__") &&
944 Extension.size() >= 4)
945 Extension = Extension.substr(2, Extension.size() - 4);
946
947 // Because we inherit the feature list from HasFeature, this string switch
948 // must be less restrictive than HasFeature's.
949 return llvm::StringSwitch<bool>(Extension)
950 // C11 features supported by other languages as extensions.
951 .Case("c_alignas", true)
952 .Case("c_atomic", true)
953 .Case("c_generic_selections", true)
954 .Case("c_static_assert", true)
955 // C++0x features supported by other languages as extensions.
956 .Case("cxx_atomic", LangOpts.CPlusPlus)
957 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
958 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
959 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
960 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
961 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
962 .Case("cxx_override_control", LangOpts.CPlusPlus)
963 .Case("cxx_range_for", LangOpts.CPlusPlus)
964 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
965 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
966 .Default(false);
967}
968
969/// HasAttribute - Return true if we recognize and implement the attribute
970/// specified by the given identifier.
971static bool HasAttribute(const IdentifierInfo *II) {
972 StringRef Name = II->getName();
973 // Normalize the attribute name, __foo__ becomes foo.
974 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
975 Name = Name.substr(2, Name.size() - 4);
976
977 // FIXME: Do we need to handle namespaces here?
978 return llvm::StringSwitch<bool>(Name)
979#include "clang/Lex/AttrSpellings.inc"
980 .Default(false);
981}
982
983/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
984/// or '__has_include_next("path")' expression.
985/// Returns true if successful.
986static bool EvaluateHasIncludeCommon(Token &Tok,
987 IdentifierInfo *II, Preprocessor &PP,
988 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000989 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman6b716c52013-01-15 21:59:46 +0000990 // that location. If not, use the end of this location instead.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000991 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +0000992
Aaron Ballman31672b12013-01-16 19:32:21 +0000993 // These expressions are only allowed within a preprocessor directive.
994 if (!PP.isParsingIfOrElifDirective()) {
995 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
996 return false;
997 }
998
Joao Matos3e1ec722012-08-31 21:34:27 +0000999 // Get '('.
1000 PP.LexNonComment(Tok);
1001
1002 // Ensure we have a '('.
1003 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001004 // No '(', use end of last token.
1005 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1006 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
1007 // If the next token looks like a filename or the start of one,
1008 // assume it is and process it as such.
1009 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1010 !Tok.is(tok::less))
1011 return false;
1012 } else {
1013 // Save '(' location for possible missing ')' message.
1014 LParenLoc = Tok.getLocation();
1015
Eli Friedmana0f2d022013-01-09 02:20:00 +00001016 if (PP.getCurrentLexer()) {
1017 // Get the file name.
1018 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1019 } else {
1020 // We're in a macro, so we can't use LexIncludeFilename; just
1021 // grab the next token.
1022 PP.Lex(Tok);
1023 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001024 }
1025
Joao Matos3e1ec722012-08-31 21:34:27 +00001026 // Reserve a buffer to get the spelling.
1027 SmallString<128> FilenameBuffer;
1028 StringRef Filename;
1029 SourceLocation EndLoc;
1030
1031 switch (Tok.getKind()) {
1032 case tok::eod:
1033 // If the token kind is EOD, the error has already been diagnosed.
1034 return false;
1035
1036 case tok::angle_string_literal:
1037 case tok::string_literal: {
1038 bool Invalid = false;
1039 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1040 if (Invalid)
1041 return false;
1042 break;
1043 }
1044
1045 case tok::less:
1046 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1047 // case, glue the tokens together into FilenameBuffer and interpret those.
1048 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +00001049 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1050 // Let the caller know a <eod> was found by changing the Token kind.
1051 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +00001052 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +00001053 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001054 Filename = FilenameBuffer.str();
1055 break;
1056 default:
1057 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1058 return false;
1059 }
1060
Richard Trieu97bc3d52012-10-22 20:28:48 +00001061 SourceLocation FilenameLoc = Tok.getLocation();
1062
Joao Matos3e1ec722012-08-31 21:34:27 +00001063 // Get ')'.
1064 PP.LexNonComment(Tok);
1065
1066 // Ensure we have a trailing ).
1067 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001068 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
1069 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +00001070 PP.Diag(LParenLoc, diag::note_matching) << "(";
1071 return false;
1072 }
1073
1074 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1075 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1076 // error.
1077 if (Filename.empty())
1078 return false;
1079
1080 // Search include directories.
1081 const DirectoryLookup *CurDir;
1082 const FileEntry *File =
1083 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
1084
1085 // Get the result value. A result of true means the file exists.
1086 return File != 0;
1087}
1088
1089/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1090/// Returns true if successful.
1091static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1092 Preprocessor &PP) {
1093 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1094}
1095
1096/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1097/// Returns true if successful.
1098static bool EvaluateHasIncludeNext(Token &Tok,
1099 IdentifierInfo *II, Preprocessor &PP) {
1100 // __has_include_next is like __has_include, except that we start
1101 // searching after the current found directory. If we can't do this,
1102 // issue a diagnostic.
1103 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1104 if (PP.isInPrimaryFile()) {
1105 Lookup = 0;
1106 PP.Diag(Tok, diag::pp_include_next_in_primary);
1107 } else if (Lookup == 0) {
1108 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1109 } else {
1110 // Start looking up in the next directory.
1111 ++Lookup;
1112 }
1113
1114 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1115}
1116
Douglas Gregorb09de512012-09-25 15:44:52 +00001117/// \brief Process __building_module(identifier) expression.
1118/// \returns true if we are building the named module, false otherwise.
1119static bool EvaluateBuildingModule(Token &Tok,
1120 IdentifierInfo *II, Preprocessor &PP) {
1121 // Get '('.
1122 PP.LexNonComment(Tok);
1123
1124 // Ensure we have a '('.
1125 if (Tok.isNot(tok::l_paren)) {
1126 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1127 return false;
1128 }
1129
1130 // Save '(' location for possible missing ')' message.
1131 SourceLocation LParenLoc = Tok.getLocation();
1132
1133 // Get the module name.
1134 PP.LexNonComment(Tok);
1135
1136 // Ensure that we have an identifier.
1137 if (Tok.isNot(tok::identifier)) {
1138 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1139 return false;
1140 }
1141
1142 bool Result
1143 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1144
1145 // Get ')'.
1146 PP.LexNonComment(Tok);
1147
1148 // Ensure we have a trailing ).
1149 if (Tok.isNot(tok::r_paren)) {
1150 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1151 PP.Diag(LParenLoc, diag::note_matching) << "(";
1152 return false;
1153 }
1154
1155 return Result;
1156}
1157
Joao Matos3e1ec722012-08-31 21:34:27 +00001158/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1159/// as a builtin macro, handle it and return the next token as 'Tok'.
1160void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1161 // Figure out which token this is.
1162 IdentifierInfo *II = Tok.getIdentifierInfo();
1163 assert(II && "Can't be a macro without id info!");
1164
1165 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1166 // invoke the pragma handler, then lex the token after it.
1167 if (II == Ident_Pragma)
1168 return Handle_Pragma(Tok);
1169 else if (II == Ident__pragma) // in non-MS mode this is null
1170 return HandleMicrosoft__pragma(Tok);
1171
1172 ++NumBuiltinMacroExpanded;
1173
1174 SmallString<128> TmpBuffer;
1175 llvm::raw_svector_ostream OS(TmpBuffer);
1176
1177 // Set up the return result.
1178 Tok.setIdentifierInfo(0);
1179 Tok.clearFlag(Token::NeedsCleaning);
1180
1181 if (II == Ident__LINE__) {
1182 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1183 // source file) of the current source line (an integer constant)". This can
1184 // be affected by #line.
1185 SourceLocation Loc = Tok.getLocation();
1186
1187 // Advance to the location of the first _, this might not be the first byte
1188 // of the token if it starts with an escaped newline.
1189 Loc = AdvanceToTokenCharacter(Loc, 0);
1190
1191 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1192 // a macro expansion. This doesn't matter for object-like macros, but
1193 // can matter for a function-like macro that expands to contain __LINE__.
1194 // Skip down through expansion points until we find a file loc for the
1195 // end of the expansion history.
1196 Loc = SourceMgr.getExpansionRange(Loc).second;
1197 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1198
1199 // __LINE__ expands to a simple numeric value.
1200 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1201 Tok.setKind(tok::numeric_constant);
1202 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1203 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1204 // character string literal)". This can be affected by #line.
1205 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1206
1207 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1208 // #include stack instead of the current file.
1209 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1210 SourceLocation NextLoc = PLoc.getIncludeLoc();
1211 while (NextLoc.isValid()) {
1212 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1213 if (PLoc.isInvalid())
1214 break;
1215
1216 NextLoc = PLoc.getIncludeLoc();
1217 }
1218 }
1219
1220 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1221 SmallString<128> FN;
1222 if (PLoc.isValid()) {
1223 FN += PLoc.getFilename();
1224 Lexer::Stringify(FN);
1225 OS << '"' << FN.str() << '"';
1226 }
1227 Tok.setKind(tok::string_literal);
1228 } else if (II == Ident__DATE__) {
1229 if (!DATELoc.isValid())
1230 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1231 Tok.setKind(tok::string_literal);
1232 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1233 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1234 Tok.getLocation(),
1235 Tok.getLength()));
1236 return;
1237 } else if (II == Ident__TIME__) {
1238 if (!TIMELoc.isValid())
1239 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1240 Tok.setKind(tok::string_literal);
1241 Tok.setLength(strlen("\"hh:mm:ss\""));
1242 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1243 Tok.getLocation(),
1244 Tok.getLength()));
1245 return;
1246 } else if (II == Ident__INCLUDE_LEVEL__) {
1247 // Compute the presumed include depth of this token. This can be affected
1248 // by GNU line markers.
1249 unsigned Depth = 0;
1250
1251 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1252 if (PLoc.isValid()) {
1253 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1254 for (; PLoc.isValid(); ++Depth)
1255 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1256 }
1257
1258 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1259 OS << Depth;
1260 Tok.setKind(tok::numeric_constant);
1261 } else if (II == Ident__TIMESTAMP__) {
1262 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1263 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1264
1265 // Get the file that we are lexing out of. If we're currently lexing from
1266 // a macro, dig into the include stack.
1267 const FileEntry *CurFile = 0;
1268 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1269
1270 if (TheLexer)
1271 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1272
1273 const char *Result;
1274 if (CurFile) {
1275 time_t TT = CurFile->getModificationTime();
1276 struct tm *TM = localtime(&TT);
1277 Result = asctime(TM);
1278 } else {
1279 Result = "??? ??? ?? ??:??:?? ????\n";
1280 }
1281 // Surround the string with " and strip the trailing newline.
1282 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1283 Tok.setKind(tok::string_literal);
1284 } else if (II == Ident__COUNTER__) {
1285 // __COUNTER__ expands to a simple numeric value.
1286 OS << CounterValue++;
1287 Tok.setKind(tok::numeric_constant);
1288 } else if (II == Ident__has_feature ||
1289 II == Ident__has_extension ||
1290 II == Ident__has_builtin ||
1291 II == Ident__has_attribute) {
1292 // The argument to these builtins should be a parenthesized identifier.
1293 SourceLocation StartLoc = Tok.getLocation();
1294
1295 bool IsValid = false;
1296 IdentifierInfo *FeatureII = 0;
1297
1298 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001299 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001300 if (Tok.is(tok::l_paren)) {
1301 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001302 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001303 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1304 FeatureII = Tok.getIdentifierInfo();
1305
1306 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001307 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001308 if (Tok.is(tok::r_paren))
1309 IsValid = true;
1310 }
1311 }
1312
1313 bool Value = false;
1314 if (!IsValid)
1315 Diag(StartLoc, diag::err_feature_check_malformed);
1316 else if (II == Ident__has_builtin) {
1317 // Check for a builtin is trivial.
1318 Value = FeatureII->getBuiltinID() != 0;
1319 } else if (II == Ident__has_attribute)
1320 Value = HasAttribute(FeatureII);
1321 else if (II == Ident__has_extension)
1322 Value = HasExtension(*this, FeatureII);
1323 else {
1324 assert(II == Ident__has_feature && "Must be feature check");
1325 Value = HasFeature(*this, FeatureII);
1326 }
1327
1328 OS << (int)Value;
1329 if (IsValid)
1330 Tok.setKind(tok::numeric_constant);
1331 } else if (II == Ident__has_include ||
1332 II == Ident__has_include_next) {
1333 // The argument to these two builtins should be a parenthesized
1334 // file name string literal using angle brackets (<>) or
1335 // double-quotes ("").
1336 bool Value;
1337 if (II == Ident__has_include)
1338 Value = EvaluateHasInclude(Tok, II, *this);
1339 else
1340 Value = EvaluateHasIncludeNext(Tok, II, *this);
1341 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001342 if (Tok.is(tok::r_paren))
1343 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001344 } else if (II == Ident__has_warning) {
1345 // The argument should be a parenthesized string literal.
1346 // The argument to these builtins should be a parenthesized identifier.
1347 SourceLocation StartLoc = Tok.getLocation();
1348 bool IsValid = false;
1349 bool Value = false;
1350 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001351 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001352 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001353 if (Tok.isNot(tok::l_paren)) {
1354 Diag(StartLoc, diag::err_warning_check_malformed);
1355 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001356 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001357
1358 LexUnexpandedToken(Tok);
1359 std::string WarningName;
1360 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001361 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1362 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001363 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001364 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1365 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001366 LexUnexpandedToken(Tok);
1367 break;
1368 }
1369
1370 // Is the end a ')'?
1371 if (!(IsValid = Tok.is(tok::r_paren))) {
1372 Diag(StartLoc, diag::err_warning_check_malformed);
1373 break;
1374 }
1375
1376 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1377 WarningName[1] != 'W') {
1378 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1379 break;
1380 }
1381
1382 // Finally, check if the warning flags maps to a diagnostic group.
1383 // We construct a SmallVector here to talk to getDiagnosticIDs().
1384 // Although we don't use the result, this isn't a hot path, and not
1385 // worth special casing.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001386 SmallVector<diag::kind, 10> Diags;
Andy Gibbs02a17682012-11-17 19:15:38 +00001387 Value = !getDiagnostics().getDiagnosticIDs()->
1388 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001389 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001390
1391 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001392 if (IsValid)
1393 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001394 } else if (II == Ident__building_module) {
1395 // The argument to this builtin should be an identifier. The
1396 // builtin evaluates to 1 when that identifier names the module we are
1397 // currently building.
1398 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1399 Tok.setKind(tok::numeric_constant);
1400 } else if (II == Ident__MODULE__) {
1401 // The current module as an identifier.
1402 OS << getLangOpts().CurrentModule;
1403 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1404 Tok.setIdentifierInfo(ModuleII);
1405 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001406 } else {
1407 llvm_unreachable("Unknown identifier!");
1408 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001409 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001410}
1411
1412void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1413 // If the 'used' status changed, and the macro requires 'unused' warning,
1414 // remove its SourceLocation from the warn-for-unused-macro locations.
1415 if (MI->isWarnIfUnused() && !MI->isUsed())
1416 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1417 MI->setIsUsed(true);
1418}