blob: 61d528267271c6d012d0f350eeaf328ae5abb508 [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///
50void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000051 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000052 Macros[II] = MI;
53 II->setHasMacroDefinition(true);
Douglas Gregoreee242f2011-10-27 09:33:13 +000054 if (II->isFromAST())
55 II->setChangedSinceDeserialization();
Chris Lattner555589d2009-04-10 21:17:07 +000056 } else if (II->hasMacroDefinition()) {
57 Macros.erase(II);
58 II->setHasMacroDefinition(false);
Douglas Gregoreee242f2011-10-27 09:33:13 +000059 if (II->isFromAST())
60 II->setChangedSinceDeserialization();
Chris Lattnera3b605e2008-03-09 03:13:06 +000061 }
62}
63
64/// RegisterBuiltinMacro - Register the specified identifier in the identifier
65/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000066static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000067 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000068 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattnera3b605e2008-03-09 03:13:06 +000070 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000071 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000072 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000073 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000074 return Id;
75}
76
77
78/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
79/// identifier table.
80void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000081 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
82 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
83 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
84 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
85 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
86 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000087
Chris Lattnera3b605e2008-03-09 03:13:06 +000088 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000089 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
90 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
91 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattner148772a2009-06-13 07:13:28 +000093 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000094 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
Peter Collingbournec1b5fa42011-05-13 20:54:45 +000095 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
John Thompson92bd8c72009-11-02 22:28:12 +000096 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000097 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000098 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
99 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Ted Kremenekd7681502011-10-12 19:46:30 +0000100 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
John McCall1ef8a2e2010-08-28 22:34:47 +0000101
102 // Microsoft Extensions.
Francois Pichet62ec1f22011-09-17 17:15:52 +0000103 if (Features.MicrosoftExt)
John McCall1ef8a2e2010-08-28 22:34:47 +0000104 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
105 else
106 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000107}
108
109/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
110/// in its expansion, currently expands to that token literally.
111static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
112 const IdentifierInfo *MacroIdent,
113 Preprocessor &PP) {
114 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
115
116 // If the token isn't an identifier, it's always literally expanded.
117 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Argyrios Kyrtzidis373cb782011-12-17 04:13:31 +0000119 // If the information about this identifier is out of date, update it from
120 // the external source.
121 if (II->isOutOfDate())
122 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
123
Chris Lattnera3b605e2008-03-09 03:13:06 +0000124 // If the identifier is a macro, and if that macro is enabled, it may be
125 // expanded so it's not a trivial expansion.
126 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
127 // Fast expanding "#define X X" is ok, because X would be disabled.
128 II != MacroIdent)
129 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Chris Lattnera3b605e2008-03-09 03:13:06 +0000131 // If this is an object-like macro invocation, it is safe to trivially expand
132 // it.
133 if (MI->isObjectLike()) return true;
134
135 // If this is a function-like macro invocation, it's safe to trivially expand
136 // as long as the identifier is not a macro argument.
137 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
138 I != E; ++I)
139 if (*I == II)
140 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Chris Lattnera3b605e2008-03-09 03:13:06 +0000142 return true;
143}
144
145
146/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
147/// lexed is a '('. If so, consume the token and return true, if not, this
148/// method should have no observable side-effect on the lexed tokens.
149bool Preprocessor::isNextPPTokenLParen() {
150 // Do some quick tests for rejection cases.
151 unsigned Val;
152 if (CurLexer)
153 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000154 else if (CurPTHLexer)
155 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000156 else
157 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Chris Lattnera3b605e2008-03-09 03:13:06 +0000159 if (Val == 2) {
160 // We have run off the end. If it's a source file we don't
161 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
162 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000163 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000164 return false;
165 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
166 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
167 if (Entry.TheLexer)
168 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000169 else if (Entry.ThePTHLexer)
170 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000171 else
172 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Chris Lattnera3b605e2008-03-09 03:13:06 +0000174 if (Val != 2)
175 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Chris Lattnera3b605e2008-03-09 03:13:06 +0000177 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000178 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000179 return false;
180 }
181 }
182
183 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
184 // have found something that isn't a '(' or we found the end of the
185 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000186 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000187}
188
189/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
190/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000191bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000192 MacroInfo *MI) {
Douglas Gregor13678972010-01-26 19:43:43 +0000193 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000194 // then the macro could expand to different things in other contexts, we need
195 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000196 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattnera3b605e2008-03-09 03:13:06 +0000198 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
199 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000200 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
201 Identifier.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000202 ExpandBuiltinMacro(Identifier);
203 return false;
204 }
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattnera3b605e2008-03-09 03:13:06 +0000206 /// Args - If this is a function-like macro expansion, this contains,
207 /// for each macro argument, the list of tokens that were provided to the
208 /// invocation.
209 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000211 // Remember where the end of the expansion occurred. For an object-like
Chris Lattnere7fb4842009-02-15 20:52:18 +0000212 // macro, this is the identifier. For a function-like macro, this is the ')'.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000213 SourceLocation ExpansionEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Chris Lattnera3b605e2008-03-09 03:13:06 +0000215 // If this is a function-like macro, read the arguments.
216 if (MI->isFunctionLike()) {
217 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000218 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000219 if (!isNextPPTokenLParen())
220 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattnera3b605e2008-03-09 03:13:06 +0000222 // Remember that we are now parsing the arguments to a macro invocation.
223 // Preprocessor directives used inside macro arguments are not portable, and
224 // this enables the warning.
225 InMacroArgs = true;
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000226 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattnera3b605e2008-03-09 03:13:06 +0000228 // Finished parsing args.
229 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattnera3b605e2008-03-09 03:13:06 +0000231 // If there was an error parsing the arguments, bail out.
232 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattnera3b605e2008-03-09 03:13:06 +0000234 ++NumFnMacroExpanded;
235 } else {
236 ++NumMacroExpanded;
237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattnera3b605e2008-03-09 03:13:06 +0000239 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000240 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000242 // Remember where the token is expanded.
243 SourceLocation ExpandLoc = Identifier.getLocation();
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000244
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000245 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
246 SourceRange(ExpandLoc, ExpansionEnd));
247
248 // If we started lexing a macro, enter the macro expansion body.
249
Chris Lattnera3b605e2008-03-09 03:13:06 +0000250 // If this macro expands to no tokens, don't bother to push it onto the
251 // expansion stack, only to take it right back off.
252 if (MI->getNumTokens() == 0) {
253 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000254 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Chris Lattnera3b605e2008-03-09 03:13:06 +0000256 // Ignore this macro use, just return the next token in the current
257 // buffer.
258 bool HadLeadingSpace = Identifier.hasLeadingSpace();
259 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattnera3b605e2008-03-09 03:13:06 +0000261 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattnera3b605e2008-03-09 03:13:06 +0000263 // If the identifier isn't on some OTHER line, inherit the leading
264 // whitespace/first-on-a-line property of this token. This handles
265 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
266 // empty.
267 if (!Identifier.isAtStartOfLine()) {
268 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
269 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
270 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000271 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000272 ++NumFastMacroExpanded;
273 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattnera3b605e2008-03-09 03:13:06 +0000275 } else if (MI->getNumTokens() == 1 &&
276 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000277 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000278 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000279 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000280 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000281
282 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000283 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000284
Chris Lattnera3b605e2008-03-09 03:13:06 +0000285 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
286 // identifier to the expanded token.
287 bool isAtStartOfLine = Identifier.isAtStartOfLine();
288 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnera3b605e2008-03-09 03:13:06 +0000290 // Replace the result token.
291 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattnera3b605e2008-03-09 03:13:06 +0000293 // Restore the StartOfLine/LeadingSpace markers.
294 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
295 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000297 // Update the tokens location to include both its expansion and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000298 // locations.
299 SourceLocation Loc =
Chandler Carruthbf340e42011-07-26 03:03:05 +0000300 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
301 ExpansionEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000302 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner8ff66de2010-03-26 17:49:16 +0000304 // If this is a disabled macro or #define X X, we must mark the result as
305 // unexpandable.
306 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
307 if (MacroInfo *NewMI = getMacroInfo(NewII))
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000308 if (!NewMI->isEnabled() || NewMI == MI) {
Chris Lattner8ff66de2010-03-26 17:49:16 +0000309 Identifier.setFlag(Token::DisableExpand);
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000310 Diag(Identifier, diag::pp_disabled_macro_expansion);
311 }
Chris Lattner8ff66de2010-03-26 17:49:16 +0000312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattnera3b605e2008-03-09 03:13:06 +0000314 // Since this is not an identifier token, it can't be macro expanded, so
315 // we're done.
316 ++NumFastMacroExpanded;
317 return false;
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattnera3b605e2008-03-09 03:13:06 +0000320 // Start expanding the macro.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000321 EnterMacro(Identifier, ExpansionEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattnera3b605e2008-03-09 03:13:06 +0000323 // Now that the macro is at the top of the include stack, ask the
324 // preprocessor to read the next token from it.
325 Lex(Identifier);
326 return false;
327}
328
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000329/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
330/// token is the '(' of the macro, this method is invoked to read all of the
331/// actual arguments specified for the macro invocation. This returns null on
332/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000333MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000334 MacroInfo *MI,
335 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000336 // The number of fixed arguments to parse.
337 unsigned NumFixedArgsLeft = MI->getNumArgs();
338 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattnera3b605e2008-03-09 03:13:06 +0000340 // Outer loop, while there are more arguments, keep reading them.
341 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000342
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000343 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
344 // an argument value in a macro could expand to ',' or '(' or ')'.
345 LexUnexpandedToken(Tok);
346 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattnera3b605e2008-03-09 03:13:06 +0000348 // ArgTokens - Build up a list of tokens that make up each argument. Each
349 // argument is separated by an EOF token. Use a SmallVector so we can avoid
350 // heap allocations in the common case.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000351 SmallVector<Token, 64> ArgTokens;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000352
353 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000354 while (Tok.isNot(tok::r_paren)) {
355 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
356 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000358 unsigned ArgTokenStart = ArgTokens.size();
359 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattnera3b605e2008-03-09 03:13:06 +0000361 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
362 // that we already consumed the first one.
363 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Chris Lattnera3b605e2008-03-09 03:13:06 +0000365 while (1) {
366 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
367 // an argument value in a macro could expand to ',' or '(' or ')'.
368 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Peter Collingbourne84021552011-02-28 02:37:51 +0000370 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000371 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000372 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000373 MacroName = Tok;
374 return 0;
375 } else if (Tok.is(tok::r_paren)) {
376 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000377 if (NumParens-- == 0) {
378 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000379 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000380 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000381 } else if (Tok.is(tok::l_paren)) {
382 ++NumParens;
383 } else if (Tok.is(tok::comma) && NumParens == 0) {
384 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000385 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000386 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000387 if (!isVariadic) break;
388 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000389 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000390 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
391 // If this is a comment token in the argument list and we're just in
392 // -C mode (not -CC mode), discard the comment.
393 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000394 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000395 // Reading macro arguments can cause macros that we are currently
396 // expanding from to be popped off the expansion stack. Doing so causes
397 // them to be reenabled for expansion. Here we record whether any
398 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000399 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400 // C99 6.10.3.4p2.
401 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
402 if (!MI->isEnabled())
403 Tok.setFlag(Token::DisableExpand);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000404 } else if (Tok.is(tok::code_completion)) {
405 if (CodeComplete)
406 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
407 MI, NumActuals);
408 // Don't mark that we reached the code-completion point because the
409 // parser is going to handle the token and there will be another
410 // code-completion callback.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000411 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000412
Chris Lattnera3b605e2008-03-09 03:13:06 +0000413 ArgTokens.push_back(Tok);
414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000416 // If this was an empty argument list foo(), don't add this as an empty
417 // argument.
418 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
419 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000420
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000421 // If this is not a variadic macro, and too many args were specified, emit
422 // an error.
423 if (!isVariadic && NumFixedArgsLeft == 0) {
424 if (ArgTokens.size() != ArgTokenStart)
425 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000427 // Emit the diagnostic at the macro name in case there is a missing ).
428 // Emitting it at the , could be far away from the macro name.
429 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
430 return 0;
431 }
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner32c13882011-04-22 23:25:09 +0000433 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000434 // other modes.
Richard Smith661a9962011-10-15 01:18:56 +0000435 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
436 Diag(Tok, Features.CPlusPlus0x ?
437 diag::warn_cxx98_compat_empty_fnmacro_arg :
438 diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattnera3b605e2008-03-09 03:13:06 +0000440 // Add a marker EOF token to the end of the token list for this argument.
441 Token EOFTok;
442 EOFTok.startToken();
443 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000444 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000445 EOFTok.setLength(0);
446 ArgTokens.push_back(EOFTok);
447 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000448 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000449 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattnera3b605e2008-03-09 03:13:06 +0000452 // Okay, we either found the r_paren. Check to see if we parsed too few
453 // arguments.
454 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Chris Lattnera3b605e2008-03-09 03:13:06 +0000456 // See MacroArgs instance var for description of this.
457 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnera3b605e2008-03-09 03:13:06 +0000459 if (NumActuals < MinArgsExpected) {
460 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000461 if (NumActuals == 0 && MinArgsExpected == 1) {
462 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattner97e2de12009-04-20 21:08:10 +0000464 // If there is exactly one argument, and that argument is missing,
465 // then we have an empty "()" argument empty list. This is fine, even if
466 // the macro expects one argument (the argument is just empty).
467 isVarargsElided = MI->isVariadic();
468 } else if (MI->isVariadic() &&
469 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
470 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000471 // Varargs where the named vararg parameter is missing: ok as extension.
472 // #define A(x, ...)
473 // A("blah")
474 Diag(Tok, diag::ext_missing_varargs_arg);
475
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000476 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000477 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000478 // #define A(x, foo...) blah(a, ## foo)
479 // #define B(x, ...) blah(a, ## __VA_ARGS__)
480 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000481 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000482 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000483 } else {
484 // Otherwise, emit the error.
485 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
486 return 0;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattnera3b605e2008-03-09 03:13:06 +0000489 // Add a marker EOF token to the end of the token list for this argument.
490 SourceLocation EndLoc = Tok.getLocation();
491 Tok.startToken();
492 Tok.setKind(tok::eof);
493 Tok.setLocation(EndLoc);
494 Tok.setLength(0);
495 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000496
497 // If we expect two arguments, add both as empty.
498 if (NumActuals == 0 && MinArgsExpected == 2)
499 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000501 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
502 // Emit the diagnostic at the macro name in case there is a missing ).
503 // Emitting it at the , could be far away from the macro name.
504 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
505 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
David Blaikied7bb6a02011-09-22 02:03:12 +0000508 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000509}
510
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000511/// \brief Keeps macro expanded tokens for TokenLexers.
512//
513/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
514/// going to lex in the cache and when it finishes the tokens are removed
515/// from the end of the cache.
516Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000517 ArrayRef<Token> tokens) {
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000518 assert(tokLexer);
519 if (tokens.empty())
520 return 0;
521
522 size_t newIndex = MacroExpandedTokens.size();
523 bool cacheNeedsToGrow = tokens.size() >
524 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
525 MacroExpandedTokens.append(tokens.begin(), tokens.end());
526
527 if (cacheNeedsToGrow) {
528 // Go through all the TokenLexers whose 'Tokens' pointer points in the
529 // buffer and update the pointers to the (potential) new buffer array.
530 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
531 TokenLexer *prevLexer;
532 size_t tokIndex;
533 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
534 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
535 }
536 }
537
538 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
539 return MacroExpandedTokens.data() + newIndex;
540}
541
542void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
543 assert(!MacroExpandingLexersStack.empty());
544 size_t tokIndex = MacroExpandingLexersStack.back().second;
545 assert(tokIndex < MacroExpandedTokens.size());
546 // Pop the cached macro expanded tokens from the end.
547 MacroExpandedTokens.resize(tokIndex);
548 MacroExpandingLexersStack.pop_back();
549}
550
Chris Lattnera3b605e2008-03-09 03:13:06 +0000551/// ComputeDATE_TIME - Compute the current time, enter it into the specified
552/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
553/// the identifier tokens inserted.
554static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
555 Preprocessor &PP) {
556 time_t TT = time(0);
557 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattnera3b605e2008-03-09 03:13:06 +0000559 static const char * const Months[] = {
560 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
561 };
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000563 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000564#ifdef LLVM_ON_WIN32
565 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
566 TM->tm_year+1900);
567#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000568 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000569 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000570#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Chris Lattner47246be2009-01-26 19:29:26 +0000572 Token TmpTok;
573 TmpTok.startToken();
574 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
575 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000576
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000577#ifdef LLVM_ON_WIN32
578 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
579#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000580 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000581#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000582 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
583 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000584}
585
Chris Lattner148772a2009-06-13 07:13:28 +0000586
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000587/// HasFeature - Return true if we recognize and implement the feature
588/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000589static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
590 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Benjamin Kramer32592e82010-01-09 18:53:11 +0000592 return llvm::StringSwitch<bool>(II->getName())
Kostya Serebryanyb6196882011-11-22 01:28:36 +0000593 .Case("address_sanitizer", LangOpts.AddressSanitizer)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000594 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000595 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000596 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000597 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000598 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000599 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000600 .Case("attribute_ns_returns_not_retained", true)
601 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000602 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000603 .Case("attribute_ns_consumed", true)
604 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000605 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000606 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000607 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000608 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000609 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000610 .Case("cxx_exceptions", LangOpts.Exceptions)
611 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000612 .Case("enumerator_attributes", true)
John McCallf85e1932011-06-15 23:02:42 +0000613 // Objective-C features
614 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
615 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
616 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
John McCall9f084a32011-07-06 00:26:06 +0000617 LangOpts.ObjCRuntimeHasWeak)
Douglas Gregor5471bc82011-09-08 17:18:35 +0000618 .Case("objc_fixed_enum", LangOpts.ObjC2)
Douglas Gregore97179c2011-09-08 01:46:34 +0000619 .Case("objc_instancetype", LangOpts.ObjC2)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000620 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000621 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000622 .Case("ownership_holds", true)
623 .Case("ownership_returns", true)
624 .Case("ownership_takes", true)
John McCalleb2ac8b2011-10-18 21:18:53 +0000625 .Case("arc_cf_code_audited", true)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000626 // C11 features
627 .Case("c_alignas", LangOpts.C11)
628 .Case("c_generic_selections", LangOpts.C11)
629 .Case("c_static_assert", LangOpts.C11)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000630 // C++0x features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000631 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000632 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000633 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000634 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000635 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000636 //.Case("cxx_constexpr", false);
Douglas Gregorc78e2592011-01-26 15:36:03 +0000637 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000638 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorf695a692011-11-01 01:19:34 +0000639 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000640 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000641 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000642 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
Sean Hunte1f6dea2011-08-07 00:34:32 +0000643 //.Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
Sebastian Redl74e611a2011-09-04 18:14:28 +0000644 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000645 //.Case("cxx_inheriting_constructors", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000646 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000647 //.Case("cxx_lambdas", false)
Douglas Gregorece38942011-08-29 17:28:38 +0000648 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000649 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000650 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000651 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000652 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000653 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000654 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000655 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
656 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
657 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
658 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000659 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000660 //.Case("cxx_unrestricted_unions", false)
661 //.Case("cxx_user_literals", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000662 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000663 // Type traits
664 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
665 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
666 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
667 .Case("has_trivial_assign", LangOpts.CPlusPlus)
668 .Case("has_trivial_copy", LangOpts.CPlusPlus)
669 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
670 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
671 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
672 .Case("is_abstract", LangOpts.CPlusPlus)
673 .Case("is_base_of", LangOpts.CPlusPlus)
674 .Case("is_class", LangOpts.CPlusPlus)
675 .Case("is_convertible_to", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000676 // __is_empty is available only if the horrible
677 // "struct __is_empty" parsing hack hasn't been needed in this
678 // translation unit. If it has, __is_empty reverts to a normal
679 // identifier and __has_feature(is_empty) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000680 .Case("is_empty",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000681 LangOpts.CPlusPlus &&
682 PP.getIdentifierInfo("__is_empty")->getTokenID()
683 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000684 .Case("is_enum", LangOpts.CPlusPlus)
Douglas Gregor5e9392b2011-12-03 18:14:24 +0000685 .Case("is_final", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000686 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000687 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000688 // __is_pod is available only if the horrible
689 // "struct __is_pod" parsing hack hasn't been needed in this
690 // translation unit. If it has, __is_pod reverts to a normal
691 // identifier and __has_feature(is_pod) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000692 .Case("is_pod",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000693 LangOpts.CPlusPlus &&
694 PP.getIdentifierInfo("__is_pod")->getTokenID()
695 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000696 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000697 .Case("is_trivial", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000698 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000699 .Case("is_union", LangOpts.CPlusPlus)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000700 .Case("tls", PP.getTargetInfo().isTLSSupported())
Sean Hunt858a3252011-07-18 17:08:00 +0000701 .Case("underlying_type", LangOpts.CPlusPlus)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000702 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000703}
704
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000705/// HasExtension - Return true if we recognize and implement the feature
706/// specified by the identifier, either as an extension or a standard language
707/// feature.
708static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
709 if (HasFeature(PP, II))
710 return true;
711
712 // If the use of an extension results in an error diagnostic, extensions are
713 // effectively unavailable, so just return false here.
David Blaikied6471f72011-09-25 23:23:43 +0000714 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
715 DiagnosticsEngine::Ext_Error)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000716 return false;
717
718 const LangOptions &LangOpts = PP.getLangOptions();
719
720 // Because we inherit the feature list from HasFeature, this string switch
721 // must be less restrictive than HasFeature's.
722 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000723 // C11 features supported by other languages as extensions.
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000724 .Case("c_alignas", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000725 .Case("c_generic_selections", true)
726 .Case("c_static_assert", true)
727 // C++0x features supported by other languages as extensions.
728 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000729 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000730 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000731 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000732 .Case("cxx_override_control", LangOpts.CPlusPlus)
Richard Smith7640c002011-09-06 18:03:41 +0000733 .Case("cxx_range_for", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000734 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
735 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
736 .Default(false);
737}
738
Anders Carlssoncae50952010-10-20 02:31:43 +0000739/// HasAttribute - Return true if we recognize and implement the attribute
740/// specified by the given identifier.
741static bool HasAttribute(const IdentifierInfo *II) {
742 return llvm::StringSwitch<bool>(II->getName())
743#include "clang/Lex/AttrSpellings.inc"
744 .Default(false);
745}
746
John Thompson92bd8c72009-11-02 22:28:12 +0000747/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
748/// or '__has_include_next("path")' expression.
749/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000750static bool EvaluateHasIncludeCommon(Token &Tok,
751 IdentifierInfo *II, Preprocessor &PP,
752 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000753 SourceLocation LParenLoc;
754
755 // Get '('.
756 PP.LexNonComment(Tok);
757
758 // Ensure we have a '('.
759 if (Tok.isNot(tok::l_paren)) {
760 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
761 return false;
762 }
763
764 // Save '(' location for possible missing ')' message.
765 LParenLoc = Tok.getLocation();
766
767 // Get the file name.
768 PP.getCurrentLexer()->LexIncludeFilename(Tok);
769
770 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000771 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000772 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000773 SourceLocation EndLoc;
774
John Thompson92bd8c72009-11-02 22:28:12 +0000775 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000776 case tok::eod:
777 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000778 return false;
779
780 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000781 case tok::string_literal: {
782 bool Invalid = false;
783 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
784 if (Invalid)
785 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000786 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000787 }
John Thompson92bd8c72009-11-02 22:28:12 +0000788
789 case tok::less:
790 // This could be a <foo/bar.h> file coming from a macro expansion. In this
791 // case, glue the tokens together into FilenameBuffer and interpret those.
792 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000793 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000794 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000795 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000796 break;
797 default:
798 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
799 return false;
800 }
801
Chris Lattnera1394812010-01-10 01:35:12 +0000802 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000803 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
804 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000805 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000806 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000807
808 // Search include directories.
809 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000810 const FileEntry *File =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000811 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000812
813 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000814 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000815
816 // Get ')'.
817 PP.LexNonComment(Tok);
818
819 // Ensure we have a trailing ).
820 if (Tok.isNot(tok::r_paren)) {
821 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
822 PP.Diag(LParenLoc, diag::note_matching) << "(";
823 return false;
824 }
825
Chris Lattner3ed572e2011-01-15 06:57:04 +0000826 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000827}
828
829/// EvaluateHasInclude - Process a '__has_include("path")' expression.
830/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000831static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000832 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000833 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000834}
835
836/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
837/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000838static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000839 IdentifierInfo *II, Preprocessor &PP) {
840 // __has_include_next is like __has_include, except that we start
841 // searching after the current found directory. If we can't do this,
842 // issue a diagnostic.
843 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
844 if (PP.isInPrimaryFile()) {
845 Lookup = 0;
846 PP.Diag(Tok, diag::pp_include_next_in_primary);
847 } else if (Lookup == 0) {
848 PP.Diag(Tok, diag::pp_include_next_absolute_path);
849 } else {
850 // Start looking up in the next directory.
851 ++Lookup;
852 }
853
Chris Lattner3ed572e2011-01-15 06:57:04 +0000854 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000855}
Chris Lattner148772a2009-06-13 07:13:28 +0000856
Chris Lattnera3b605e2008-03-09 03:13:06 +0000857/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
858/// as a builtin macro, handle it and return the next token as 'Tok'.
859void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
860 // Figure out which token this is.
861 IdentifierInfo *II = Tok.getIdentifierInfo();
862 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000863
John McCall1ef8a2e2010-08-28 22:34:47 +0000864 // If this is an _Pragma or Microsoft __pragma directive, expand it,
865 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000866 if (II == Ident_Pragma)
867 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000868 else if (II == Ident__pragma) // in non-MS mode this is null
869 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Chris Lattnera3b605e2008-03-09 03:13:06 +0000871 ++NumBuiltinMacroExpanded;
872
Benjamin Kramerb1765912010-01-27 16:38:22 +0000873 llvm::SmallString<128> TmpBuffer;
874 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000875
876 // Set up the return result.
877 Tok.setIdentifierInfo(0);
878 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Chris Lattnera3b605e2008-03-09 03:13:06 +0000880 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000881 // C99 6.10.8: "__LINE__: The presumed line number (within the current
882 // source file) of the current source line (an integer constant)". This can
883 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000884 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Chris Lattnerdff070f2009-04-18 22:29:33 +0000886 // Advance to the location of the first _, this might not be the first byte
887 // of the token if it starts with an escaped newline.
888 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattner081927b2009-02-15 21:06:39 +0000890 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000891 // a macro expansion. This doesn't matter for object-like macros, but
Chris Lattner081927b2009-02-15 21:06:39 +0000892 // can matter for a function-like macro that expands to contain __LINE__.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000893 // Skip down through expansion points until we find a file loc for the
894 // end of the expansion history.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000895 Loc = SourceMgr.getExpansionRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000896 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattner1fa49532009-03-08 08:08:45 +0000898 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000899 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000900 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000901 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000902 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
903 // character string literal)". This can be affected by #line.
904 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
905
906 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
907 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000908 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000909 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000910 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000911 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000912 if (PLoc.isInvalid())
913 break;
914
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000915 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000916 }
917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Chris Lattnera3b605e2008-03-09 03:13:06 +0000919 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000920 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000921 if (PLoc.isValid()) {
922 FN += PLoc.getFilename();
923 Lexer::Stringify(FN);
924 OS << '"' << FN.str() << '"';
925 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000926 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000927 } else if (II == Ident__DATE__) {
928 if (!DATELoc.isValid())
929 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
930 Tok.setKind(tok::string_literal);
931 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000932 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
933 Tok.getLocation(),
934 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000935 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000936 } else if (II == Ident__TIME__) {
937 if (!TIMELoc.isValid())
938 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
939 Tok.setKind(tok::string_literal);
940 Tok.setLength(strlen("\"hh:mm:ss\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000941 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
942 Tok.getLocation(),
943 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000944 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000945 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000946 // Compute the presumed include depth of this token. This can be affected
947 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000948 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000950 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000951 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000952 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000953 for (; PLoc.isValid(); ++Depth)
954 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
955 }
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Chris Lattner1fa49532009-03-08 08:08:45 +0000957 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000958 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000959 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000960 } else if (II == Ident__TIMESTAMP__) {
961 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
962 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000963
964 // Get the file that we are lexing out of. If we're currently lexing from
965 // a macro, dig into the include stack.
966 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000967 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattnera3b605e2008-03-09 03:13:06 +0000969 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000970 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattnera3b605e2008-03-09 03:13:06 +0000972 const char *Result;
973 if (CurFile) {
974 time_t TT = CurFile->getModificationTime();
975 struct tm *TM = localtime(&TT);
976 Result = asctime(TM);
977 } else {
978 Result = "??? ??? ?? ??:??:?? ????\n";
979 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000980 // Surround the string with " and strip the trailing newline.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000981 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000982 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000983 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000984 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000985 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000986 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000987 } else if (II == Ident__has_feature ||
988 II == Ident__has_extension ||
989 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000990 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000991 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +0000992 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner148772a2009-06-13 07:13:28 +0000994 bool IsValid = false;
995 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner148772a2009-06-13 07:13:28 +0000997 // Read the '('.
998 Lex(Tok);
999 if (Tok.is(tok::l_paren)) {
1000 // Read the identifier
1001 Lex(Tok);
1002 if (Tok.is(tok::identifier)) {
1003 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner148772a2009-06-13 07:13:28 +00001005 // Read the ')'.
1006 Lex(Tok);
1007 if (Tok.is(tok::r_paren))
1008 IsValid = true;
1009 }
1010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner148772a2009-06-13 07:13:28 +00001012 bool Value = false;
1013 if (!IsValid)
1014 Diag(StartLoc, diag::err_feature_check_malformed);
1015 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +00001016 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +00001017 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +00001018 } else if (II == Ident__has_attribute)
1019 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001020 else if (II == Ident__has_extension)
1021 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +00001022 else {
Chris Lattner148772a2009-06-13 07:13:28 +00001023 assert(II == Ident__has_feature && "Must be feature check");
1024 Value = HasFeature(*this, FeatureII);
1025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Benjamin Kramerb1765912010-01-27 16:38:22 +00001027 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +00001028 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +00001029 } else if (II == Ident__has_include ||
1030 II == Ident__has_include_next) {
1031 // The argument to these two builtins should be a parenthesized
1032 // file name string literal using angle brackets (<>) or
1033 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +00001034 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001035 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +00001036 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +00001037 else
Chris Lattner3ed572e2011-01-15 06:57:04 +00001038 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +00001039 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001040 Tok.setKind(tok::numeric_constant);
Ted Kremenekd7681502011-10-12 19:46:30 +00001041 } else if (II == Ident__has_warning) {
1042 // The argument should be a parenthesized string literal.
1043 // The argument to these builtins should be a parenthesized identifier.
1044 SourceLocation StartLoc = Tok.getLocation();
1045 bool IsValid = false;
1046 bool Value = false;
1047 // Read the '('.
1048 Lex(Tok);
1049 do {
1050 if (Tok.is(tok::l_paren)) {
1051 // Read the string.
1052 Lex(Tok);
1053
1054 // We need at least one string literal.
1055 if (!Tok.is(tok::string_literal)) {
1056 StartLoc = Tok.getLocation();
1057 IsValid = false;
1058 // Eat tokens until ')'.
1059 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1060 break;
1061 }
1062
1063 // String concatenation allows multiple strings, which can even come
1064 // from macro expansion.
1065 SmallVector<Token, 4> StrToks;
1066 while (Tok.is(tok::string_literal)) {
1067 StrToks.push_back(Tok);
1068 LexUnexpandedToken(Tok);
1069 }
1070
1071 // Is the end a ')'?
1072 if (!(IsValid = Tok.is(tok::r_paren)))
1073 break;
1074
1075 // Concatenate and parse the strings.
1076 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1077 assert(Literal.isAscii() && "Didn't allow wide strings in");
1078 if (Literal.hadError)
1079 break;
1080 if (Literal.Pascal) {
1081 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1082 break;
1083 }
1084
1085 StringRef WarningName(Literal.GetString());
1086
1087 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1088 WarningName[1] != 'W') {
1089 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1090 break;
1091 }
1092
1093 // Finally, check if the warning flags maps to a diagnostic group.
1094 // We construct a SmallVector here to talk to getDiagnosticIDs().
1095 // Although we don't use the result, this isn't a hot path, and not
1096 // worth special casing.
1097 llvm::SmallVector<diag::kind, 10> Diags;
1098 Value = !getDiagnostics().getDiagnosticIDs()->
1099 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1100 }
1101 } while (false);
1102
1103 if (!IsValid)
1104 Diag(StartLoc, diag::err_warning_check_malformed);
1105
1106 OS << (int)Value;
1107 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001108 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001109 llvm_unreachable("Unknown identifier!");
Chris Lattnera3b605e2008-03-09 03:13:06 +00001110 }
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001111 CreateString(OS.str().data(), OS.str().size(), Tok,
1112 Tok.getLocation(), Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +00001113}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001114
1115void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1116 // If the 'used' status changed, and the macro requires 'unused' warning,
1117 // remove its SourceLocation from the warn-for-unused-macro locations.
1118 if (MI->isWarnIfUnused() && !MI->isUsed())
1119 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1120 MI->setIsUsed(true);
1121}