blob: 247bbf47fccb89fc0da3d714b5b36c166ce8933b [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Eric Christopher1f84f8d2010-06-24 02:02:00 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000021#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf29c5232010-08-24 22:20:20 +000022#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor295a2a62010-10-30 00:23:06 +000023#include "clang/Lex/ExternalPreprocessorSource.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000024#include "llvm/ADT/StringSwitch.h"
Douglas Gregor6665ffb2010-11-09 05:43:53 +000025#include "llvm/Config/config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000027#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000028#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000029using namespace clang;
30
Douglas Gregor295a2a62010-10-30 00:23:06 +000031MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
32 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
33
34 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
35 = Macros.find(II);
36 if (Pos == Macros.end()) {
37 // Load this macro from the external source.
38 getExternalSource()->LoadMacroDefinition(II);
39 Pos = Macros.find(II);
40 }
41 assert(Pos != Macros.end() && "Identifier macro info is missing!");
42 return Pos->second;
43}
44
Chris Lattnera3b605e2008-03-09 03:13:06 +000045/// setMacroInfo - Specify a macro for this identifier.
46///
47void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000048 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000049 Macros[II] = MI;
50 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000051 } else if (II->hasMacroDefinition()) {
52 Macros.erase(II);
53 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000054 }
55}
56
57/// RegisterBuiltinMacro - Register the specified identifier in the identifier
58/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000059static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000060 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000061 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattnera3b605e2008-03-09 03:13:06 +000063 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000064 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000065 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000066 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000067 return Id;
68}
69
70
71/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
72/// identifier table.
73void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000074 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
75 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
76 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
77 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
78 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
79 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattnera3b605e2008-03-09 03:13:06 +000081 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000082 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
83 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
84 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner148772a2009-06-13 07:13:28 +000086 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000087 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
88 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000089 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000090 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
91 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000092
93 // Microsoft Extensions.
94 if (Features.Microsoft)
95 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
96 else
97 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000098}
99
100/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
101/// in its expansion, currently expands to that token literally.
102static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
103 const IdentifierInfo *MacroIdent,
104 Preprocessor &PP) {
105 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
106
107 // If the token isn't an identifier, it's always literally expanded.
108 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Chris Lattnera3b605e2008-03-09 03:13:06 +0000110 // If the identifier is a macro, and if that macro is enabled, it may be
111 // expanded so it's not a trivial expansion.
112 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
113 // Fast expanding "#define X X" is ok, because X would be disabled.
114 II != MacroIdent)
115 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattnera3b605e2008-03-09 03:13:06 +0000117 // If this is an object-like macro invocation, it is safe to trivially expand
118 // it.
119 if (MI->isObjectLike()) return true;
120
121 // If this is a function-like macro invocation, it's safe to trivially expand
122 // as long as the identifier is not a macro argument.
123 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
124 I != E; ++I)
125 if (*I == II)
126 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Chris Lattnera3b605e2008-03-09 03:13:06 +0000128 return true;
129}
130
131
132/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
133/// lexed is a '('. If so, consume the token and return true, if not, this
134/// method should have no observable side-effect on the lexed tokens.
135bool Preprocessor::isNextPPTokenLParen() {
136 // Do some quick tests for rejection cases.
137 unsigned Val;
138 if (CurLexer)
139 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000140 else if (CurPTHLexer)
141 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000142 else
143 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattnera3b605e2008-03-09 03:13:06 +0000145 if (Val == 2) {
146 // We have run off the end. If it's a source file we don't
147 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
148 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000149 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000150 return false;
151 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
152 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
153 if (Entry.TheLexer)
154 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000155 else if (Entry.ThePTHLexer)
156 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 else
158 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 if (Val != 2)
161 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattnera3b605e2008-03-09 03:13:06 +0000163 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000164 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 return false;
166 }
167 }
168
169 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
170 // have found something that isn't a '(' or we found the end of the
171 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000172 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000173}
174
175/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
176/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000177bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000179 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Douglas Gregor13678972010-01-26 19:43:43 +0000181 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000182 // then the macro could expand to different things in other contexts, we need
183 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000184 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattnera3b605e2008-03-09 03:13:06 +0000186 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
187 if (MI->isBuiltinMacro()) {
188 ExpandBuiltinMacro(Identifier);
189 return false;
190 }
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattnera3b605e2008-03-09 03:13:06 +0000192 /// Args - If this is a function-like macro expansion, this contains,
193 /// for each macro argument, the list of tokens that were provided to the
194 /// invocation.
195 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnere7fb4842009-02-15 20:52:18 +0000197 // Remember where the end of the instantiation occurred. For an object-like
198 // macro, this is the identifier. For a function-like macro, this is the ')'.
199 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnera3b605e2008-03-09 03:13:06 +0000201 // If this is a function-like macro, read the arguments.
202 if (MI->isFunctionLike()) {
203 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000204 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000205 if (!isNextPPTokenLParen())
206 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Chris Lattnera3b605e2008-03-09 03:13:06 +0000208 // Remember that we are now parsing the arguments to a macro invocation.
209 // Preprocessor directives used inside macro arguments are not portable, and
210 // this enables the warning.
211 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000212 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattnera3b605e2008-03-09 03:13:06 +0000214 // Finished parsing args.
215 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnera3b605e2008-03-09 03:13:06 +0000217 // If there was an error parsing the arguments, bail out.
218 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 ++NumFnMacroExpanded;
221 } else {
222 ++NumMacroExpanded;
223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera3b605e2008-03-09 03:13:06 +0000225 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattnera3b605e2008-03-09 03:13:06 +0000228 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera3b605e2008-03-09 03:13:06 +0000230 // If this macro expands to no tokens, don't bother to push it onto the
231 // expansion stack, only to take it right back off.
232 if (MI->getNumTokens() == 0) {
233 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000234 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattnera3b605e2008-03-09 03:13:06 +0000236 // Ignore this macro use, just return the next token in the current
237 // buffer.
238 bool HadLeadingSpace = Identifier.hasLeadingSpace();
239 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattnera3b605e2008-03-09 03:13:06 +0000241 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattnera3b605e2008-03-09 03:13:06 +0000243 // If the identifier isn't on some OTHER line, inherit the leading
244 // whitespace/first-on-a-line property of this token. This handles
245 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
246 // empty.
247 if (!Identifier.isAtStartOfLine()) {
248 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
249 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
250 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000251 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000252 ++NumFastMacroExpanded;
253 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattnera3b605e2008-03-09 03:13:06 +0000255 } else if (MI->getNumTokens() == 1 &&
256 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000257 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000258 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000259 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000260 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000261
262 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000263 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000264
Chris Lattnera3b605e2008-03-09 03:13:06 +0000265 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
266 // identifier to the expanded token.
267 bool isAtStartOfLine = Identifier.isAtStartOfLine();
268 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Chris Lattnera3b605e2008-03-09 03:13:06 +0000270 // Remember where the token is instantiated.
271 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnera3b605e2008-03-09 03:13:06 +0000273 // Replace the result token.
274 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattnera3b605e2008-03-09 03:13:06 +0000276 // Restore the StartOfLine/LeadingSpace markers.
277 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
278 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000280 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000281 // locations.
282 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000283 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000284 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000285 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattner8ff66de2010-03-26 17:49:16 +0000287 // If this is a disabled macro or #define X X, we must mark the result as
288 // unexpandable.
289 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
290 if (MacroInfo *NewMI = getMacroInfo(NewII))
291 if (!NewMI->isEnabled() || NewMI == MI)
292 Identifier.setFlag(Token::DisableExpand);
293 }
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnera3b605e2008-03-09 03:13:06 +0000295 // Since this is not an identifier token, it can't be macro expanded, so
296 // we're done.
297 ++NumFastMacroExpanded;
298 return false;
299 }
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattnera3b605e2008-03-09 03:13:06 +0000301 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000302 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // Now that the macro is at the top of the include stack, ask the
305 // preprocessor to read the next token from it.
306 Lex(Identifier);
307 return false;
308}
309
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000310/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
311/// token is the '(' of the macro, this method is invoked to read all of the
312/// actual arguments specified for the macro invocation. This returns null on
313/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000314MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000315 MacroInfo *MI,
316 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000317 // The number of fixed arguments to parse.
318 unsigned NumFixedArgsLeft = MI->getNumArgs();
319 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 // Outer loop, while there are more arguments, keep reading them.
322 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000323
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000324 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
325 // an argument value in a macro could expand to ',' or '(' or ')'.
326 LexUnexpandedToken(Tok);
327 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattnera3b605e2008-03-09 03:13:06 +0000329 // ArgTokens - Build up a list of tokens that make up each argument. Each
330 // argument is separated by an EOF token. Use a SmallVector so we can avoid
331 // heap allocations in the common case.
332 llvm::SmallVector<Token, 64> ArgTokens;
333
334 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000335 while (Tok.isNot(tok::r_paren)) {
336 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
337 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000339 unsigned ArgTokenStart = ArgTokens.size();
340 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattnera3b605e2008-03-09 03:13:06 +0000342 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
343 // that we already consumed the first one.
344 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattnera3b605e2008-03-09 03:13:06 +0000346 while (1) {
347 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
348 // an argument value in a macro could expand to ',' or '(' or ')'.
349 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Douglas Gregorf29c5232010-08-24 22:20:20 +0000351 if (Tok.is(tok::code_completion)) {
352 if (CodeComplete)
353 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
354 MI, NumActuals);
355 LexUnexpandedToken(Tok);
356 }
357
Chris Lattnera3b605e2008-03-09 03:13:06 +0000358 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
359 Diag(MacroName, diag::err_unterm_macro_invoc);
360 // Do not lose the EOF/EOM. Return it to the client.
361 MacroName = Tok;
362 return 0;
363 } else if (Tok.is(tok::r_paren)) {
364 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000365 if (NumParens-- == 0) {
366 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000367 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000368 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000369 } else if (Tok.is(tok::l_paren)) {
370 ++NumParens;
371 } else if (Tok.is(tok::comma) && NumParens == 0) {
372 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000373 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000375 if (!isVariadic) break;
376 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000377 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000378 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
379 // If this is a comment token in the argument list and we're just in
380 // -C mode (not -CC mode), discard the comment.
381 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000382 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000383 // Reading macro arguments can cause macros that we are currently
384 // expanding from to be popped off the expansion stack. Doing so causes
385 // them to be reenabled for expansion. Here we record whether any
386 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000387 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000388 // C99 6.10.3.4p2.
389 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
390 if (!MI->isEnabled())
391 Tok.setFlag(Token::DisableExpand);
392 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000393 ArgTokens.push_back(Tok);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000396 // If this was an empty argument list foo(), don't add this as an empty
397 // argument.
398 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
399 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000401 // If this is not a variadic macro, and too many args were specified, emit
402 // an error.
403 if (!isVariadic && NumFixedArgsLeft == 0) {
404 if (ArgTokens.size() != ArgTokenStart)
405 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000407 // Emit the diagnostic at the macro name in case there is a missing ).
408 // Emitting it at the , could be far away from the macro name.
409 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
410 return 0;
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattnera3b605e2008-03-09 03:13:06 +0000413 // Empty arguments are standard in C99 and supported as an extension in
414 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000415 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000416 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Chris Lattnera3b605e2008-03-09 03:13:06 +0000418 // Add a marker EOF token to the end of the token list for this argument.
419 Token EOFTok;
420 EOFTok.startToken();
421 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000422 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000423 EOFTok.setLength(0);
424 ArgTokens.push_back(EOFTok);
425 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000426 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000427 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattnera3b605e2008-03-09 03:13:06 +0000430 // Okay, we either found the r_paren. Check to see if we parsed too few
431 // arguments.
432 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattnera3b605e2008-03-09 03:13:06 +0000434 // See MacroArgs instance var for description of this.
435 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattnera3b605e2008-03-09 03:13:06 +0000437 if (NumActuals < MinArgsExpected) {
438 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000439 if (NumActuals == 0 && MinArgsExpected == 1) {
440 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner97e2de12009-04-20 21:08:10 +0000442 // If there is exactly one argument, and that argument is missing,
443 // then we have an empty "()" argument empty list. This is fine, even if
444 // the macro expects one argument (the argument is just empty).
445 isVarargsElided = MI->isVariadic();
446 } else if (MI->isVariadic() &&
447 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
448 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000449 // Varargs where the named vararg parameter is missing: ok as extension.
450 // #define A(x, ...)
451 // A("blah")
452 Diag(Tok, diag::ext_missing_varargs_arg);
453
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000454 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000455 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000456 // #define A(x, foo...) blah(a, ## foo)
457 // #define B(x, ...) blah(a, ## __VA_ARGS__)
458 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000459 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000460 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000461 } else {
462 // Otherwise, emit the error.
463 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
464 return 0;
465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Chris Lattnera3b605e2008-03-09 03:13:06 +0000467 // Add a marker EOF token to the end of the token list for this argument.
468 SourceLocation EndLoc = Tok.getLocation();
469 Tok.startToken();
470 Tok.setKind(tok::eof);
471 Tok.setLocation(EndLoc);
472 Tok.setLength(0);
473 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000474
475 // If we expect two arguments, add both as empty.
476 if (NumActuals == 0 && MinArgsExpected == 2)
477 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000479 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
480 // Emit the diagnostic at the macro name in case there is a missing ).
481 // Emitting it at the , could be far away from the macro name.
482 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
483 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Jay Foadbeaaccd2009-05-21 09:52:38 +0000486 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000487 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000488}
489
490/// ComputeDATE_TIME - Compute the current time, enter it into the specified
491/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
492/// the identifier tokens inserted.
493static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
494 Preprocessor &PP) {
495 time_t TT = time(0);
496 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Chris Lattnera3b605e2008-03-09 03:13:06 +0000498 static const char * const Months[] = {
499 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
500 };
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000502 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000503#ifdef LLVM_ON_WIN32
504 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
505 TM->tm_year+1900);
506#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000507 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000508 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000509#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner47246be2009-01-26 19:29:26 +0000511 Token TmpTok;
512 TmpTok.startToken();
513 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
514 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000515
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000516#ifdef LLVM_ON_WIN32
517 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
518#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000519 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000520#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000521 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
522 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000523}
524
Chris Lattner148772a2009-06-13 07:13:28 +0000525
526/// HasFeature - Return true if we recognize and implement the specified feature
527/// specified by the identifier.
528static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
529 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Benjamin Kramer32592e82010-01-09 18:53:11 +0000531 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000532 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000533 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000534 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000535 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000536 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000537 .Case("attribute_ns_returns_not_retained", true)
538 .Case("attribute_ns_returns_retained", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000539 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000540 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000541 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000542 .Case("blocks", LangOpts.Blocks)
543 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
544 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
545 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Anders Carlsson37bf9d22010-09-24 21:25:25 +0000546 .Case("cxx_deleted_functions", true) // Accepted as an extension.
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000547 .Case("cxx_exceptions", LangOpts.Exceptions)
548 .Case("cxx_rtti", LangOpts.RTTI)
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000549 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000550 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
Douglas Gregordab60ad2010-10-01 18:44:50 +0000551 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
John McCall48209082010-11-08 19:48:17 +0000552 .Case("enumerator_attributes", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000553 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000554 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000555 .Case("ownership_holds", true)
556 .Case("ownership_returns", true)
557 .Case("ownership_takes", true)
Sebastian Redlf6c09772010-08-31 23:28:47 +0000558 .Case("cxx_inline_namespaces", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000559 //.Case("cxx_concepts", false)
560 //.Case("cxx_lambdas", false)
561 //.Case("cxx_nullptr", false)
562 //.Case("cxx_rvalue_references", false)
563 //.Case("cxx_variadic_templates", false)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000564 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000565 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000566}
567
Anders Carlssoncae50952010-10-20 02:31:43 +0000568/// HasAttribute - Return true if we recognize and implement the attribute
569/// specified by the given identifier.
570static bool HasAttribute(const IdentifierInfo *II) {
571 return llvm::StringSwitch<bool>(II->getName())
572#include "clang/Lex/AttrSpellings.inc"
573 .Default(false);
574}
575
John Thompson92bd8c72009-11-02 22:28:12 +0000576/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
577/// or '__has_include_next("path")' expression.
578/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000579static bool EvaluateHasIncludeCommon(Token &Tok,
580 IdentifierInfo *II, Preprocessor &PP,
581 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000582 SourceLocation LParenLoc;
583
584 // Get '('.
585 PP.LexNonComment(Tok);
586
587 // Ensure we have a '('.
588 if (Tok.isNot(tok::l_paren)) {
589 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
590 return false;
591 }
592
593 // Save '(' location for possible missing ')' message.
594 LParenLoc = Tok.getLocation();
595
596 // Get the file name.
597 PP.getCurrentLexer()->LexIncludeFilename(Tok);
598
599 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000600 llvm::SmallString<128> FilenameBuffer;
601 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000602 SourceLocation EndLoc;
603
John Thompson92bd8c72009-11-02 22:28:12 +0000604 switch (Tok.getKind()) {
605 case tok::eom:
606 // If the token kind is EOM, the error has already been diagnosed.
607 return false;
608
609 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000610 case tok::string_literal: {
611 bool Invalid = false;
612 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
613 if (Invalid)
614 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000615 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000616 }
John Thompson92bd8c72009-11-02 22:28:12 +0000617
618 case tok::less:
619 // This could be a <foo/bar.h> file coming from a macro expansion. In this
620 // case, glue the tokens together into FilenameBuffer and interpret those.
621 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000622 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
John Thompson92bd8c72009-11-02 22:28:12 +0000623 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000624 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000625 break;
626 default:
627 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
628 return false;
629 }
630
Chris Lattnera1394812010-01-10 01:35:12 +0000631 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000632 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
633 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000634 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000635 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000636
637 // Search include directories.
638 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000639 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000640
641 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000642 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000643
644 // Get ')'.
645 PP.LexNonComment(Tok);
646
647 // Ensure we have a trailing ).
648 if (Tok.isNot(tok::r_paren)) {
649 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
650 PP.Diag(LParenLoc, diag::note_matching) << "(";
651 return false;
652 }
653
Chris Lattner3ed572e2011-01-15 06:57:04 +0000654 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000655}
656
657/// EvaluateHasInclude - Process a '__has_include("path")' expression.
658/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000659static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000660 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000661 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000662}
663
664/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
665/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000666static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000667 IdentifierInfo *II, Preprocessor &PP) {
668 // __has_include_next is like __has_include, except that we start
669 // searching after the current found directory. If we can't do this,
670 // issue a diagnostic.
671 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
672 if (PP.isInPrimaryFile()) {
673 Lookup = 0;
674 PP.Diag(Tok, diag::pp_include_next_in_primary);
675 } else if (Lookup == 0) {
676 PP.Diag(Tok, diag::pp_include_next_absolute_path);
677 } else {
678 // Start looking up in the next directory.
679 ++Lookup;
680 }
681
Chris Lattner3ed572e2011-01-15 06:57:04 +0000682 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000683}
Chris Lattner148772a2009-06-13 07:13:28 +0000684
Chris Lattnera3b605e2008-03-09 03:13:06 +0000685/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
686/// as a builtin macro, handle it and return the next token as 'Tok'.
687void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
688 // Figure out which token this is.
689 IdentifierInfo *II = Tok.getIdentifierInfo();
690 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000691
John McCall1ef8a2e2010-08-28 22:34:47 +0000692 // If this is an _Pragma or Microsoft __pragma directive, expand it,
693 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000694 if (II == Ident_Pragma)
695 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000696 else if (II == Ident__pragma) // in non-MS mode this is null
697 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattnera3b605e2008-03-09 03:13:06 +0000699 ++NumBuiltinMacroExpanded;
700
Benjamin Kramerb1765912010-01-27 16:38:22 +0000701 llvm::SmallString<128> TmpBuffer;
702 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000703
704 // Set up the return result.
705 Tok.setIdentifierInfo(0);
706 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattnera3b605e2008-03-09 03:13:06 +0000708 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000709 // C99 6.10.8: "__LINE__: The presumed line number (within the current
710 // source file) of the current source line (an integer constant)". This can
711 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000712 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattnerdff070f2009-04-18 22:29:33 +0000714 // Advance to the location of the first _, this might not be the first byte
715 // of the token if it starts with an escaped newline.
716 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner081927b2009-02-15 21:06:39 +0000718 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
719 // a macro instantiation. This doesn't matter for object-like macros, but
720 // can matter for a function-like macro that expands to contain __LINE__.
721 // Skip down through instantiation points until we find a file loc for the
722 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000723 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000724 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattner1fa49532009-03-08 08:08:45 +0000726 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000727 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000728 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000729 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000730 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
731 // character string literal)". This can be affected by #line.
732 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
733
734 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
735 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000736 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000737 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000738 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000739 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000740 if (PLoc.isInvalid())
741 break;
742
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000743 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000744 }
745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattnera3b605e2008-03-09 03:13:06 +0000747 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000748 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000749 if (PLoc.isValid()) {
750 FN += PLoc.getFilename();
751 Lexer::Stringify(FN);
752 OS << '"' << FN.str() << '"';
753 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000754 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000755 } else if (II == Ident__DATE__) {
756 if (!DATELoc.isValid())
757 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
758 Tok.setKind(tok::string_literal);
759 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000760 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000761 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000762 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000763 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000764 } else if (II == Ident__TIME__) {
765 if (!TIMELoc.isValid())
766 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
767 Tok.setKind(tok::string_literal);
768 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000769 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000770 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000771 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000772 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000773 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000774 // Compute the presumed include depth of this token. This can be affected
775 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000776 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000778 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000779 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000780 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000781 for (; PLoc.isValid(); ++Depth)
782 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
783 }
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Chris Lattner1fa49532009-03-08 08:08:45 +0000785 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000786 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000787 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000788 } else if (II == Ident__TIMESTAMP__) {
789 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
790 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000791
792 // Get the file that we are lexing out of. If we're currently lexing from
793 // a macro, dig into the include stack.
794 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000795 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattnera3b605e2008-03-09 03:13:06 +0000797 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000798 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chris Lattnera3b605e2008-03-09 03:13:06 +0000800 const char *Result;
801 if (CurFile) {
802 time_t TT = CurFile->getModificationTime();
803 struct tm *TM = localtime(&TT);
804 Result = asctime(TM);
805 } else {
806 Result = "??? ??? ?? ??:??:?? ????\n";
807 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000808 // Surround the string with " and strip the trailing newline.
809 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000810 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000811 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000812 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000813 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000814 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000815 } else if (II == Ident__has_feature ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000816 II == Ident__has_builtin ||
817 II == Ident__has_attribute) {
Chris Lattner148772a2009-06-13 07:13:28 +0000818 // The argument to these two builtins should be a parenthesized identifier.
819 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner148772a2009-06-13 07:13:28 +0000821 bool IsValid = false;
822 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Chris Lattner148772a2009-06-13 07:13:28 +0000824 // Read the '('.
825 Lex(Tok);
826 if (Tok.is(tok::l_paren)) {
827 // Read the identifier
828 Lex(Tok);
829 if (Tok.is(tok::identifier)) {
830 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Chris Lattner148772a2009-06-13 07:13:28 +0000832 // Read the ')'.
833 Lex(Tok);
834 if (Tok.is(tok::r_paren))
835 IsValid = true;
836 }
837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner148772a2009-06-13 07:13:28 +0000839 bool Value = false;
840 if (!IsValid)
841 Diag(StartLoc, diag::err_feature_check_malformed);
842 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000843 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000844 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +0000845 } else if (II == Ident__has_attribute)
846 Value = HasAttribute(FeatureII);
847 else {
Chris Lattner148772a2009-06-13 07:13:28 +0000848 assert(II == Ident__has_feature && "Must be feature check");
849 Value = HasFeature(*this, FeatureII);
850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Benjamin Kramerb1765912010-01-27 16:38:22 +0000852 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000853 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000854 } else if (II == Ident__has_include ||
855 II == Ident__has_include_next) {
856 // The argument to these two builtins should be a parenthesized
857 // file name string literal using angle brackets (<>) or
858 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +0000859 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000860 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +0000861 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +0000862 else
Chris Lattner3ed572e2011-01-15 06:57:04 +0000863 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000864 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000865 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000866 } else {
867 assert(0 && "Unknown identifier!");
868 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000869 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000870}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000871
872void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
873 // If the 'used' status changed, and the macro requires 'unused' warning,
874 // remove its SourceLocation from the warn-for-unused-macro locations.
875 if (MI->isWarnIfUnused() && !MI->isUsed())
876 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
877 MI->setIsUsed(true);
878}