1 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the top level handling of macro expasion for the
13 //===----------------------------------------------------------------------===//
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"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Lex/LexDiagnostic.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Lex/ExternalPreprocessorSource.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/Support/raw_ostream.h"
30 using namespace clang;
32 MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
33 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
35 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
37 if (Pos == Macros.end()) {
38 // Load this macro from the external source.
39 getExternalSource()->LoadMacroDefinition(II);
40 Pos = Macros.find(II);
42 assert(Pos != Macros.end() && "Identifier macro info is missing!");
46 /// setMacroInfo - Specify a macro for this identifier.
48 void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
51 II->setHasMacroDefinition(true);
52 } else if (II->hasMacroDefinition()) {
54 II->setHasMacroDefinition(false);
58 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
59 /// table and mark it as a builtin macro to be expanded.
60 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
61 // Get the identifier.
62 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
64 // Mark it as being a macro that is builtin.
65 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
66 MI->setIsBuiltinMacro();
67 PP.setMacroInfo(Id, MI);
72 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
74 void Preprocessor::RegisterBuiltinMacros() {
75 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
76 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
77 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
78 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
79 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
80 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
83 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
84 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
85 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
88 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
89 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
90 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
91 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
92 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
93 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
95 // Microsoft Extensions.
96 if (Features.Microsoft)
97 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
102 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
103 /// in its expansion, currently expands to that token literally.
104 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
105 const IdentifierInfo *MacroIdent,
107 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
109 // If the token isn't an identifier, it's always literally expanded.
110 if (II == 0) return true;
112 // If the identifier is a macro, and if that macro is enabled, it may be
113 // expanded so it's not a trivial expansion.
114 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
115 // Fast expanding "#define X X" is ok, because X would be disabled.
119 // If this is an object-like macro invocation, it is safe to trivially expand
121 if (MI->isObjectLike()) return true;
123 // If this is a function-like macro invocation, it's safe to trivially expand
124 // as long as the identifier is not a macro argument.
125 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
128 return false; // Identifier is a macro argument.
134 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
135 /// lexed is a '('. If so, consume the token and return true, if not, this
136 /// method should have no observable side-effect on the lexed tokens.
137 bool Preprocessor::isNextPPTokenLParen() {
138 // Do some quick tests for rejection cases.
141 Val = CurLexer->isNextPPTokenLParen();
142 else if (CurPTHLexer)
143 Val = CurPTHLexer->isNextPPTokenLParen();
145 Val = CurTokenLexer->isNextTokenLParen();
148 // We have run off the end. If it's a source file we don't
149 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
153 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
154 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
156 Val = Entry.TheLexer->isNextPPTokenLParen();
157 else if (Entry.ThePTHLexer)
158 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
160 Val = Entry.TheTokenLexer->isNextTokenLParen();
165 // Ran off the end of a source file?
166 if (Entry.ThePPLexer)
171 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
172 // have found something that isn't a '(' or we found the end of the
173 // translation unit. In either case, return false.
177 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
178 /// expanded as a macro, handle it and return the next token as 'Identifier'.
179 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
181 // If this is a macro expansion in the "#if !defined(x)" line for the file,
182 // then the macro could expand to different things in other contexts, we need
183 // to disable the optimization in this case.
184 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
186 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
187 if (MI->isBuiltinMacro()) {
188 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
189 ExpandBuiltinMacro(Identifier);
193 /// Args - If this is a function-like macro expansion, this contains,
194 /// for each macro argument, the list of tokens that were provided to the
198 // Remember where the end of the expansion occurred. For an object-like
199 // macro, this is the identifier. For a function-like macro, this is the ')'.
200 SourceLocation ExpansionEnd = Identifier.getLocation();
202 // If this is a function-like macro, read the arguments.
203 if (MI->isFunctionLike()) {
204 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
205 // name isn't a '(', this macro should not be expanded.
206 if (!isNextPPTokenLParen())
209 // Remember that we are now parsing the arguments to a macro invocation.
210 // Preprocessor directives used inside macro arguments are not portable, and
211 // this enables the warning.
213 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
215 // Finished parsing args.
218 // If there was an error parsing the arguments, bail out.
219 if (Args == 0) return false;
221 ++NumFnMacroExpanded;
226 // Notice that this macro has been used.
229 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
231 // If we started lexing a macro, enter the macro expansion body.
233 // Remember where the token is expanded.
234 SourceLocation ExpandLoc = Identifier.getLocation();
236 // If this macro expands to no tokens, don't bother to push it onto the
237 // expansion stack, only to take it right back off.
238 if (MI->getNumTokens() == 0) {
239 // No need for arg info.
240 if (Args) Args->destroy(*this);
242 // Ignore this macro use, just return the next token in the current
244 bool HadLeadingSpace = Identifier.hasLeadingSpace();
245 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
249 // If the identifier isn't on some OTHER line, inherit the leading
250 // whitespace/first-on-a-line property of this token. This handles
251 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
253 if (!Identifier.isAtStartOfLine()) {
254 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
255 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
257 Identifier.setFlag(Token::LeadingEmptyMacro);
258 LastEmptyMacroExpansionLoc = ExpandLoc;
259 ++NumFastMacroExpanded;
262 } else if (MI->getNumTokens() == 1 &&
263 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
265 // Otherwise, if this macro expands into a single trivially-expanded
266 // token: expand it now. This handles common cases like
269 // No need for arg info.
270 if (Args) Args->destroy(*this);
272 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
273 // identifier to the expanded token.
274 bool isAtStartOfLine = Identifier.isAtStartOfLine();
275 bool hasLeadingSpace = Identifier.hasLeadingSpace();
277 // Replace the result token.
278 Identifier = MI->getReplacementToken(0);
280 // Restore the StartOfLine/LeadingSpace markers.
281 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
282 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
284 // Update the tokens location to include both its expansion and physical
287 SourceMgr.createInstantiationLoc(Identifier.getLocation(), ExpandLoc,
288 ExpansionEnd,Identifier.getLength());
289 Identifier.setLocation(Loc);
291 // If this is a disabled macro or #define X X, we must mark the result as
293 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
294 if (MacroInfo *NewMI = getMacroInfo(NewII))
295 if (!NewMI->isEnabled() || NewMI == MI)
296 Identifier.setFlag(Token::DisableExpand);
299 // Since this is not an identifier token, it can't be macro expanded, so
301 ++NumFastMacroExpanded;
305 // Start expanding the macro.
306 EnterMacro(Identifier, ExpansionEnd, Args);
308 // Now that the macro is at the top of the include stack, ask the
309 // preprocessor to read the next token from it.
314 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
315 /// token is the '(' of the macro, this method is invoked to read all of the
316 /// actual arguments specified for the macro invocation. This returns null on
318 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
320 SourceLocation &MacroEnd) {
321 // The number of fixed arguments to parse.
322 unsigned NumFixedArgsLeft = MI->getNumArgs();
323 bool isVariadic = MI->isVariadic();
325 // Outer loop, while there are more arguments, keep reading them.
328 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
329 // an argument value in a macro could expand to ',' or '(' or ')'.
330 LexUnexpandedToken(Tok);
331 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
333 // ArgTokens - Build up a list of tokens that make up each argument. Each
334 // argument is separated by an EOF token. Use a SmallVector so we can avoid
335 // heap allocations in the common case.
336 llvm::SmallVector<Token, 64> ArgTokens;
338 unsigned NumActuals = 0;
339 while (Tok.isNot(tok::r_paren)) {
340 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
341 "only expect argument separators here");
343 unsigned ArgTokenStart = ArgTokens.size();
344 SourceLocation ArgStartLoc = Tok.getLocation();
346 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
347 // that we already consumed the first one.
348 unsigned NumParens = 0;
351 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
352 // an argument value in a macro could expand to ',' or '(' or ')'.
353 LexUnexpandedToken(Tok);
355 if (Tok.is(tok::code_completion)) {
357 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
359 LexUnexpandedToken(Tok);
362 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
363 Diag(MacroName, diag::err_unterm_macro_invoc);
364 // Do not lose the EOF/EOD. Return it to the client.
367 } else if (Tok.is(tok::r_paren)) {
368 // If we found the ) token, the macro arg list is done.
369 if (NumParens-- == 0) {
370 MacroEnd = Tok.getLocation();
373 } else if (Tok.is(tok::l_paren)) {
375 } else if (Tok.is(tok::comma) && NumParens == 0) {
376 // Comma ends this argument if there are more fixed arguments expected.
377 // However, if this is a variadic macro, and this is part of the
378 // variadic part, then the comma is just an argument token.
379 if (!isVariadic) break;
380 if (NumFixedArgsLeft > 1)
382 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
383 // If this is a comment token in the argument list and we're just in
384 // -C mode (not -CC mode), discard the comment.
386 } else if (Tok.getIdentifierInfo() != 0) {
387 // Reading macro arguments can cause macros that we are currently
388 // expanding from to be popped off the expansion stack. Doing so causes
389 // them to be reenabled for expansion. Here we record whether any
390 // identifiers we lex as macro arguments correspond to disabled macros.
391 // If so, we mark the token as noexpand. This is a subtle aspect of
393 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
394 if (!MI->isEnabled())
395 Tok.setFlag(Token::DisableExpand);
397 ArgTokens.push_back(Tok);
400 // If this was an empty argument list foo(), don't add this as an empty
402 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
405 // If this is not a variadic macro, and too many args were specified, emit
407 if (!isVariadic && NumFixedArgsLeft == 0) {
408 if (ArgTokens.size() != ArgTokenStart)
409 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
411 // Emit the diagnostic at the macro name in case there is a missing ).
412 // Emitting it at the , could be far away from the macro name.
413 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
417 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
419 if (ArgTokens.size() == ArgTokenStart && !Features.C99 && !Features.CPlusPlus0x)
420 Diag(Tok, diag::ext_empty_fnmacro_arg);
422 // Add a marker EOF token to the end of the token list for this argument.
425 EOFTok.setKind(tok::eof);
426 EOFTok.setLocation(Tok.getLocation());
428 ArgTokens.push_back(EOFTok);
430 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
434 // Okay, we either found the r_paren. Check to see if we parsed too few
436 unsigned MinArgsExpected = MI->getNumArgs();
438 // See MacroArgs instance var for description of this.
439 bool isVarargsElided = false;
441 if (NumActuals < MinArgsExpected) {
442 // There are several cases where too few arguments is ok, handle them now.
443 if (NumActuals == 0 && MinArgsExpected == 1) {
444 // #define A(X) or #define A(...) ---> A()
446 // If there is exactly one argument, and that argument is missing,
447 // then we have an empty "()" argument empty list. This is fine, even if
448 // the macro expects one argument (the argument is just empty).
449 isVarargsElided = MI->isVariadic();
450 } else if (MI->isVariadic() &&
451 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
452 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
453 // Varargs where the named vararg parameter is missing: ok as extension.
456 Diag(Tok, diag::ext_missing_varargs_arg);
458 // Remember this occurred, allowing us to elide the comma when used for
460 // #define A(x, foo...) blah(a, ## foo)
461 // #define B(x, ...) blah(a, ## __VA_ARGS__)
462 // #define C(...) blah(a, ## __VA_ARGS__)
464 isVarargsElided = true;
466 // Otherwise, emit the error.
467 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
471 // Add a marker EOF token to the end of the token list for this argument.
472 SourceLocation EndLoc = Tok.getLocation();
474 Tok.setKind(tok::eof);
475 Tok.setLocation(EndLoc);
477 ArgTokens.push_back(Tok);
479 // If we expect two arguments, add both as empty.
480 if (NumActuals == 0 && MinArgsExpected == 2)
481 ArgTokens.push_back(Tok);
483 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
484 // Emit the diagnostic at the macro name in case there is a missing ).
485 // Emitting it at the , could be far away from the macro name.
486 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
490 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
491 isVarargsElided, *this);
494 /// \brief Keeps macro expanded tokens for TokenLexers.
496 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
497 /// going to lex in the cache and when it finishes the tokens are removed
498 /// from the end of the cache.
499 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
500 llvm::ArrayRef<Token> tokens) {
505 size_t newIndex = MacroExpandedTokens.size();
506 bool cacheNeedsToGrow = tokens.size() >
507 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
508 MacroExpandedTokens.append(tokens.begin(), tokens.end());
510 if (cacheNeedsToGrow) {
511 // Go through all the TokenLexers whose 'Tokens' pointer points in the
512 // buffer and update the pointers to the (potential) new buffer array.
513 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
514 TokenLexer *prevLexer;
516 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
517 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
521 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
522 return MacroExpandedTokens.data() + newIndex;
525 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
526 assert(!MacroExpandingLexersStack.empty());
527 size_t tokIndex = MacroExpandingLexersStack.back().second;
528 assert(tokIndex < MacroExpandedTokens.size());
529 // Pop the cached macro expanded tokens from the end.
530 MacroExpandedTokens.resize(tokIndex);
531 MacroExpandingLexersStack.pop_back();
534 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
535 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
536 /// the identifier tokens inserted.
537 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
540 struct tm *TM = localtime(&TT);
542 static const char * const Months[] = {
543 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
548 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
551 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
557 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
558 DATELoc = TmpTok.getLocation();
561 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
563 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
565 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
566 TIMELoc = TmpTok.getLocation();
570 /// HasFeature - Return true if we recognize and implement the feature
571 /// specified by the identifier as a standard language feature.
572 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
573 const LangOptions &LangOpts = PP.getLangOptions();
575 return llvm::StringSwitch<bool>(II->getName())
576 .Case("attribute_analyzer_noreturn", true)
577 .Case("attribute_availability", true)
578 .Case("attribute_cf_returns_not_retained", true)
579 .Case("attribute_cf_returns_retained", true)
580 .Case("attribute_deprecated_with_message", true)
581 .Case("attribute_ext_vector_type", true)
582 .Case("attribute_ns_returns_not_retained", true)
583 .Case("attribute_ns_returns_retained", true)
584 .Case("attribute_ns_consumes_self", true)
585 .Case("attribute_ns_consumed", true)
586 .Case("attribute_cf_consumed", true)
587 .Case("attribute_objc_ivar_unused", true)
588 .Case("attribute_objc_method_family", true)
589 .Case("attribute_overloadable", true)
590 .Case("attribute_unavailable_with_message", true)
591 .Case("blocks", LangOpts.Blocks)
592 .Case("cxx_exceptions", LangOpts.Exceptions)
593 .Case("cxx_rtti", LangOpts.RTTI)
594 .Case("enumerator_attributes", true)
595 // Objective-C features
596 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
597 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
598 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
599 LangOpts.ObjCRuntimeHasWeak)
600 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
601 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
602 .Case("ownership_holds", true)
603 .Case("ownership_returns", true)
604 .Case("ownership_takes", true)
606 .Case("c_generic_selections", LangOpts.C1X)
607 .Case("c_static_assert", LangOpts.C1X)
609 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
610 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
611 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
612 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
613 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
614 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
615 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
616 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
617 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
618 //.Case("cxx_lambdas", false)
619 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
620 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
621 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
622 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
623 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
624 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
625 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
626 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
627 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
628 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
630 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
631 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
632 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
633 .Case("has_trivial_assign", LangOpts.CPlusPlus)
634 .Case("has_trivial_copy", LangOpts.CPlusPlus)
635 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
636 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
637 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
638 .Case("is_abstract", LangOpts.CPlusPlus)
639 .Case("is_base_of", LangOpts.CPlusPlus)
640 .Case("is_class", LangOpts.CPlusPlus)
641 .Case("is_convertible_to", LangOpts.CPlusPlus)
642 .Case("is_empty", LangOpts.CPlusPlus)
643 .Case("is_enum", LangOpts.CPlusPlus)
644 .Case("is_literal", LangOpts.CPlusPlus)
645 .Case("is_standard_layout", LangOpts.CPlusPlus)
646 .Case("is_pod", LangOpts.CPlusPlus)
647 .Case("is_polymorphic", LangOpts.CPlusPlus)
648 .Case("is_trivial", LangOpts.CPlusPlus)
649 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
650 .Case("is_union", LangOpts.CPlusPlus)
651 .Case("tls", PP.getTargetInfo().isTLSSupported())
655 /// HasExtension - Return true if we recognize and implement the feature
656 /// specified by the identifier, either as an extension or a standard language
658 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
659 if (HasFeature(PP, II))
662 // If the use of an extension results in an error diagnostic, extensions are
663 // effectively unavailable, so just return false here.
664 if (PP.getDiagnostics().getExtensionHandlingBehavior()==Diagnostic::Ext_Error)
667 const LangOptions &LangOpts = PP.getLangOptions();
669 // Because we inherit the feature list from HasFeature, this string switch
670 // must be less restrictive than HasFeature's.
671 return llvm::StringSwitch<bool>(II->getName())
672 // C1X features supported by other languages as extensions.
673 .Case("c_generic_selections", true)
674 .Case("c_static_assert", true)
675 // C++0x features supported by other languages as extensions.
676 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
677 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
678 .Case("cxx_override_control", LangOpts.CPlusPlus)
679 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
680 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
684 /// HasAttribute - Return true if we recognize and implement the attribute
685 /// specified by the given identifier.
686 static bool HasAttribute(const IdentifierInfo *II) {
687 return llvm::StringSwitch<bool>(II->getName())
688 #include "clang/Lex/AttrSpellings.inc"
692 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
693 /// or '__has_include_next("path")' expression.
694 /// Returns true if successful.
695 static bool EvaluateHasIncludeCommon(Token &Tok,
696 IdentifierInfo *II, Preprocessor &PP,
697 const DirectoryLookup *LookupFrom) {
698 SourceLocation LParenLoc;
701 PP.LexNonComment(Tok);
703 // Ensure we have a '('.
704 if (Tok.isNot(tok::l_paren)) {
705 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
709 // Save '(' location for possible missing ')' message.
710 LParenLoc = Tok.getLocation();
712 // Get the file name.
713 PP.getCurrentLexer()->LexIncludeFilename(Tok);
715 // Reserve a buffer to get the spelling.
716 llvm::SmallString<128> FilenameBuffer;
717 llvm::StringRef Filename;
718 SourceLocation EndLoc;
720 switch (Tok.getKind()) {
722 // If the token kind is EOD, the error has already been diagnosed.
725 case tok::angle_string_literal:
726 case tok::string_literal: {
727 bool Invalid = false;
728 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
735 // This could be a <foo/bar.h> file coming from a macro expansion. In this
736 // case, glue the tokens together into FilenameBuffer and interpret those.
737 FilenameBuffer.push_back('<');
738 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
739 return false; // Found <eod> but no ">"? Diagnostic already emitted.
740 Filename = FilenameBuffer.str();
743 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
747 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
748 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
750 if (Filename.empty())
753 // Search include directories.
754 const DirectoryLookup *CurDir;
755 const FileEntry *File =
756 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL);
758 // Get the result value. Result = true means the file exists.
759 bool Result = File != 0;
762 PP.LexNonComment(Tok);
764 // Ensure we have a trailing ).
765 if (Tok.isNot(tok::r_paren)) {
766 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
767 PP.Diag(LParenLoc, diag::note_matching) << "(";
774 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
775 /// Returns true if successful.
776 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
778 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
781 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
782 /// Returns true if successful.
783 static bool EvaluateHasIncludeNext(Token &Tok,
784 IdentifierInfo *II, Preprocessor &PP) {
785 // __has_include_next is like __has_include, except that we start
786 // searching after the current found directory. If we can't do this,
787 // issue a diagnostic.
788 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
789 if (PP.isInPrimaryFile()) {
791 PP.Diag(Tok, diag::pp_include_next_in_primary);
792 } else if (Lookup == 0) {
793 PP.Diag(Tok, diag::pp_include_next_absolute_path);
795 // Start looking up in the next directory.
799 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
802 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
803 /// as a builtin macro, handle it and return the next token as 'Tok'.
804 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
805 // Figure out which token this is.
806 IdentifierInfo *II = Tok.getIdentifierInfo();
807 assert(II && "Can't be a macro without id info!");
809 // If this is an _Pragma or Microsoft __pragma directive, expand it,
810 // invoke the pragma handler, then lex the token after it.
811 if (II == Ident_Pragma)
812 return Handle_Pragma(Tok);
813 else if (II == Ident__pragma) // in non-MS mode this is null
814 return HandleMicrosoft__pragma(Tok);
816 ++NumBuiltinMacroExpanded;
818 llvm::SmallString<128> TmpBuffer;
819 llvm::raw_svector_ostream OS(TmpBuffer);
821 // Set up the return result.
822 Tok.setIdentifierInfo(0);
823 Tok.clearFlag(Token::NeedsCleaning);
825 if (II == Ident__LINE__) {
826 // C99 6.10.8: "__LINE__: The presumed line number (within the current
827 // source file) of the current source line (an integer constant)". This can
828 // be affected by #line.
829 SourceLocation Loc = Tok.getLocation();
831 // Advance to the location of the first _, this might not be the first byte
832 // of the token if it starts with an escaped newline.
833 Loc = AdvanceToTokenCharacter(Loc, 0);
835 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
836 // a macro expansion. This doesn't matter for object-like macros, but
837 // can matter for a function-like macro that expands to contain __LINE__.
838 // Skip down through expansion points until we find a file loc for the
839 // end of the expansion history.
840 Loc = SourceMgr.getInstantiationRange(Loc).second;
841 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
843 // __LINE__ expands to a simple numeric value.
844 OS << (PLoc.isValid()? PLoc.getLine() : 1);
845 Tok.setKind(tok::numeric_constant);
846 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
847 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
848 // character string literal)". This can be affected by #line.
849 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
851 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
852 // #include stack instead of the current file.
853 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
854 SourceLocation NextLoc = PLoc.getIncludeLoc();
855 while (NextLoc.isValid()) {
856 PLoc = SourceMgr.getPresumedLoc(NextLoc);
857 if (PLoc.isInvalid())
860 NextLoc = PLoc.getIncludeLoc();
864 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
865 llvm::SmallString<128> FN;
866 if (PLoc.isValid()) {
867 FN += PLoc.getFilename();
868 Lexer::Stringify(FN);
869 OS << '"' << FN.str() << '"';
871 Tok.setKind(tok::string_literal);
872 } else if (II == Ident__DATE__) {
873 if (!DATELoc.isValid())
874 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
875 Tok.setKind(tok::string_literal);
876 Tok.setLength(strlen("\"Mmm dd yyyy\""));
877 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
881 } else if (II == Ident__TIME__) {
882 if (!TIMELoc.isValid())
883 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
884 Tok.setKind(tok::string_literal);
885 Tok.setLength(strlen("\"hh:mm:ss\""));
886 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
890 } else if (II == Ident__INCLUDE_LEVEL__) {
891 // Compute the presumed include depth of this token. This can be affected
892 // by GNU line markers.
895 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
896 if (PLoc.isValid()) {
897 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
898 for (; PLoc.isValid(); ++Depth)
899 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
902 // __INCLUDE_LEVEL__ expands to a simple numeric value.
904 Tok.setKind(tok::numeric_constant);
905 } else if (II == Ident__TIMESTAMP__) {
906 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
907 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
909 // Get the file that we are lexing out of. If we're currently lexing from
910 // a macro, dig into the include stack.
911 const FileEntry *CurFile = 0;
912 PreprocessorLexer *TheLexer = getCurrentFileLexer();
915 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
919 time_t TT = CurFile->getModificationTime();
920 struct tm *TM = localtime(&TT);
921 Result = asctime(TM);
923 Result = "??? ??? ?? ??:??:?? ????\n";
925 // Surround the string with " and strip the trailing newline.
926 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
927 Tok.setKind(tok::string_literal);
928 } else if (II == Ident__COUNTER__) {
929 // __COUNTER__ expands to a simple numeric value.
930 OS << CounterValue++;
931 Tok.setKind(tok::numeric_constant);
932 } else if (II == Ident__has_feature ||
933 II == Ident__has_extension ||
934 II == Ident__has_builtin ||
935 II == Ident__has_attribute) {
936 // The argument to these builtins should be a parenthesized identifier.
937 SourceLocation StartLoc = Tok.getLocation();
939 bool IsValid = false;
940 IdentifierInfo *FeatureII = 0;
944 if (Tok.is(tok::l_paren)) {
945 // Read the identifier
947 if (Tok.is(tok::identifier)) {
948 FeatureII = Tok.getIdentifierInfo();
952 if (Tok.is(tok::r_paren))
959 Diag(StartLoc, diag::err_feature_check_malformed);
960 else if (II == Ident__has_builtin) {
961 // Check for a builtin is trivial.
962 Value = FeatureII->getBuiltinID() != 0;
963 } else if (II == Ident__has_attribute)
964 Value = HasAttribute(FeatureII);
965 else if (II == Ident__has_extension)
966 Value = HasExtension(*this, FeatureII);
968 assert(II == Ident__has_feature && "Must be feature check");
969 Value = HasFeature(*this, FeatureII);
973 Tok.setKind(tok::numeric_constant);
974 } else if (II == Ident__has_include ||
975 II == Ident__has_include_next) {
976 // The argument to these two builtins should be a parenthesized
977 // file name string literal using angle brackets (<>) or
978 // double-quotes ("").
980 if (II == Ident__has_include)
981 Value = EvaluateHasInclude(Tok, II, *this);
983 Value = EvaluateHasIncludeNext(Tok, II, *this);
985 Tok.setKind(tok::numeric_constant);
987 assert(0 && "Unknown identifier!");
989 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
992 void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
993 // If the 'used' status changed, and the macro requires 'unused' warning,
994 // remove its SourceLocation from the warn-for-unused-macro locations.
995 if (MI->isWarnIfUnused() && !MI->isUsed())
996 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());