blob: a0d203f8c8cc67cb6fdf45a944483d08bbf6c8e9 [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))
308 if (!NewMI->isEnabled() || NewMI == MI)
309 Identifier.setFlag(Token::DisableExpand);
310 }
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312 // Since this is not an identifier token, it can't be macro expanded, so
313 // we're done.
314 ++NumFastMacroExpanded;
315 return false;
316 }
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Chris Lattnera3b605e2008-03-09 03:13:06 +0000318 // Start expanding the macro.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000319 EnterMacro(Identifier, ExpansionEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 // Now that the macro is at the top of the include stack, ask the
322 // preprocessor to read the next token from it.
323 Lex(Identifier);
324 return false;
325}
326
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000327/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
328/// token is the '(' of the macro, this method is invoked to read all of the
329/// actual arguments specified for the macro invocation. This returns null on
330/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000331MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000332 MacroInfo *MI,
333 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000334 // The number of fixed arguments to parse.
335 unsigned NumFixedArgsLeft = MI->getNumArgs();
336 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattnera3b605e2008-03-09 03:13:06 +0000338 // Outer loop, while there are more arguments, keep reading them.
339 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000340
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000341 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
342 // an argument value in a macro could expand to ',' or '(' or ')'.
343 LexUnexpandedToken(Tok);
344 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattnera3b605e2008-03-09 03:13:06 +0000346 // ArgTokens - Build up a list of tokens that make up each argument. Each
347 // argument is separated by an EOF token. Use a SmallVector so we can avoid
348 // heap allocations in the common case.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 SmallVector<Token, 64> ArgTokens;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000350
351 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000352 while (Tok.isNot(tok::r_paren)) {
353 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
354 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000356 unsigned ArgTokenStart = ArgTokens.size();
357 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattnera3b605e2008-03-09 03:13:06 +0000359 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
360 // that we already consumed the first one.
361 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattnera3b605e2008-03-09 03:13:06 +0000363 while (1) {
364 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
365 // an argument value in a macro could expand to ',' or '(' or ')'.
366 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Peter Collingbourne84021552011-02-28 02:37:51 +0000368 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000369 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000370 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000371 MacroName = Tok;
372 return 0;
373 } else if (Tok.is(tok::r_paren)) {
374 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000375 if (NumParens-- == 0) {
376 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000377 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000378 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000379 } else if (Tok.is(tok::l_paren)) {
380 ++NumParens;
381 } else if (Tok.is(tok::comma) && NumParens == 0) {
382 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000383 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000384 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000385 if (!isVariadic) break;
386 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000387 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000388 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
389 // If this is a comment token in the argument list and we're just in
390 // -C mode (not -CC mode), discard the comment.
391 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000392 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000393 // Reading macro arguments can cause macros that we are currently
394 // expanding from to be popped off the expansion stack. Doing so causes
395 // them to be reenabled for expansion. Here we record whether any
396 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000397 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000398 // C99 6.10.3.4p2.
399 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
400 if (!MI->isEnabled())
401 Tok.setFlag(Token::DisableExpand);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000402 } else if (Tok.is(tok::code_completion)) {
403 if (CodeComplete)
404 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
405 MI, NumActuals);
406 // Don't mark that we reached the code-completion point because the
407 // parser is going to handle the token and there will be another
408 // code-completion callback.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000409 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000410
Chris Lattnera3b605e2008-03-09 03:13:06 +0000411 ArgTokens.push_back(Tok);
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000414 // If this was an empty argument list foo(), don't add this as an empty
415 // argument.
416 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
417 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000418
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000419 // If this is not a variadic macro, and too many args were specified, emit
420 // an error.
421 if (!isVariadic && NumFixedArgsLeft == 0) {
422 if (ArgTokens.size() != ArgTokenStart)
423 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000425 // Emit the diagnostic at the macro name in case there is a missing ).
426 // Emitting it at the , could be far away from the macro name.
427 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
428 return 0;
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner32c13882011-04-22 23:25:09 +0000431 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000432 // other modes.
Richard Smith661a9962011-10-15 01:18:56 +0000433 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
434 Diag(Tok, Features.CPlusPlus0x ?
435 diag::warn_cxx98_compat_empty_fnmacro_arg :
436 diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattnera3b605e2008-03-09 03:13:06 +0000438 // Add a marker EOF token to the end of the token list for this argument.
439 Token EOFTok;
440 EOFTok.startToken();
441 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000442 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000443 EOFTok.setLength(0);
444 ArgTokens.push_back(EOFTok);
445 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000446 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000447 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000448 }
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattnera3b605e2008-03-09 03:13:06 +0000450 // Okay, we either found the r_paren. Check to see if we parsed too few
451 // arguments.
452 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Chris Lattnera3b605e2008-03-09 03:13:06 +0000454 // See MacroArgs instance var for description of this.
455 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattnera3b605e2008-03-09 03:13:06 +0000457 if (NumActuals < MinArgsExpected) {
458 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000459 if (NumActuals == 0 && MinArgsExpected == 1) {
460 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner97e2de12009-04-20 21:08:10 +0000462 // If there is exactly one argument, and that argument is missing,
463 // then we have an empty "()" argument empty list. This is fine, even if
464 // the macro expects one argument (the argument is just empty).
465 isVarargsElided = MI->isVariadic();
466 } else if (MI->isVariadic() &&
467 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
468 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000469 // Varargs where the named vararg parameter is missing: ok as extension.
470 // #define A(x, ...)
471 // A("blah")
472 Diag(Tok, diag::ext_missing_varargs_arg);
473
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000474 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000475 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000476 // #define A(x, foo...) blah(a, ## foo)
477 // #define B(x, ...) blah(a, ## __VA_ARGS__)
478 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000479 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000480 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000481 } else {
482 // Otherwise, emit the error.
483 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
484 return 0;
485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattnera3b605e2008-03-09 03:13:06 +0000487 // Add a marker EOF token to the end of the token list for this argument.
488 SourceLocation EndLoc = Tok.getLocation();
489 Tok.startToken();
490 Tok.setKind(tok::eof);
491 Tok.setLocation(EndLoc);
492 Tok.setLength(0);
493 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000494
495 // If we expect two arguments, add both as empty.
496 if (NumActuals == 0 && MinArgsExpected == 2)
497 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000499 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
500 // Emit the diagnostic at the macro name in case there is a missing ).
501 // Emitting it at the , could be far away from the macro name.
502 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
503 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
David Blaikied7bb6a02011-09-22 02:03:12 +0000506 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000507}
508
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000509/// \brief Keeps macro expanded tokens for TokenLexers.
510//
511/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
512/// going to lex in the cache and when it finishes the tokens are removed
513/// from the end of the cache.
514Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000515 ArrayRef<Token> tokens) {
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000516 assert(tokLexer);
517 if (tokens.empty())
518 return 0;
519
520 size_t newIndex = MacroExpandedTokens.size();
521 bool cacheNeedsToGrow = tokens.size() >
522 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
523 MacroExpandedTokens.append(tokens.begin(), tokens.end());
524
525 if (cacheNeedsToGrow) {
526 // Go through all the TokenLexers whose 'Tokens' pointer points in the
527 // buffer and update the pointers to the (potential) new buffer array.
528 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
529 TokenLexer *prevLexer;
530 size_t tokIndex;
531 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
532 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
533 }
534 }
535
536 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
537 return MacroExpandedTokens.data() + newIndex;
538}
539
540void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
541 assert(!MacroExpandingLexersStack.empty());
542 size_t tokIndex = MacroExpandingLexersStack.back().second;
543 assert(tokIndex < MacroExpandedTokens.size());
544 // Pop the cached macro expanded tokens from the end.
545 MacroExpandedTokens.resize(tokIndex);
546 MacroExpandingLexersStack.pop_back();
547}
548
Chris Lattnera3b605e2008-03-09 03:13:06 +0000549/// ComputeDATE_TIME - Compute the current time, enter it into the specified
550/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
551/// the identifier tokens inserted.
552static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
553 Preprocessor &PP) {
554 time_t TT = time(0);
555 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattnera3b605e2008-03-09 03:13:06 +0000557 static const char * const Months[] = {
558 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
559 };
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000561 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000562#ifdef LLVM_ON_WIN32
563 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
564 TM->tm_year+1900);
565#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000566 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000567 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000568#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner47246be2009-01-26 19:29:26 +0000570 Token TmpTok;
571 TmpTok.startToken();
572 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
573 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000574
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000575#ifdef LLVM_ON_WIN32
576 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
577#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000578 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000579#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000580 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
581 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000582}
583
Chris Lattner148772a2009-06-13 07:13:28 +0000584
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000585/// HasFeature - Return true if we recognize and implement the feature
586/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000587static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
588 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Benjamin Kramer32592e82010-01-09 18:53:11 +0000590 return llvm::StringSwitch<bool>(II->getName())
Kostya Serebryanyb6196882011-11-22 01:28:36 +0000591 .Case("address_sanitizer", LangOpts.AddressSanitizer)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000592 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000593 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000594 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000595 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000596 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000597 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000598 .Case("attribute_ns_returns_not_retained", true)
599 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000600 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000601 .Case("attribute_ns_consumed", true)
602 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000603 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000604 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000605 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000606 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000607 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000608 .Case("cxx_exceptions", LangOpts.Exceptions)
609 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000610 .Case("enumerator_attributes", true)
John McCallf85e1932011-06-15 23:02:42 +0000611 // Objective-C features
612 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
613 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
614 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
John McCall9f084a32011-07-06 00:26:06 +0000615 LangOpts.ObjCRuntimeHasWeak)
Douglas Gregor5471bc82011-09-08 17:18:35 +0000616 .Case("objc_fixed_enum", LangOpts.ObjC2)
Douglas Gregore97179c2011-09-08 01:46:34 +0000617 .Case("objc_instancetype", LangOpts.ObjC2)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000618 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000619 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000620 .Case("ownership_holds", true)
621 .Case("ownership_returns", true)
622 .Case("ownership_takes", true)
John McCalleb2ac8b2011-10-18 21:18:53 +0000623 .Case("arc_cf_code_audited", true)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000624 // C11 features
625 .Case("c_alignas", LangOpts.C11)
626 .Case("c_generic_selections", LangOpts.C11)
627 .Case("c_static_assert", LangOpts.C11)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000628 // C++0x features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000629 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000630 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000631 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000632 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000633 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000634 //.Case("cxx_constexpr", false);
Douglas Gregorc78e2592011-01-26 15:36:03 +0000635 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000636 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorf695a692011-11-01 01:19:34 +0000637 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000638 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000639 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000640 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
Sean Hunte1f6dea2011-08-07 00:34:32 +0000641 //.Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
Sebastian Redl74e611a2011-09-04 18:14:28 +0000642 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000643 //.Case("cxx_inheriting_constructors", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000644 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000645 //.Case("cxx_lambdas", false)
Douglas Gregorece38942011-08-29 17:28:38 +0000646 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000647 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000648 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000649 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000650 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000651 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000652 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000653 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
654 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
655 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
656 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000657 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000658 //.Case("cxx_unrestricted_unions", false)
659 //.Case("cxx_user_literals", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000660 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000661 // Type traits
662 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
663 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
664 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
665 .Case("has_trivial_assign", LangOpts.CPlusPlus)
666 .Case("has_trivial_copy", LangOpts.CPlusPlus)
667 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
668 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
669 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
670 .Case("is_abstract", LangOpts.CPlusPlus)
671 .Case("is_base_of", LangOpts.CPlusPlus)
672 .Case("is_class", LangOpts.CPlusPlus)
673 .Case("is_convertible_to", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000674 // __is_empty is available only if the horrible
675 // "struct __is_empty" parsing hack hasn't been needed in this
676 // translation unit. If it has, __is_empty reverts to a normal
677 // identifier and __has_feature(is_empty) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000678 .Case("is_empty",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000679 LangOpts.CPlusPlus &&
680 PP.getIdentifierInfo("__is_empty")->getTokenID()
681 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000682 .Case("is_enum", LangOpts.CPlusPlus)
Douglas Gregor5e9392b2011-12-03 18:14:24 +0000683 .Case("is_final", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000684 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000685 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000686 // __is_pod is available only if the horrible
687 // "struct __is_pod" parsing hack hasn't been needed in this
688 // translation unit. If it has, __is_pod reverts to a normal
689 // identifier and __has_feature(is_pod) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000690 .Case("is_pod",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000691 LangOpts.CPlusPlus &&
692 PP.getIdentifierInfo("__is_pod")->getTokenID()
693 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000694 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000695 .Case("is_trivial", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000696 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000697 .Case("is_union", LangOpts.CPlusPlus)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000698 .Case("tls", PP.getTargetInfo().isTLSSupported())
Sean Hunt858a3252011-07-18 17:08:00 +0000699 .Case("underlying_type", LangOpts.CPlusPlus)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000700 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000701}
702
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000703/// HasExtension - Return true if we recognize and implement the feature
704/// specified by the identifier, either as an extension or a standard language
705/// feature.
706static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
707 if (HasFeature(PP, II))
708 return true;
709
710 // If the use of an extension results in an error diagnostic, extensions are
711 // effectively unavailable, so just return false here.
David Blaikied6471f72011-09-25 23:23:43 +0000712 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
713 DiagnosticsEngine::Ext_Error)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000714 return false;
715
716 const LangOptions &LangOpts = PP.getLangOptions();
717
718 // Because we inherit the feature list from HasFeature, this string switch
719 // must be less restrictive than HasFeature's.
720 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000721 // C11 features supported by other languages as extensions.
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000722 .Case("c_alignas", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000723 .Case("c_generic_selections", true)
724 .Case("c_static_assert", true)
725 // C++0x features supported by other languages as extensions.
726 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000727 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000728 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000729 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000730 .Case("cxx_override_control", LangOpts.CPlusPlus)
Richard Smith7640c002011-09-06 18:03:41 +0000731 .Case("cxx_range_for", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000732 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
733 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
734 .Default(false);
735}
736
Anders Carlssoncae50952010-10-20 02:31:43 +0000737/// HasAttribute - Return true if we recognize and implement the attribute
738/// specified by the given identifier.
739static bool HasAttribute(const IdentifierInfo *II) {
740 return llvm::StringSwitch<bool>(II->getName())
741#include "clang/Lex/AttrSpellings.inc"
742 .Default(false);
743}
744
John Thompson92bd8c72009-11-02 22:28:12 +0000745/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
746/// or '__has_include_next("path")' expression.
747/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000748static bool EvaluateHasIncludeCommon(Token &Tok,
749 IdentifierInfo *II, Preprocessor &PP,
750 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000751 SourceLocation LParenLoc;
752
753 // Get '('.
754 PP.LexNonComment(Tok);
755
756 // Ensure we have a '('.
757 if (Tok.isNot(tok::l_paren)) {
758 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
759 return false;
760 }
761
762 // Save '(' location for possible missing ')' message.
763 LParenLoc = Tok.getLocation();
764
765 // Get the file name.
766 PP.getCurrentLexer()->LexIncludeFilename(Tok);
767
768 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000769 llvm::SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000770 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000771 SourceLocation EndLoc;
772
John Thompson92bd8c72009-11-02 22:28:12 +0000773 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000774 case tok::eod:
775 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000776 return false;
777
778 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000779 case tok::string_literal: {
780 bool Invalid = false;
781 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
782 if (Invalid)
783 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000784 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000785 }
John Thompson92bd8c72009-11-02 22:28:12 +0000786
787 case tok::less:
788 // This could be a <foo/bar.h> file coming from a macro expansion. In this
789 // case, glue the tokens together into FilenameBuffer and interpret those.
790 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000791 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000792 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000793 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000794 break;
795 default:
796 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
797 return false;
798 }
799
Chris Lattnera1394812010-01-10 01:35:12 +0000800 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000801 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
802 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000803 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000804 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000805
806 // Search include directories.
807 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000808 const FileEntry *File =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000809 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000810
811 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000812 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000813
814 // Get ')'.
815 PP.LexNonComment(Tok);
816
817 // Ensure we have a trailing ).
818 if (Tok.isNot(tok::r_paren)) {
819 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
820 PP.Diag(LParenLoc, diag::note_matching) << "(";
821 return false;
822 }
823
Chris Lattner3ed572e2011-01-15 06:57:04 +0000824 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000825}
826
827/// EvaluateHasInclude - Process a '__has_include("path")' expression.
828/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000829static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000830 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000831 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000832}
833
834/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
835/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000836static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000837 IdentifierInfo *II, Preprocessor &PP) {
838 // __has_include_next is like __has_include, except that we start
839 // searching after the current found directory. If we can't do this,
840 // issue a diagnostic.
841 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
842 if (PP.isInPrimaryFile()) {
843 Lookup = 0;
844 PP.Diag(Tok, diag::pp_include_next_in_primary);
845 } else if (Lookup == 0) {
846 PP.Diag(Tok, diag::pp_include_next_absolute_path);
847 } else {
848 // Start looking up in the next directory.
849 ++Lookup;
850 }
851
Chris Lattner3ed572e2011-01-15 06:57:04 +0000852 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000853}
Chris Lattner148772a2009-06-13 07:13:28 +0000854
Chris Lattnera3b605e2008-03-09 03:13:06 +0000855/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
856/// as a builtin macro, handle it and return the next token as 'Tok'.
857void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
858 // Figure out which token this is.
859 IdentifierInfo *II = Tok.getIdentifierInfo();
860 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000861
John McCall1ef8a2e2010-08-28 22:34:47 +0000862 // If this is an _Pragma or Microsoft __pragma directive, expand it,
863 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000864 if (II == Ident_Pragma)
865 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000866 else if (II == Ident__pragma) // in non-MS mode this is null
867 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Chris Lattnera3b605e2008-03-09 03:13:06 +0000869 ++NumBuiltinMacroExpanded;
870
Benjamin Kramerb1765912010-01-27 16:38:22 +0000871 llvm::SmallString<128> TmpBuffer;
872 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000873
874 // Set up the return result.
875 Tok.setIdentifierInfo(0);
876 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Chris Lattnera3b605e2008-03-09 03:13:06 +0000878 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000879 // C99 6.10.8: "__LINE__: The presumed line number (within the current
880 // source file) of the current source line (an integer constant)". This can
881 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000882 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattnerdff070f2009-04-18 22:29:33 +0000884 // Advance to the location of the first _, this might not be the first byte
885 // of the token if it starts with an escaped newline.
886 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Chris Lattner081927b2009-02-15 21:06:39 +0000888 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000889 // a macro expansion. This doesn't matter for object-like macros, but
Chris Lattner081927b2009-02-15 21:06:39 +0000890 // can matter for a function-like macro that expands to contain __LINE__.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000891 // Skip down through expansion points until we find a file loc for the
892 // end of the expansion history.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000893 Loc = SourceMgr.getExpansionRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000894 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner1fa49532009-03-08 08:08:45 +0000896 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000897 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000898 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000899 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000900 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
901 // character string literal)". This can be affected by #line.
902 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
903
904 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
905 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000906 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000907 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000908 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000909 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000910 if (PLoc.isInvalid())
911 break;
912
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000913 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000914 }
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattnera3b605e2008-03-09 03:13:06 +0000917 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000918 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000919 if (PLoc.isValid()) {
920 FN += PLoc.getFilename();
921 Lexer::Stringify(FN);
922 OS << '"' << FN.str() << '"';
923 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000924 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000925 } else if (II == Ident__DATE__) {
926 if (!DATELoc.isValid())
927 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
928 Tok.setKind(tok::string_literal);
929 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000930 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
931 Tok.getLocation(),
932 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000933 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000934 } else if (II == Ident__TIME__) {
935 if (!TIMELoc.isValid())
936 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
937 Tok.setKind(tok::string_literal);
938 Tok.setLength(strlen("\"hh:mm:ss\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000939 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
940 Tok.getLocation(),
941 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000942 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000943 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000944 // Compute the presumed include depth of this token. This can be affected
945 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000946 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000948 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000949 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000950 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000951 for (; PLoc.isValid(); ++Depth)
952 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
953 }
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattner1fa49532009-03-08 08:08:45 +0000955 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000956 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000957 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000958 } else if (II == Ident__TIMESTAMP__) {
959 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
960 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000961
962 // Get the file that we are lexing out of. If we're currently lexing from
963 // a macro, dig into the include stack.
964 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000965 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattnera3b605e2008-03-09 03:13:06 +0000967 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000968 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattnera3b605e2008-03-09 03:13:06 +0000970 const char *Result;
971 if (CurFile) {
972 time_t TT = CurFile->getModificationTime();
973 struct tm *TM = localtime(&TT);
974 Result = asctime(TM);
975 } else {
976 Result = "??? ??? ?? ??:??:?? ????\n";
977 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000978 // Surround the string with " and strip the trailing newline.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000979 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000980 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000981 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000982 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000983 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000984 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000985 } else if (II == Ident__has_feature ||
986 II == Ident__has_extension ||
987 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000988 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000989 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +0000990 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner148772a2009-06-13 07:13:28 +0000992 bool IsValid = false;
993 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner148772a2009-06-13 07:13:28 +0000995 // Read the '('.
996 Lex(Tok);
997 if (Tok.is(tok::l_paren)) {
998 // Read the identifier
999 Lex(Tok);
1000 if (Tok.is(tok::identifier)) {
1001 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner148772a2009-06-13 07:13:28 +00001003 // Read the ')'.
1004 Lex(Tok);
1005 if (Tok.is(tok::r_paren))
1006 IsValid = true;
1007 }
1008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner148772a2009-06-13 07:13:28 +00001010 bool Value = false;
1011 if (!IsValid)
1012 Diag(StartLoc, diag::err_feature_check_malformed);
1013 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +00001014 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +00001015 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +00001016 } else if (II == Ident__has_attribute)
1017 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001018 else if (II == Ident__has_extension)
1019 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +00001020 else {
Chris Lattner148772a2009-06-13 07:13:28 +00001021 assert(II == Ident__has_feature && "Must be feature check");
1022 Value = HasFeature(*this, FeatureII);
1023 }
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Benjamin Kramerb1765912010-01-27 16:38:22 +00001025 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +00001026 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +00001027 } else if (II == Ident__has_include ||
1028 II == Ident__has_include_next) {
1029 // The argument to these two builtins should be a parenthesized
1030 // file name string literal using angle brackets (<>) or
1031 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +00001032 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001033 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +00001034 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +00001035 else
Chris Lattner3ed572e2011-01-15 06:57:04 +00001036 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +00001037 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001038 Tok.setKind(tok::numeric_constant);
Ted Kremenekd7681502011-10-12 19:46:30 +00001039 } else if (II == Ident__has_warning) {
1040 // The argument should be a parenthesized string literal.
1041 // The argument to these builtins should be a parenthesized identifier.
1042 SourceLocation StartLoc = Tok.getLocation();
1043 bool IsValid = false;
1044 bool Value = false;
1045 // Read the '('.
1046 Lex(Tok);
1047 do {
1048 if (Tok.is(tok::l_paren)) {
1049 // Read the string.
1050 Lex(Tok);
1051
1052 // We need at least one string literal.
1053 if (!Tok.is(tok::string_literal)) {
1054 StartLoc = Tok.getLocation();
1055 IsValid = false;
1056 // Eat tokens until ')'.
1057 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1058 break;
1059 }
1060
1061 // String concatenation allows multiple strings, which can even come
1062 // from macro expansion.
1063 SmallVector<Token, 4> StrToks;
1064 while (Tok.is(tok::string_literal)) {
1065 StrToks.push_back(Tok);
1066 LexUnexpandedToken(Tok);
1067 }
1068
1069 // Is the end a ')'?
1070 if (!(IsValid = Tok.is(tok::r_paren)))
1071 break;
1072
1073 // Concatenate and parse the strings.
1074 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1075 assert(Literal.isAscii() && "Didn't allow wide strings in");
1076 if (Literal.hadError)
1077 break;
1078 if (Literal.Pascal) {
1079 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1080 break;
1081 }
1082
1083 StringRef WarningName(Literal.GetString());
1084
1085 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1086 WarningName[1] != 'W') {
1087 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1088 break;
1089 }
1090
1091 // Finally, check if the warning flags maps to a diagnostic group.
1092 // We construct a SmallVector here to talk to getDiagnosticIDs().
1093 // Although we don't use the result, this isn't a hot path, and not
1094 // worth special casing.
1095 llvm::SmallVector<diag::kind, 10> Diags;
1096 Value = !getDiagnostics().getDiagnosticIDs()->
1097 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1098 }
1099 } while (false);
1100
1101 if (!IsValid)
1102 Diag(StartLoc, diag::err_warning_check_malformed);
1103
1104 OS << (int)Value;
1105 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001106 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001107 llvm_unreachable("Unknown identifier!");
Chris Lattnera3b605e2008-03-09 03:13:06 +00001108 }
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001109 CreateString(OS.str().data(), OS.str().size(), Tok,
1110 Tok.getLocation(), Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +00001111}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001112
1113void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1114 // If the 'used' status changed, and the macro requires 'unused' warning,
1115 // remove its SourceLocation from the warn-for-unused-macro locations.
1116 if (MI->isWarnIfUnused() && !MI->isUsed())
1117 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1118 MI->setIsUsed(true);
1119}