blob: 3e68fbdf011886df574ada159f79084b207c1b5e [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
44/// setMacroInfo - Specify a macro for this identifier.
45///
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000046void Preprocessor::setMacroDirective(IdentifierInfo *II, MacroInfo *MI,
47 SourceLocation Loc, bool isImported) {
Joao Matos3e1ec722012-08-31 21:34:27 +000048 assert(MI && "MacroInfo should be non-zero!");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000049
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000050 MacroDirective *MD = AllocateMacroDirective(MI, Loc, isImported);
51 MacroDirective *&StoredMD = Macros[II];
52 MD->setPrevious(StoredMD);
53 StoredMD = MD;
54 II->setHasMacroDefinition(true);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000055 if (II->isFromAST())
Joao Matos3e1ec722012-08-31 21:34:27 +000056 II->setChangedSinceDeserialization();
57}
58
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000059void Preprocessor::addLoadedMacroInfo(IdentifierInfo *II, MacroDirective *MD,
60 MacroDirective *Hint) {
61 assert(MD && "Missing macro?");
62 assert(MD->isImported() && "Macro is not from an AST?");
63 assert(!MD->getPrevious() && "Macro already in chain?");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000064
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000065 MacroDirective *&StoredMD = Macros[II];
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000066
67 // Easy case: this is the first macro definition for this macro.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000068 if (!StoredMD) {
69 StoredMD = MD;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000070
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000071 if (MD->isDefined())
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000072 II->setHasMacroDefinition(true);
73 return;
74 }
75
76 // If this macro is a definition and this identifier has been neither
77 // defined nor undef'd in the current translation unit, add this macro
78 // to the end of the chain of definitions.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000079 if (MD->isDefined() && StoredMD->isImported()) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000080 // Simple case: if this is the first actual definition, just put it at
81 // th beginning.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000082 if (!StoredMD->isDefined()) {
83 MD->setPrevious(StoredMD);
84 StoredMD = MD;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000085
86 II->setHasMacroDefinition(true);
87 return;
88 }
89
90 // Find the end of the definition chain.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000091 MacroDirective *Prev;
92 MacroDirective *PrevPrev = StoredMD;
93 bool Ambiguous = StoredMD->isAmbiguous();
Douglas Gregore8219a62012-10-11 21:07:39 +000094 bool MatchedOther = false;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000095 do {
Douglas Gregor54c8a402012-10-12 00:16:50 +000096 Prev = PrevPrev;
97
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000098 // If the macros are not identical, we have an ambiguity.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000099 if (!Prev->getInfo()->isIdenticalTo(*MD->getInfo(), *this)) {
Douglas Gregore8219a62012-10-11 21:07:39 +0000100 if (!Ambiguous) {
101 Ambiguous = true;
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000102 StoredMD->setAmbiguous(true);
Douglas Gregore8219a62012-10-11 21:07:39 +0000103 }
104 } else {
105 MatchedOther = true;
106 }
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000107 } while ((PrevPrev = Prev->getPrevious()) &&
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000108 PrevPrev->isDefined());
109
Douglas Gregore8219a62012-10-11 21:07:39 +0000110 // If there are ambiguous definitions, and we didn't match any other
111 // definition, then mark us as ambiguous.
112 if (Ambiguous && !MatchedOther)
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000113 MD->setAmbiguous(true);
Douglas Gregor7097be92012-10-11 00:48:48 +0000114
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000115 // Wire this macro information into the chain.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000116 MD->setPrevious(Prev->getPrevious());
117 Prev->setPrevious(MD);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000118 return;
119 }
120
121 // The macro is not a definition; put it at the end of the list.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000122 MacroDirective *Prev = Hint? Hint : StoredMD;
123 while (Prev->getPrevious())
124 Prev = Prev->getPrevious();
125 Prev->setPrevious(MD);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000126}
127
128void Preprocessor::makeLoadedMacroInfoVisible(IdentifierInfo *II,
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000129 MacroDirective *MD) {
130 assert(MD->isImported() && "Macro must be from the AST");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000131
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000132 MacroDirective *&StoredMD = Macros[II];
133 if (StoredMD == MD) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000134 // Easy case: this is the first macro anyway.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000135 II->setHasMacroDefinition(MD->isDefined());
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000136 return;
137 }
138
139 // Go find the macro and pull it out of the list.
Douglas Gregor54c8a402012-10-12 00:16:50 +0000140 // FIXME: Yes, this is O(N), and making a pile of macros visible or hidden
141 // would be quadratic, but it's extremely rare.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000142 MacroDirective *Prev = StoredMD;
143 while (Prev->getPrevious() != MD)
144 Prev = Prev->getPrevious();
145 Prev->setPrevious(MD->getPrevious());
146 MD->setPrevious(0);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000147
148 // Add the macro back to the list.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000149 addLoadedMacroInfo(II, MD);
Douglas Gregor54c8a402012-10-12 00:16:50 +0000150
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000151 II->setHasMacroDefinition(StoredMD->isDefined());
Douglas Gregor54c8a402012-10-12 00:16:50 +0000152 if (II->isFromAST())
153 II->setChangedSinceDeserialization();
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000154}
155
Joao Matos3e1ec722012-08-31 21:34:27 +0000156/// \brief Undefine a macro for this identifier.
157void Preprocessor::clearMacroInfo(IdentifierInfo *II) {
158 assert(II->hasMacroDefinition() && "Macro is not defined!");
159 assert(Macros[II]->getUndefLoc().isValid() && "Macro is still defined!");
160 II->setHasMacroDefinition(false);
161 if (II->isFromAST())
162 II->setChangedSinceDeserialization();
163}
164
165/// RegisterBuiltinMacro - Register the specified identifier in the identifier
166/// table and mark it as a builtin macro to be expanded.
167static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
168 // Get the identifier.
169 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
170
171 // Mark it as being a macro that is builtin.
172 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
173 MI->setIsBuiltinMacro();
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000174 PP.setMacroDirective(Id, MI);
Joao Matos3e1ec722012-08-31 21:34:27 +0000175 return Id;
176}
177
178
179/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
180/// identifier table.
181void Preprocessor::RegisterBuiltinMacros() {
182 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
183 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
184 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
185 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
186 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
187 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
188
189 // GCC Extensions.
190 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
191 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
192 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
193
194 // Clang Extensions.
195 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
196 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
197 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
198 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
199 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
200 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
201 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
202
Douglas Gregorb09de512012-09-25 15:44:52 +0000203 // Modules.
204 if (LangOpts.Modules) {
205 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
206
207 // __MODULE__
208 if (!LangOpts.CurrentModule.empty())
209 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
210 else
211 Ident__MODULE__ = 0;
212 } else {
213 Ident__building_module = 0;
214 Ident__MODULE__ = 0;
215 }
216
Joao Matos3e1ec722012-08-31 21:34:27 +0000217 // Microsoft Extensions.
218 if (LangOpts.MicrosoftExt)
219 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
220 else
221 Ident__pragma = 0;
222}
223
224/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
225/// in its expansion, currently expands to that token literally.
226static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
227 const IdentifierInfo *MacroIdent,
228 Preprocessor &PP) {
229 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
230
231 // If the token isn't an identifier, it's always literally expanded.
232 if (II == 0) return true;
233
234 // If the information about this identifier is out of date, update it from
235 // the external source.
236 if (II->isOutOfDate())
237 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
238
239 // If the identifier is a macro, and if that macro is enabled, it may be
240 // expanded so it's not a trivial expansion.
241 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
242 // Fast expanding "#define X X" is ok, because X would be disabled.
243 II != MacroIdent)
244 return false;
245
246 // If this is an object-like macro invocation, it is safe to trivially expand
247 // it.
248 if (MI->isObjectLike()) return true;
249
250 // If this is a function-like macro invocation, it's safe to trivially expand
251 // as long as the identifier is not a macro argument.
252 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
253 I != E; ++I)
254 if (*I == II)
255 return false; // Identifier is a macro argument.
256
257 return true;
258}
259
260
261/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
262/// lexed is a '('. If so, consume the token and return true, if not, this
263/// method should have no observable side-effect on the lexed tokens.
264bool Preprocessor::isNextPPTokenLParen() {
265 // Do some quick tests for rejection cases.
266 unsigned Val;
267 if (CurLexer)
268 Val = CurLexer->isNextPPTokenLParen();
269 else if (CurPTHLexer)
270 Val = CurPTHLexer->isNextPPTokenLParen();
271 else
272 Val = CurTokenLexer->isNextTokenLParen();
273
274 if (Val == 2) {
275 // We have run off the end. If it's a source file we don't
276 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
277 // macro stack.
278 if (CurPPLexer)
279 return false;
280 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
281 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
282 if (Entry.TheLexer)
283 Val = Entry.TheLexer->isNextPPTokenLParen();
284 else if (Entry.ThePTHLexer)
285 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
286 else
287 Val = Entry.TheTokenLexer->isNextTokenLParen();
288
289 if (Val != 2)
290 break;
291
292 // Ran off the end of a source file?
293 if (Entry.ThePPLexer)
294 return false;
295 }
296 }
297
298 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
299 // have found something that isn't a '(' or we found the end of the
300 // translation unit. In either case, return false.
301 return Val == 1;
302}
303
304/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
305/// expanded as a macro, handle it and return the next token as 'Identifier'.
306bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
307 MacroInfo *MI) {
308 // If this is a macro expansion in the "#if !defined(x)" line for the file,
309 // then the macro could expand to different things in other contexts, we need
310 // to disable the optimization in this case.
311 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
312
313 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
314 if (MI->isBuiltinMacro()) {
315 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
316 Identifier.getLocation());
317 ExpandBuiltinMacro(Identifier);
318 return false;
319 }
320
321 /// Args - If this is a function-like macro expansion, this contains,
322 /// for each macro argument, the list of tokens that were provided to the
323 /// invocation.
324 MacroArgs *Args = 0;
325
326 // Remember where the end of the expansion occurred. For an object-like
327 // macro, this is the identifier. For a function-like macro, this is the ')'.
328 SourceLocation ExpansionEnd = Identifier.getLocation();
329
330 // If this is a function-like macro, read the arguments.
331 if (MI->isFunctionLike()) {
332 // C99 6.10.3p10: If the preprocessing token immediately after the macro
333 // name isn't a '(', this macro should not be expanded.
334 if (!isNextPPTokenLParen())
335 return true;
336
337 // Remember that we are now parsing the arguments to a macro invocation.
338 // Preprocessor directives used inside macro arguments are not portable, and
339 // this enables the warning.
340 InMacroArgs = true;
341 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
342
343 // Finished parsing args.
344 InMacroArgs = false;
345
346 // If there was an error parsing the arguments, bail out.
347 if (Args == 0) return false;
348
349 ++NumFnMacroExpanded;
350 } else {
351 ++NumMacroExpanded;
352 }
353
354 // Notice that this macro has been used.
355 markMacroAsUsed(MI);
356
357 // Remember where the token is expanded.
358 SourceLocation ExpandLoc = Identifier.getLocation();
359 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
360
361 if (Callbacks) {
362 if (InMacroArgs) {
363 // We can have macro expansion inside a conditional directive while
364 // reading the function macro arguments. To ensure, in that case, that
365 // MacroExpands callbacks still happen in source order, queue this
366 // callback to have it happen after the function macro callback.
367 DelayedMacroExpandsCallbacks.push_back(
368 MacroExpandsInfo(Identifier, MI, ExpansionRange));
369 } else {
370 Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
371 if (!DelayedMacroExpandsCallbacks.empty()) {
372 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
373 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
374 Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
375 }
376 DelayedMacroExpandsCallbacks.clear();
377 }
378 }
379 }
Douglas Gregore8219a62012-10-11 21:07:39 +0000380
Argyrios Kyrtzidis0c06cbc2013-01-23 18:21:56 +0000381 // FIXME: Temporarily disable this warning that is currently bogus with a PCH
382 // that redefined a macro without undef'ing it first (test/PCH/macro-redef.c).
383#if 0
Douglas Gregore8219a62012-10-11 21:07:39 +0000384 // If the macro definition is ambiguous, complain.
385 if (MI->isAmbiguous()) {
386 Diag(Identifier, diag::warn_pp_ambiguous_macro)
387 << Identifier.getIdentifierInfo();
388 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
389 << Identifier.getIdentifierInfo();
390 for (MacroInfo *PrevMI = MI->getPreviousDefinition();
391 PrevMI && PrevMI->isDefined();
392 PrevMI = PrevMI->getPreviousDefinition()) {
393 if (PrevMI->isAmbiguous()) {
394 Diag(PrevMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
395 << Identifier.getIdentifierInfo();
396 }
397 }
398 }
Argyrios Kyrtzidis0c06cbc2013-01-23 18:21:56 +0000399#endif
Douglas Gregore8219a62012-10-11 21:07:39 +0000400
Joao Matos3e1ec722012-08-31 21:34:27 +0000401 // If we started lexing a macro, enter the macro expansion body.
402
403 // If this macro expands to no tokens, don't bother to push it onto the
404 // expansion stack, only to take it right back off.
405 if (MI->getNumTokens() == 0) {
406 // No need for arg info.
407 if (Args) Args->destroy(*this);
408
409 // Ignore this macro use, just return the next token in the current
410 // buffer.
411 bool HadLeadingSpace = Identifier.hasLeadingSpace();
412 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
413
414 Lex(Identifier);
415
416 // If the identifier isn't on some OTHER line, inherit the leading
417 // whitespace/first-on-a-line property of this token. This handles
418 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
419 // empty.
420 if (!Identifier.isAtStartOfLine()) {
421 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
422 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
423 }
424 Identifier.setFlag(Token::LeadingEmptyMacro);
425 ++NumFastMacroExpanded;
426 return false;
427
428 } else if (MI->getNumTokens() == 1 &&
429 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
430 *this)) {
431 // Otherwise, if this macro expands into a single trivially-expanded
432 // token: expand it now. This handles common cases like
433 // "#define VAL 42".
434
435 // No need for arg info.
436 if (Args) Args->destroy(*this);
437
438 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
439 // identifier to the expanded token.
440 bool isAtStartOfLine = Identifier.isAtStartOfLine();
441 bool hasLeadingSpace = Identifier.hasLeadingSpace();
442
443 // Replace the result token.
444 Identifier = MI->getReplacementToken(0);
445
446 // Restore the StartOfLine/LeadingSpace markers.
447 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
448 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
449
450 // Update the tokens location to include both its expansion and physical
451 // locations.
452 SourceLocation Loc =
453 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
454 ExpansionEnd,Identifier.getLength());
455 Identifier.setLocation(Loc);
456
457 // If this is a disabled macro or #define X X, we must mark the result as
458 // unexpandable.
459 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
460 if (MacroInfo *NewMI = getMacroInfo(NewII))
461 if (!NewMI->isEnabled() || NewMI == MI) {
462 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor40f56e52013-01-30 23:10:17 +0000463 // Don't warn for "#define X X" like "#define bool bool" from
464 // stdbool.h.
465 if (NewMI != MI || MI->isFunctionLike())
466 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matos3e1ec722012-08-31 21:34:27 +0000467 }
468 }
469
470 // Since this is not an identifier token, it can't be macro expanded, so
471 // we're done.
472 ++NumFastMacroExpanded;
473 return false;
474 }
475
476 // Start expanding the macro.
477 EnterMacro(Identifier, ExpansionEnd, MI, Args);
478
479 // Now that the macro is at the top of the include stack, ask the
480 // preprocessor to read the next token from it.
481 Lex(Identifier);
482 return false;
483}
484
485/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
486/// token is the '(' of the macro, this method is invoked to read all of the
487/// actual arguments specified for the macro invocation. This returns null on
488/// error.
489MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
490 MacroInfo *MI,
491 SourceLocation &MacroEnd) {
492 // The number of fixed arguments to parse.
493 unsigned NumFixedArgsLeft = MI->getNumArgs();
494 bool isVariadic = MI->isVariadic();
495
496 // Outer loop, while there are more arguments, keep reading them.
497 Token Tok;
498
499 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
500 // an argument value in a macro could expand to ',' or '(' or ')'.
501 LexUnexpandedToken(Tok);
502 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
503
504 // ArgTokens - Build up a list of tokens that make up each argument. Each
505 // argument is separated by an EOF token. Use a SmallVector so we can avoid
506 // heap allocations in the common case.
507 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000508 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000509
510 unsigned NumActuals = 0;
511 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000512 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
513 break;
514
Joao Matos3e1ec722012-08-31 21:34:27 +0000515 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
516 "only expect argument separators here");
517
518 unsigned ArgTokenStart = ArgTokens.size();
519 SourceLocation ArgStartLoc = Tok.getLocation();
520
521 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
522 // that we already consumed the first one.
523 unsigned NumParens = 0;
524
525 while (1) {
526 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
527 // an argument value in a macro could expand to ',' or '(' or ')'.
528 LexUnexpandedToken(Tok);
529
530 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000531 if (!ContainsCodeCompletionTok) {
532 Diag(MacroName, diag::err_unterm_macro_invoc);
533 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
534 << MacroName.getIdentifierInfo();
535 // Do not lose the EOF/EOD. Return it to the client.
536 MacroName = Tok;
537 return 0;
538 } else {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000539 // Do not lose the EOF/EOD.
540 Token *Toks = new Token[1];
541 Toks[0] = Tok;
542 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000543 break;
544 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000545 } else if (Tok.is(tok::r_paren)) {
546 // If we found the ) token, the macro arg list is done.
547 if (NumParens-- == 0) {
548 MacroEnd = Tok.getLocation();
549 break;
550 }
551 } else if (Tok.is(tok::l_paren)) {
552 ++NumParens;
Nico Weber93dec512012-09-26 08:19:01 +0000553 } else if (Tok.is(tok::comma) && NumParens == 0) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000554 // Comma ends this argument if there are more fixed arguments expected.
555 // However, if this is a variadic macro, and this is part of the
556 // variadic part, then the comma is just an argument token.
557 if (!isVariadic) break;
558 if (NumFixedArgsLeft > 1)
559 break;
560 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
561 // If this is a comment token in the argument list and we're just in
562 // -C mode (not -CC mode), discard the comment.
563 continue;
564 } else if (Tok.getIdentifierInfo() != 0) {
565 // Reading macro arguments can cause macros that we are currently
566 // expanding from to be popped off the expansion stack. Doing so causes
567 // them to be reenabled for expansion. Here we record whether any
568 // identifiers we lex as macro arguments correspond to disabled macros.
569 // If so, we mark the token as noexpand. This is a subtle aspect of
570 // C99 6.10.3.4p2.
571 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
572 if (!MI->isEnabled())
573 Tok.setFlag(Token::DisableExpand);
574 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000575 ContainsCodeCompletionTok = true;
Joao Matos3e1ec722012-08-31 21:34:27 +0000576 if (CodeComplete)
577 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
578 MI, NumActuals);
579 // Don't mark that we reached the code-completion point because the
580 // parser is going to handle the token and there will be another
581 // code-completion callback.
582 }
583
584 ArgTokens.push_back(Tok);
585 }
586
587 // If this was an empty argument list foo(), don't add this as an empty
588 // argument.
589 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
590 break;
591
592 // If this is not a variadic macro, and too many args were specified, emit
593 // an error.
594 if (!isVariadic && NumFixedArgsLeft == 0) {
595 if (ArgTokens.size() != ArgTokenStart)
596 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
597
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000598 if (!ContainsCodeCompletionTok) {
599 // Emit the diagnostic at the macro name in case there is a missing ).
600 // Emitting it at the , could be far away from the macro name.
601 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
602 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
603 << MacroName.getIdentifierInfo();
604 return 0;
605 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000606 }
607
608 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
609 // other modes.
610 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +0000611 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matos3e1ec722012-08-31 21:34:27 +0000612 diag::warn_cxx98_compat_empty_fnmacro_arg :
613 diag::ext_empty_fnmacro_arg);
614
615 // Add a marker EOF token to the end of the token list for this argument.
616 Token EOFTok;
617 EOFTok.startToken();
618 EOFTok.setKind(tok::eof);
619 EOFTok.setLocation(Tok.getLocation());
620 EOFTok.setLength(0);
621 ArgTokens.push_back(EOFTok);
622 ++NumActuals;
623 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
624 --NumFixedArgsLeft;
625 }
626
627 // Okay, we either found the r_paren. Check to see if we parsed too few
628 // arguments.
629 unsigned MinArgsExpected = MI->getNumArgs();
630
631 // See MacroArgs instance var for description of this.
632 bool isVarargsElided = false;
633
Argyrios Kyrtzidisf1e5b152012-12-21 01:51:12 +0000634 if (ContainsCodeCompletionTok) {
635 // Recover from not-fully-formed macro invocation during code-completion.
636 Token EOFTok;
637 EOFTok.startToken();
638 EOFTok.setKind(tok::eof);
639 EOFTok.setLocation(Tok.getLocation());
640 EOFTok.setLength(0);
641 for (; NumActuals < MinArgsExpected; ++NumActuals)
642 ArgTokens.push_back(EOFTok);
643 }
644
Joao Matos3e1ec722012-08-31 21:34:27 +0000645 if (NumActuals < MinArgsExpected) {
646 // There are several cases where too few arguments is ok, handle them now.
647 if (NumActuals == 0 && MinArgsExpected == 1) {
648 // #define A(X) or #define A(...) ---> A()
649
650 // If there is exactly one argument, and that argument is missing,
651 // then we have an empty "()" argument empty list. This is fine, even if
652 // the macro expects one argument (the argument is just empty).
653 isVarargsElided = MI->isVariadic();
654 } else if (MI->isVariadic() &&
655 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
656 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
657 // Varargs where the named vararg parameter is missing: OK as extension.
658 // #define A(x, ...)
659 // A("blah")
Eli Friedman4fa4b482012-11-14 02:18:46 +0000660 //
661 // If the macro contains the comma pasting extension, the diagnostic
662 // is suppressed; we know we'll get another diagnostic later.
663 if (!MI->hasCommaPasting()) {
664 Diag(Tok, diag::ext_missing_varargs_arg);
665 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
666 << MacroName.getIdentifierInfo();
667 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000668
669 // Remember this occurred, allowing us to elide the comma when used for
670 // cases like:
671 // #define A(x, foo...) blah(a, ## foo)
672 // #define B(x, ...) blah(a, ## __VA_ARGS__)
673 // #define C(...) blah(a, ## __VA_ARGS__)
674 // A(x) B(x) C()
675 isVarargsElided = true;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000676 } else if (!ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000677 // Otherwise, emit the error.
678 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000679 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
680 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000681 return 0;
682 }
683
684 // Add a marker EOF token to the end of the token list for this argument.
685 SourceLocation EndLoc = Tok.getLocation();
686 Tok.startToken();
687 Tok.setKind(tok::eof);
688 Tok.setLocation(EndLoc);
689 Tok.setLength(0);
690 ArgTokens.push_back(Tok);
691
692 // If we expect two arguments, add both as empty.
693 if (NumActuals == 0 && MinArgsExpected == 2)
694 ArgTokens.push_back(Tok);
695
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000696 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
697 !ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000698 // Emit the diagnostic at the macro name in case there is a missing ).
699 // Emitting it at the , could be far away from the macro name.
700 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000701 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
702 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000703 return 0;
704 }
705
706 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
707}
708
709/// \brief Keeps macro expanded tokens for TokenLexers.
710//
711/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
712/// going to lex in the cache and when it finishes the tokens are removed
713/// from the end of the cache.
714Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
715 ArrayRef<Token> tokens) {
716 assert(tokLexer);
717 if (tokens.empty())
718 return 0;
719
720 size_t newIndex = MacroExpandedTokens.size();
721 bool cacheNeedsToGrow = tokens.size() >
722 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
723 MacroExpandedTokens.append(tokens.begin(), tokens.end());
724
725 if (cacheNeedsToGrow) {
726 // Go through all the TokenLexers whose 'Tokens' pointer points in the
727 // buffer and update the pointers to the (potential) new buffer array.
728 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
729 TokenLexer *prevLexer;
730 size_t tokIndex;
731 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
732 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
733 }
734 }
735
736 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
737 return MacroExpandedTokens.data() + newIndex;
738}
739
740void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
741 assert(!MacroExpandingLexersStack.empty());
742 size_t tokIndex = MacroExpandingLexersStack.back().second;
743 assert(tokIndex < MacroExpandedTokens.size());
744 // Pop the cached macro expanded tokens from the end.
745 MacroExpandedTokens.resize(tokIndex);
746 MacroExpandingLexersStack.pop_back();
747}
748
749/// ComputeDATE_TIME - Compute the current time, enter it into the specified
750/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
751/// the identifier tokens inserted.
752static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
753 Preprocessor &PP) {
754 time_t TT = time(0);
755 struct tm *TM = localtime(&TT);
756
757 static const char * const Months[] = {
758 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
759 };
760
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000761 {
762 SmallString<32> TmpBuffer;
763 llvm::raw_svector_ostream TmpStream(TmpBuffer);
764 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
765 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000766 Token TmpTok;
767 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000768 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000769 DATELoc = TmpTok.getLocation();
770 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000771
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000772 {
773 SmallString<32> TmpBuffer;
774 llvm::raw_svector_ostream TmpStream(TmpBuffer);
775 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
776 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000777 Token TmpTok;
778 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000779 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000780 TIMELoc = TmpTok.getLocation();
781 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000782}
783
784
785/// HasFeature - Return true if we recognize and implement the feature
786/// specified by the identifier as a standard language feature.
787static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
788 const LangOptions &LangOpts = PP.getLangOpts();
789 StringRef Feature = II->getName();
790
791 // Normalize the feature name, __foo__ becomes foo.
792 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
793 Feature = Feature.substr(2, Feature.size() - 4);
794
795 return llvm::StringSwitch<bool>(Feature)
Will Dietz4f45bc02013-01-18 11:30:38 +0000796 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matos3e1ec722012-08-31 21:34:27 +0000797 .Case("attribute_analyzer_noreturn", true)
798 .Case("attribute_availability", true)
799 .Case("attribute_availability_with_message", true)
800 .Case("attribute_cf_returns_not_retained", true)
801 .Case("attribute_cf_returns_retained", true)
802 .Case("attribute_deprecated_with_message", true)
803 .Case("attribute_ext_vector_type", true)
804 .Case("attribute_ns_returns_not_retained", true)
805 .Case("attribute_ns_returns_retained", true)
806 .Case("attribute_ns_consumes_self", true)
807 .Case("attribute_ns_consumed", true)
808 .Case("attribute_cf_consumed", true)
809 .Case("attribute_objc_ivar_unused", true)
810 .Case("attribute_objc_method_family", true)
811 .Case("attribute_overloadable", true)
812 .Case("attribute_unavailable_with_message", true)
813 .Case("attribute_unused_on_fields", true)
814 .Case("blocks", LangOpts.Blocks)
815 .Case("cxx_exceptions", LangOpts.Exceptions)
816 .Case("cxx_rtti", LangOpts.RTTI)
817 .Case("enumerator_attributes", true)
Will Dietz4f45bc02013-01-18 11:30:38 +0000818 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
819 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Joao Matos3e1ec722012-08-31 21:34:27 +0000820 // Objective-C features
821 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
822 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
823 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
824 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
825 .Case("objc_fixed_enum", LangOpts.ObjC2)
826 .Case("objc_instancetype", LangOpts.ObjC2)
827 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
828 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremeneke4057c22013-01-04 19:04:44 +0000829 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Joao Matos3e1ec722012-08-31 21:34:27 +0000830 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
831 .Case("ownership_holds", true)
832 .Case("ownership_returns", true)
833 .Case("ownership_takes", true)
834 .Case("objc_bool", true)
835 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
836 .Case("objc_array_literals", LangOpts.ObjC2)
837 .Case("objc_dictionary_literals", LangOpts.ObjC2)
838 .Case("objc_boxed_expressions", LangOpts.ObjC2)
839 .Case("arc_cf_code_audited", true)
840 // C11 features
841 .Case("c_alignas", LangOpts.C11)
842 .Case("c_atomic", LangOpts.C11)
843 .Case("c_generic_selections", LangOpts.C11)
844 .Case("c_static_assert", LangOpts.C11)
845 // C++11 features
Richard Smith80ad52f2013-01-02 11:42:31 +0000846 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
847 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
848 .Case("cxx_alignas", LangOpts.CPlusPlus11)
849 .Case("cxx_atomic", LangOpts.CPlusPlus11)
850 .Case("cxx_attributes", LangOpts.CPlusPlus11)
851 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
852 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
853 .Case("cxx_decltype", LangOpts.CPlusPlus11)
854 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
855 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
856 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
857 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
858 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
859 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
860 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
861 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000862 //.Case("cxx_inheriting_constructors", false)
Richard Smith80ad52f2013-01-02 11:42:31 +0000863 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
864 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
865 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
866 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
867 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
868 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
869 .Case("cxx_override_control", LangOpts.CPlusPlus11)
870 .Case("cxx_range_for", LangOpts.CPlusPlus11)
871 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
872 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
873 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
874 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
875 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
876 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
877 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
878 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
879 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
880 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000881 // Type traits
882 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
883 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
884 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
885 .Case("has_trivial_assign", LangOpts.CPlusPlus)
886 .Case("has_trivial_copy", LangOpts.CPlusPlus)
887 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
888 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
889 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
890 .Case("is_abstract", LangOpts.CPlusPlus)
891 .Case("is_base_of", LangOpts.CPlusPlus)
892 .Case("is_class", LangOpts.CPlusPlus)
893 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000894 .Case("is_empty", LangOpts.CPlusPlus)
895 .Case("is_enum", LangOpts.CPlusPlus)
896 .Case("is_final", LangOpts.CPlusPlus)
897 .Case("is_literal", LangOpts.CPlusPlus)
898 .Case("is_standard_layout", LangOpts.CPlusPlus)
899 .Case("is_pod", LangOpts.CPlusPlus)
900 .Case("is_polymorphic", LangOpts.CPlusPlus)
901 .Case("is_trivial", LangOpts.CPlusPlus)
902 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
903 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
904 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
905 .Case("is_union", LangOpts.CPlusPlus)
906 .Case("modules", LangOpts.Modules)
907 .Case("tls", PP.getTargetInfo().isTLSSupported())
908 .Case("underlying_type", LangOpts.CPlusPlus)
909 .Default(false);
910}
911
912/// HasExtension - Return true if we recognize and implement the feature
913/// specified by the identifier, either as an extension or a standard language
914/// feature.
915static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
916 if (HasFeature(PP, II))
917 return true;
918
919 // If the use of an extension results in an error diagnostic, extensions are
920 // effectively unavailable, so just return false here.
921 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
922 DiagnosticsEngine::Ext_Error)
923 return false;
924
925 const LangOptions &LangOpts = PP.getLangOpts();
926 StringRef Extension = II->getName();
927
928 // Normalize the extension name, __foo__ becomes foo.
929 if (Extension.startswith("__") && Extension.endswith("__") &&
930 Extension.size() >= 4)
931 Extension = Extension.substr(2, Extension.size() - 4);
932
933 // Because we inherit the feature list from HasFeature, this string switch
934 // must be less restrictive than HasFeature's.
935 return llvm::StringSwitch<bool>(Extension)
936 // C11 features supported by other languages as extensions.
937 .Case("c_alignas", true)
938 .Case("c_atomic", true)
939 .Case("c_generic_selections", true)
940 .Case("c_static_assert", true)
941 // C++0x features supported by other languages as extensions.
942 .Case("cxx_atomic", LangOpts.CPlusPlus)
943 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
944 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
945 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
946 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
947 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
948 .Case("cxx_override_control", LangOpts.CPlusPlus)
949 .Case("cxx_range_for", LangOpts.CPlusPlus)
950 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
951 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
952 .Default(false);
953}
954
955/// HasAttribute - Return true if we recognize and implement the attribute
956/// specified by the given identifier.
957static bool HasAttribute(const IdentifierInfo *II) {
958 StringRef Name = II->getName();
959 // Normalize the attribute name, __foo__ becomes foo.
960 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
961 Name = Name.substr(2, Name.size() - 4);
962
963 // FIXME: Do we need to handle namespaces here?
964 return llvm::StringSwitch<bool>(Name)
965#include "clang/Lex/AttrSpellings.inc"
966 .Default(false);
967}
968
969/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
970/// or '__has_include_next("path")' expression.
971/// Returns true if successful.
972static bool EvaluateHasIncludeCommon(Token &Tok,
973 IdentifierInfo *II, Preprocessor &PP,
974 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000975 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman6b716c52013-01-15 21:59:46 +0000976 // that location. If not, use the end of this location instead.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000977 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +0000978
Aaron Ballman31672b12013-01-16 19:32:21 +0000979 // These expressions are only allowed within a preprocessor directive.
980 if (!PP.isParsingIfOrElifDirective()) {
981 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
982 return false;
983 }
984
Joao Matos3e1ec722012-08-31 21:34:27 +0000985 // Get '('.
986 PP.LexNonComment(Tok);
987
988 // Ensure we have a '('.
989 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000990 // No '(', use end of last token.
991 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
992 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
993 // If the next token looks like a filename or the start of one,
994 // assume it is and process it as such.
995 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
996 !Tok.is(tok::less))
997 return false;
998 } else {
999 // Save '(' location for possible missing ')' message.
1000 LParenLoc = Tok.getLocation();
1001
Eli Friedmana0f2d022013-01-09 02:20:00 +00001002 if (PP.getCurrentLexer()) {
1003 // Get the file name.
1004 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1005 } else {
1006 // We're in a macro, so we can't use LexIncludeFilename; just
1007 // grab the next token.
1008 PP.Lex(Tok);
1009 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001010 }
1011
Joao Matos3e1ec722012-08-31 21:34:27 +00001012 // Reserve a buffer to get the spelling.
1013 SmallString<128> FilenameBuffer;
1014 StringRef Filename;
1015 SourceLocation EndLoc;
1016
1017 switch (Tok.getKind()) {
1018 case tok::eod:
1019 // If the token kind is EOD, the error has already been diagnosed.
1020 return false;
1021
1022 case tok::angle_string_literal:
1023 case tok::string_literal: {
1024 bool Invalid = false;
1025 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1026 if (Invalid)
1027 return false;
1028 break;
1029 }
1030
1031 case tok::less:
1032 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1033 // case, glue the tokens together into FilenameBuffer and interpret those.
1034 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +00001035 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1036 // Let the caller know a <eod> was found by changing the Token kind.
1037 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +00001038 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +00001039 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001040 Filename = FilenameBuffer.str();
1041 break;
1042 default:
1043 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1044 return false;
1045 }
1046
Richard Trieu97bc3d52012-10-22 20:28:48 +00001047 SourceLocation FilenameLoc = Tok.getLocation();
1048
Joao Matos3e1ec722012-08-31 21:34:27 +00001049 // Get ')'.
1050 PP.LexNonComment(Tok);
1051
1052 // Ensure we have a trailing ).
1053 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001054 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
1055 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +00001056 PP.Diag(LParenLoc, diag::note_matching) << "(";
1057 return false;
1058 }
1059
1060 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1061 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1062 // error.
1063 if (Filename.empty())
1064 return false;
1065
1066 // Search include directories.
1067 const DirectoryLookup *CurDir;
1068 const FileEntry *File =
1069 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
1070
1071 // Get the result value. A result of true means the file exists.
1072 return File != 0;
1073}
1074
1075/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1076/// Returns true if successful.
1077static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1078 Preprocessor &PP) {
1079 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1080}
1081
1082/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1083/// Returns true if successful.
1084static bool EvaluateHasIncludeNext(Token &Tok,
1085 IdentifierInfo *II, Preprocessor &PP) {
1086 // __has_include_next is like __has_include, except that we start
1087 // searching after the current found directory. If we can't do this,
1088 // issue a diagnostic.
1089 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1090 if (PP.isInPrimaryFile()) {
1091 Lookup = 0;
1092 PP.Diag(Tok, diag::pp_include_next_in_primary);
1093 } else if (Lookup == 0) {
1094 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1095 } else {
1096 // Start looking up in the next directory.
1097 ++Lookup;
1098 }
1099
1100 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1101}
1102
Douglas Gregorb09de512012-09-25 15:44:52 +00001103/// \brief Process __building_module(identifier) expression.
1104/// \returns true if we are building the named module, false otherwise.
1105static bool EvaluateBuildingModule(Token &Tok,
1106 IdentifierInfo *II, Preprocessor &PP) {
1107 // Get '('.
1108 PP.LexNonComment(Tok);
1109
1110 // Ensure we have a '('.
1111 if (Tok.isNot(tok::l_paren)) {
1112 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1113 return false;
1114 }
1115
1116 // Save '(' location for possible missing ')' message.
1117 SourceLocation LParenLoc = Tok.getLocation();
1118
1119 // Get the module name.
1120 PP.LexNonComment(Tok);
1121
1122 // Ensure that we have an identifier.
1123 if (Tok.isNot(tok::identifier)) {
1124 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1125 return false;
1126 }
1127
1128 bool Result
1129 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1130
1131 // Get ')'.
1132 PP.LexNonComment(Tok);
1133
1134 // Ensure we have a trailing ).
1135 if (Tok.isNot(tok::r_paren)) {
1136 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1137 PP.Diag(LParenLoc, diag::note_matching) << "(";
1138 return false;
1139 }
1140
1141 return Result;
1142}
1143
Joao Matos3e1ec722012-08-31 21:34:27 +00001144/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1145/// as a builtin macro, handle it and return the next token as 'Tok'.
1146void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1147 // Figure out which token this is.
1148 IdentifierInfo *II = Tok.getIdentifierInfo();
1149 assert(II && "Can't be a macro without id info!");
1150
1151 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1152 // invoke the pragma handler, then lex the token after it.
1153 if (II == Ident_Pragma)
1154 return Handle_Pragma(Tok);
1155 else if (II == Ident__pragma) // in non-MS mode this is null
1156 return HandleMicrosoft__pragma(Tok);
1157
1158 ++NumBuiltinMacroExpanded;
1159
1160 SmallString<128> TmpBuffer;
1161 llvm::raw_svector_ostream OS(TmpBuffer);
1162
1163 // Set up the return result.
1164 Tok.setIdentifierInfo(0);
1165 Tok.clearFlag(Token::NeedsCleaning);
1166
1167 if (II == Ident__LINE__) {
1168 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1169 // source file) of the current source line (an integer constant)". This can
1170 // be affected by #line.
1171 SourceLocation Loc = Tok.getLocation();
1172
1173 // Advance to the location of the first _, this might not be the first byte
1174 // of the token if it starts with an escaped newline.
1175 Loc = AdvanceToTokenCharacter(Loc, 0);
1176
1177 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1178 // a macro expansion. This doesn't matter for object-like macros, but
1179 // can matter for a function-like macro that expands to contain __LINE__.
1180 // Skip down through expansion points until we find a file loc for the
1181 // end of the expansion history.
1182 Loc = SourceMgr.getExpansionRange(Loc).second;
1183 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1184
1185 // __LINE__ expands to a simple numeric value.
1186 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1187 Tok.setKind(tok::numeric_constant);
1188 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1189 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1190 // character string literal)". This can be affected by #line.
1191 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1192
1193 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1194 // #include stack instead of the current file.
1195 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1196 SourceLocation NextLoc = PLoc.getIncludeLoc();
1197 while (NextLoc.isValid()) {
1198 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1199 if (PLoc.isInvalid())
1200 break;
1201
1202 NextLoc = PLoc.getIncludeLoc();
1203 }
1204 }
1205
1206 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1207 SmallString<128> FN;
1208 if (PLoc.isValid()) {
1209 FN += PLoc.getFilename();
1210 Lexer::Stringify(FN);
1211 OS << '"' << FN.str() << '"';
1212 }
1213 Tok.setKind(tok::string_literal);
1214 } else if (II == Ident__DATE__) {
1215 if (!DATELoc.isValid())
1216 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1217 Tok.setKind(tok::string_literal);
1218 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1219 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1220 Tok.getLocation(),
1221 Tok.getLength()));
1222 return;
1223 } else if (II == Ident__TIME__) {
1224 if (!TIMELoc.isValid())
1225 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1226 Tok.setKind(tok::string_literal);
1227 Tok.setLength(strlen("\"hh:mm:ss\""));
1228 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1229 Tok.getLocation(),
1230 Tok.getLength()));
1231 return;
1232 } else if (II == Ident__INCLUDE_LEVEL__) {
1233 // Compute the presumed include depth of this token. This can be affected
1234 // by GNU line markers.
1235 unsigned Depth = 0;
1236
1237 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1238 if (PLoc.isValid()) {
1239 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1240 for (; PLoc.isValid(); ++Depth)
1241 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1242 }
1243
1244 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1245 OS << Depth;
1246 Tok.setKind(tok::numeric_constant);
1247 } else if (II == Ident__TIMESTAMP__) {
1248 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1249 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1250
1251 // Get the file that we are lexing out of. If we're currently lexing from
1252 // a macro, dig into the include stack.
1253 const FileEntry *CurFile = 0;
1254 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1255
1256 if (TheLexer)
1257 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1258
1259 const char *Result;
1260 if (CurFile) {
1261 time_t TT = CurFile->getModificationTime();
1262 struct tm *TM = localtime(&TT);
1263 Result = asctime(TM);
1264 } else {
1265 Result = "??? ??? ?? ??:??:?? ????\n";
1266 }
1267 // Surround the string with " and strip the trailing newline.
1268 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1269 Tok.setKind(tok::string_literal);
1270 } else if (II == Ident__COUNTER__) {
1271 // __COUNTER__ expands to a simple numeric value.
1272 OS << CounterValue++;
1273 Tok.setKind(tok::numeric_constant);
1274 } else if (II == Ident__has_feature ||
1275 II == Ident__has_extension ||
1276 II == Ident__has_builtin ||
1277 II == Ident__has_attribute) {
1278 // The argument to these builtins should be a parenthesized identifier.
1279 SourceLocation StartLoc = Tok.getLocation();
1280
1281 bool IsValid = false;
1282 IdentifierInfo *FeatureII = 0;
1283
1284 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001285 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001286 if (Tok.is(tok::l_paren)) {
1287 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001288 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001289 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1290 FeatureII = Tok.getIdentifierInfo();
1291
1292 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001293 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001294 if (Tok.is(tok::r_paren))
1295 IsValid = true;
1296 }
1297 }
1298
1299 bool Value = false;
1300 if (!IsValid)
1301 Diag(StartLoc, diag::err_feature_check_malformed);
1302 else if (II == Ident__has_builtin) {
1303 // Check for a builtin is trivial.
1304 Value = FeatureII->getBuiltinID() != 0;
1305 } else if (II == Ident__has_attribute)
1306 Value = HasAttribute(FeatureII);
1307 else if (II == Ident__has_extension)
1308 Value = HasExtension(*this, FeatureII);
1309 else {
1310 assert(II == Ident__has_feature && "Must be feature check");
1311 Value = HasFeature(*this, FeatureII);
1312 }
1313
1314 OS << (int)Value;
1315 if (IsValid)
1316 Tok.setKind(tok::numeric_constant);
1317 } else if (II == Ident__has_include ||
1318 II == Ident__has_include_next) {
1319 // The argument to these two builtins should be a parenthesized
1320 // file name string literal using angle brackets (<>) or
1321 // double-quotes ("").
1322 bool Value;
1323 if (II == Ident__has_include)
1324 Value = EvaluateHasInclude(Tok, II, *this);
1325 else
1326 Value = EvaluateHasIncludeNext(Tok, II, *this);
1327 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001328 if (Tok.is(tok::r_paren))
1329 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001330 } else if (II == Ident__has_warning) {
1331 // The argument should be a parenthesized string literal.
1332 // The argument to these builtins should be a parenthesized identifier.
1333 SourceLocation StartLoc = Tok.getLocation();
1334 bool IsValid = false;
1335 bool Value = false;
1336 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001337 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001338 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001339 if (Tok.isNot(tok::l_paren)) {
1340 Diag(StartLoc, diag::err_warning_check_malformed);
1341 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001342 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001343
1344 LexUnexpandedToken(Tok);
1345 std::string WarningName;
1346 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001347 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1348 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001349 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001350 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1351 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001352 LexUnexpandedToken(Tok);
1353 break;
1354 }
1355
1356 // Is the end a ')'?
1357 if (!(IsValid = Tok.is(tok::r_paren))) {
1358 Diag(StartLoc, diag::err_warning_check_malformed);
1359 break;
1360 }
1361
1362 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1363 WarningName[1] != 'W') {
1364 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1365 break;
1366 }
1367
1368 // Finally, check if the warning flags maps to a diagnostic group.
1369 // We construct a SmallVector here to talk to getDiagnosticIDs().
1370 // Although we don't use the result, this isn't a hot path, and not
1371 // worth special casing.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001372 SmallVector<diag::kind, 10> Diags;
Andy Gibbs02a17682012-11-17 19:15:38 +00001373 Value = !getDiagnostics().getDiagnosticIDs()->
1374 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001375 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001376
1377 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001378 if (IsValid)
1379 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001380 } else if (II == Ident__building_module) {
1381 // The argument to this builtin should be an identifier. The
1382 // builtin evaluates to 1 when that identifier names the module we are
1383 // currently building.
1384 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1385 Tok.setKind(tok::numeric_constant);
1386 } else if (II == Ident__MODULE__) {
1387 // The current module as an identifier.
1388 OS << getLangOpts().CurrentModule;
1389 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1390 Tok.setIdentifierInfo(ModuleII);
1391 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001392 } else {
1393 llvm_unreachable("Unknown identifier!");
1394 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001395 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001396}
1397
1398void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1399 // If the 'used' status changed, and the macro requires 'unused' warning,
1400 // remove its SourceLocation from the warn-for-unused-macro locations.
1401 if (MI->isWarnIfUnused() && !MI->isUsed())
1402 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1403 MI->setIsUsed(true);
1404}