blob: 37460f5e0fcbcc1554b2e2ec8c55b686d0fd6407 [file] [log] [blame]
Joao Matosc0d4c1b2012-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//
James Dennett32740042013-12-02 17:39:27 +000010// This file implements the top level handling of macro expansion for the
Joao Matosc0d4c1b2012-08-31 21:34:27 +000011// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Aaron Ballman2fbf9942014-03-31 13:14:44 +000016#include "clang/Basic/Attributes.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/MacroInfo.h"
25#include "llvm/ADT/STLExtras.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000026#include "llvm/ADT/SmallString.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000027#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000028#include "llvm/Config/llvm-config.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000029#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000030#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/Support/raw_ostream.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000032#include <cstdio>
33#include <ctime>
34using namespace clang;
35
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000036MacroDirective *
37Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko1d26c022012-09-25 17:18:14 +000038 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000039
40 macro_iterator Pos = Macros.find(II);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000041 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000042 return Pos->second;
43}
44
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000045void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000046 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000047 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000048
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000049 MacroDirective *&StoredMD = Macros[II];
50 MD->setPrevious(StoredMD);
51 StoredMD = MD;
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000052 // Setup the identifier as having associated macro history.
53 II->setHasMacroDefinition(true);
54 if (!MD->isDefined())
55 II->setHasMacroDefinition(false);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000056 bool isImportedMacro = isa<DefMacroDirective>(MD) &&
57 cast<DefMacroDirective>(MD)->isImported();
58 if (II->isFromAST() && !isImportedMacro)
Joao Matosc0d4c1b2012-08-31 21:34:27 +000059 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000060}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000061
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000062void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
63 MacroDirective *MD) {
64 assert(II && MD);
65 MacroDirective *&StoredMD = Macros[II];
66 assert(!StoredMD &&
67 "the macro history was modified before initializing it from a pch");
68 StoredMD = MD;
69 // Setup the identifier as having associated macro history.
70 II->setHasMacroDefinition(true);
71 if (!MD->isDefined())
72 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000073}
74
Joao Matosc0d4c1b2012-08-31 21:34:27 +000075/// RegisterBuiltinMacro - Register the specified identifier in the identifier
76/// table and mark it as a builtin macro to be expanded.
77static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
78 // Get the identifier.
79 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
80
81 // Mark it as being a macro that is builtin.
82 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
83 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000084 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000085 return Id;
86}
87
88
89/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
90/// identifier table.
91void Preprocessor::RegisterBuiltinMacros() {
92 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
93 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
94 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
95 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
96 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
97 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
98
Aaron Ballmana0344c52014-11-14 13:44:02 +000099 // C++ Standing Document Extensions.
100 Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute");
101
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000102 // GCC Extensions.
103 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
104 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
105 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
106
Richard Smithae385082014-03-15 00:06:08 +0000107 // Microsoft Extensions.
108 if (LangOpts.MicrosoftExt) {
109 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
110 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
111 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000112 Ident__identifier = nullptr;
113 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000114 }
115
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000116 // Clang Extensions.
117 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
118 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
119 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
120 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
121 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
122 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
123 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000124 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000125
Douglas Gregorc83de302012-09-25 15:44:52 +0000126 // Modules.
127 if (LangOpts.Modules) {
128 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
129
130 // __MODULE__
131 if (!LangOpts.CurrentModule.empty())
132 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
133 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000134 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000135 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000136 Ident__building_module = nullptr;
137 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000138 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000139}
140
141/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
142/// in its expansion, currently expands to that token literally.
143static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
144 const IdentifierInfo *MacroIdent,
145 Preprocessor &PP) {
146 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
147
148 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000149 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000150
151 // If the information about this identifier is out of date, update it from
152 // the external source.
153 if (II->isOutOfDate())
154 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
155
156 // If the identifier is a macro, and if that macro is enabled, it may be
157 // expanded so it's not a trivial expansion.
158 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
159 // Fast expanding "#define X X" is ok, because X would be disabled.
160 II != MacroIdent)
161 return false;
162
163 // If this is an object-like macro invocation, it is safe to trivially expand
164 // it.
165 if (MI->isObjectLike()) return true;
166
167 // If this is a function-like macro invocation, it's safe to trivially expand
168 // as long as the identifier is not a macro argument.
169 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
170 I != E; ++I)
171 if (*I == II)
172 return false; // Identifier is a macro argument.
173
174 return true;
175}
176
177
178/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
179/// lexed is a '('. If so, consume the token and return true, if not, this
180/// method should have no observable side-effect on the lexed tokens.
181bool Preprocessor::isNextPPTokenLParen() {
182 // Do some quick tests for rejection cases.
183 unsigned Val;
184 if (CurLexer)
185 Val = CurLexer->isNextPPTokenLParen();
186 else if (CurPTHLexer)
187 Val = CurPTHLexer->isNextPPTokenLParen();
188 else
189 Val = CurTokenLexer->isNextTokenLParen();
190
191 if (Val == 2) {
192 // We have run off the end. If it's a source file we don't
193 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
194 // macro stack.
195 if (CurPPLexer)
196 return false;
197 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
198 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
199 if (Entry.TheLexer)
200 Val = Entry.TheLexer->isNextPPTokenLParen();
201 else if (Entry.ThePTHLexer)
202 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
203 else
204 Val = Entry.TheTokenLexer->isNextTokenLParen();
205
206 if (Val != 2)
207 break;
208
209 // Ran off the end of a source file?
210 if (Entry.ThePPLexer)
211 return false;
212 }
213 }
214
215 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
216 // have found something that isn't a '(' or we found the end of the
217 // translation unit. In either case, return false.
218 return Val == 1;
219}
220
221/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
222/// expanded as a macro, handle it and return the next token as 'Identifier'.
223bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000224 MacroDirective *MD) {
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000225 MacroDirective::DefInfo Def = MD->getDefinition();
226 assert(Def.isValid());
227 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000228
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000229 // If this is a macro expansion in the "#if !defined(x)" line for the file,
230 // then the macro could expand to different things in other contexts, we need
231 // to disable the optimization in this case.
232 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
233
234 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
235 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000236 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Craig Topperd2d442c2014-05-17 23:10:59 +0000237 Identifier.getLocation(),
238 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000239 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000240 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000241 }
242
243 /// Args - If this is a function-like macro expansion, this contains,
244 /// for each macro argument, the list of tokens that were provided to the
245 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000246 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000247
248 // Remember where the end of the expansion occurred. For an object-like
249 // macro, this is the identifier. For a function-like macro, this is the ')'.
250 SourceLocation ExpansionEnd = Identifier.getLocation();
251
252 // If this is a function-like macro, read the arguments.
253 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000254 // Remember that we are now parsing the arguments to a macro invocation.
255 // Preprocessor directives used inside macro arguments are not portable, and
256 // this enables the warning.
257 InMacroArgs = true;
258 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
259
260 // Finished parsing args.
261 InMacroArgs = false;
262
263 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000264 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000265
266 ++NumFnMacroExpanded;
267 } else {
268 ++NumMacroExpanded;
269 }
270
271 // Notice that this macro has been used.
272 markMacroAsUsed(MI);
273
274 // Remember where the token is expanded.
275 SourceLocation ExpandLoc = Identifier.getLocation();
276 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
277
278 if (Callbacks) {
279 if (InMacroArgs) {
280 // We can have macro expansion inside a conditional directive while
281 // reading the function macro arguments. To ensure, in that case, that
282 // MacroExpands callbacks still happen in source order, queue this
283 // callback to have it happen after the function macro callback.
284 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000285 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000286 } else {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000287 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000288 if (!DelayedMacroExpandsCallbacks.empty()) {
289 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
290 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000291 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000292 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
293 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000294 }
295 DelayedMacroExpandsCallbacks.clear();
296 }
297 }
298 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000299
300 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000301 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000302 Diag(Identifier, diag::warn_pp_ambiguous_macro)
303 << Identifier.getIdentifierInfo();
304 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
305 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000306 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
307 PrevDef && !PrevDef.isUndefined();
308 PrevDef = PrevDef.getPreviousDefinition()) {
Richard Smith49f906a2014-03-01 00:08:04 +0000309 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
310 diag::note_pp_ambiguous_macro_other)
311 << Identifier.getIdentifierInfo();
312 if (!PrevDef.getDirective()->isAmbiguous())
313 break;
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000314 }
315 }
316
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000317 // If we started lexing a macro, enter the macro expansion body.
318
319 // If this macro expands to no tokens, don't bother to push it onto the
320 // expansion stack, only to take it right back off.
321 if (MI->getNumTokens() == 0) {
322 // No need for arg info.
323 if (Args) Args->destroy(*this);
324
Eli Friedman0834a4b2013-09-19 00:41:32 +0000325 // Propagate whitespace info as if we had pushed, then popped,
326 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000327 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000328 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000329 ++NumFastMacroExpanded;
330 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000331 } else if (MI->getNumTokens() == 1 &&
332 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
333 *this)) {
334 // Otherwise, if this macro expands into a single trivially-expanded
335 // token: expand it now. This handles common cases like
336 // "#define VAL 42".
337
338 // No need for arg info.
339 if (Args) Args->destroy(*this);
340
341 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
342 // identifier to the expanded token.
343 bool isAtStartOfLine = Identifier.isAtStartOfLine();
344 bool hasLeadingSpace = Identifier.hasLeadingSpace();
345
346 // Replace the result token.
347 Identifier = MI->getReplacementToken(0);
348
349 // Restore the StartOfLine/LeadingSpace markers.
350 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
351 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
352
353 // Update the tokens location to include both its expansion and physical
354 // locations.
355 SourceLocation Loc =
356 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
357 ExpansionEnd,Identifier.getLength());
358 Identifier.setLocation(Loc);
359
360 // If this is a disabled macro or #define X X, we must mark the result as
361 // unexpandable.
362 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
363 if (MacroInfo *NewMI = getMacroInfo(NewII))
364 if (!NewMI->isEnabled() || NewMI == MI) {
365 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000366 // Don't warn for "#define X X" like "#define bool bool" from
367 // stdbool.h.
368 if (NewMI != MI || MI->isFunctionLike())
369 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000370 }
371 }
372
373 // Since this is not an identifier token, it can't be macro expanded, so
374 // we're done.
375 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000376 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000377 }
378
379 // Start expanding the macro.
380 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000381 return false;
382}
383
Richard Trieu79b45382013-07-23 18:01:49 +0000384enum Bracket {
385 Brace,
386 Paren
387};
388
389/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
390/// token vector are properly nested.
391static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
392 SmallVector<Bracket, 8> Brackets;
393 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
394 E = Tokens.end();
395 I != E; ++I) {
396 if (I->is(tok::l_paren)) {
397 Brackets.push_back(Paren);
398 } else if (I->is(tok::r_paren)) {
399 if (Brackets.empty() || Brackets.back() == Brace)
400 return false;
401 Brackets.pop_back();
402 } else if (I->is(tok::l_brace)) {
403 Brackets.push_back(Brace);
404 } else if (I->is(tok::r_brace)) {
405 if (Brackets.empty() || Brackets.back() == Paren)
406 return false;
407 Brackets.pop_back();
408 }
409 }
410 if (!Brackets.empty())
411 return false;
412 return true;
413}
414
415/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
416/// vector of tokens in NewTokens. The new number of arguments will be placed
417/// in NumArgs and the ranges which need to surrounded in parentheses will be
418/// in ParenHints.
419/// Returns false if the token stream cannot be changed. If this is because
420/// of an initializer list starting a macro argument, the range of those
421/// initializer lists will be place in InitLists.
422static bool GenerateNewArgTokens(Preprocessor &PP,
423 SmallVectorImpl<Token> &OldTokens,
424 SmallVectorImpl<Token> &NewTokens,
425 unsigned &NumArgs,
426 SmallVectorImpl<SourceRange> &ParenHints,
427 SmallVectorImpl<SourceRange> &InitLists) {
428 if (!CheckMatchedBrackets(OldTokens))
429 return false;
430
431 // Once it is known that the brackets are matched, only a simple count of the
432 // braces is needed.
433 unsigned Braces = 0;
434
435 // First token of a new macro argument.
436 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
437
438 // First closing brace in a new macro argument. Used to generate
439 // SourceRanges for InitLists.
440 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
441 NumArgs = 0;
442 Token TempToken;
443 // Set to true when a macro separator token is found inside a braced list.
444 // If true, the fixed argument spans multiple old arguments and ParenHints
445 // will be updated.
446 bool FoundSeparatorToken = false;
447 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
448 E = OldTokens.end();
449 I != E; ++I) {
450 if (I->is(tok::l_brace)) {
451 ++Braces;
452 } else if (I->is(tok::r_brace)) {
453 --Braces;
454 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
455 ClosingBrace = I;
456 } else if (I->is(tok::eof)) {
457 // EOF token is used to separate macro arguments
458 if (Braces != 0) {
459 // Assume comma separator is actually braced list separator and change
460 // it back to a comma.
461 FoundSeparatorToken = true;
462 I->setKind(tok::comma);
463 I->setLength(1);
464 } else { // Braces == 0
465 // Separator token still separates arguments.
466 ++NumArgs;
467
468 // If the argument starts with a brace, it can't be fixed with
469 // parentheses. A different diagnostic will be given.
470 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
471 InitLists.push_back(
472 SourceRange(ArgStartIterator->getLocation(),
473 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
474 ClosingBrace = E;
475 }
476
477 // Add left paren
478 if (FoundSeparatorToken) {
479 TempToken.startToken();
480 TempToken.setKind(tok::l_paren);
481 TempToken.setLocation(ArgStartIterator->getLocation());
482 TempToken.setLength(0);
483 NewTokens.push_back(TempToken);
484 }
485
486 // Copy over argument tokens
487 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
488
489 // Add right paren and store the paren locations in ParenHints
490 if (FoundSeparatorToken) {
491 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
492 TempToken.startToken();
493 TempToken.setKind(tok::r_paren);
494 TempToken.setLocation(Loc);
495 TempToken.setLength(0);
496 NewTokens.push_back(TempToken);
497 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
498 Loc));
499 }
500
501 // Copy separator token
502 NewTokens.push_back(*I);
503
504 // Reset values
505 ArgStartIterator = I + 1;
506 FoundSeparatorToken = false;
507 }
508 }
509 }
510
511 return !ParenHints.empty() && InitLists.empty();
512}
513
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000514/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
515/// token is the '(' of the macro, this method is invoked to read all of the
516/// actual arguments specified for the macro invocation. This returns null on
517/// error.
518MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
519 MacroInfo *MI,
520 SourceLocation &MacroEnd) {
521 // The number of fixed arguments to parse.
522 unsigned NumFixedArgsLeft = MI->getNumArgs();
523 bool isVariadic = MI->isVariadic();
524
525 // Outer loop, while there are more arguments, keep reading them.
526 Token Tok;
527
528 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
529 // an argument value in a macro could expand to ',' or '(' or ')'.
530 LexUnexpandedToken(Tok);
531 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
532
533 // ArgTokens - Build up a list of tokens that make up each argument. Each
534 // argument is separated by an EOF token. Use a SmallVector so we can avoid
535 // heap allocations in the common case.
536 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000537 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000538
Richard Trieu79b45382013-07-23 18:01:49 +0000539 SourceLocation TooManyArgsLoc;
540
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000541 unsigned NumActuals = 0;
542 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000543 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
544 break;
545
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000546 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
547 "only expect argument separators here");
548
549 unsigned ArgTokenStart = ArgTokens.size();
550 SourceLocation ArgStartLoc = Tok.getLocation();
551
552 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
553 // that we already consumed the first one.
554 unsigned NumParens = 0;
555
556 while (1) {
557 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
558 // an argument value in a macro could expand to ',' or '(' or ')'.
559 LexUnexpandedToken(Tok);
560
561 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000562 if (!ContainsCodeCompletionTok) {
563 Diag(MacroName, diag::err_unterm_macro_invoc);
564 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
565 << MacroName.getIdentifierInfo();
566 // Do not lose the EOF/EOD. Return it to the client.
567 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000568 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000569 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000570 // Do not lose the EOF/EOD.
571 Token *Toks = new Token[1];
572 Toks[0] = Tok;
573 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000574 break;
575 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000576 } else if (Tok.is(tok::r_paren)) {
577 // If we found the ) token, the macro arg list is done.
578 if (NumParens-- == 0) {
579 MacroEnd = Tok.getLocation();
580 break;
581 }
582 } else if (Tok.is(tok::l_paren)) {
583 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000584 } else if (Tok.is(tok::comma) && NumParens == 0 &&
585 !(Tok.getFlags() & Token::IgnoredComma)) {
586 // In Microsoft-compatibility mode, single commas from nested macro
587 // expansions should not be considered as argument separators. We test
588 // for this with the IgnoredComma token flag above.
589
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000590 // Comma ends this argument if there are more fixed arguments expected.
591 // However, if this is a variadic macro, and this is part of the
592 // variadic part, then the comma is just an argument token.
593 if (!isVariadic) break;
594 if (NumFixedArgsLeft > 1)
595 break;
596 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
597 // If this is a comment token in the argument list and we're just in
598 // -C mode (not -CC mode), discard the comment.
599 continue;
Craig Topperd2d442c2014-05-17 23:10:59 +0000600 } else if (Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000601 // Reading macro arguments can cause macros that we are currently
602 // expanding from to be popped off the expansion stack. Doing so causes
603 // them to be reenabled for expansion. Here we record whether any
604 // identifiers we lex as macro arguments correspond to disabled macros.
605 // If so, we mark the token as noexpand. This is a subtle aspect of
606 // C99 6.10.3.4p2.
607 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
608 if (!MI->isEnabled())
609 Tok.setFlag(Token::DisableExpand);
610 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000611 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000612 if (CodeComplete)
613 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
614 MI, NumActuals);
615 // Don't mark that we reached the code-completion point because the
616 // parser is going to handle the token and there will be another
617 // code-completion callback.
618 }
619
620 ArgTokens.push_back(Tok);
621 }
622
623 // If this was an empty argument list foo(), don't add this as an empty
624 // argument.
625 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
626 break;
627
628 // If this is not a variadic macro, and too many args were specified, emit
629 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000630 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000631 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000632 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
633 else
634 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000635 }
636
Richard Trieu79b45382013-07-23 18:01:49 +0000637 // Empty arguments are standard in C99 and C++0x, and are supported as an
638 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000639 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000640 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000641 diag::warn_cxx98_compat_empty_fnmacro_arg :
642 diag::ext_empty_fnmacro_arg);
643
644 // Add a marker EOF token to the end of the token list for this argument.
645 Token EOFTok;
646 EOFTok.startToken();
647 EOFTok.setKind(tok::eof);
648 EOFTok.setLocation(Tok.getLocation());
649 EOFTok.setLength(0);
650 ArgTokens.push_back(EOFTok);
651 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000652 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000653 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000654 }
655
656 // Okay, we either found the r_paren. Check to see if we parsed too few
657 // arguments.
658 unsigned MinArgsExpected = MI->getNumArgs();
659
Richard Trieu79b45382013-07-23 18:01:49 +0000660 // If this is not a variadic macro, and too many args were specified, emit
661 // an error.
662 if (!isVariadic && NumActuals > MinArgsExpected &&
663 !ContainsCodeCompletionTok) {
664 // Emit the diagnostic at the macro name in case there is a missing ).
665 // Emitting it at the , could be far away from the macro name.
666 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
667 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
668 << MacroName.getIdentifierInfo();
669
670 // Commas from braced initializer lists will be treated as argument
671 // separators inside macros. Attempt to correct for this with parentheses.
672 // TODO: See if this can be generalized to angle brackets for templates
673 // inside macro arguments.
674
Bob Wilson57217352013-07-27 21:59:57 +0000675 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000676 unsigned FixedNumArgs = 0;
677 SmallVector<SourceRange, 4> ParenHints, InitLists;
678 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
679 ParenHints, InitLists)) {
680 if (!InitLists.empty()) {
681 DiagnosticBuilder DB =
682 Diag(MacroName,
683 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000684 for (const SourceRange &Range : InitLists)
685 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000686 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000687 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000688 }
689 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000690 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000691
692 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000693 for (const SourceRange &ParenLocation : ParenHints) {
694 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
695 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000696 }
697 ArgTokens.swap(FixedArgTokens);
698 NumActuals = FixedNumArgs;
699 }
700
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000701 // See MacroArgs instance var for description of this.
702 bool isVarargsElided = false;
703
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000704 if (ContainsCodeCompletionTok) {
705 // Recover from not-fully-formed macro invocation during code-completion.
706 Token EOFTok;
707 EOFTok.startToken();
708 EOFTok.setKind(tok::eof);
709 EOFTok.setLocation(Tok.getLocation());
710 EOFTok.setLength(0);
711 for (; NumActuals < MinArgsExpected; ++NumActuals)
712 ArgTokens.push_back(EOFTok);
713 }
714
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000715 if (NumActuals < MinArgsExpected) {
716 // There are several cases where too few arguments is ok, handle them now.
717 if (NumActuals == 0 && MinArgsExpected == 1) {
718 // #define A(X) or #define A(...) ---> A()
719
720 // If there is exactly one argument, and that argument is missing,
721 // then we have an empty "()" argument empty list. This is fine, even if
722 // the macro expects one argument (the argument is just empty).
723 isVarargsElided = MI->isVariadic();
724 } else if (MI->isVariadic() &&
725 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
726 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
727 // Varargs where the named vararg parameter is missing: OK as extension.
728 // #define A(x, ...)
729 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000730 //
731 // If the macro contains the comma pasting extension, the diagnostic
732 // is suppressed; we know we'll get another diagnostic later.
733 if (!MI->hasCommaPasting()) {
734 Diag(Tok, diag::ext_missing_varargs_arg);
735 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
736 << MacroName.getIdentifierInfo();
737 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000738
739 // Remember this occurred, allowing us to elide the comma when used for
740 // cases like:
741 // #define A(x, foo...) blah(a, ## foo)
742 // #define B(x, ...) blah(a, ## __VA_ARGS__)
743 // #define C(...) blah(a, ## __VA_ARGS__)
744 // A(x) B(x) C()
745 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000746 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000747 // Otherwise, emit the error.
748 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000749 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
750 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000751 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000752 }
753
754 // Add a marker EOF token to the end of the token list for this argument.
755 SourceLocation EndLoc = Tok.getLocation();
756 Tok.startToken();
757 Tok.setKind(tok::eof);
758 Tok.setLocation(EndLoc);
759 Tok.setLength(0);
760 ArgTokens.push_back(Tok);
761
762 // If we expect two arguments, add both as empty.
763 if (NumActuals == 0 && MinArgsExpected == 2)
764 ArgTokens.push_back(Tok);
765
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000766 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
767 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000768 // Emit the diagnostic at the macro name in case there is a missing ).
769 // Emitting it at the , could be far away from the macro name.
770 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000771 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
772 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000773 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000774 }
775
776 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
777}
778
779/// \brief Keeps macro expanded tokens for TokenLexers.
780//
781/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
782/// going to lex in the cache and when it finishes the tokens are removed
783/// from the end of the cache.
784Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
785 ArrayRef<Token> tokens) {
786 assert(tokLexer);
787 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000788 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000789
790 size_t newIndex = MacroExpandedTokens.size();
791 bool cacheNeedsToGrow = tokens.size() >
792 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
793 MacroExpandedTokens.append(tokens.begin(), tokens.end());
794
795 if (cacheNeedsToGrow) {
796 // Go through all the TokenLexers whose 'Tokens' pointer points in the
797 // buffer and update the pointers to the (potential) new buffer array.
798 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
799 TokenLexer *prevLexer;
800 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000801 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000802 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
803 }
804 }
805
806 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
807 return MacroExpandedTokens.data() + newIndex;
808}
809
810void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
811 assert(!MacroExpandingLexersStack.empty());
812 size_t tokIndex = MacroExpandingLexersStack.back().second;
813 assert(tokIndex < MacroExpandedTokens.size());
814 // Pop the cached macro expanded tokens from the end.
815 MacroExpandedTokens.resize(tokIndex);
816 MacroExpandingLexersStack.pop_back();
817}
818
819/// ComputeDATE_TIME - Compute the current time, enter it into the specified
820/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
821/// the identifier tokens inserted.
822static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
823 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000824 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000825 struct tm *TM = localtime(&TT);
826
827 static const char * const Months[] = {
828 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
829 };
830
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000831 {
832 SmallString<32> TmpBuffer;
833 llvm::raw_svector_ostream TmpStream(TmpBuffer);
834 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
835 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000836 Token TmpTok;
837 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000838 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000839 DATELoc = TmpTok.getLocation();
840 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000841
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000842 {
843 SmallString<32> TmpBuffer;
844 llvm::raw_svector_ostream TmpStream(TmpBuffer);
845 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
846 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000847 Token TmpTok;
848 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000849 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000850 TIMELoc = TmpTok.getLocation();
851 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000852}
853
854
855/// HasFeature - Return true if we recognize and implement the feature
856/// specified by the identifier as a standard language feature.
857static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
858 const LangOptions &LangOpts = PP.getLangOpts();
859 StringRef Feature = II->getName();
860
861 // Normalize the feature name, __foo__ becomes foo.
862 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
863 Feature = Feature.substr(2, Feature.size() - 4);
864
865 return llvm::StringSwitch<bool>(Feature)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000866 .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
867 .Case("attribute_analyzer_noreturn", true)
868 .Case("attribute_availability", true)
869 .Case("attribute_availability_with_message", true)
870 .Case("attribute_cf_returns_not_retained", true)
871 .Case("attribute_cf_returns_retained", true)
872 .Case("attribute_deprecated_with_message", true)
873 .Case("attribute_ext_vector_type", true)
874 .Case("attribute_ns_returns_not_retained", true)
875 .Case("attribute_ns_returns_retained", true)
876 .Case("attribute_ns_consumes_self", true)
877 .Case("attribute_ns_consumed", true)
878 .Case("attribute_cf_consumed", true)
879 .Case("attribute_objc_ivar_unused", true)
880 .Case("attribute_objc_method_family", true)
881 .Case("attribute_overloadable", true)
882 .Case("attribute_unavailable_with_message", true)
883 .Case("attribute_unused_on_fields", true)
884 .Case("blocks", LangOpts.Blocks)
885 .Case("c_thread_safety_attributes", true)
886 .Case("cxx_exceptions", LangOpts.CXXExceptions)
887 .Case("cxx_rtti", LangOpts.RTTI)
888 .Case("enumerator_attributes", true)
889 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
890 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
891 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
892 // Objective-C features
893 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
894 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
895 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
896 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
897 .Case("objc_fixed_enum", LangOpts.ObjC2)
898 .Case("objc_instancetype", LangOpts.ObjC2)
899 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
900 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
901 .Case("objc_property_explicit_atomic",
902 true) // Does clang support explicit "atomic" keyword?
903 .Case("objc_protocol_qualifier_mangling", true)
904 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
905 .Case("ownership_holds", true)
906 .Case("ownership_returns", true)
907 .Case("ownership_takes", true)
908 .Case("objc_bool", true)
909 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
910 .Case("objc_array_literals", LangOpts.ObjC2)
911 .Case("objc_dictionary_literals", LangOpts.ObjC2)
912 .Case("objc_boxed_expressions", LangOpts.ObjC2)
913 .Case("arc_cf_code_audited", true)
914 // C11 features
915 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +0000916 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000917 .Case("c_atomic", LangOpts.C11)
918 .Case("c_generic_selections", LangOpts.C11)
919 .Case("c_static_assert", LangOpts.C11)
920 .Case("c_thread_local",
921 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
922 // C++11 features
923 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
924 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
925 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +0000926 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000927 .Case("cxx_atomic", LangOpts.CPlusPlus11)
928 .Case("cxx_attributes", LangOpts.CPlusPlus11)
929 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
930 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
931 .Case("cxx_decltype", LangOpts.CPlusPlus11)
932 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
933 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
934 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
935 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
936 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
937 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
938 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
939 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
940 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
941 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
942 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
943 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
944 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
945 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
946 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
947 .Case("cxx_override_control", LangOpts.CPlusPlus11)
948 .Case("cxx_range_for", LangOpts.CPlusPlus11)
949 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
950 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
951 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
952 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
953 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
954 .Case("cxx_thread_local",
955 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
956 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
957 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
958 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
959 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
960 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
961 // C++1y features
962 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
963 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
964 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
965 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
966 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
967 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
968 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
969 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
970 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
971 // C++ TSes
972 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
973 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
974 // FIXME: Should this be __has_feature or __has_extension?
975 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
976 // Type traits
977 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
978 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
979 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
980 .Case("has_trivial_assign", LangOpts.CPlusPlus)
981 .Case("has_trivial_copy", LangOpts.CPlusPlus)
982 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
983 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
984 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
985 .Case("is_abstract", LangOpts.CPlusPlus)
986 .Case("is_base_of", LangOpts.CPlusPlus)
987 .Case("is_class", LangOpts.CPlusPlus)
988 .Case("is_constructible", LangOpts.CPlusPlus)
989 .Case("is_convertible_to", LangOpts.CPlusPlus)
990 .Case("is_empty", LangOpts.CPlusPlus)
991 .Case("is_enum", LangOpts.CPlusPlus)
992 .Case("is_final", LangOpts.CPlusPlus)
993 .Case("is_literal", LangOpts.CPlusPlus)
994 .Case("is_standard_layout", LangOpts.CPlusPlus)
995 .Case("is_pod", LangOpts.CPlusPlus)
996 .Case("is_polymorphic", LangOpts.CPlusPlus)
997 .Case("is_sealed", LangOpts.MicrosoftExt)
998 .Case("is_trivial", LangOpts.CPlusPlus)
999 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1000 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1001 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1002 .Case("is_union", LangOpts.CPlusPlus)
1003 .Case("modules", LangOpts.Modules)
1004 .Case("tls", PP.getTargetInfo().isTLSSupported())
1005 .Case("underlying_type", LangOpts.CPlusPlus)
1006 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001007}
1008
1009/// HasExtension - Return true if we recognize and implement the feature
1010/// specified by the identifier, either as an extension or a standard language
1011/// feature.
1012static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1013 if (HasFeature(PP, II))
1014 return true;
1015
1016 // If the use of an extension results in an error diagnostic, extensions are
1017 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001018 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1019 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001020 return false;
1021
1022 const LangOptions &LangOpts = PP.getLangOpts();
1023 StringRef Extension = II->getName();
1024
1025 // Normalize the extension name, __foo__ becomes foo.
1026 if (Extension.startswith("__") && Extension.endswith("__") &&
1027 Extension.size() >= 4)
1028 Extension = Extension.substr(2, Extension.size() - 4);
1029
1030 // Because we inherit the feature list from HasFeature, this string switch
1031 // must be less restrictive than HasFeature's.
1032 return llvm::StringSwitch<bool>(Extension)
1033 // C11 features supported by other languages as extensions.
1034 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001035 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001036 .Case("c_atomic", true)
1037 .Case("c_generic_selections", true)
1038 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001039 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001040 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001041 .Case("cxx_atomic", LangOpts.CPlusPlus)
1042 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1043 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1044 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1045 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1046 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1047 .Case("cxx_override_control", LangOpts.CPlusPlus)
1048 .Case("cxx_range_for", LangOpts.CPlusPlus)
1049 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1050 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001051 // C++1y features supported by other languages as extensions.
1052 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001053 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001054 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001055 .Default(false);
1056}
1057
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001058/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1059/// or '__has_include_next("path")' expression.
1060/// Returns true if successful.
1061static bool EvaluateHasIncludeCommon(Token &Tok,
1062 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001063 const DirectoryLookup *LookupFrom,
1064 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001065 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001066 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001067 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001068
Aaron Ballman6ce00002013-01-16 19:32:21 +00001069 // These expressions are only allowed within a preprocessor directive.
1070 if (!PP.isParsingIfOrElifDirective()) {
1071 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1072 return false;
1073 }
1074
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001075 // Get '('.
1076 PP.LexNonComment(Tok);
1077
1078 // Ensure we have a '('.
1079 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001080 // No '(', use end of last token.
1081 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001082 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001083 // If the next token looks like a filename or the start of one,
1084 // assume it is and process it as such.
1085 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1086 !Tok.is(tok::less))
1087 return false;
1088 } else {
1089 // Save '(' location for possible missing ')' message.
1090 LParenLoc = Tok.getLocation();
1091
Eli Friedmanec94b612013-01-09 02:20:00 +00001092 if (PP.getCurrentLexer()) {
1093 // Get the file name.
1094 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1095 } else {
1096 // We're in a macro, so we can't use LexIncludeFilename; just
1097 // grab the next token.
1098 PP.Lex(Tok);
1099 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001100 }
1101
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001102 // Reserve a buffer to get the spelling.
1103 SmallString<128> FilenameBuffer;
1104 StringRef Filename;
1105 SourceLocation EndLoc;
1106
1107 switch (Tok.getKind()) {
1108 case tok::eod:
1109 // If the token kind is EOD, the error has already been diagnosed.
1110 return false;
1111
1112 case tok::angle_string_literal:
1113 case tok::string_literal: {
1114 bool Invalid = false;
1115 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1116 if (Invalid)
1117 return false;
1118 break;
1119 }
1120
1121 case tok::less:
1122 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1123 // case, glue the tokens together into FilenameBuffer and interpret those.
1124 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001125 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1126 // Let the caller know a <eod> was found by changing the Token kind.
1127 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001128 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001129 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001130 Filename = FilenameBuffer.str();
1131 break;
1132 default:
1133 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1134 return false;
1135 }
1136
Richard Trieuda031982012-10-22 20:28:48 +00001137 SourceLocation FilenameLoc = Tok.getLocation();
1138
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001139 // Get ')'.
1140 PP.LexNonComment(Tok);
1141
1142 // Ensure we have a trailing ).
1143 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001144 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1145 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001146 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001147 return false;
1148 }
1149
1150 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1151 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1152 // error.
1153 if (Filename.empty())
1154 return false;
1155
1156 // Search include directories.
1157 const DirectoryLookup *CurDir;
1158 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001159 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1160 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001161
1162 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001163 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001164}
1165
1166/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1167/// Returns true if successful.
1168static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1169 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001170 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001171}
1172
1173/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1174/// Returns true if successful.
1175static bool EvaluateHasIncludeNext(Token &Tok,
1176 IdentifierInfo *II, Preprocessor &PP) {
1177 // __has_include_next is like __has_include, except that we start
1178 // searching after the current found directory. If we can't do this,
1179 // issue a diagnostic.
Richard Smith25d50752014-10-20 00:15:49 +00001180 // FIXME: Factor out duplication wiht
1181 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001182 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001183 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001184 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001185 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001186 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001187 } else if (PP.getCurrentSubmodule()) {
1188 // Start looking up in the directory *after* the one in which the current
1189 // file would be found, if any.
1190 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1191 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1192 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001193 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001194 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1195 } else {
1196 // Start looking up in the next directory.
1197 ++Lookup;
1198 }
1199
Richard Smith25d50752014-10-20 00:15:49 +00001200 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001201}
1202
Douglas Gregorc83de302012-09-25 15:44:52 +00001203/// \brief Process __building_module(identifier) expression.
1204/// \returns true if we are building the named module, false otherwise.
1205static bool EvaluateBuildingModule(Token &Tok,
1206 IdentifierInfo *II, Preprocessor &PP) {
1207 // Get '('.
1208 PP.LexNonComment(Tok);
1209
1210 // Ensure we have a '('.
1211 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001212 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1213 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001214 return false;
1215 }
1216
1217 // Save '(' location for possible missing ')' message.
1218 SourceLocation LParenLoc = Tok.getLocation();
1219
1220 // Get the module name.
1221 PP.LexNonComment(Tok);
1222
1223 // Ensure that we have an identifier.
1224 if (Tok.isNot(tok::identifier)) {
1225 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1226 return false;
1227 }
1228
1229 bool Result
1230 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1231
1232 // Get ')'.
1233 PP.LexNonComment(Tok);
1234
1235 // Ensure we have a trailing ).
1236 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001237 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1238 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001239 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001240 return false;
1241 }
1242
1243 return Result;
1244}
1245
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001246/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1247/// as a builtin macro, handle it and return the next token as 'Tok'.
1248void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1249 // Figure out which token this is.
1250 IdentifierInfo *II = Tok.getIdentifierInfo();
1251 assert(II && "Can't be a macro without id info!");
1252
1253 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1254 // invoke the pragma handler, then lex the token after it.
1255 if (II == Ident_Pragma)
1256 return Handle_Pragma(Tok);
1257 else if (II == Ident__pragma) // in non-MS mode this is null
1258 return HandleMicrosoft__pragma(Tok);
1259
1260 ++NumBuiltinMacroExpanded;
1261
1262 SmallString<128> TmpBuffer;
1263 llvm::raw_svector_ostream OS(TmpBuffer);
1264
1265 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001266 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001267 Tok.clearFlag(Token::NeedsCleaning);
1268
1269 if (II == Ident__LINE__) {
1270 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1271 // source file) of the current source line (an integer constant)". This can
1272 // be affected by #line.
1273 SourceLocation Loc = Tok.getLocation();
1274
1275 // Advance to the location of the first _, this might not be the first byte
1276 // of the token if it starts with an escaped newline.
1277 Loc = AdvanceToTokenCharacter(Loc, 0);
1278
1279 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1280 // a macro expansion. This doesn't matter for object-like macros, but
1281 // can matter for a function-like macro that expands to contain __LINE__.
1282 // Skip down through expansion points until we find a file loc for the
1283 // end of the expansion history.
1284 Loc = SourceMgr.getExpansionRange(Loc).second;
1285 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1286
1287 // __LINE__ expands to a simple numeric value.
1288 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1289 Tok.setKind(tok::numeric_constant);
1290 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1291 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1292 // character string literal)". This can be affected by #line.
1293 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1294
1295 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1296 // #include stack instead of the current file.
1297 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1298 SourceLocation NextLoc = PLoc.getIncludeLoc();
1299 while (NextLoc.isValid()) {
1300 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1301 if (PLoc.isInvalid())
1302 break;
1303
1304 NextLoc = PLoc.getIncludeLoc();
1305 }
1306 }
1307
1308 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1309 SmallString<128> FN;
1310 if (PLoc.isValid()) {
1311 FN += PLoc.getFilename();
1312 Lexer::Stringify(FN);
1313 OS << '"' << FN.str() << '"';
1314 }
1315 Tok.setKind(tok::string_literal);
1316 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001317 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001318 if (!DATELoc.isValid())
1319 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1320 Tok.setKind(tok::string_literal);
1321 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1322 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1323 Tok.getLocation(),
1324 Tok.getLength()));
1325 return;
1326 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001327 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001328 if (!TIMELoc.isValid())
1329 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1330 Tok.setKind(tok::string_literal);
1331 Tok.setLength(strlen("\"hh:mm:ss\""));
1332 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1333 Tok.getLocation(),
1334 Tok.getLength()));
1335 return;
1336 } else if (II == Ident__INCLUDE_LEVEL__) {
1337 // Compute the presumed include depth of this token. This can be affected
1338 // by GNU line markers.
1339 unsigned Depth = 0;
1340
1341 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1342 if (PLoc.isValid()) {
1343 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1344 for (; PLoc.isValid(); ++Depth)
1345 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1346 }
1347
1348 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1349 OS << Depth;
1350 Tok.setKind(tok::numeric_constant);
1351 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001352 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001353 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1354 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1355
1356 // Get the file that we are lexing out of. If we're currently lexing from
1357 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001358 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001359 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1360
1361 if (TheLexer)
1362 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1363
1364 const char *Result;
1365 if (CurFile) {
1366 time_t TT = CurFile->getModificationTime();
1367 struct tm *TM = localtime(&TT);
1368 Result = asctime(TM);
1369 } else {
1370 Result = "??? ??? ?? ??:??:?? ????\n";
1371 }
1372 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001373 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001374 Tok.setKind(tok::string_literal);
1375 } else if (II == Ident__COUNTER__) {
1376 // __COUNTER__ expands to a simple numeric value.
1377 OS << CounterValue++;
1378 Tok.setKind(tok::numeric_constant);
1379 } else if (II == Ident__has_feature ||
1380 II == Ident__has_extension ||
1381 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001382 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001383 II == Ident__has_attribute ||
1384 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001385 // The argument to these builtins should be a parenthesized identifier.
1386 SourceLocation StartLoc = Tok.getLocation();
1387
1388 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001389 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001390 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001391
1392 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001393 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001394 if (Tok.is(tok::l_paren)) {
1395 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001396 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001397 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001398 // If we're checking __has_cpp_attribute, it is possible to receive a
1399 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001400 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001401 bool IsScopeValid = true;
1402 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1403 LexUnexpandedToken(Tok);
1404 // The first thing we read was not the feature, it was the scope.
1405 ScopeII = FeatureII;
Aaron Ballman918474c2014-11-14 14:40:49 +00001406 if ((FeatureII = Tok.getIdentifierInfo()))
Aaron Ballmana0344c52014-11-14 13:44:02 +00001407 LexUnexpandedToken(Tok);
1408 else
1409 IsScopeValid = false;
1410 }
1411 // Read the closing paren.
1412 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001413 IsValid = true;
1414 }
1415 }
1416
Aaron Ballmana0344c52014-11-14 13:44:02 +00001417 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001418 if (!IsValid)
1419 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001420 else if (II == Ident__is_identifier)
1421 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001422 else if (II == Ident__has_builtin) {
1423 // Check for a builtin is trivial.
1424 Value = FeatureII->getBuiltinID() != 0;
1425 } else if (II == Ident__has_attribute)
Aaron Ballman759c71d2014-03-31 15:26:40 +00001426 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001427 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001428 else if (II == Ident__has_cpp_attribute)
1429 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1430 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001431 else if (II == Ident__has_extension)
1432 Value = HasExtension(*this, FeatureII);
1433 else {
1434 assert(II == Ident__has_feature && "Must be feature check");
1435 Value = HasFeature(*this, FeatureII);
1436 }
1437
Aaron Ballmana0344c52014-11-14 13:44:02 +00001438 OS << Value;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001439 if (IsValid)
1440 Tok.setKind(tok::numeric_constant);
1441 } else if (II == Ident__has_include ||
1442 II == Ident__has_include_next) {
1443 // The argument to these two builtins should be a parenthesized
1444 // file name string literal using angle brackets (<>) or
1445 // double-quotes ("").
1446 bool Value;
1447 if (II == Ident__has_include)
1448 Value = EvaluateHasInclude(Tok, II, *this);
1449 else
1450 Value = EvaluateHasIncludeNext(Tok, II, *this);
1451 OS << (int)Value;
Richard Trieuda031982012-10-22 20:28:48 +00001452 if (Tok.is(tok::r_paren))
1453 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001454 } else if (II == Ident__has_warning) {
1455 // The argument should be a parenthesized string literal.
1456 // The argument to these builtins should be a parenthesized identifier.
1457 SourceLocation StartLoc = Tok.getLocation();
1458 bool IsValid = false;
1459 bool Value = false;
1460 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001461 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001462 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001463 if (Tok.isNot(tok::l_paren)) {
1464 Diag(StartLoc, diag::err_warning_check_malformed);
1465 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001466 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001467
1468 LexUnexpandedToken(Tok);
1469 std::string WarningName;
1470 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001471 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1472 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001473 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001474 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1475 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001476 LexUnexpandedToken(Tok);
1477 break;
1478 }
1479
1480 // Is the end a ')'?
1481 if (!(IsValid = Tok.is(tok::r_paren))) {
1482 Diag(StartLoc, diag::err_warning_check_malformed);
1483 break;
1484 }
1485
Richard Smith3be1cb22014-08-07 00:24:21 +00001486 // FIXME: Should we accept "-R..." flags here, or should that be handled
1487 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001488 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1489 WarningName[1] != 'W') {
1490 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1491 break;
1492 }
1493
1494 // Finally, check if the warning flags maps to a diagnostic group.
1495 // We construct a SmallVector here to talk to getDiagnosticIDs().
1496 // Although we don't use the result, this isn't a hot path, and not
1497 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001498 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001499 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001500 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1501 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001502 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001503
1504 OS << (int)Value;
Andy Gibbsf591982b2012-11-17 19:14:53 +00001505 if (IsValid)
1506 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001507 } else if (II == Ident__building_module) {
1508 // The argument to this builtin should be an identifier. The
1509 // builtin evaluates to 1 when that identifier names the module we are
1510 // currently building.
1511 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1512 Tok.setKind(tok::numeric_constant);
1513 } else if (II == Ident__MODULE__) {
1514 // The current module as an identifier.
1515 OS << getLangOpts().CurrentModule;
1516 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1517 Tok.setIdentifierInfo(ModuleII);
1518 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001519 } else if (II == Ident__identifier) {
1520 SourceLocation Loc = Tok.getLocation();
1521
1522 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1523 // if the parens are missing.
1524 LexNonComment(Tok);
1525 if (Tok.isNot(tok::l_paren)) {
1526 // No '(', use end of last token.
1527 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1528 << II << tok::l_paren;
1529 // If the next token isn't valid as our argument, we can't recover.
1530 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1531 Tok.setKind(tok::identifier);
1532 return;
1533 }
1534
1535 SourceLocation LParenLoc = Tok.getLocation();
1536 LexNonComment(Tok);
1537
1538 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1539 Tok.setKind(tok::identifier);
1540 else {
1541 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1542 << Tok.getKind();
1543 // Don't walk past anything that's not a real token.
1544 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1545 return;
1546 }
1547
1548 // Discard the ')', preserving 'Tok' as our result.
1549 Token RParen;
1550 LexNonComment(RParen);
1551 if (RParen.isNot(tok::r_paren)) {
1552 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1553 << Tok.getKind() << tok::r_paren;
1554 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1555 }
1556 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001557 } else {
1558 llvm_unreachable("Unknown identifier!");
1559 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001560 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001561}
1562
1563void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1564 // If the 'used' status changed, and the macro requires 'unused' warning,
1565 // remove its SourceLocation from the warn-for-unused-macro locations.
1566 if (MI->isWarnIfUnused() && !MI->isUsed())
1567 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1568 MI->setIsUsed(true);
1569}