blob: 826fa03621c4b0fd9b7e35a2c9ce1e889835224a [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Eric Christopher1f84f8d2010-06-24 02:02:00 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000021#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf29c5232010-08-24 22:20:20 +000022#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor295a2a62010-10-30 00:23:06 +000023#include "clang/Lex/ExternalPreprocessorSource.h"
Ted Kremenekd7681502011-10-12 19:46:30 +000024#include "clang/Lex/LiteralSupport.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000025#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +000026#include "llvm/ADT/STLExtras.h"
Dylan Noblesmith1770e0d2011-12-22 22:49:47 +000027#include "llvm/Config/llvm-config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000028#include "llvm/Support/raw_ostream.h"
David Blaikie9fe8c742011-09-23 05:35:21 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner3daed522009-03-02 22:20:04 +000030#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000031#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000032using namespace clang;
33
Douglas Gregor295a2a62010-10-30 00:23:06 +000034MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
35 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
36
37 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
38 = Macros.find(II);
39 if (Pos == Macros.end()) {
40 // Load this macro from the external source.
41 getExternalSource()->LoadMacroDefinition(II);
42 Pos = Macros.find(II);
43 }
44 assert(Pos != Macros.end() && "Identifier macro info is missing!");
45 return Pos->second;
46}
47
Chris Lattnera3b605e2008-03-09 03:13:06 +000048/// setMacroInfo - Specify a macro for this identifier.
49///
Douglas Gregor5d5051f2012-01-24 15:24:38 +000050void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
51 bool LoadedFromAST) {
Chris Lattner555589d2009-04-10 21:17:07 +000052 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000053 Macros[II] = MI;
54 II->setHasMacroDefinition(true);
Douglas Gregor5d5051f2012-01-24 15:24:38 +000055 if (II->isFromAST() && !LoadedFromAST)
Douglas Gregoreee242f2011-10-27 09:33:13 +000056 II->setChangedSinceDeserialization();
Chris Lattner555589d2009-04-10 21:17:07 +000057 } else if (II->hasMacroDefinition()) {
58 Macros.erase(II);
59 II->setHasMacroDefinition(false);
Douglas Gregor5d5051f2012-01-24 15:24:38 +000060 if (II->isFromAST() && !LoadedFromAST)
Douglas Gregoreee242f2011-10-27 09:33:13 +000061 II->setChangedSinceDeserialization();
Chris Lattnera3b605e2008-03-09 03:13:06 +000062 }
63}
64
65/// RegisterBuiltinMacro - Register the specified identifier in the identifier
66/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000067static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000068 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000069 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattnera3b605e2008-03-09 03:13:06 +000071 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000072 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000073 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000074 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000075 return Id;
76}
77
78
79/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
80/// identifier table.
81void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000082 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
83 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
84 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
85 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
86 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
87 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattnera3b605e2008-03-09 03:13:06 +000089 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000090 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
91 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
92 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner148772a2009-06-13 07:13:28 +000094 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000095 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
Peter Collingbournec1b5fa42011-05-13 20:54:45 +000096 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
John Thompson92bd8c72009-11-02 22:28:12 +000097 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000098 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000099 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
100 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Ted Kremenekd7681502011-10-12 19:46:30 +0000101 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
John McCall1ef8a2e2010-08-28 22:34:47 +0000102
103 // Microsoft Extensions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000104 if (LangOpts.MicrosoftExt)
John McCall1ef8a2e2010-08-28 22:34:47 +0000105 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
106 else
107 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000108}
109
110/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
111/// in its expansion, currently expands to that token literally.
112static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
113 const IdentifierInfo *MacroIdent,
114 Preprocessor &PP) {
115 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
116
117 // If the token isn't an identifier, it's always literally expanded.
118 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Argyrios Kyrtzidis373cb782011-12-17 04:13:31 +0000120 // If the information about this identifier is out of date, update it from
121 // the external source.
122 if (II->isOutOfDate())
123 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
124
Chris Lattnera3b605e2008-03-09 03:13:06 +0000125 // If the identifier is a macro, and if that macro is enabled, it may be
126 // expanded so it's not a trivial expansion.
127 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
128 // Fast expanding "#define X X" is ok, because X would be disabled.
129 II != MacroIdent)
130 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Chris Lattnera3b605e2008-03-09 03:13:06 +0000132 // If this is an object-like macro invocation, it is safe to trivially expand
133 // it.
134 if (MI->isObjectLike()) return true;
135
136 // If this is a function-like macro invocation, it's safe to trivially expand
137 // as long as the identifier is not a macro argument.
138 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
139 I != E; ++I)
140 if (*I == II)
141 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattnera3b605e2008-03-09 03:13:06 +0000143 return true;
144}
145
146
147/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
148/// lexed is a '('. If so, consume the token and return true, if not, this
149/// method should have no observable side-effect on the lexed tokens.
150bool Preprocessor::isNextPPTokenLParen() {
151 // Do some quick tests for rejection cases.
152 unsigned Val;
153 if (CurLexer)
154 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000155 else if (CurPTHLexer)
156 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 else
158 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 if (Val == 2) {
161 // We have run off the end. If it's a source file we don't
162 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
163 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000164 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 return false;
166 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
167 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
168 if (Entry.TheLexer)
169 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000170 else if (Entry.ThePTHLexer)
171 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000172 else
173 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnera3b605e2008-03-09 03:13:06 +0000175 if (Val != 2)
176 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000179 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000180 return false;
181 }
182 }
183
184 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
185 // have found something that isn't a '(' or we found the end of the
186 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000187 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188}
189
190/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
191/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000192bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000193 MacroInfo *MI) {
Douglas Gregor13678972010-01-26 19:43:43 +0000194 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000195 // then the macro could expand to different things in other contexts, we need
196 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000197 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattnera3b605e2008-03-09 03:13:06 +0000199 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
200 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000201 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
202 Identifier.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000203 ExpandBuiltinMacro(Identifier);
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnera3b605e2008-03-09 03:13:06 +0000207 /// Args - If this is a function-like macro expansion, this contains,
208 /// for each macro argument, the list of tokens that were provided to the
209 /// invocation.
210 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000212 // Remember where the end of the expansion occurred. For an object-like
Chris Lattnere7fb4842009-02-15 20:52:18 +0000213 // macro, this is the identifier. For a function-like macro, this is the ')'.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000214 SourceLocation ExpansionEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattnera3b605e2008-03-09 03:13:06 +0000216 // If this is a function-like macro, read the arguments.
217 if (MI->isFunctionLike()) {
218 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000219 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 if (!isNextPPTokenLParen())
221 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnera3b605e2008-03-09 03:13:06 +0000223 // Remember that we are now parsing the arguments to a macro invocation.
224 // Preprocessor directives used inside macro arguments are not portable, and
225 // this enables the warning.
226 InMacroArgs = true;
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000227 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnera3b605e2008-03-09 03:13:06 +0000229 // Finished parsing args.
230 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnera3b605e2008-03-09 03:13:06 +0000232 // If there was an error parsing the arguments, bail out.
233 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattnera3b605e2008-03-09 03:13:06 +0000235 ++NumFnMacroExpanded;
236 } else {
237 ++NumMacroExpanded;
238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnera3b605e2008-03-09 03:13:06 +0000240 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000241 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000243 // Remember where the token is expanded.
244 SourceLocation ExpandLoc = Identifier.getLocation();
Argyrios Kyrtzidis66c44e72012-05-10 18:57:19 +0000245 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000246
Argyrios Kyrtzidis66c44e72012-05-10 18:57:19 +0000247 if (Callbacks) {
248 if (InMacroArgs) {
249 // We can have macro expansion inside a conditional directive while
250 // reading the function macro arguments. To ensure, in that case, that
251 // MacroExpands callbacks still happen in source order, queue this
252 // callback to have it happen after the function macro callback.
253 DelayedMacroExpandsCallbacks.push_back(
254 MacroExpandsInfo(Identifier, MI, ExpansionRange));
255 } else {
256 Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
257 if (!DelayedMacroExpandsCallbacks.empty()) {
258 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
259 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
260 Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
261 }
262 DelayedMacroExpandsCallbacks.clear();
263 }
264 }
265 }
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000266
267 // If we started lexing a macro, enter the macro expansion body.
268
Chris Lattnera3b605e2008-03-09 03:13:06 +0000269 // If this macro expands to no tokens, don't bother to push it onto the
270 // expansion stack, only to take it right back off.
271 if (MI->getNumTokens() == 0) {
272 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000273 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattnera3b605e2008-03-09 03:13:06 +0000275 // Ignore this macro use, just return the next token in the current
276 // buffer.
277 bool HadLeadingSpace = Identifier.hasLeadingSpace();
278 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnera3b605e2008-03-09 03:13:06 +0000280 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Chris Lattnera3b605e2008-03-09 03:13:06 +0000282 // If the identifier isn't on some OTHER line, inherit the leading
283 // whitespace/first-on-a-line property of this token. This handles
284 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
285 // empty.
286 if (!Identifier.isAtStartOfLine()) {
287 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
288 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
289 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000290 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000291 ++NumFastMacroExpanded;
292 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnera3b605e2008-03-09 03:13:06 +0000294 } else if (MI->getNumTokens() == 1 &&
295 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000296 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000297 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000298 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000299 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000300
301 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000302 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
305 // identifier to the expanded token.
306 bool isAtStartOfLine = Identifier.isAtStartOfLine();
307 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattnera3b605e2008-03-09 03:13:06 +0000309 // Replace the result token.
310 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312 // Restore the StartOfLine/LeadingSpace markers.
313 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
314 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000316 // Update the tokens location to include both its expansion and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000317 // locations.
318 SourceLocation Loc =
Chandler Carruthbf340e42011-07-26 03:03:05 +0000319 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
320 ExpansionEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner8ff66de2010-03-26 17:49:16 +0000323 // If this is a disabled macro or #define X X, we must mark the result as
324 // unexpandable.
325 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
326 if (MacroInfo *NewMI = getMacroInfo(NewII))
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000327 if (!NewMI->isEnabled() || NewMI == MI) {
Chris Lattner8ff66de2010-03-26 17:49:16 +0000328 Identifier.setFlag(Token::DisableExpand);
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000329 Diag(Identifier, diag::pp_disabled_macro_expansion);
330 }
Chris Lattner8ff66de2010-03-26 17:49:16 +0000331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnera3b605e2008-03-09 03:13:06 +0000333 // Since this is not an identifier token, it can't be macro expanded, so
334 // we're done.
335 ++NumFastMacroExpanded;
336 return false;
337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattnera3b605e2008-03-09 03:13:06 +0000339 // Start expanding the macro.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000340 EnterMacro(Identifier, ExpansionEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattnera3b605e2008-03-09 03:13:06 +0000342 // Now that the macro is at the top of the include stack, ask the
343 // preprocessor to read the next token from it.
344 Lex(Identifier);
345 return false;
346}
347
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000348/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
349/// token is the '(' of the macro, this method is invoked to read all of the
350/// actual arguments specified for the macro invocation. This returns null on
351/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000352MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000353 MacroInfo *MI,
354 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000355 // The number of fixed arguments to parse.
356 unsigned NumFixedArgsLeft = MI->getNumArgs();
357 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattnera3b605e2008-03-09 03:13:06 +0000359 // Outer loop, while there are more arguments, keep reading them.
360 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000361
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000362 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
363 // an argument value in a macro could expand to ',' or '(' or ')'.
364 LexUnexpandedToken(Tok);
365 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattnera3b605e2008-03-09 03:13:06 +0000367 // ArgTokens - Build up a list of tokens that make up each argument. Each
368 // argument is separated by an EOF token. Use a SmallVector so we can avoid
369 // heap allocations in the common case.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000370 SmallVector<Token, 64> ArgTokens;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000371
372 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000373 while (Tok.isNot(tok::r_paren)) {
374 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
375 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000377 unsigned ArgTokenStart = ArgTokens.size();
378 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattnera3b605e2008-03-09 03:13:06 +0000380 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
381 // that we already consumed the first one.
382 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattnera3b605e2008-03-09 03:13:06 +0000384 while (1) {
385 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
386 // an argument value in a macro could expand to ',' or '(' or ')'.
387 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Peter Collingbourne84021552011-02-28 02:37:51 +0000389 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000390 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000391 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000392 MacroName = Tok;
393 return 0;
394 } else if (Tok.is(tok::r_paren)) {
395 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000396 if (NumParens-- == 0) {
397 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000398 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000399 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400 } else if (Tok.is(tok::l_paren)) {
401 ++NumParens;
402 } else if (Tok.is(tok::comma) && NumParens == 0) {
403 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000404 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000405 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000406 if (!isVariadic) break;
407 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000408 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000409 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
410 // If this is a comment token in the argument list and we're just in
411 // -C mode (not -CC mode), discard the comment.
412 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000413 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000414 // Reading macro arguments can cause macros that we are currently
415 // expanding from to be popped off the expansion stack. Doing so causes
416 // them to be reenabled for expansion. Here we record whether any
417 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000418 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000419 // C99 6.10.3.4p2.
420 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
421 if (!MI->isEnabled())
422 Tok.setFlag(Token::DisableExpand);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000423 } else if (Tok.is(tok::code_completion)) {
424 if (CodeComplete)
425 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
426 MI, NumActuals);
427 // Don't mark that we reached the code-completion point because the
428 // parser is going to handle the token and there will be another
429 // code-completion callback.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000430 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000431
Chris Lattnera3b605e2008-03-09 03:13:06 +0000432 ArgTokens.push_back(Tok);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000435 // If this was an empty argument list foo(), don't add this as an empty
436 // argument.
437 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
438 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000439
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000440 // If this is not a variadic macro, and too many args were specified, emit
441 // an error.
442 if (!isVariadic && NumFixedArgsLeft == 0) {
443 if (ArgTokens.size() != ArgTokenStart)
444 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000446 // Emit the diagnostic at the macro name in case there is a missing ).
447 // Emitting it at the , could be far away from the macro name.
448 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
449 return 0;
450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner32c13882011-04-22 23:25:09 +0000452 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000453 // other modes.
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
455 Diag(Tok, LangOpts.CPlusPlus0x ?
Richard Smith661a9962011-10-15 01:18:56 +0000456 diag::warn_cxx98_compat_empty_fnmacro_arg :
457 diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnera3b605e2008-03-09 03:13:06 +0000459 // Add a marker EOF token to the end of the token list for this argument.
460 Token EOFTok;
461 EOFTok.startToken();
462 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000463 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000464 EOFTok.setLength(0);
465 ArgTokens.push_back(EOFTok);
466 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000467 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000468 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Chris Lattnera3b605e2008-03-09 03:13:06 +0000471 // Okay, we either found the r_paren. Check to see if we parsed too few
472 // arguments.
473 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Chris Lattnera3b605e2008-03-09 03:13:06 +0000475 // See MacroArgs instance var for description of this.
476 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Chris Lattnera3b605e2008-03-09 03:13:06 +0000478 if (NumActuals < MinArgsExpected) {
479 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000480 if (NumActuals == 0 && MinArgsExpected == 1) {
481 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner97e2de12009-04-20 21:08:10 +0000483 // If there is exactly one argument, and that argument is missing,
484 // then we have an empty "()" argument empty list. This is fine, even if
485 // the macro expects one argument (the argument is just empty).
486 isVarargsElided = MI->isVariadic();
487 } else if (MI->isVariadic() &&
488 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
489 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000490 // Varargs where the named vararg parameter is missing: ok as extension.
491 // #define A(x, ...)
492 // A("blah")
493 Diag(Tok, diag::ext_missing_varargs_arg);
494
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000495 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000496 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000497 // #define A(x, foo...) blah(a, ## foo)
498 // #define B(x, ...) blah(a, ## __VA_ARGS__)
499 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000500 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000501 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000502 } else {
503 // Otherwise, emit the error.
504 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
505 return 0;
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattnera3b605e2008-03-09 03:13:06 +0000508 // Add a marker EOF token to the end of the token list for this argument.
509 SourceLocation EndLoc = Tok.getLocation();
510 Tok.startToken();
511 Tok.setKind(tok::eof);
512 Tok.setLocation(EndLoc);
513 Tok.setLength(0);
514 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000515
516 // If we expect two arguments, add both as empty.
517 if (NumActuals == 0 && MinArgsExpected == 2)
518 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000520 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
521 // Emit the diagnostic at the macro name in case there is a missing ).
522 // Emitting it at the , could be far away from the macro name.
523 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
524 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
David Blaikied7bb6a02011-09-22 02:03:12 +0000527 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000528}
529
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000530/// \brief Keeps macro expanded tokens for TokenLexers.
531//
532/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
533/// going to lex in the cache and when it finishes the tokens are removed
534/// from the end of the cache.
535Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000536 ArrayRef<Token> tokens) {
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000537 assert(tokLexer);
538 if (tokens.empty())
539 return 0;
540
541 size_t newIndex = MacroExpandedTokens.size();
542 bool cacheNeedsToGrow = tokens.size() >
543 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
544 MacroExpandedTokens.append(tokens.begin(), tokens.end());
545
546 if (cacheNeedsToGrow) {
547 // Go through all the TokenLexers whose 'Tokens' pointer points in the
548 // buffer and update the pointers to the (potential) new buffer array.
549 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
550 TokenLexer *prevLexer;
551 size_t tokIndex;
552 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
553 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
554 }
555 }
556
557 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
558 return MacroExpandedTokens.data() + newIndex;
559}
560
561void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
562 assert(!MacroExpandingLexersStack.empty());
563 size_t tokIndex = MacroExpandingLexersStack.back().second;
564 assert(tokIndex < MacroExpandedTokens.size());
565 // Pop the cached macro expanded tokens from the end.
566 MacroExpandedTokens.resize(tokIndex);
567 MacroExpandingLexersStack.pop_back();
568}
569
Chris Lattnera3b605e2008-03-09 03:13:06 +0000570/// ComputeDATE_TIME - Compute the current time, enter it into the specified
571/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
572/// the identifier tokens inserted.
573static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
574 Preprocessor &PP) {
575 time_t TT = time(0);
576 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattnera3b605e2008-03-09 03:13:06 +0000578 static const char * const Months[] = {
579 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
580 };
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000582 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000583#ifdef LLVM_ON_WIN32
584 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
585 TM->tm_year+1900);
586#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000587 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000588 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000589#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattner47246be2009-01-26 19:29:26 +0000591 Token TmpTok;
592 TmpTok.startToken();
593 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
594 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000595
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000596#ifdef LLVM_ON_WIN32
597 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
598#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000599 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000600#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000601 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
602 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000603}
604
Chris Lattner148772a2009-06-13 07:13:28 +0000605
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000606/// HasFeature - Return true if we recognize and implement the feature
607/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000608static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000609 const LangOptions &LangOpts = PP.getLangOpts();
Richard Smith5297d712012-02-25 10:41:10 +0000610 StringRef Feature = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Richard Smith5297d712012-02-25 10:41:10 +0000612 // Normalize the feature name, __foo__ becomes foo.
613 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
614 Feature = Feature.substr(2, Feature.size() - 4);
615
616 return llvm::StringSwitch<bool>(Feature)
Kostya Serebryanyb6196882011-11-22 01:28:36 +0000617 .Case("address_sanitizer", LangOpts.AddressSanitizer)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000618 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000619 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000620 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000621 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000622 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000623 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000624 .Case("attribute_ns_returns_not_retained", true)
625 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000626 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000627 .Case("attribute_ns_consumed", true)
628 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000629 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000630 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000631 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000632 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000633 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000634 .Case("cxx_exceptions", LangOpts.Exceptions)
635 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000636 .Case("enumerator_attributes", true)
John McCallf85e1932011-06-15 23:02:42 +0000637 // Objective-C features
638 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
639 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
640 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
John McCall9f084a32011-07-06 00:26:06 +0000641 LangOpts.ObjCRuntimeHasWeak)
Fariborz Jahanianf83a6152012-02-02 00:15:51 +0000642 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
Douglas Gregor5471bc82011-09-08 17:18:35 +0000643 .Case("objc_fixed_enum", LangOpts.ObjC2)
Douglas Gregore97179c2011-09-08 01:46:34 +0000644 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorbd507c52012-01-04 21:16:09 +0000645 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
John McCall260611a2012-06-20 06:18:46 +0000646 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
647 .Case("objc_weak_class", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000648 .Case("ownership_holds", true)
649 .Case("ownership_returns", true)
650 .Case("ownership_takes", true)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000651 .Case("objc_bool", true)
John McCall260611a2012-06-20 06:18:46 +0000652 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000653 .Case("objc_array_literals", LangOpts.ObjC2)
654 .Case("objc_dictionary_literals", LangOpts.ObjC2)
Patrick Beardeb382ec2012-04-19 00:25:12 +0000655 .Case("objc_boxed_expressions", LangOpts.ObjC2)
John McCalleb2ac8b2011-10-18 21:18:53 +0000656 .Case("arc_cf_code_audited", true)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000657 // C11 features
658 .Case("c_alignas", LangOpts.C11)
David Chisnall7a7ee302012-01-16 17:27:18 +0000659 .Case("c_atomic", LangOpts.C11)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000660 .Case("c_generic_selections", LangOpts.C11)
661 .Case("c_static_assert", LangOpts.C11)
Richard Smith9c1dda72012-03-09 08:41:27 +0000662 // C++11 features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000663 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000664 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000665 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
David Chisnall7a7ee302012-01-16 17:27:18 +0000666 .Case("cxx_atomic", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000667 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000668 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Richard Smithb5216aa2012-02-14 22:56:17 +0000669 .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000670 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor316551f2012-04-10 20:00:33 +0000671 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000672 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorf695a692011-11-01 01:19:34 +0000673 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000674 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000675 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000676 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
Sebastian Redld1dc3aa2012-02-25 20:51:27 +0000677 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
Sebastian Redl74e611a2011-09-04 18:14:28 +0000678 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000679 //.Case("cxx_inheriting_constructors", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000680 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Douglas Gregor7c07e962012-02-23 03:02:32 +0000681 .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
Douglas Gregor7b156dd2012-04-04 00:48:39 +0000682 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000683 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000684 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000685 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000686 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000687 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000688 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000689 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000690 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
691 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
692 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
693 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000694 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
Richard Smithec92bc72012-03-03 23:51:05 +0000695 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
Richard Smith9c1dda72012-03-09 08:41:27 +0000696 .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000697 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000698 // Type traits
699 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
700 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
701 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
702 .Case("has_trivial_assign", LangOpts.CPlusPlus)
703 .Case("has_trivial_copy", LangOpts.CPlusPlus)
704 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
705 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
706 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
707 .Case("is_abstract", LangOpts.CPlusPlus)
708 .Case("is_base_of", LangOpts.CPlusPlus)
709 .Case("is_class", LangOpts.CPlusPlus)
710 .Case("is_convertible_to", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000711 // __is_empty is available only if the horrible
712 // "struct __is_empty" parsing hack hasn't been needed in this
713 // translation unit. If it has, __is_empty reverts to a normal
714 // identifier and __has_feature(is_empty) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000715 .Case("is_empty",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000716 LangOpts.CPlusPlus &&
717 PP.getIdentifierInfo("__is_empty")->getTokenID()
718 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000719 .Case("is_enum", LangOpts.CPlusPlus)
Douglas Gregor5e9392b2011-12-03 18:14:24 +0000720 .Case("is_final", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000721 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000722 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000723 // __is_pod is available only if the horrible
724 // "struct __is_pod" parsing hack hasn't been needed in this
725 // translation unit. If it has, __is_pod reverts to a normal
726 // identifier and __has_feature(is_pod) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000727 .Case("is_pod",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000728 LangOpts.CPlusPlus &&
729 PP.getIdentifierInfo("__is_pod")->getTokenID()
730 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000731 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000732 .Case("is_trivial", LangOpts.CPlusPlus)
Douglas Gregor25d0a0f2012-02-23 07:33:15 +0000733 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
Douglas Gregor4ca8ac22012-02-24 07:38:34 +0000734 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000735 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000736 .Case("is_union", LangOpts.CPlusPlus)
Douglas Gregorbd507c52012-01-04 21:16:09 +0000737 .Case("modules", LangOpts.Modules)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000738 .Case("tls", PP.getTargetInfo().isTLSSupported())
Sean Hunt858a3252011-07-18 17:08:00 +0000739 .Case("underlying_type", LangOpts.CPlusPlus)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000740 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000741}
742
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000743/// HasExtension - Return true if we recognize and implement the feature
744/// specified by the identifier, either as an extension or a standard language
745/// feature.
746static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
747 if (HasFeature(PP, II))
748 return true;
749
750 // If the use of an extension results in an error diagnostic, extensions are
751 // effectively unavailable, so just return false here.
David Blaikied6471f72011-09-25 23:23:43 +0000752 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
753 DiagnosticsEngine::Ext_Error)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000754 return false;
755
David Blaikie4e4d0842012-03-11 07:00:24 +0000756 const LangOptions &LangOpts = PP.getLangOpts();
Richard Smith5297d712012-02-25 10:41:10 +0000757 StringRef Extension = II->getName();
758
759 // Normalize the extension name, __foo__ becomes foo.
760 if (Extension.startswith("__") && Extension.endswith("__") &&
761 Extension.size() >= 4)
762 Extension = Extension.substr(2, Extension.size() - 4);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000763
764 // Because we inherit the feature list from HasFeature, this string switch
765 // must be less restrictive than HasFeature's.
Richard Smith5297d712012-02-25 10:41:10 +0000766 return llvm::StringSwitch<bool>(Extension)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000767 // C11 features supported by other languages as extensions.
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000768 .Case("c_alignas", true)
David Chisnall7a7ee302012-01-16 17:27:18 +0000769 .Case("c_atomic", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000770 .Case("c_generic_selections", true)
771 .Case("c_static_assert", true)
772 // C++0x features supported by other languages as extensions.
David Chisnall7a7ee302012-01-16 17:27:18 +0000773 .Case("cxx_atomic", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000774 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000775 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000776 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
Douglas Gregor7b156dd2012-04-04 00:48:39 +0000777 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000778 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000779 .Case("cxx_override_control", LangOpts.CPlusPlus)
Richard Smith7640c002011-09-06 18:03:41 +0000780 .Case("cxx_range_for", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000781 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
782 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
783 .Default(false);
784}
785
Anders Carlssoncae50952010-10-20 02:31:43 +0000786/// HasAttribute - Return true if we recognize and implement the attribute
787/// specified by the given identifier.
788static bool HasAttribute(const IdentifierInfo *II) {
Jean-Daniel Dupas8a5e7fd2012-03-01 14:53:16 +0000789 StringRef Name = II->getName();
790 // Normalize the attribute name, __foo__ becomes foo.
791 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
792 Name = Name.substr(2, Name.size() - 4);
793
Sean Hunt8e083e72012-06-19 23:57:03 +0000794 // FIXME: Do we need to handle namespaces here?
Jean-Daniel Dupas8a5e7fd2012-03-01 14:53:16 +0000795 return llvm::StringSwitch<bool>(Name)
Anders Carlssoncae50952010-10-20 02:31:43 +0000796#include "clang/Lex/AttrSpellings.inc"
797 .Default(false);
798}
799
John Thompson92bd8c72009-11-02 22:28:12 +0000800/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
801/// or '__has_include_next("path")' expression.
802/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000803static bool EvaluateHasIncludeCommon(Token &Tok,
804 IdentifierInfo *II, Preprocessor &PP,
805 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000806 SourceLocation LParenLoc;
807
808 // Get '('.
809 PP.LexNonComment(Tok);
810
811 // Ensure we have a '('.
812 if (Tok.isNot(tok::l_paren)) {
813 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
814 return false;
815 }
816
817 // Save '(' location for possible missing ')' message.
818 LParenLoc = Tok.getLocation();
819
820 // Get the file name.
821 PP.getCurrentLexer()->LexIncludeFilename(Tok);
822
823 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000824 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000825 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000826 SourceLocation EndLoc;
827
John Thompson92bd8c72009-11-02 22:28:12 +0000828 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000829 case tok::eod:
830 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000831 return false;
832
833 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000834 case tok::string_literal: {
835 bool Invalid = false;
836 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
837 if (Invalid)
838 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000839 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000840 }
John Thompson92bd8c72009-11-02 22:28:12 +0000841
842 case tok::less:
843 // This could be a <foo/bar.h> file coming from a macro expansion. In this
844 // case, glue the tokens together into FilenameBuffer and interpret those.
845 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000846 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000847 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000848 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000849 break;
850 default:
851 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
852 return false;
853 }
854
Richard Smith99831e42012-03-06 03:21:47 +0000855 // Get ')'.
856 PP.LexNonComment(Tok);
857
858 // Ensure we have a trailing ).
859 if (Tok.isNot(tok::r_paren)) {
860 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
861 PP.Diag(LParenLoc, diag::note_matching) << "(";
862 return false;
863 }
864
Chris Lattnera1394812010-01-10 01:35:12 +0000865 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000866 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
867 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000868 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000869 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000870
871 // Search include directories.
872 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000873 const FileEntry *File =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000874 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000875
Richard Smith99831e42012-03-06 03:21:47 +0000876 // Get the result value. A result of true means the file exists.
877 return File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000878}
879
880/// EvaluateHasInclude - Process a '__has_include("path")' expression.
881/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000882static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000883 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000884 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000885}
886
887/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
888/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000889static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000890 IdentifierInfo *II, Preprocessor &PP) {
891 // __has_include_next is like __has_include, except that we start
892 // searching after the current found directory. If we can't do this,
893 // issue a diagnostic.
894 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
895 if (PP.isInPrimaryFile()) {
896 Lookup = 0;
897 PP.Diag(Tok, diag::pp_include_next_in_primary);
898 } else if (Lookup == 0) {
899 PP.Diag(Tok, diag::pp_include_next_absolute_path);
900 } else {
901 // Start looking up in the next directory.
902 ++Lookup;
903 }
904
Chris Lattner3ed572e2011-01-15 06:57:04 +0000905 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000906}
Chris Lattner148772a2009-06-13 07:13:28 +0000907
Chris Lattnera3b605e2008-03-09 03:13:06 +0000908/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
909/// as a builtin macro, handle it and return the next token as 'Tok'.
910void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
911 // Figure out which token this is.
912 IdentifierInfo *II = Tok.getIdentifierInfo();
913 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000914
John McCall1ef8a2e2010-08-28 22:34:47 +0000915 // If this is an _Pragma or Microsoft __pragma directive, expand it,
916 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000917 if (II == Ident_Pragma)
918 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000919 else if (II == Ident__pragma) // in non-MS mode this is null
920 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattnera3b605e2008-03-09 03:13:06 +0000922 ++NumBuiltinMacroExpanded;
923
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000924 SmallString<128> TmpBuffer;
Benjamin Kramerb1765912010-01-27 16:38:22 +0000925 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000926
927 // Set up the return result.
928 Tok.setIdentifierInfo(0);
929 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Chris Lattnera3b605e2008-03-09 03:13:06 +0000931 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000932 // C99 6.10.8: "__LINE__: The presumed line number (within the current
933 // source file) of the current source line (an integer constant)". This can
934 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000935 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Chris Lattnerdff070f2009-04-18 22:29:33 +0000937 // Advance to the location of the first _, this might not be the first byte
938 // of the token if it starts with an escaped newline.
939 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner081927b2009-02-15 21:06:39 +0000941 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000942 // a macro expansion. This doesn't matter for object-like macros, but
Chris Lattner081927b2009-02-15 21:06:39 +0000943 // can matter for a function-like macro that expands to contain __LINE__.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000944 // Skip down through expansion points until we find a file loc for the
945 // end of the expansion history.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000946 Loc = SourceMgr.getExpansionRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000947 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner1fa49532009-03-08 08:08:45 +0000949 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000950 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000951 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000952 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000953 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
954 // character string literal)". This can be affected by #line.
955 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
956
957 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
958 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000959 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000960 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000961 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000962 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000963 if (PLoc.isInvalid())
964 break;
965
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000966 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000967 }
968 }
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattnera3b605e2008-03-09 03:13:06 +0000970 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000971 SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000972 if (PLoc.isValid()) {
973 FN += PLoc.getFilename();
974 Lexer::Stringify(FN);
975 OS << '"' << FN.str() << '"';
976 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000977 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000978 } else if (II == Ident__DATE__) {
979 if (!DATELoc.isValid())
980 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
981 Tok.setKind(tok::string_literal);
982 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000983 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
984 Tok.getLocation(),
985 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000986 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000987 } else if (II == Ident__TIME__) {
988 if (!TIMELoc.isValid())
989 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
990 Tok.setKind(tok::string_literal);
991 Tok.setLength(strlen("\"hh:mm:ss\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000992 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
993 Tok.getLocation(),
994 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000995 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000996 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000997 // Compute the presumed include depth of this token. This can be affected
998 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000999 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001001 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +00001002 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001003 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +00001004 for (; PLoc.isValid(); ++Depth)
1005 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1006 }
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner1fa49532009-03-08 08:08:45 +00001008 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +00001009 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +00001010 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001011 } else if (II == Ident__TIMESTAMP__) {
1012 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1013 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +00001014
1015 // Get the file that we are lexing out of. If we're currently lexing from
1016 // a macro, dig into the include stack.
1017 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +00001018 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Chris Lattnera3b605e2008-03-09 03:13:06 +00001020 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +00001021 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattnera3b605e2008-03-09 03:13:06 +00001023 const char *Result;
1024 if (CurFile) {
1025 time_t TT = CurFile->getModificationTime();
1026 struct tm *TM = localtime(&TT);
1027 Result = asctime(TM);
1028 } else {
1029 Result = "??? ??? ?? ??:??:?? ????\n";
1030 }
Benjamin Kramerb1765912010-01-27 16:38:22 +00001031 // Surround the string with " and strip the trailing newline.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001032 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +00001033 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001034 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001035 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +00001036 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001037 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001038 } else if (II == Ident__has_feature ||
1039 II == Ident__has_extension ||
1040 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +00001041 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001042 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +00001043 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner148772a2009-06-13 07:13:28 +00001045 bool IsValid = false;
1046 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Chris Lattner148772a2009-06-13 07:13:28 +00001048 // Read the '('.
1049 Lex(Tok);
1050 if (Tok.is(tok::l_paren)) {
1051 // Read the identifier
1052 Lex(Tok);
1053 if (Tok.is(tok::identifier)) {
1054 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Chris Lattner148772a2009-06-13 07:13:28 +00001056 // Read the ')'.
1057 Lex(Tok);
1058 if (Tok.is(tok::r_paren))
1059 IsValid = true;
1060 }
1061 }
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Chris Lattner148772a2009-06-13 07:13:28 +00001063 bool Value = false;
1064 if (!IsValid)
1065 Diag(StartLoc, diag::err_feature_check_malformed);
1066 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +00001067 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +00001068 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +00001069 } else if (II == Ident__has_attribute)
1070 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001071 else if (II == Ident__has_extension)
1072 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +00001073 else {
Chris Lattner148772a2009-06-13 07:13:28 +00001074 assert(II == Ident__has_feature && "Must be feature check");
1075 Value = HasFeature(*this, FeatureII);
1076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Benjamin Kramerb1765912010-01-27 16:38:22 +00001078 OS << (int)Value;
Chris Lattner28310922012-01-31 18:53:44 +00001079 if (IsValid)
1080 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +00001081 } else if (II == Ident__has_include ||
1082 II == Ident__has_include_next) {
1083 // The argument to these two builtins should be a parenthesized
1084 // file name string literal using angle brackets (<>) or
1085 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +00001086 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001087 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +00001088 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +00001089 else
Chris Lattner3ed572e2011-01-15 06:57:04 +00001090 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +00001091 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001092 Tok.setKind(tok::numeric_constant);
Ted Kremenekd7681502011-10-12 19:46:30 +00001093 } else if (II == Ident__has_warning) {
1094 // The argument should be a parenthesized string literal.
1095 // The argument to these builtins should be a parenthesized identifier.
1096 SourceLocation StartLoc = Tok.getLocation();
1097 bool IsValid = false;
1098 bool Value = false;
1099 // Read the '('.
1100 Lex(Tok);
1101 do {
1102 if (Tok.is(tok::l_paren)) {
1103 // Read the string.
1104 Lex(Tok);
1105
1106 // We need at least one string literal.
1107 if (!Tok.is(tok::string_literal)) {
1108 StartLoc = Tok.getLocation();
1109 IsValid = false;
1110 // Eat tokens until ')'.
1111 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1112 break;
1113 }
1114
1115 // String concatenation allows multiple strings, which can even come
1116 // from macro expansion.
1117 SmallVector<Token, 4> StrToks;
1118 while (Tok.is(tok::string_literal)) {
Richard Smith99831e42012-03-06 03:21:47 +00001119 // Complain about, and drop, any ud-suffix.
1120 if (Tok.hasUDSuffix())
1121 Diag(Tok, diag::err_invalid_string_udl);
Ted Kremenekd7681502011-10-12 19:46:30 +00001122 StrToks.push_back(Tok);
1123 LexUnexpandedToken(Tok);
1124 }
1125
1126 // Is the end a ')'?
1127 if (!(IsValid = Tok.is(tok::r_paren)))
1128 break;
1129
1130 // Concatenate and parse the strings.
1131 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1132 assert(Literal.isAscii() && "Didn't allow wide strings in");
1133 if (Literal.hadError)
1134 break;
1135 if (Literal.Pascal) {
1136 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1137 break;
1138 }
1139
1140 StringRef WarningName(Literal.GetString());
1141
1142 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1143 WarningName[1] != 'W') {
1144 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1145 break;
1146 }
1147
1148 // Finally, check if the warning flags maps to a diagnostic group.
1149 // We construct a SmallVector here to talk to getDiagnosticIDs().
1150 // Although we don't use the result, this isn't a hot path, and not
1151 // worth special casing.
1152 llvm::SmallVector<diag::kind, 10> Diags;
1153 Value = !getDiagnostics().getDiagnosticIDs()->
1154 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1155 }
1156 } while (false);
1157
1158 if (!IsValid)
1159 Diag(StartLoc, diag::err_warning_check_malformed);
1160
1161 OS << (int)Value;
1162 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001163 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001164 llvm_unreachable("Unknown identifier!");
Chris Lattnera3b605e2008-03-09 03:13:06 +00001165 }
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001166 CreateString(OS.str().data(), OS.str().size(), Tok,
1167 Tok.getLocation(), Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +00001168}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001169
1170void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1171 // If the 'used' status changed, and the macro requires 'unused' warning,
1172 // remove its SourceLocation from the warn-for-unused-macro locations.
1173 if (MI->isWarnIfUnused() && !MI->isUsed())
1174 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1175 MI->setIsUsed(true);
1176}