blob: 26cf5439e7a8231796b917a291f8c427d132ea5b [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");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000121 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000122 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
123 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
124 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000125 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000126
Douglas Gregorc83de302012-09-25 15:44:52 +0000127 // Modules.
128 if (LangOpts.Modules) {
129 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
130
131 // __MODULE__
132 if (!LangOpts.CurrentModule.empty())
133 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
134 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000135 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000136 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000137 Ident__building_module = nullptr;
138 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000139 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000140}
141
142/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
143/// in its expansion, currently expands to that token literally.
144static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
145 const IdentifierInfo *MacroIdent,
146 Preprocessor &PP) {
147 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
148
149 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000150 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000151
152 // If the information about this identifier is out of date, update it from
153 // the external source.
154 if (II->isOutOfDate())
155 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
156
157 // If the identifier is a macro, and if that macro is enabled, it may be
158 // expanded so it's not a trivial expansion.
159 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
160 // Fast expanding "#define X X" is ok, because X would be disabled.
161 II != MacroIdent)
162 return false;
163
164 // If this is an object-like macro invocation, it is safe to trivially expand
165 // it.
166 if (MI->isObjectLike()) return true;
167
168 // If this is a function-like macro invocation, it's safe to trivially expand
169 // as long as the identifier is not a macro argument.
170 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
171 I != E; ++I)
172 if (*I == II)
173 return false; // Identifier is a macro argument.
174
175 return true;
176}
177
178
179/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
180/// lexed is a '('. If so, consume the token and return true, if not, this
181/// method should have no observable side-effect on the lexed tokens.
182bool Preprocessor::isNextPPTokenLParen() {
183 // Do some quick tests for rejection cases.
184 unsigned Val;
185 if (CurLexer)
186 Val = CurLexer->isNextPPTokenLParen();
187 else if (CurPTHLexer)
188 Val = CurPTHLexer->isNextPPTokenLParen();
189 else
190 Val = CurTokenLexer->isNextTokenLParen();
191
192 if (Val == 2) {
193 // We have run off the end. If it's a source file we don't
194 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
195 // macro stack.
196 if (CurPPLexer)
197 return false;
198 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
199 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
200 if (Entry.TheLexer)
201 Val = Entry.TheLexer->isNextPPTokenLParen();
202 else if (Entry.ThePTHLexer)
203 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
204 else
205 Val = Entry.TheTokenLexer->isNextTokenLParen();
206
207 if (Val != 2)
208 break;
209
210 // Ran off the end of a source file?
211 if (Entry.ThePPLexer)
212 return false;
213 }
214 }
215
216 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
217 // have found something that isn't a '(' or we found the end of the
218 // translation unit. In either case, return false.
219 return Val == 1;
220}
221
222/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
223/// expanded as a macro, handle it and return the next token as 'Identifier'.
224bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000225 MacroDirective *MD) {
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000226 MacroDirective::DefInfo Def = MD->getDefinition();
227 assert(Def.isValid());
228 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000229
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000230 // If this is a macro expansion in the "#if !defined(x)" line for the file,
231 // then the macro could expand to different things in other contexts, we need
232 // to disable the optimization in this case.
233 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
234
235 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
236 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000237 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Craig Topperd2d442c2014-05-17 23:10:59 +0000238 Identifier.getLocation(),
239 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000240 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000241 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000242 }
243
244 /// Args - If this is a function-like macro expansion, this contains,
245 /// for each macro argument, the list of tokens that were provided to the
246 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000247 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000248
249 // Remember where the end of the expansion occurred. For an object-like
250 // macro, this is the identifier. For a function-like macro, this is the ')'.
251 SourceLocation ExpansionEnd = Identifier.getLocation();
252
253 // If this is a function-like macro, read the arguments.
254 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000255 // Remember that we are now parsing the arguments to a macro invocation.
256 // Preprocessor directives used inside macro arguments are not portable, and
257 // this enables the warning.
258 InMacroArgs = true;
259 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
260
261 // Finished parsing args.
262 InMacroArgs = false;
263
264 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000265 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000266
267 ++NumFnMacroExpanded;
268 } else {
269 ++NumMacroExpanded;
270 }
271
272 // Notice that this macro has been used.
273 markMacroAsUsed(MI);
274
275 // Remember where the token is expanded.
276 SourceLocation ExpandLoc = Identifier.getLocation();
277 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
278
279 if (Callbacks) {
280 if (InMacroArgs) {
281 // We can have macro expansion inside a conditional directive while
282 // reading the function macro arguments. To ensure, in that case, that
283 // MacroExpands callbacks still happen in source order, queue this
284 // callback to have it happen after the function macro callback.
285 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000286 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000287 } else {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000288 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000289 if (!DelayedMacroExpandsCallbacks.empty()) {
290 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
291 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000292 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000293 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
294 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000295 }
296 DelayedMacroExpandsCallbacks.clear();
297 }
298 }
299 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000300
301 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000302 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000303 Diag(Identifier, diag::warn_pp_ambiguous_macro)
304 << Identifier.getIdentifierInfo();
305 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
306 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000307 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
308 PrevDef && !PrevDef.isUndefined();
309 PrevDef = PrevDef.getPreviousDefinition()) {
Richard Smith49f906a2014-03-01 00:08:04 +0000310 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
311 diag::note_pp_ambiguous_macro_other)
312 << Identifier.getIdentifierInfo();
313 if (!PrevDef.getDirective()->isAmbiguous())
314 break;
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000315 }
316 }
317
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000318 // If we started lexing a macro, enter the macro expansion body.
319
320 // If this macro expands to no tokens, don't bother to push it onto the
321 // expansion stack, only to take it right back off.
322 if (MI->getNumTokens() == 0) {
323 // No need for arg info.
324 if (Args) Args->destroy(*this);
325
Eli Friedman0834a4b2013-09-19 00:41:32 +0000326 // Propagate whitespace info as if we had pushed, then popped,
327 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000328 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000329 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000330 ++NumFastMacroExpanded;
331 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000332 } else if (MI->getNumTokens() == 1 &&
333 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
334 *this)) {
335 // Otherwise, if this macro expands into a single trivially-expanded
336 // token: expand it now. This handles common cases like
337 // "#define VAL 42".
338
339 // No need for arg info.
340 if (Args) Args->destroy(*this);
341
342 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
343 // identifier to the expanded token.
344 bool isAtStartOfLine = Identifier.isAtStartOfLine();
345 bool hasLeadingSpace = Identifier.hasLeadingSpace();
346
347 // Replace the result token.
348 Identifier = MI->getReplacementToken(0);
349
350 // Restore the StartOfLine/LeadingSpace markers.
351 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
352 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
353
354 // Update the tokens location to include both its expansion and physical
355 // locations.
356 SourceLocation Loc =
357 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
358 ExpansionEnd,Identifier.getLength());
359 Identifier.setLocation(Loc);
360
361 // If this is a disabled macro or #define X X, we must mark the result as
362 // unexpandable.
363 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
364 if (MacroInfo *NewMI = getMacroInfo(NewII))
365 if (!NewMI->isEnabled() || NewMI == MI) {
366 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000367 // Don't warn for "#define X X" like "#define bool bool" from
368 // stdbool.h.
369 if (NewMI != MI || MI->isFunctionLike())
370 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000371 }
372 }
373
374 // Since this is not an identifier token, it can't be macro expanded, so
375 // we're done.
376 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000377 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000378 }
379
380 // Start expanding the macro.
381 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000382 return false;
383}
384
Richard Trieu79b45382013-07-23 18:01:49 +0000385enum Bracket {
386 Brace,
387 Paren
388};
389
390/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
391/// token vector are properly nested.
392static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
393 SmallVector<Bracket, 8> Brackets;
394 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
395 E = Tokens.end();
396 I != E; ++I) {
397 if (I->is(tok::l_paren)) {
398 Brackets.push_back(Paren);
399 } else if (I->is(tok::r_paren)) {
400 if (Brackets.empty() || Brackets.back() == Brace)
401 return false;
402 Brackets.pop_back();
403 } else if (I->is(tok::l_brace)) {
404 Brackets.push_back(Brace);
405 } else if (I->is(tok::r_brace)) {
406 if (Brackets.empty() || Brackets.back() == Paren)
407 return false;
408 Brackets.pop_back();
409 }
410 }
411 if (!Brackets.empty())
412 return false;
413 return true;
414}
415
416/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
417/// vector of tokens in NewTokens. The new number of arguments will be placed
418/// in NumArgs and the ranges which need to surrounded in parentheses will be
419/// in ParenHints.
420/// Returns false if the token stream cannot be changed. If this is because
421/// of an initializer list starting a macro argument, the range of those
422/// initializer lists will be place in InitLists.
423static bool GenerateNewArgTokens(Preprocessor &PP,
424 SmallVectorImpl<Token> &OldTokens,
425 SmallVectorImpl<Token> &NewTokens,
426 unsigned &NumArgs,
427 SmallVectorImpl<SourceRange> &ParenHints,
428 SmallVectorImpl<SourceRange> &InitLists) {
429 if (!CheckMatchedBrackets(OldTokens))
430 return false;
431
432 // Once it is known that the brackets are matched, only a simple count of the
433 // braces is needed.
434 unsigned Braces = 0;
435
436 // First token of a new macro argument.
437 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
438
439 // First closing brace in a new macro argument. Used to generate
440 // SourceRanges for InitLists.
441 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
442 NumArgs = 0;
443 Token TempToken;
444 // Set to true when a macro separator token is found inside a braced list.
445 // If true, the fixed argument spans multiple old arguments and ParenHints
446 // will be updated.
447 bool FoundSeparatorToken = false;
448 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
449 E = OldTokens.end();
450 I != E; ++I) {
451 if (I->is(tok::l_brace)) {
452 ++Braces;
453 } else if (I->is(tok::r_brace)) {
454 --Braces;
455 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
456 ClosingBrace = I;
457 } else if (I->is(tok::eof)) {
458 // EOF token is used to separate macro arguments
459 if (Braces != 0) {
460 // Assume comma separator is actually braced list separator and change
461 // it back to a comma.
462 FoundSeparatorToken = true;
463 I->setKind(tok::comma);
464 I->setLength(1);
465 } else { // Braces == 0
466 // Separator token still separates arguments.
467 ++NumArgs;
468
469 // If the argument starts with a brace, it can't be fixed with
470 // parentheses. A different diagnostic will be given.
471 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
472 InitLists.push_back(
473 SourceRange(ArgStartIterator->getLocation(),
474 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
475 ClosingBrace = E;
476 }
477
478 // Add left paren
479 if (FoundSeparatorToken) {
480 TempToken.startToken();
481 TempToken.setKind(tok::l_paren);
482 TempToken.setLocation(ArgStartIterator->getLocation());
483 TempToken.setLength(0);
484 NewTokens.push_back(TempToken);
485 }
486
487 // Copy over argument tokens
488 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
489
490 // Add right paren and store the paren locations in ParenHints
491 if (FoundSeparatorToken) {
492 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
493 TempToken.startToken();
494 TempToken.setKind(tok::r_paren);
495 TempToken.setLocation(Loc);
496 TempToken.setLength(0);
497 NewTokens.push_back(TempToken);
498 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
499 Loc));
500 }
501
502 // Copy separator token
503 NewTokens.push_back(*I);
504
505 // Reset values
506 ArgStartIterator = I + 1;
507 FoundSeparatorToken = false;
508 }
509 }
510 }
511
512 return !ParenHints.empty() && InitLists.empty();
513}
514
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000515/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
516/// token is the '(' of the macro, this method is invoked to read all of the
517/// actual arguments specified for the macro invocation. This returns null on
518/// error.
519MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
520 MacroInfo *MI,
521 SourceLocation &MacroEnd) {
522 // The number of fixed arguments to parse.
523 unsigned NumFixedArgsLeft = MI->getNumArgs();
524 bool isVariadic = MI->isVariadic();
525
526 // Outer loop, while there are more arguments, keep reading them.
527 Token Tok;
528
529 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
530 // an argument value in a macro could expand to ',' or '(' or ')'.
531 LexUnexpandedToken(Tok);
532 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
533
534 // ArgTokens - Build up a list of tokens that make up each argument. Each
535 // argument is separated by an EOF token. Use a SmallVector so we can avoid
536 // heap allocations in the common case.
537 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000538 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000539
Richard Trieu79b45382013-07-23 18:01:49 +0000540 SourceLocation TooManyArgsLoc;
541
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000542 unsigned NumActuals = 0;
543 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000544 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
545 break;
546
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000547 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
548 "only expect argument separators here");
549
550 unsigned ArgTokenStart = ArgTokens.size();
551 SourceLocation ArgStartLoc = Tok.getLocation();
552
553 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
554 // that we already consumed the first one.
555 unsigned NumParens = 0;
556
557 while (1) {
558 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
559 // an argument value in a macro could expand to ',' or '(' or ')'.
560 LexUnexpandedToken(Tok);
561
562 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000563 if (!ContainsCodeCompletionTok) {
564 Diag(MacroName, diag::err_unterm_macro_invoc);
565 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
566 << MacroName.getIdentifierInfo();
567 // Do not lose the EOF/EOD. Return it to the client.
568 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000569 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000570 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000571 // Do not lose the EOF/EOD.
572 Token *Toks = new Token[1];
573 Toks[0] = Tok;
574 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000575 break;
576 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000577 } else if (Tok.is(tok::r_paren)) {
578 // If we found the ) token, the macro arg list is done.
579 if (NumParens-- == 0) {
580 MacroEnd = Tok.getLocation();
581 break;
582 }
583 } else if (Tok.is(tok::l_paren)) {
584 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000585 } else if (Tok.is(tok::comma) && NumParens == 0 &&
586 !(Tok.getFlags() & Token::IgnoredComma)) {
587 // In Microsoft-compatibility mode, single commas from nested macro
588 // expansions should not be considered as argument separators. We test
589 // for this with the IgnoredComma token flag above.
590
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000591 // Comma ends this argument if there are more fixed arguments expected.
592 // However, if this is a variadic macro, and this is part of the
593 // variadic part, then the comma is just an argument token.
594 if (!isVariadic) break;
595 if (NumFixedArgsLeft > 1)
596 break;
597 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
598 // If this is a comment token in the argument list and we're just in
599 // -C mode (not -CC mode), discard the comment.
600 continue;
Craig Topperd2d442c2014-05-17 23:10:59 +0000601 } else if (Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000602 // Reading macro arguments can cause macros that we are currently
603 // expanding from to be popped off the expansion stack. Doing so causes
604 // them to be reenabled for expansion. Here we record whether any
605 // identifiers we lex as macro arguments correspond to disabled macros.
606 // If so, we mark the token as noexpand. This is a subtle aspect of
607 // C99 6.10.3.4p2.
608 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
609 if (!MI->isEnabled())
610 Tok.setFlag(Token::DisableExpand);
611 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000612 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000613 if (CodeComplete)
614 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
615 MI, NumActuals);
616 // Don't mark that we reached the code-completion point because the
617 // parser is going to handle the token and there will be another
618 // code-completion callback.
619 }
620
621 ArgTokens.push_back(Tok);
622 }
623
624 // If this was an empty argument list foo(), don't add this as an empty
625 // argument.
626 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
627 break;
628
629 // If this is not a variadic macro, and too many args were specified, emit
630 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000631 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000632 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000633 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
634 else
635 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000636 }
637
Richard Trieu79b45382013-07-23 18:01:49 +0000638 // Empty arguments are standard in C99 and C++0x, and are supported as an
639 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000640 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000641 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000642 diag::warn_cxx98_compat_empty_fnmacro_arg :
643 diag::ext_empty_fnmacro_arg);
644
645 // Add a marker EOF token to the end of the token list for this argument.
646 Token EOFTok;
647 EOFTok.startToken();
648 EOFTok.setKind(tok::eof);
649 EOFTok.setLocation(Tok.getLocation());
650 EOFTok.setLength(0);
651 ArgTokens.push_back(EOFTok);
652 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000653 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000654 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000655 }
656
657 // Okay, we either found the r_paren. Check to see if we parsed too few
658 // arguments.
659 unsigned MinArgsExpected = MI->getNumArgs();
660
Richard Trieu79b45382013-07-23 18:01:49 +0000661 // If this is not a variadic macro, and too many args were specified, emit
662 // an error.
663 if (!isVariadic && NumActuals > MinArgsExpected &&
664 !ContainsCodeCompletionTok) {
665 // Emit the diagnostic at the macro name in case there is a missing ).
666 // Emitting it at the , could be far away from the macro name.
667 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
668 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
669 << MacroName.getIdentifierInfo();
670
671 // Commas from braced initializer lists will be treated as argument
672 // separators inside macros. Attempt to correct for this with parentheses.
673 // TODO: See if this can be generalized to angle brackets for templates
674 // inside macro arguments.
675
Bob Wilson57217352013-07-27 21:59:57 +0000676 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000677 unsigned FixedNumArgs = 0;
678 SmallVector<SourceRange, 4> ParenHints, InitLists;
679 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
680 ParenHints, InitLists)) {
681 if (!InitLists.empty()) {
682 DiagnosticBuilder DB =
683 Diag(MacroName,
684 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000685 for (const SourceRange &Range : InitLists)
686 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000687 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000688 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000689 }
690 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000691 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000692
693 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000694 for (const SourceRange &ParenLocation : ParenHints) {
695 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
696 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000697 }
698 ArgTokens.swap(FixedArgTokens);
699 NumActuals = FixedNumArgs;
700 }
701
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000702 // See MacroArgs instance var for description of this.
703 bool isVarargsElided = false;
704
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000705 if (ContainsCodeCompletionTok) {
706 // Recover from not-fully-formed macro invocation during code-completion.
707 Token EOFTok;
708 EOFTok.startToken();
709 EOFTok.setKind(tok::eof);
710 EOFTok.setLocation(Tok.getLocation());
711 EOFTok.setLength(0);
712 for (; NumActuals < MinArgsExpected; ++NumActuals)
713 ArgTokens.push_back(EOFTok);
714 }
715
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000716 if (NumActuals < MinArgsExpected) {
717 // There are several cases where too few arguments is ok, handle them now.
718 if (NumActuals == 0 && MinArgsExpected == 1) {
719 // #define A(X) or #define A(...) ---> A()
720
721 // If there is exactly one argument, and that argument is missing,
722 // then we have an empty "()" argument empty list. This is fine, even if
723 // the macro expects one argument (the argument is just empty).
724 isVarargsElided = MI->isVariadic();
725 } else if (MI->isVariadic() &&
726 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
727 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
728 // Varargs where the named vararg parameter is missing: OK as extension.
729 // #define A(x, ...)
730 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000731 //
732 // If the macro contains the comma pasting extension, the diagnostic
733 // is suppressed; we know we'll get another diagnostic later.
734 if (!MI->hasCommaPasting()) {
735 Diag(Tok, diag::ext_missing_varargs_arg);
736 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
737 << MacroName.getIdentifierInfo();
738 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000739
740 // Remember this occurred, allowing us to elide the comma when used for
741 // cases like:
742 // #define A(x, foo...) blah(a, ## foo)
743 // #define B(x, ...) blah(a, ## __VA_ARGS__)
744 // #define C(...) blah(a, ## __VA_ARGS__)
745 // A(x) B(x) C()
746 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000747 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000748 // Otherwise, emit the error.
749 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000750 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
751 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000752 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000753 }
754
755 // Add a marker EOF token to the end of the token list for this argument.
756 SourceLocation EndLoc = Tok.getLocation();
757 Tok.startToken();
758 Tok.setKind(tok::eof);
759 Tok.setLocation(EndLoc);
760 Tok.setLength(0);
761 ArgTokens.push_back(Tok);
762
763 // If we expect two arguments, add both as empty.
764 if (NumActuals == 0 && MinArgsExpected == 2)
765 ArgTokens.push_back(Tok);
766
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000767 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
768 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000769 // Emit the diagnostic at the macro name in case there is a missing ).
770 // Emitting it at the , could be far away from the macro name.
771 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000772 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
773 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000774 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000775 }
776
777 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
778}
779
780/// \brief Keeps macro expanded tokens for TokenLexers.
781//
782/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
783/// going to lex in the cache and when it finishes the tokens are removed
784/// from the end of the cache.
785Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
786 ArrayRef<Token> tokens) {
787 assert(tokLexer);
788 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000789 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000790
791 size_t newIndex = MacroExpandedTokens.size();
792 bool cacheNeedsToGrow = tokens.size() >
793 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
794 MacroExpandedTokens.append(tokens.begin(), tokens.end());
795
796 if (cacheNeedsToGrow) {
797 // Go through all the TokenLexers whose 'Tokens' pointer points in the
798 // buffer and update the pointers to the (potential) new buffer array.
799 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
800 TokenLexer *prevLexer;
801 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000802 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000803 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
804 }
805 }
806
807 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
808 return MacroExpandedTokens.data() + newIndex;
809}
810
811void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
812 assert(!MacroExpandingLexersStack.empty());
813 size_t tokIndex = MacroExpandingLexersStack.back().second;
814 assert(tokIndex < MacroExpandedTokens.size());
815 // Pop the cached macro expanded tokens from the end.
816 MacroExpandedTokens.resize(tokIndex);
817 MacroExpandingLexersStack.pop_back();
818}
819
820/// ComputeDATE_TIME - Compute the current time, enter it into the specified
821/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
822/// the identifier tokens inserted.
823static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
824 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000825 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000826 struct tm *TM = localtime(&TT);
827
828 static const char * const Months[] = {
829 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
830 };
831
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000832 {
833 SmallString<32> TmpBuffer;
834 llvm::raw_svector_ostream TmpStream(TmpBuffer);
835 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
836 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000837 Token TmpTok;
838 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000839 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000840 DATELoc = TmpTok.getLocation();
841 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000842
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000843 {
844 SmallString<32> TmpBuffer;
845 llvm::raw_svector_ostream TmpStream(TmpBuffer);
846 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
847 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000848 Token TmpTok;
849 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000850 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000851 TIMELoc = TmpTok.getLocation();
852 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000853}
854
855
856/// HasFeature - Return true if we recognize and implement the feature
857/// specified by the identifier as a standard language feature.
858static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
859 const LangOptions &LangOpts = PP.getLangOpts();
860 StringRef Feature = II->getName();
861
862 // Normalize the feature name, __foo__ becomes foo.
863 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
864 Feature = Feature.substr(2, Feature.size() - 4);
865
866 return llvm::StringSwitch<bool>(Feature)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000867 .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
868 .Case("attribute_analyzer_noreturn", true)
869 .Case("attribute_availability", true)
870 .Case("attribute_availability_with_message", true)
871 .Case("attribute_cf_returns_not_retained", true)
872 .Case("attribute_cf_returns_retained", true)
873 .Case("attribute_deprecated_with_message", true)
874 .Case("attribute_ext_vector_type", true)
875 .Case("attribute_ns_returns_not_retained", true)
876 .Case("attribute_ns_returns_retained", true)
877 .Case("attribute_ns_consumes_self", true)
878 .Case("attribute_ns_consumed", true)
879 .Case("attribute_cf_consumed", true)
880 .Case("attribute_objc_ivar_unused", true)
881 .Case("attribute_objc_method_family", true)
882 .Case("attribute_overloadable", true)
883 .Case("attribute_unavailable_with_message", true)
884 .Case("attribute_unused_on_fields", true)
885 .Case("blocks", LangOpts.Blocks)
886 .Case("c_thread_safety_attributes", true)
887 .Case("cxx_exceptions", LangOpts.CXXExceptions)
888 .Case("cxx_rtti", LangOpts.RTTI)
889 .Case("enumerator_attributes", true)
890 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
891 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
892 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
893 // Objective-C features
894 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
895 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
896 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
897 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
898 .Case("objc_fixed_enum", LangOpts.ObjC2)
899 .Case("objc_instancetype", LangOpts.ObjC2)
900 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
901 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
902 .Case("objc_property_explicit_atomic",
903 true) // Does clang support explicit "atomic" keyword?
904 .Case("objc_protocol_qualifier_mangling", true)
905 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
906 .Case("ownership_holds", true)
907 .Case("ownership_returns", true)
908 .Case("ownership_takes", true)
909 .Case("objc_bool", true)
910 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
911 .Case("objc_array_literals", LangOpts.ObjC2)
912 .Case("objc_dictionary_literals", LangOpts.ObjC2)
913 .Case("objc_boxed_expressions", LangOpts.ObjC2)
914 .Case("arc_cf_code_audited", true)
915 // C11 features
916 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +0000917 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000918 .Case("c_atomic", LangOpts.C11)
919 .Case("c_generic_selections", LangOpts.C11)
920 .Case("c_static_assert", LangOpts.C11)
921 .Case("c_thread_local",
922 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
923 // C++11 features
924 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
925 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
926 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +0000927 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000928 .Case("cxx_atomic", LangOpts.CPlusPlus11)
929 .Case("cxx_attributes", LangOpts.CPlusPlus11)
930 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
931 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
932 .Case("cxx_decltype", LangOpts.CPlusPlus11)
933 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
934 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
935 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
936 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
937 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
938 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
939 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
940 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
941 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
942 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
943 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
944 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
945 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
946 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
947 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
948 .Case("cxx_override_control", LangOpts.CPlusPlus11)
949 .Case("cxx_range_for", LangOpts.CPlusPlus11)
950 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
951 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
952 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
953 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
954 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
955 .Case("cxx_thread_local",
956 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
957 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
958 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
959 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
960 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
961 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
962 // C++1y features
963 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
964 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
965 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
966 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
967 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
968 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
969 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
970 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
971 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
972 // C++ TSes
973 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
974 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
975 // FIXME: Should this be __has_feature or __has_extension?
976 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
977 // Type traits
978 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
979 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
980 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
981 .Case("has_trivial_assign", LangOpts.CPlusPlus)
982 .Case("has_trivial_copy", LangOpts.CPlusPlus)
983 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
984 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
985 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
986 .Case("is_abstract", LangOpts.CPlusPlus)
987 .Case("is_base_of", LangOpts.CPlusPlus)
988 .Case("is_class", LangOpts.CPlusPlus)
989 .Case("is_constructible", LangOpts.CPlusPlus)
990 .Case("is_convertible_to", LangOpts.CPlusPlus)
991 .Case("is_empty", LangOpts.CPlusPlus)
992 .Case("is_enum", LangOpts.CPlusPlus)
993 .Case("is_final", LangOpts.CPlusPlus)
994 .Case("is_literal", LangOpts.CPlusPlus)
995 .Case("is_standard_layout", LangOpts.CPlusPlus)
996 .Case("is_pod", LangOpts.CPlusPlus)
997 .Case("is_polymorphic", LangOpts.CPlusPlus)
998 .Case("is_sealed", LangOpts.MicrosoftExt)
999 .Case("is_trivial", LangOpts.CPlusPlus)
1000 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1001 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1002 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1003 .Case("is_union", LangOpts.CPlusPlus)
1004 .Case("modules", LangOpts.Modules)
1005 .Case("tls", PP.getTargetInfo().isTLSSupported())
1006 .Case("underlying_type", LangOpts.CPlusPlus)
1007 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001008}
1009
1010/// HasExtension - Return true if we recognize and implement the feature
1011/// specified by the identifier, either as an extension or a standard language
1012/// feature.
1013static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1014 if (HasFeature(PP, II))
1015 return true;
1016
1017 // If the use of an extension results in an error diagnostic, extensions are
1018 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001019 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1020 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001021 return false;
1022
1023 const LangOptions &LangOpts = PP.getLangOpts();
1024 StringRef Extension = II->getName();
1025
1026 // Normalize the extension name, __foo__ becomes foo.
1027 if (Extension.startswith("__") && Extension.endswith("__") &&
1028 Extension.size() >= 4)
1029 Extension = Extension.substr(2, Extension.size() - 4);
1030
1031 // Because we inherit the feature list from HasFeature, this string switch
1032 // must be less restrictive than HasFeature's.
1033 return llvm::StringSwitch<bool>(Extension)
1034 // C11 features supported by other languages as extensions.
1035 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001036 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001037 .Case("c_atomic", true)
1038 .Case("c_generic_selections", true)
1039 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001040 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001041 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001042 .Case("cxx_atomic", LangOpts.CPlusPlus)
1043 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1044 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1045 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1046 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1047 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1048 .Case("cxx_override_control", LangOpts.CPlusPlus)
1049 .Case("cxx_range_for", LangOpts.CPlusPlus)
1050 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1051 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001052 // C++1y features supported by other languages as extensions.
1053 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001054 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001055 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001056 .Default(false);
1057}
1058
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001059/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1060/// or '__has_include_next("path")' expression.
1061/// Returns true if successful.
1062static bool EvaluateHasIncludeCommon(Token &Tok,
1063 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001064 const DirectoryLookup *LookupFrom,
1065 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001066 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001067 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001068 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001069
Aaron Ballman6ce00002013-01-16 19:32:21 +00001070 // These expressions are only allowed within a preprocessor directive.
1071 if (!PP.isParsingIfOrElifDirective()) {
1072 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1073 return false;
1074 }
1075
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001076 // Get '('.
1077 PP.LexNonComment(Tok);
1078
1079 // Ensure we have a '('.
1080 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001081 // No '(', use end of last token.
1082 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001083 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001084 // If the next token looks like a filename or the start of one,
1085 // assume it is and process it as such.
1086 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1087 !Tok.is(tok::less))
1088 return false;
1089 } else {
1090 // Save '(' location for possible missing ')' message.
1091 LParenLoc = Tok.getLocation();
1092
Eli Friedmanec94b612013-01-09 02:20:00 +00001093 if (PP.getCurrentLexer()) {
1094 // Get the file name.
1095 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1096 } else {
1097 // We're in a macro, so we can't use LexIncludeFilename; just
1098 // grab the next token.
1099 PP.Lex(Tok);
1100 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001101 }
1102
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001103 // Reserve a buffer to get the spelling.
1104 SmallString<128> FilenameBuffer;
1105 StringRef Filename;
1106 SourceLocation EndLoc;
1107
1108 switch (Tok.getKind()) {
1109 case tok::eod:
1110 // If the token kind is EOD, the error has already been diagnosed.
1111 return false;
1112
1113 case tok::angle_string_literal:
1114 case tok::string_literal: {
1115 bool Invalid = false;
1116 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1117 if (Invalid)
1118 return false;
1119 break;
1120 }
1121
1122 case tok::less:
1123 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1124 // case, glue the tokens together into FilenameBuffer and interpret those.
1125 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001126 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1127 // Let the caller know a <eod> was found by changing the Token kind.
1128 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001129 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001130 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001131 Filename = FilenameBuffer.str();
1132 break;
1133 default:
1134 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1135 return false;
1136 }
1137
Richard Trieuda031982012-10-22 20:28:48 +00001138 SourceLocation FilenameLoc = Tok.getLocation();
1139
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001140 // Get ')'.
1141 PP.LexNonComment(Tok);
1142
1143 // Ensure we have a trailing ).
1144 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001145 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1146 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001147 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001148 return false;
1149 }
1150
1151 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1152 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1153 // error.
1154 if (Filename.empty())
1155 return false;
1156
1157 // Search include directories.
1158 const DirectoryLookup *CurDir;
1159 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001160 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1161 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001162
1163 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001164 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001165}
1166
1167/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1168/// Returns true if successful.
1169static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1170 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001171 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001172}
1173
1174/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1175/// Returns true if successful.
1176static bool EvaluateHasIncludeNext(Token &Tok,
1177 IdentifierInfo *II, Preprocessor &PP) {
1178 // __has_include_next is like __has_include, except that we start
1179 // searching after the current found directory. If we can't do this,
1180 // issue a diagnostic.
Richard Smith25d50752014-10-20 00:15:49 +00001181 // FIXME: Factor out duplication wiht
1182 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001183 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001184 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001185 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001186 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001187 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001188 } else if (PP.getCurrentSubmodule()) {
1189 // Start looking up in the directory *after* the one in which the current
1190 // file would be found, if any.
1191 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1192 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1193 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001194 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001195 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1196 } else {
1197 // Start looking up in the next directory.
1198 ++Lookup;
1199 }
1200
Richard Smith25d50752014-10-20 00:15:49 +00001201 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001202}
1203
Douglas Gregorc83de302012-09-25 15:44:52 +00001204/// \brief Process __building_module(identifier) expression.
1205/// \returns true if we are building the named module, false otherwise.
1206static bool EvaluateBuildingModule(Token &Tok,
1207 IdentifierInfo *II, Preprocessor &PP) {
1208 // Get '('.
1209 PP.LexNonComment(Tok);
1210
1211 // Ensure we have a '('.
1212 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001213 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1214 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001215 return false;
1216 }
1217
1218 // Save '(' location for possible missing ')' message.
1219 SourceLocation LParenLoc = Tok.getLocation();
1220
1221 // Get the module name.
1222 PP.LexNonComment(Tok);
1223
1224 // Ensure that we have an identifier.
1225 if (Tok.isNot(tok::identifier)) {
1226 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1227 return false;
1228 }
1229
1230 bool Result
1231 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1232
1233 // Get ')'.
1234 PP.LexNonComment(Tok);
1235
1236 // Ensure we have a trailing ).
1237 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001238 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1239 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001240 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001241 return false;
1242 }
1243
1244 return Result;
1245}
1246
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001247/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1248/// as a builtin macro, handle it and return the next token as 'Tok'.
1249void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1250 // Figure out which token this is.
1251 IdentifierInfo *II = Tok.getIdentifierInfo();
1252 assert(II && "Can't be a macro without id info!");
1253
1254 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1255 // invoke the pragma handler, then lex the token after it.
1256 if (II == Ident_Pragma)
1257 return Handle_Pragma(Tok);
1258 else if (II == Ident__pragma) // in non-MS mode this is null
1259 return HandleMicrosoft__pragma(Tok);
1260
1261 ++NumBuiltinMacroExpanded;
1262
1263 SmallString<128> TmpBuffer;
1264 llvm::raw_svector_ostream OS(TmpBuffer);
1265
1266 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001267 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001268 Tok.clearFlag(Token::NeedsCleaning);
1269
1270 if (II == Ident__LINE__) {
1271 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1272 // source file) of the current source line (an integer constant)". This can
1273 // be affected by #line.
1274 SourceLocation Loc = Tok.getLocation();
1275
1276 // Advance to the location of the first _, this might not be the first byte
1277 // of the token if it starts with an escaped newline.
1278 Loc = AdvanceToTokenCharacter(Loc, 0);
1279
1280 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1281 // a macro expansion. This doesn't matter for object-like macros, but
1282 // can matter for a function-like macro that expands to contain __LINE__.
1283 // Skip down through expansion points until we find a file loc for the
1284 // end of the expansion history.
1285 Loc = SourceMgr.getExpansionRange(Loc).second;
1286 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1287
1288 // __LINE__ expands to a simple numeric value.
1289 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1290 Tok.setKind(tok::numeric_constant);
1291 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1292 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1293 // character string literal)". This can be affected by #line.
1294 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1295
1296 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1297 // #include stack instead of the current file.
1298 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1299 SourceLocation NextLoc = PLoc.getIncludeLoc();
1300 while (NextLoc.isValid()) {
1301 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1302 if (PLoc.isInvalid())
1303 break;
1304
1305 NextLoc = PLoc.getIncludeLoc();
1306 }
1307 }
1308
1309 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1310 SmallString<128> FN;
1311 if (PLoc.isValid()) {
1312 FN += PLoc.getFilename();
1313 Lexer::Stringify(FN);
1314 OS << '"' << FN.str() << '"';
1315 }
1316 Tok.setKind(tok::string_literal);
1317 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001318 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001319 if (!DATELoc.isValid())
1320 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1321 Tok.setKind(tok::string_literal);
1322 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1323 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1324 Tok.getLocation(),
1325 Tok.getLength()));
1326 return;
1327 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001328 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001329 if (!TIMELoc.isValid())
1330 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1331 Tok.setKind(tok::string_literal);
1332 Tok.setLength(strlen("\"hh:mm:ss\""));
1333 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1334 Tok.getLocation(),
1335 Tok.getLength()));
1336 return;
1337 } else if (II == Ident__INCLUDE_LEVEL__) {
1338 // Compute the presumed include depth of this token. This can be affected
1339 // by GNU line markers.
1340 unsigned Depth = 0;
1341
1342 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1343 if (PLoc.isValid()) {
1344 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1345 for (; PLoc.isValid(); ++Depth)
1346 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1347 }
1348
1349 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1350 OS << Depth;
1351 Tok.setKind(tok::numeric_constant);
1352 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001353 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001354 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1355 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1356
1357 // Get the file that we are lexing out of. If we're currently lexing from
1358 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001359 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001360 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1361
1362 if (TheLexer)
1363 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1364
1365 const char *Result;
1366 if (CurFile) {
1367 time_t TT = CurFile->getModificationTime();
1368 struct tm *TM = localtime(&TT);
1369 Result = asctime(TM);
1370 } else {
1371 Result = "??? ??? ?? ??:??:?? ????\n";
1372 }
1373 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001374 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001375 Tok.setKind(tok::string_literal);
1376 } else if (II == Ident__COUNTER__) {
1377 // __COUNTER__ expands to a simple numeric value.
1378 OS << CounterValue++;
1379 Tok.setKind(tok::numeric_constant);
1380 } else if (II == Ident__has_feature ||
1381 II == Ident__has_extension ||
1382 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001383 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001384 II == Ident__has_attribute ||
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001385 II == Ident__has_declspec ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001386 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001387 // The argument to these builtins should be a parenthesized identifier.
1388 SourceLocation StartLoc = Tok.getLocation();
1389
1390 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001391 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001392 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001393
1394 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001395 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001396 if (Tok.is(tok::l_paren)) {
1397 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001398 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001399 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001400 // If we're checking __has_cpp_attribute, it is possible to receive a
1401 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001402 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001403 bool IsScopeValid = true;
1404 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1405 LexUnexpandedToken(Tok);
1406 // The first thing we read was not the feature, it was the scope.
1407 ScopeII = FeatureII;
Aaron Ballman918474c2014-11-14 14:40:49 +00001408 if ((FeatureII = Tok.getIdentifierInfo()))
Aaron Ballmana0344c52014-11-14 13:44:02 +00001409 LexUnexpandedToken(Tok);
1410 else
1411 IsScopeValid = false;
1412 }
1413 // Read the closing paren.
1414 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001415 IsValid = true;
1416 }
1417 }
1418
Aaron Ballmana0344c52014-11-14 13:44:02 +00001419 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001420 if (!IsValid)
1421 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001422 else if (II == Ident__is_identifier)
1423 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001424 else if (II == Ident__has_builtin) {
1425 // Check for a builtin is trivial.
1426 Value = FeatureII->getBuiltinID() != 0;
1427 } else if (II == Ident__has_attribute)
Aaron Ballman759c71d2014-03-31 15:26:40 +00001428 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001429 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001430 else if (II == Ident__has_cpp_attribute)
1431 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1432 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001433 else if (II == Ident__has_declspec)
1434 Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
1435 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001436 else if (II == Ident__has_extension)
1437 Value = HasExtension(*this, FeatureII);
1438 else {
1439 assert(II == Ident__has_feature && "Must be feature check");
1440 Value = HasFeature(*this, FeatureII);
1441 }
1442
Aaron Ballmana0344c52014-11-14 13:44:02 +00001443 OS << Value;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001444 if (IsValid)
1445 Tok.setKind(tok::numeric_constant);
1446 } else if (II == Ident__has_include ||
1447 II == Ident__has_include_next) {
1448 // The argument to these two builtins should be a parenthesized
1449 // file name string literal using angle brackets (<>) or
1450 // double-quotes ("").
1451 bool Value;
1452 if (II == Ident__has_include)
1453 Value = EvaluateHasInclude(Tok, II, *this);
1454 else
1455 Value = EvaluateHasIncludeNext(Tok, II, *this);
1456 OS << (int)Value;
Richard Trieuda031982012-10-22 20:28:48 +00001457 if (Tok.is(tok::r_paren))
1458 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001459 } else if (II == Ident__has_warning) {
1460 // The argument should be a parenthesized string literal.
1461 // The argument to these builtins should be a parenthesized identifier.
1462 SourceLocation StartLoc = Tok.getLocation();
1463 bool IsValid = false;
1464 bool Value = false;
1465 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001466 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001467 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001468 if (Tok.isNot(tok::l_paren)) {
1469 Diag(StartLoc, diag::err_warning_check_malformed);
1470 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001471 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001472
1473 LexUnexpandedToken(Tok);
1474 std::string WarningName;
1475 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001476 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1477 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001478 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001479 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1480 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001481 LexUnexpandedToken(Tok);
1482 break;
1483 }
1484
1485 // Is the end a ')'?
1486 if (!(IsValid = Tok.is(tok::r_paren))) {
1487 Diag(StartLoc, diag::err_warning_check_malformed);
1488 break;
1489 }
1490
Richard Smith3be1cb22014-08-07 00:24:21 +00001491 // FIXME: Should we accept "-R..." flags here, or should that be handled
1492 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001493 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1494 WarningName[1] != 'W') {
1495 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1496 break;
1497 }
1498
1499 // Finally, check if the warning flags maps to a diagnostic group.
1500 // We construct a SmallVector here to talk to getDiagnosticIDs().
1501 // Although we don't use the result, this isn't a hot path, and not
1502 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001503 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001504 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001505 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1506 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001507 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001508
1509 OS << (int)Value;
Andy Gibbsf591982b2012-11-17 19:14:53 +00001510 if (IsValid)
1511 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001512 } else if (II == Ident__building_module) {
1513 // The argument to this builtin should be an identifier. The
1514 // builtin evaluates to 1 when that identifier names the module we are
1515 // currently building.
1516 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1517 Tok.setKind(tok::numeric_constant);
1518 } else if (II == Ident__MODULE__) {
1519 // The current module as an identifier.
1520 OS << getLangOpts().CurrentModule;
1521 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1522 Tok.setIdentifierInfo(ModuleII);
1523 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001524 } else if (II == Ident__identifier) {
1525 SourceLocation Loc = Tok.getLocation();
1526
1527 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1528 // if the parens are missing.
1529 LexNonComment(Tok);
1530 if (Tok.isNot(tok::l_paren)) {
1531 // No '(', use end of last token.
1532 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1533 << II << tok::l_paren;
1534 // If the next token isn't valid as our argument, we can't recover.
1535 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1536 Tok.setKind(tok::identifier);
1537 return;
1538 }
1539
1540 SourceLocation LParenLoc = Tok.getLocation();
1541 LexNonComment(Tok);
1542
1543 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1544 Tok.setKind(tok::identifier);
1545 else {
1546 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1547 << Tok.getKind();
1548 // Don't walk past anything that's not a real token.
1549 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1550 return;
1551 }
1552
1553 // Discard the ')', preserving 'Tok' as our result.
1554 Token RParen;
1555 LexNonComment(RParen);
1556 if (RParen.isNot(tok::r_paren)) {
1557 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1558 << Tok.getKind() << tok::r_paren;
1559 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1560 }
1561 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001562 } else {
1563 llvm_unreachable("Unknown identifier!");
1564 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001565 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001566}
1567
1568void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1569 // If the 'used' status changed, and the macro requires 'unused' warning,
1570 // remove its SourceLocation from the warn-for-unused-macro locations.
1571 if (MI->isWarnIfUnused() && !MI->isUsed())
1572 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1573 MI->setIsUsed(true);
1574}