blob: bc346927027ee2f3b7c6f29d37d8cb45874fcdfe [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"
Ted Kremenekd7681502011-10-12 19:46:30 +000024#include "clang/Lex/LiteralSupport.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000025#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +000026#include "llvm/ADT/STLExtras.h"
Dylan Noblesmith1770e0d2011-12-22 22:49:47 +000027#include "llvm/Config/llvm-config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000028#include "llvm/Support/raw_ostream.h"
David Blaikie9fe8c742011-09-23 05:35:21 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner3daed522009-03-02 22:20:04 +000030#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000031#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000032using namespace clang;
33
Douglas Gregor295a2a62010-10-30 00:23:06 +000034MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
35 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
36
37 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
38 = Macros.find(II);
39 if (Pos == Macros.end()) {
40 // Load this macro from the external source.
41 getExternalSource()->LoadMacroDefinition(II);
42 Pos = Macros.find(II);
43 }
44 assert(Pos != Macros.end() && "Identifier macro info is missing!");
45 return Pos->second;
46}
47
Chris Lattnera3b605e2008-03-09 03:13:06 +000048/// setMacroInfo - Specify a macro for this identifier.
49///
Douglas Gregor5d5051f2012-01-24 15:24:38 +000050void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
51 bool LoadedFromAST) {
Chris Lattner555589d2009-04-10 21:17:07 +000052 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000053 Macros[II] = MI;
54 II->setHasMacroDefinition(true);
Douglas Gregor5d5051f2012-01-24 15:24:38 +000055 if (II->isFromAST() && !LoadedFromAST)
Douglas Gregoreee242f2011-10-27 09:33:13 +000056 II->setChangedSinceDeserialization();
Chris Lattner555589d2009-04-10 21:17:07 +000057 } else if (II->hasMacroDefinition()) {
58 Macros.erase(II);
59 II->setHasMacroDefinition(false);
Douglas Gregor5d5051f2012-01-24 15:24:38 +000060 if (II->isFromAST() && !LoadedFromAST)
Douglas Gregoreee242f2011-10-27 09:33:13 +000061 II->setChangedSinceDeserialization();
Chris Lattnera3b605e2008-03-09 03:13:06 +000062 }
63}
64
65/// RegisterBuiltinMacro - Register the specified identifier in the identifier
66/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000067static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000068 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000069 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattnera3b605e2008-03-09 03:13:06 +000071 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000072 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000073 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000074 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000075 return Id;
76}
77
78
79/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
80/// identifier table.
81void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000082 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
83 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
84 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
85 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
86 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
87 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattnera3b605e2008-03-09 03:13:06 +000089 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000090 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
91 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
92 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner148772a2009-06-13 07:13:28 +000094 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000095 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
Peter Collingbournec1b5fa42011-05-13 20:54:45 +000096 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
John Thompson92bd8c72009-11-02 22:28:12 +000097 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000098 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000099 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
100 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Ted Kremenekd7681502011-10-12 19:46:30 +0000101 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
John McCall1ef8a2e2010-08-28 22:34:47 +0000102
103 // Microsoft Extensions.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000104 if (Features.MicrosoftExt)
John McCall1ef8a2e2010-08-28 22:34:47 +0000105 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
106 else
107 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000108}
109
110/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
111/// in its expansion, currently expands to that token literally.
112static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
113 const IdentifierInfo *MacroIdent,
114 Preprocessor &PP) {
115 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
116
117 // If the token isn't an identifier, it's always literally expanded.
118 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Argyrios Kyrtzidis373cb782011-12-17 04:13:31 +0000120 // If the information about this identifier is out of date, update it from
121 // the external source.
122 if (II->isOutOfDate())
123 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
124
Chris Lattnera3b605e2008-03-09 03:13:06 +0000125 // If the identifier is a macro, and if that macro is enabled, it may be
126 // expanded so it's not a trivial expansion.
127 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
128 // Fast expanding "#define X X" is ok, because X would be disabled.
129 II != MacroIdent)
130 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Chris Lattnera3b605e2008-03-09 03:13:06 +0000132 // If this is an object-like macro invocation, it is safe to trivially expand
133 // it.
134 if (MI->isObjectLike()) return true;
135
136 // If this is a function-like macro invocation, it's safe to trivially expand
137 // as long as the identifier is not a macro argument.
138 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
139 I != E; ++I)
140 if (*I == II)
141 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattnera3b605e2008-03-09 03:13:06 +0000143 return true;
144}
145
146
147/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
148/// lexed is a '('. If so, consume the token and return true, if not, this
149/// method should have no observable side-effect on the lexed tokens.
150bool Preprocessor::isNextPPTokenLParen() {
151 // Do some quick tests for rejection cases.
152 unsigned Val;
153 if (CurLexer)
154 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000155 else if (CurPTHLexer)
156 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 else
158 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 if (Val == 2) {
161 // We have run off the end. If it's a source file we don't
162 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
163 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000164 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 return false;
166 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
167 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
168 if (Entry.TheLexer)
169 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000170 else if (Entry.ThePTHLexer)
171 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000172 else
173 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnera3b605e2008-03-09 03:13:06 +0000175 if (Val != 2)
176 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000179 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000180 return false;
181 }
182 }
183
184 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
185 // have found something that isn't a '(' or we found the end of the
186 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000187 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188}
189
190/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
191/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000192bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000193 MacroInfo *MI) {
Douglas Gregor13678972010-01-26 19:43:43 +0000194 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000195 // then the macro could expand to different things in other contexts, we need
196 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000197 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattnera3b605e2008-03-09 03:13:06 +0000199 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
200 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000201 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
202 Identifier.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000203 ExpandBuiltinMacro(Identifier);
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnera3b605e2008-03-09 03:13:06 +0000207 /// Args - If this is a function-like macro expansion, this contains,
208 /// for each macro argument, the list of tokens that were provided to the
209 /// invocation.
210 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000212 // Remember where the end of the expansion occurred. For an object-like
Chris Lattnere7fb4842009-02-15 20:52:18 +0000213 // macro, this is the identifier. For a function-like macro, this is the ')'.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000214 SourceLocation ExpansionEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattnera3b605e2008-03-09 03:13:06 +0000216 // If this is a function-like macro, read the arguments.
217 if (MI->isFunctionLike()) {
218 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000219 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 if (!isNextPPTokenLParen())
221 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnera3b605e2008-03-09 03:13:06 +0000223 // Remember that we are now parsing the arguments to a macro invocation.
224 // Preprocessor directives used inside macro arguments are not portable, and
225 // this enables the warning.
226 InMacroArgs = true;
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000227 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnera3b605e2008-03-09 03:13:06 +0000229 // Finished parsing args.
230 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnera3b605e2008-03-09 03:13:06 +0000232 // If there was an error parsing the arguments, bail out.
233 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattnera3b605e2008-03-09 03:13:06 +0000235 ++NumFnMacroExpanded;
236 } else {
237 ++NumMacroExpanded;
238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnera3b605e2008-03-09 03:13:06 +0000240 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000241 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000243 // Remember where the token is expanded.
244 SourceLocation ExpandLoc = Identifier.getLocation();
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000245
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000246 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
247 SourceRange(ExpandLoc, ExpansionEnd));
248
249 // If we started lexing a macro, enter the macro expansion body.
250
Chris Lattnera3b605e2008-03-09 03:13:06 +0000251 // If this macro expands to no tokens, don't bother to push it onto the
252 // expansion stack, only to take it right back off.
253 if (MI->getNumTokens() == 0) {
254 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000255 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattnera3b605e2008-03-09 03:13:06 +0000257 // Ignore this macro use, just return the next token in the current
258 // buffer.
259 bool HadLeadingSpace = Identifier.hasLeadingSpace();
260 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattnera3b605e2008-03-09 03:13:06 +0000262 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnera3b605e2008-03-09 03:13:06 +0000264 // If the identifier isn't on some OTHER line, inherit the leading
265 // whitespace/first-on-a-line property of this token. This handles
266 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
267 // empty.
268 if (!Identifier.isAtStartOfLine()) {
269 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
270 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
271 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000272 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000273 ++NumFastMacroExpanded;
274 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattnera3b605e2008-03-09 03:13:06 +0000276 } else if (MI->getNumTokens() == 1 &&
277 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000278 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000279 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000280 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000281 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000282
283 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000284 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000285
Chris Lattnera3b605e2008-03-09 03:13:06 +0000286 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
287 // identifier to the expanded token.
288 bool isAtStartOfLine = Identifier.isAtStartOfLine();
289 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnera3b605e2008-03-09 03:13:06 +0000291 // Replace the result token.
292 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnera3b605e2008-03-09 03:13:06 +0000294 // Restore the StartOfLine/LeadingSpace markers.
295 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
296 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000298 // Update the tokens location to include both its expansion and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000299 // locations.
300 SourceLocation Loc =
Chandler Carruthbf340e42011-07-26 03:03:05 +0000301 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
302 ExpansionEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000303 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner8ff66de2010-03-26 17:49:16 +0000305 // If this is a disabled macro or #define X X, we must mark the result as
306 // unexpandable.
307 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
308 if (MacroInfo *NewMI = getMacroInfo(NewII))
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000309 if (!NewMI->isEnabled() || NewMI == MI) {
Chris Lattner8ff66de2010-03-26 17:49:16 +0000310 Identifier.setFlag(Token::DisableExpand);
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000311 Diag(Identifier, diag::pp_disabled_macro_expansion);
312 }
Chris Lattner8ff66de2010-03-26 17:49:16 +0000313 }
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattnera3b605e2008-03-09 03:13:06 +0000315 // Since this is not an identifier token, it can't be macro expanded, so
316 // we're done.
317 ++NumFastMacroExpanded;
318 return false;
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 // Start expanding the macro.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000322 EnterMacro(Identifier, ExpansionEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnera3b605e2008-03-09 03:13:06 +0000324 // Now that the macro is at the top of the include stack, ask the
325 // preprocessor to read the next token from it.
326 Lex(Identifier);
327 return false;
328}
329
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000330/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
331/// token is the '(' of the macro, this method is invoked to read all of the
332/// actual arguments specified for the macro invocation. This returns null on
333/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000334MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000335 MacroInfo *MI,
336 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000337 // The number of fixed arguments to parse.
338 unsigned NumFixedArgsLeft = MI->getNumArgs();
339 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Chris Lattnera3b605e2008-03-09 03:13:06 +0000341 // Outer loop, while there are more arguments, keep reading them.
342 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000343
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000344 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
345 // an argument value in a macro could expand to ',' or '(' or ')'.
346 LexUnexpandedToken(Tok);
347 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattnera3b605e2008-03-09 03:13:06 +0000349 // ArgTokens - Build up a list of tokens that make up each argument. Each
350 // argument is separated by an EOF token. Use a SmallVector so we can avoid
351 // heap allocations in the common case.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000352 SmallVector<Token, 64> ArgTokens;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000353
354 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000355 while (Tok.isNot(tok::r_paren)) {
356 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
357 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000359 unsigned ArgTokenStart = ArgTokens.size();
360 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattnera3b605e2008-03-09 03:13:06 +0000362 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
363 // that we already consumed the first one.
364 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Chris Lattnera3b605e2008-03-09 03:13:06 +0000366 while (1) {
367 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
368 // an argument value in a macro could expand to ',' or '(' or ')'.
369 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Peter Collingbourne84021552011-02-28 02:37:51 +0000371 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000372 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000373 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000374 MacroName = Tok;
375 return 0;
376 } else if (Tok.is(tok::r_paren)) {
377 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000378 if (NumParens-- == 0) {
379 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000380 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000381 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000382 } else if (Tok.is(tok::l_paren)) {
383 ++NumParens;
384 } else if (Tok.is(tok::comma) && NumParens == 0) {
385 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000386 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000387 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000388 if (!isVariadic) break;
389 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000390 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000391 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
392 // If this is a comment token in the argument list and we're just in
393 // -C mode (not -CC mode), discard the comment.
394 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000395 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000396 // Reading macro arguments can cause macros that we are currently
397 // expanding from to be popped off the expansion stack. Doing so causes
398 // them to be reenabled for expansion. Here we record whether any
399 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000400 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000401 // C99 6.10.3.4p2.
402 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
403 if (!MI->isEnabled())
404 Tok.setFlag(Token::DisableExpand);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000405 } else if (Tok.is(tok::code_completion)) {
406 if (CodeComplete)
407 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
408 MI, NumActuals);
409 // Don't mark that we reached the code-completion point because the
410 // parser is going to handle the token and there will be another
411 // code-completion callback.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000412 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000413
Chris Lattnera3b605e2008-03-09 03:13:06 +0000414 ArgTokens.push_back(Tok);
415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000417 // If this was an empty argument list foo(), don't add this as an empty
418 // argument.
419 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
420 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000421
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000422 // If this is not a variadic macro, and too many args were specified, emit
423 // an error.
424 if (!isVariadic && NumFixedArgsLeft == 0) {
425 if (ArgTokens.size() != ArgTokenStart)
426 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000428 // Emit the diagnostic at the macro name in case there is a missing ).
429 // Emitting it at the , could be far away from the macro name.
430 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
431 return 0;
432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner32c13882011-04-22 23:25:09 +0000434 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000435 // other modes.
Richard Smith661a9962011-10-15 01:18:56 +0000436 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
437 Diag(Tok, Features.CPlusPlus0x ?
438 diag::warn_cxx98_compat_empty_fnmacro_arg :
439 diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattnera3b605e2008-03-09 03:13:06 +0000441 // Add a marker EOF token to the end of the token list for this argument.
442 Token EOFTok;
443 EOFTok.startToken();
444 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000445 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000446 EOFTok.setLength(0);
447 ArgTokens.push_back(EOFTok);
448 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000449 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000450 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000451 }
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattnera3b605e2008-03-09 03:13:06 +0000453 // Okay, we either found the r_paren. Check to see if we parsed too few
454 // arguments.
455 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattnera3b605e2008-03-09 03:13:06 +0000457 // See MacroArgs instance var for description of this.
458 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Chris Lattnera3b605e2008-03-09 03:13:06 +0000460 if (NumActuals < MinArgsExpected) {
461 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000462 if (NumActuals == 0 && MinArgsExpected == 1) {
463 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattner97e2de12009-04-20 21:08:10 +0000465 // If there is exactly one argument, and that argument is missing,
466 // then we have an empty "()" argument empty list. This is fine, even if
467 // the macro expects one argument (the argument is just empty).
468 isVarargsElided = MI->isVariadic();
469 } else if (MI->isVariadic() &&
470 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
471 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000472 // Varargs where the named vararg parameter is missing: ok as extension.
473 // #define A(x, ...)
474 // A("blah")
475 Diag(Tok, diag::ext_missing_varargs_arg);
476
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000477 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000478 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000479 // #define A(x, foo...) blah(a, ## foo)
480 // #define B(x, ...) blah(a, ## __VA_ARGS__)
481 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000482 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000483 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000484 } else {
485 // Otherwise, emit the error.
486 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
487 return 0;
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattnera3b605e2008-03-09 03:13:06 +0000490 // Add a marker EOF token to the end of the token list for this argument.
491 SourceLocation EndLoc = Tok.getLocation();
492 Tok.startToken();
493 Tok.setKind(tok::eof);
494 Tok.setLocation(EndLoc);
495 Tok.setLength(0);
496 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000497
498 // If we expect two arguments, add both as empty.
499 if (NumActuals == 0 && MinArgsExpected == 2)
500 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000502 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
503 // Emit the diagnostic at the macro name in case there is a missing ).
504 // Emitting it at the , could be far away from the macro name.
505 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
506 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000507 }
Mike Stump1eb44332009-09-09 15:08:12 +0000508
David Blaikied7bb6a02011-09-22 02:03:12 +0000509 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000510}
511
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000512/// \brief Keeps macro expanded tokens for TokenLexers.
513//
514/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
515/// going to lex in the cache and when it finishes the tokens are removed
516/// from the end of the cache.
517Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000518 ArrayRef<Token> tokens) {
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000519 assert(tokLexer);
520 if (tokens.empty())
521 return 0;
522
523 size_t newIndex = MacroExpandedTokens.size();
524 bool cacheNeedsToGrow = tokens.size() >
525 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
526 MacroExpandedTokens.append(tokens.begin(), tokens.end());
527
528 if (cacheNeedsToGrow) {
529 // Go through all the TokenLexers whose 'Tokens' pointer points in the
530 // buffer and update the pointers to the (potential) new buffer array.
531 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
532 TokenLexer *prevLexer;
533 size_t tokIndex;
534 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
535 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
536 }
537 }
538
539 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
540 return MacroExpandedTokens.data() + newIndex;
541}
542
543void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
544 assert(!MacroExpandingLexersStack.empty());
545 size_t tokIndex = MacroExpandingLexersStack.back().second;
546 assert(tokIndex < MacroExpandedTokens.size());
547 // Pop the cached macro expanded tokens from the end.
548 MacroExpandedTokens.resize(tokIndex);
549 MacroExpandingLexersStack.pop_back();
550}
551
Chris Lattnera3b605e2008-03-09 03:13:06 +0000552/// ComputeDATE_TIME - Compute the current time, enter it into the specified
553/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
554/// the identifier tokens inserted.
555static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
556 Preprocessor &PP) {
557 time_t TT = time(0);
558 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattnera3b605e2008-03-09 03:13:06 +0000560 static const char * const Months[] = {
561 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
562 };
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000564 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000565#ifdef LLVM_ON_WIN32
566 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
567 TM->tm_year+1900);
568#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000569 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000570 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000571#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattner47246be2009-01-26 19:29:26 +0000573 Token TmpTok;
574 TmpTok.startToken();
575 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
576 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000577
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000578#ifdef LLVM_ON_WIN32
579 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
580#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000581 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000582#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000583 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
584 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000585}
586
Chris Lattner148772a2009-06-13 07:13:28 +0000587
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000588/// HasFeature - Return true if we recognize and implement the feature
589/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000590static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
591 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Benjamin Kramer32592e82010-01-09 18:53:11 +0000593 return llvm::StringSwitch<bool>(II->getName())
Kostya Serebryanyb6196882011-11-22 01:28:36 +0000594 .Case("address_sanitizer", LangOpts.AddressSanitizer)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000595 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000596 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000597 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000598 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000599 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000600 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000601 .Case("attribute_ns_returns_not_retained", true)
602 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000603 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000604 .Case("attribute_ns_consumed", true)
605 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000606 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000607 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000608 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000609 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000610 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000611 .Case("cxx_exceptions", LangOpts.Exceptions)
612 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000613 .Case("enumerator_attributes", true)
John McCallf85e1932011-06-15 23:02:42 +0000614 // Objective-C features
615 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
616 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
617 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
John McCall9f084a32011-07-06 00:26:06 +0000618 LangOpts.ObjCRuntimeHasWeak)
Fariborz Jahanianf83a6152012-02-02 00:15:51 +0000619 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
Douglas Gregor5471bc82011-09-08 17:18:35 +0000620 .Case("objc_fixed_enum", LangOpts.ObjC2)
Douglas Gregore97179c2011-09-08 01:46:34 +0000621 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorbd507c52012-01-04 21:16:09 +0000622 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000623 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000624 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000625 .Case("ownership_holds", true)
626 .Case("ownership_returns", true)
627 .Case("ownership_takes", true)
John McCalleb2ac8b2011-10-18 21:18:53 +0000628 .Case("arc_cf_code_audited", true)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000629 // C11 features
630 .Case("c_alignas", LangOpts.C11)
David Chisnall7a7ee302012-01-16 17:27:18 +0000631 .Case("c_atomic", LangOpts.C11)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000632 .Case("c_generic_selections", LangOpts.C11)
633 .Case("c_static_assert", LangOpts.C11)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000634 // C++0x features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000635 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000636 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000637 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
David Chisnall7a7ee302012-01-16 17:27:18 +0000638 .Case("cxx_atomic", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000639 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000640 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Richard Smithb5216aa2012-02-14 22:56:17 +0000641 .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000642 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000643 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorf695a692011-11-01 01:19:34 +0000644 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000645 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000646 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000647 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
Sean Hunte1f6dea2011-08-07 00:34:32 +0000648 //.Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
Sebastian Redl74e611a2011-09-04 18:14:28 +0000649 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000650 //.Case("cxx_inheriting_constructors", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000651 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Douglas Gregor7c07e962012-02-23 03:02:32 +0000652 .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000653 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000654 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000655 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000656 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000657 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000658 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000659 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000660 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
661 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
662 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
663 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000664 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000665 //.Case("cxx_unrestricted_unions", false)
666 //.Case("cxx_user_literals", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000667 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000668 // Type traits
669 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
670 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
671 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
672 .Case("has_trivial_assign", LangOpts.CPlusPlus)
673 .Case("has_trivial_copy", LangOpts.CPlusPlus)
674 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
675 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
676 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
677 .Case("is_abstract", LangOpts.CPlusPlus)
678 .Case("is_base_of", LangOpts.CPlusPlus)
679 .Case("is_class", LangOpts.CPlusPlus)
680 .Case("is_convertible_to", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000681 // __is_empty is available only if the horrible
682 // "struct __is_empty" parsing hack hasn't been needed in this
683 // translation unit. If it has, __is_empty reverts to a normal
684 // identifier and __has_feature(is_empty) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000685 .Case("is_empty",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000686 LangOpts.CPlusPlus &&
687 PP.getIdentifierInfo("__is_empty")->getTokenID()
688 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000689 .Case("is_enum", LangOpts.CPlusPlus)
Douglas Gregor5e9392b2011-12-03 18:14:24 +0000690 .Case("is_final", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000691 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000692 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000693 // __is_pod is available only if the horrible
694 // "struct __is_pod" parsing hack hasn't been needed in this
695 // translation unit. If it has, __is_pod reverts to a normal
696 // identifier and __has_feature(is_pod) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000697 .Case("is_pod",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000698 LangOpts.CPlusPlus &&
699 PP.getIdentifierInfo("__is_pod")->getTokenID()
700 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000701 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000702 .Case("is_trivial", LangOpts.CPlusPlus)
Douglas Gregor25d0a0f2012-02-23 07:33:15 +0000703 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
Douglas Gregor4ca8ac22012-02-24 07:38:34 +0000704 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000705 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000706 .Case("is_union", LangOpts.CPlusPlus)
Douglas Gregorbd507c52012-01-04 21:16:09 +0000707 .Case("modules", LangOpts.Modules)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000708 .Case("tls", PP.getTargetInfo().isTLSSupported())
Sean Hunt858a3252011-07-18 17:08:00 +0000709 .Case("underlying_type", LangOpts.CPlusPlus)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000710 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000711}
712
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000713/// HasExtension - Return true if we recognize and implement the feature
714/// specified by the identifier, either as an extension or a standard language
715/// feature.
716static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
717 if (HasFeature(PP, II))
718 return true;
719
720 // If the use of an extension results in an error diagnostic, extensions are
721 // effectively unavailable, so just return false here.
David Blaikied6471f72011-09-25 23:23:43 +0000722 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
723 DiagnosticsEngine::Ext_Error)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000724 return false;
725
726 const LangOptions &LangOpts = PP.getLangOptions();
727
728 // Because we inherit the feature list from HasFeature, this string switch
729 // must be less restrictive than HasFeature's.
730 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000731 // C11 features supported by other languages as extensions.
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000732 .Case("c_alignas", true)
David Chisnall7a7ee302012-01-16 17:27:18 +0000733 .Case("c_atomic", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000734 .Case("c_generic_selections", true)
735 .Case("c_static_assert", true)
736 // C++0x features supported by other languages as extensions.
David Chisnall7a7ee302012-01-16 17:27:18 +0000737 .Case("cxx_atomic", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000738 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000739 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000740 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000741 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000742 .Case("cxx_override_control", LangOpts.CPlusPlus)
Richard Smith7640c002011-09-06 18:03:41 +0000743 .Case("cxx_range_for", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000744 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
745 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
746 .Default(false);
747}
748
Anders Carlssoncae50952010-10-20 02:31:43 +0000749/// HasAttribute - Return true if we recognize and implement the attribute
750/// specified by the given identifier.
751static bool HasAttribute(const IdentifierInfo *II) {
752 return llvm::StringSwitch<bool>(II->getName())
753#include "clang/Lex/AttrSpellings.inc"
754 .Default(false);
755}
756
John Thompson92bd8c72009-11-02 22:28:12 +0000757/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
758/// or '__has_include_next("path")' expression.
759/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000760static bool EvaluateHasIncludeCommon(Token &Tok,
761 IdentifierInfo *II, Preprocessor &PP,
762 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000763 SourceLocation LParenLoc;
764
765 // Get '('.
766 PP.LexNonComment(Tok);
767
768 // Ensure we have a '('.
769 if (Tok.isNot(tok::l_paren)) {
770 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
771 return false;
772 }
773
774 // Save '(' location for possible missing ')' message.
775 LParenLoc = Tok.getLocation();
776
777 // Get the file name.
778 PP.getCurrentLexer()->LexIncludeFilename(Tok);
779
780 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000781 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000782 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000783 SourceLocation EndLoc;
784
John Thompson92bd8c72009-11-02 22:28:12 +0000785 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000786 case tok::eod:
787 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000788 return false;
789
790 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000791 case tok::string_literal: {
792 bool Invalid = false;
793 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
794 if (Invalid)
795 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000796 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000797 }
John Thompson92bd8c72009-11-02 22:28:12 +0000798
799 case tok::less:
800 // This could be a <foo/bar.h> file coming from a macro expansion. In this
801 // case, glue the tokens together into FilenameBuffer and interpret those.
802 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000803 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000804 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000805 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000806 break;
807 default:
808 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
809 return false;
810 }
811
Chris Lattnera1394812010-01-10 01:35:12 +0000812 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000813 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
814 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000815 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000816 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000817
818 // Search include directories.
819 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000820 const FileEntry *File =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000821 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000822
823 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000824 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000825
826 // Get ')'.
827 PP.LexNonComment(Tok);
828
829 // Ensure we have a trailing ).
830 if (Tok.isNot(tok::r_paren)) {
831 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
832 PP.Diag(LParenLoc, diag::note_matching) << "(";
833 return false;
834 }
835
Chris Lattner3ed572e2011-01-15 06:57:04 +0000836 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000837}
838
839/// EvaluateHasInclude - Process a '__has_include("path")' expression.
840/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000841static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000842 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000843 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000844}
845
846/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
847/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000848static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000849 IdentifierInfo *II, Preprocessor &PP) {
850 // __has_include_next is like __has_include, except that we start
851 // searching after the current found directory. If we can't do this,
852 // issue a diagnostic.
853 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
854 if (PP.isInPrimaryFile()) {
855 Lookup = 0;
856 PP.Diag(Tok, diag::pp_include_next_in_primary);
857 } else if (Lookup == 0) {
858 PP.Diag(Tok, diag::pp_include_next_absolute_path);
859 } else {
860 // Start looking up in the next directory.
861 ++Lookup;
862 }
863
Chris Lattner3ed572e2011-01-15 06:57:04 +0000864 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000865}
Chris Lattner148772a2009-06-13 07:13:28 +0000866
Chris Lattnera3b605e2008-03-09 03:13:06 +0000867/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
868/// as a builtin macro, handle it and return the next token as 'Tok'.
869void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
870 // Figure out which token this is.
871 IdentifierInfo *II = Tok.getIdentifierInfo();
872 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000873
John McCall1ef8a2e2010-08-28 22:34:47 +0000874 // If this is an _Pragma or Microsoft __pragma directive, expand it,
875 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000876 if (II == Ident_Pragma)
877 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000878 else if (II == Ident__pragma) // in non-MS mode this is null
879 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattnera3b605e2008-03-09 03:13:06 +0000881 ++NumBuiltinMacroExpanded;
882
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000883 SmallString<128> TmpBuffer;
Benjamin Kramerb1765912010-01-27 16:38:22 +0000884 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000885
886 // Set up the return result.
887 Tok.setIdentifierInfo(0);
888 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattnera3b605e2008-03-09 03:13:06 +0000890 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000891 // C99 6.10.8: "__LINE__: The presumed line number (within the current
892 // source file) of the current source line (an integer constant)". This can
893 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000894 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattnerdff070f2009-04-18 22:29:33 +0000896 // Advance to the location of the first _, this might not be the first byte
897 // of the token if it starts with an escaped newline.
898 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner081927b2009-02-15 21:06:39 +0000900 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000901 // a macro expansion. This doesn't matter for object-like macros, but
Chris Lattner081927b2009-02-15 21:06:39 +0000902 // can matter for a function-like macro that expands to contain __LINE__.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000903 // Skip down through expansion points until we find a file loc for the
904 // end of the expansion history.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000905 Loc = SourceMgr.getExpansionRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000906 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Chris Lattner1fa49532009-03-08 08:08:45 +0000908 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000909 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000910 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000911 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000912 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
913 // character string literal)". This can be affected by #line.
914 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
915
916 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
917 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000918 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000919 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000920 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000921 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000922 if (PLoc.isInvalid())
923 break;
924
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000925 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000926 }
927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Chris Lattnera3b605e2008-03-09 03:13:06 +0000929 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000930 SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000931 if (PLoc.isValid()) {
932 FN += PLoc.getFilename();
933 Lexer::Stringify(FN);
934 OS << '"' << FN.str() << '"';
935 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000936 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000937 } else if (II == Ident__DATE__) {
938 if (!DATELoc.isValid())
939 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
940 Tok.setKind(tok::string_literal);
941 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000942 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
943 Tok.getLocation(),
944 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000945 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000946 } else if (II == Ident__TIME__) {
947 if (!TIMELoc.isValid())
948 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
949 Tok.setKind(tok::string_literal);
950 Tok.setLength(strlen("\"hh:mm:ss\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000951 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
952 Tok.getLocation(),
953 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000954 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000955 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000956 // Compute the presumed include depth of this token. This can be affected
957 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000958 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000960 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000961 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000962 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000963 for (; PLoc.isValid(); ++Depth)
964 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattner1fa49532009-03-08 08:08:45 +0000967 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000968 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000969 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000970 } else if (II == Ident__TIMESTAMP__) {
971 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
972 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000973
974 // Get the file that we are lexing out of. If we're currently lexing from
975 // a macro, dig into the include stack.
976 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000977 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattnera3b605e2008-03-09 03:13:06 +0000979 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000980 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattnera3b605e2008-03-09 03:13:06 +0000982 const char *Result;
983 if (CurFile) {
984 time_t TT = CurFile->getModificationTime();
985 struct tm *TM = localtime(&TT);
986 Result = asctime(TM);
987 } else {
988 Result = "??? ??? ?? ??:??:?? ????\n";
989 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000990 // Surround the string with " and strip the trailing newline.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000991 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000992 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000993 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000994 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000995 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000996 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000997 } else if (II == Ident__has_feature ||
998 II == Ident__has_extension ||
999 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +00001000 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001001 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +00001002 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner148772a2009-06-13 07:13:28 +00001004 bool IsValid = false;
1005 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Chris Lattner148772a2009-06-13 07:13:28 +00001007 // Read the '('.
1008 Lex(Tok);
1009 if (Tok.is(tok::l_paren)) {
1010 // Read the identifier
1011 Lex(Tok);
1012 if (Tok.is(tok::identifier)) {
1013 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Chris Lattner148772a2009-06-13 07:13:28 +00001015 // Read the ')'.
1016 Lex(Tok);
1017 if (Tok.is(tok::r_paren))
1018 IsValid = true;
1019 }
1020 }
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner148772a2009-06-13 07:13:28 +00001022 bool Value = false;
1023 if (!IsValid)
1024 Diag(StartLoc, diag::err_feature_check_malformed);
1025 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +00001026 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +00001027 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +00001028 } else if (II == Ident__has_attribute)
1029 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001030 else if (II == Ident__has_extension)
1031 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +00001032 else {
Chris Lattner148772a2009-06-13 07:13:28 +00001033 assert(II == Ident__has_feature && "Must be feature check");
1034 Value = HasFeature(*this, FeatureII);
1035 }
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Benjamin Kramerb1765912010-01-27 16:38:22 +00001037 OS << (int)Value;
Chris Lattner28310922012-01-31 18:53:44 +00001038 if (IsValid)
1039 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +00001040 } else if (II == Ident__has_include ||
1041 II == Ident__has_include_next) {
1042 // The argument to these two builtins should be a parenthesized
1043 // file name string literal using angle brackets (<>) or
1044 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +00001045 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001046 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +00001047 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +00001048 else
Chris Lattner3ed572e2011-01-15 06:57:04 +00001049 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +00001050 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001051 Tok.setKind(tok::numeric_constant);
Ted Kremenekd7681502011-10-12 19:46:30 +00001052 } else if (II == Ident__has_warning) {
1053 // The argument should be a parenthesized string literal.
1054 // The argument to these builtins should be a parenthesized identifier.
1055 SourceLocation StartLoc = Tok.getLocation();
1056 bool IsValid = false;
1057 bool Value = false;
1058 // Read the '('.
1059 Lex(Tok);
1060 do {
1061 if (Tok.is(tok::l_paren)) {
1062 // Read the string.
1063 Lex(Tok);
1064
1065 // We need at least one string literal.
1066 if (!Tok.is(tok::string_literal)) {
1067 StartLoc = Tok.getLocation();
1068 IsValid = false;
1069 // Eat tokens until ')'.
1070 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1071 break;
1072 }
1073
1074 // String concatenation allows multiple strings, which can even come
1075 // from macro expansion.
1076 SmallVector<Token, 4> StrToks;
1077 while (Tok.is(tok::string_literal)) {
1078 StrToks.push_back(Tok);
1079 LexUnexpandedToken(Tok);
1080 }
1081
1082 // Is the end a ')'?
1083 if (!(IsValid = Tok.is(tok::r_paren)))
1084 break;
1085
1086 // Concatenate and parse the strings.
1087 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1088 assert(Literal.isAscii() && "Didn't allow wide strings in");
1089 if (Literal.hadError)
1090 break;
1091 if (Literal.Pascal) {
1092 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1093 break;
1094 }
1095
1096 StringRef WarningName(Literal.GetString());
1097
1098 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1099 WarningName[1] != 'W') {
1100 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1101 break;
1102 }
1103
1104 // Finally, check if the warning flags maps to a diagnostic group.
1105 // We construct a SmallVector here to talk to getDiagnosticIDs().
1106 // Although we don't use the result, this isn't a hot path, and not
1107 // worth special casing.
1108 llvm::SmallVector<diag::kind, 10> Diags;
1109 Value = !getDiagnostics().getDiagnosticIDs()->
1110 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1111 }
1112 } while (false);
1113
1114 if (!IsValid)
1115 Diag(StartLoc, diag::err_warning_check_malformed);
1116
1117 OS << (int)Value;
1118 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001119 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001120 llvm_unreachable("Unknown identifier!");
Chris Lattnera3b605e2008-03-09 03:13:06 +00001121 }
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001122 CreateString(OS.str().data(), OS.str().size(), Tok,
1123 Tok.getLocation(), Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +00001124}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001125
1126void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1127 // If the 'used' status changed, and the macro requires 'unused' warning,
1128 // remove its SourceLocation from the warn-for-unused-macro locations.
1129 if (MI->isWarnIfUnused() && !MI->isUsed())
1130 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1131 MI->setIsUsed(true);
1132}