PPMacroExpansion.cpp revision 212904
1//===--- 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"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/CodeCompletionHandler.h"
23#include "llvm/ADT/StringSwitch.h"
24#include "llvm/Support/raw_ostream.h"
25#include <cstdio>
26#include <ctime>
27using namespace clang;
28
29/// setMacroInfo - Specify a macro for this identifier.
30///
31void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
32  if (MI) {
33    Macros[II] = MI;
34    II->setHasMacroDefinition(true);
35  } else if (II->hasMacroDefinition()) {
36    Macros.erase(II);
37    II->setHasMacroDefinition(false);
38  }
39}
40
41/// RegisterBuiltinMacro - Register the specified identifier in the identifier
42/// table and mark it as a builtin macro to be expanded.
43static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
44  // Get the identifier.
45  IdentifierInfo *Id = PP.getIdentifierInfo(Name);
46
47  // Mark it as being a macro that is builtin.
48  MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
49  MI->setIsBuiltinMacro();
50  PP.setMacroInfo(Id, MI);
51  return Id;
52}
53
54
55/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
56/// identifier table.
57void Preprocessor::RegisterBuiltinMacros() {
58  Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
59  Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
60  Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
61  Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
62  Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
63  Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
64
65  // GCC Extensions.
66  Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
67  Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
68  Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
69
70  // Clang Extensions.
71  Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
72  Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
73  Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
74  Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
75
76  // Microsoft Extensions.
77  if (Features.Microsoft)
78    Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
79  else
80    Ident__pragma = 0;
81}
82
83/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
84/// in its expansion, currently expands to that token literally.
85static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
86                                          const IdentifierInfo *MacroIdent,
87                                          Preprocessor &PP) {
88  IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
89
90  // If the token isn't an identifier, it's always literally expanded.
91  if (II == 0) return true;
92
93  // If the identifier is a macro, and if that macro is enabled, it may be
94  // expanded so it's not a trivial expansion.
95  if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
96      // Fast expanding "#define X X" is ok, because X would be disabled.
97      II != MacroIdent)
98    return false;
99
100  // If this is an object-like macro invocation, it is safe to trivially expand
101  // it.
102  if (MI->isObjectLike()) return true;
103
104  // If this is a function-like macro invocation, it's safe to trivially expand
105  // as long as the identifier is not a macro argument.
106  for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
107       I != E; ++I)
108    if (*I == II)
109      return false;   // Identifier is a macro argument.
110
111  return true;
112}
113
114
115/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
116/// lexed is a '('.  If so, consume the token and return true, if not, this
117/// method should have no observable side-effect on the lexed tokens.
118bool Preprocessor::isNextPPTokenLParen() {
119  // Do some quick tests for rejection cases.
120  unsigned Val;
121  if (CurLexer)
122    Val = CurLexer->isNextPPTokenLParen();
123  else if (CurPTHLexer)
124    Val = CurPTHLexer->isNextPPTokenLParen();
125  else
126    Val = CurTokenLexer->isNextTokenLParen();
127
128  if (Val == 2) {
129    // We have run off the end.  If it's a source file we don't
130    // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
131    // macro stack.
132    if (CurPPLexer)
133      return false;
134    for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
135      IncludeStackInfo &Entry = IncludeMacroStack[i-1];
136      if (Entry.TheLexer)
137        Val = Entry.TheLexer->isNextPPTokenLParen();
138      else if (Entry.ThePTHLexer)
139        Val = Entry.ThePTHLexer->isNextPPTokenLParen();
140      else
141        Val = Entry.TheTokenLexer->isNextTokenLParen();
142
143      if (Val != 2)
144        break;
145
146      // Ran off the end of a source file?
147      if (Entry.ThePPLexer)
148        return false;
149    }
150  }
151
152  // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
153  // have found something that isn't a '(' or we found the end of the
154  // translation unit.  In either case, return false.
155  return Val == 1;
156}
157
158/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
159/// expanded as a macro, handle it and return the next token as 'Identifier'.
160bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
161                                                 MacroInfo *MI) {
162  if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
163
164  // If this is a macro expansion in the "#if !defined(x)" line for the file,
165  // then the macro could expand to different things in other contexts, we need
166  // to disable the optimization in this case.
167  if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
168
169  // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
170  if (MI->isBuiltinMacro()) {
171    ExpandBuiltinMacro(Identifier);
172    return false;
173  }
174
175  /// Args - If this is a function-like macro expansion, this contains,
176  /// for each macro argument, the list of tokens that were provided to the
177  /// invocation.
178  MacroArgs *Args = 0;
179
180  // Remember where the end of the instantiation occurred.  For an object-like
181  // macro, this is the identifier.  For a function-like macro, this is the ')'.
182  SourceLocation InstantiationEnd = Identifier.getLocation();
183
184  // If this is a function-like macro, read the arguments.
185  if (MI->isFunctionLike()) {
186    // C99 6.10.3p10: If the preprocessing token immediately after the the macro
187    // name isn't a '(', this macro should not be expanded.
188    if (!isNextPPTokenLParen())
189      return true;
190
191    // Remember that we are now parsing the arguments to a macro invocation.
192    // Preprocessor directives used inside macro arguments are not portable, and
193    // this enables the warning.
194    InMacroArgs = true;
195    Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
196
197    // Finished parsing args.
198    InMacroArgs = false;
199
200    // If there was an error parsing the arguments, bail out.
201    if (Args == 0) return false;
202
203    ++NumFnMacroExpanded;
204  } else {
205    ++NumMacroExpanded;
206  }
207
208  // Notice that this macro has been used.
209  MI->setIsUsed(true);
210
211  // If we started lexing a macro, enter the macro expansion body.
212
213  // If this macro expands to no tokens, don't bother to push it onto the
214  // expansion stack, only to take it right back off.
215  if (MI->getNumTokens() == 0) {
216    // No need for arg info.
217    if (Args) Args->destroy(*this);
218
219    // Ignore this macro use, just return the next token in the current
220    // buffer.
221    bool HadLeadingSpace = Identifier.hasLeadingSpace();
222    bool IsAtStartOfLine = Identifier.isAtStartOfLine();
223
224    Lex(Identifier);
225
226    // If the identifier isn't on some OTHER line, inherit the leading
227    // whitespace/first-on-a-line property of this token.  This handles
228    // stuff like "! XX," -> "! ," and "   XX," -> "    ,", when XX is
229    // empty.
230    if (!Identifier.isAtStartOfLine()) {
231      if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
232      if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
233    }
234    ++NumFastMacroExpanded;
235    return false;
236
237  } else if (MI->getNumTokens() == 1 &&
238             isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
239                                           *this)) {
240    // Otherwise, if this macro expands into a single trivially-expanded
241    // token: expand it now.  This handles common cases like
242    // "#define VAL 42".
243
244    // No need for arg info.
245    if (Args) Args->destroy(*this);
246
247    // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
248    // identifier to the expanded token.
249    bool isAtStartOfLine = Identifier.isAtStartOfLine();
250    bool hasLeadingSpace = Identifier.hasLeadingSpace();
251
252    // Remember where the token is instantiated.
253    SourceLocation InstantiateLoc = Identifier.getLocation();
254
255    // Replace the result token.
256    Identifier = MI->getReplacementToken(0);
257
258    // Restore the StartOfLine/LeadingSpace markers.
259    Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
260    Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
261
262    // Update the tokens location to include both its instantiation and physical
263    // locations.
264    SourceLocation Loc =
265      SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
266                                       InstantiationEnd,Identifier.getLength());
267    Identifier.setLocation(Loc);
268
269    // If this is a disabled macro or #define X X, we must mark the result as
270    // unexpandable.
271    if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
272      if (MacroInfo *NewMI = getMacroInfo(NewII))
273        if (!NewMI->isEnabled() || NewMI == MI)
274          Identifier.setFlag(Token::DisableExpand);
275    }
276
277    // Since this is not an identifier token, it can't be macro expanded, so
278    // we're done.
279    ++NumFastMacroExpanded;
280    return false;
281  }
282
283  // Start expanding the macro.
284  EnterMacro(Identifier, InstantiationEnd, Args);
285
286  // Now that the macro is at the top of the include stack, ask the
287  // preprocessor to read the next token from it.
288  Lex(Identifier);
289  return false;
290}
291
292/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
293/// token is the '(' of the macro, this method is invoked to read all of the
294/// actual arguments specified for the macro invocation.  This returns null on
295/// error.
296MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
297                                                   MacroInfo *MI,
298                                                   SourceLocation &MacroEnd) {
299  // The number of fixed arguments to parse.
300  unsigned NumFixedArgsLeft = MI->getNumArgs();
301  bool isVariadic = MI->isVariadic();
302
303  // Outer loop, while there are more arguments, keep reading them.
304  Token Tok;
305
306  // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
307  // an argument value in a macro could expand to ',' or '(' or ')'.
308  LexUnexpandedToken(Tok);
309  assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
310
311  // ArgTokens - Build up a list of tokens that make up each argument.  Each
312  // argument is separated by an EOF token.  Use a SmallVector so we can avoid
313  // heap allocations in the common case.
314  llvm::SmallVector<Token, 64> ArgTokens;
315
316  unsigned NumActuals = 0;
317  while (Tok.isNot(tok::r_paren)) {
318    assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
319           "only expect argument separators here");
320
321    unsigned ArgTokenStart = ArgTokens.size();
322    SourceLocation ArgStartLoc = Tok.getLocation();
323
324    // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
325    // that we already consumed the first one.
326    unsigned NumParens = 0;
327
328    while (1) {
329      // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
330      // an argument value in a macro could expand to ',' or '(' or ')'.
331      LexUnexpandedToken(Tok);
332
333      if (Tok.is(tok::code_completion)) {
334        if (CodeComplete)
335          CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
336                                                  MI, NumActuals);
337        LexUnexpandedToken(Tok);
338      }
339
340      if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
341        Diag(MacroName, diag::err_unterm_macro_invoc);
342        // Do not lose the EOF/EOM.  Return it to the client.
343        MacroName = Tok;
344        return 0;
345      } else if (Tok.is(tok::r_paren)) {
346        // If we found the ) token, the macro arg list is done.
347        if (NumParens-- == 0) {
348          MacroEnd = Tok.getLocation();
349          break;
350        }
351      } else if (Tok.is(tok::l_paren)) {
352        ++NumParens;
353      } else if (Tok.is(tok::comma) && NumParens == 0) {
354        // Comma ends this argument if there are more fixed arguments expected.
355        // However, if this is a variadic macro, and this is part of the
356        // variadic part, then the comma is just an argument token.
357        if (!isVariadic) break;
358        if (NumFixedArgsLeft > 1)
359          break;
360      } else if (Tok.is(tok::comment) && !KeepMacroComments) {
361        // If this is a comment token in the argument list and we're just in
362        // -C mode (not -CC mode), discard the comment.
363        continue;
364      } else if (Tok.getIdentifierInfo() != 0) {
365        // Reading macro arguments can cause macros that we are currently
366        // expanding from to be popped off the expansion stack.  Doing so causes
367        // them to be reenabled for expansion.  Here we record whether any
368        // identifiers we lex as macro arguments correspond to disabled macros.
369        // If so, we mark the token as noexpand.  This is a subtle aspect of
370        // C99 6.10.3.4p2.
371        if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
372          if (!MI->isEnabled())
373            Tok.setFlag(Token::DisableExpand);
374      }
375      ArgTokens.push_back(Tok);
376    }
377
378    // If this was an empty argument list foo(), don't add this as an empty
379    // argument.
380    if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
381      break;
382
383    // If this is not a variadic macro, and too many args were specified, emit
384    // an error.
385    if (!isVariadic && NumFixedArgsLeft == 0) {
386      if (ArgTokens.size() != ArgTokenStart)
387        ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
388
389      // Emit the diagnostic at the macro name in case there is a missing ).
390      // Emitting it at the , could be far away from the macro name.
391      Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
392      return 0;
393    }
394
395    // Empty arguments are standard in C99 and supported as an extension in
396    // other modes.
397    if (ArgTokens.size() == ArgTokenStart && !Features.C99)
398      Diag(Tok, diag::ext_empty_fnmacro_arg);
399
400    // Add a marker EOF token to the end of the token list for this argument.
401    Token EOFTok;
402    EOFTok.startToken();
403    EOFTok.setKind(tok::eof);
404    EOFTok.setLocation(Tok.getLocation());
405    EOFTok.setLength(0);
406    ArgTokens.push_back(EOFTok);
407    ++NumActuals;
408    assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
409    --NumFixedArgsLeft;
410  }
411
412  // Okay, we either found the r_paren.  Check to see if we parsed too few
413  // arguments.
414  unsigned MinArgsExpected = MI->getNumArgs();
415
416  // See MacroArgs instance var for description of this.
417  bool isVarargsElided = false;
418
419  if (NumActuals < MinArgsExpected) {
420    // There are several cases where too few arguments is ok, handle them now.
421    if (NumActuals == 0 && MinArgsExpected == 1) {
422      // #define A(X)  or  #define A(...)   ---> A()
423
424      // If there is exactly one argument, and that argument is missing,
425      // then we have an empty "()" argument empty list.  This is fine, even if
426      // the macro expects one argument (the argument is just empty).
427      isVarargsElided = MI->isVariadic();
428    } else if (MI->isVariadic() &&
429               (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
430                (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
431      // Varargs where the named vararg parameter is missing: ok as extension.
432      // #define A(x, ...)
433      // A("blah")
434      Diag(Tok, diag::ext_missing_varargs_arg);
435
436      // Remember this occurred, allowing us to elide the comma when used for
437      // cases like:
438      //   #define A(x, foo...) blah(a, ## foo)
439      //   #define B(x, ...) blah(a, ## __VA_ARGS__)
440      //   #define C(...) blah(a, ## __VA_ARGS__)
441      //  A(x) B(x) C()
442      isVarargsElided = true;
443    } else {
444      // Otherwise, emit the error.
445      Diag(Tok, diag::err_too_few_args_in_macro_invoc);
446      return 0;
447    }
448
449    // Add a marker EOF token to the end of the token list for this argument.
450    SourceLocation EndLoc = Tok.getLocation();
451    Tok.startToken();
452    Tok.setKind(tok::eof);
453    Tok.setLocation(EndLoc);
454    Tok.setLength(0);
455    ArgTokens.push_back(Tok);
456
457    // If we expect two arguments, add both as empty.
458    if (NumActuals == 0 && MinArgsExpected == 2)
459      ArgTokens.push_back(Tok);
460
461  } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
462    // Emit the diagnostic at the macro name in case there is a missing ).
463    // Emitting it at the , could be far away from the macro name.
464    Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
465    return 0;
466  }
467
468  return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
469                           isVarargsElided, *this);
470}
471
472/// ComputeDATE_TIME - Compute the current time, enter it into the specified
473/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
474/// the identifier tokens inserted.
475static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
476                             Preprocessor &PP) {
477  time_t TT = time(0);
478  struct tm *TM = localtime(&TT);
479
480  static const char * const Months[] = {
481    "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
482  };
483
484  char TmpBuffer[100];
485  sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
486          TM->tm_year+1900);
487
488  Token TmpTok;
489  TmpTok.startToken();
490  PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
491  DATELoc = TmpTok.getLocation();
492
493  sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
494  PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
495  TIMELoc = TmpTok.getLocation();
496}
497
498
499/// HasFeature - Return true if we recognize and implement the specified feature
500/// specified by the identifier.
501static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
502  const LangOptions &LangOpts = PP.getLangOptions();
503
504  return llvm::StringSwitch<bool>(II->getName())
505           .Case("attribute_analyzer_noreturn", true)
506           .Case("attribute_cf_returns_not_retained", true)
507           .Case("attribute_cf_returns_retained", true)
508           .Case("attribute_ext_vector_type", true)
509           .Case("attribute_ns_returns_not_retained", true)
510           .Case("attribute_ns_returns_retained", true)
511           .Case("attribute_objc_ivar_unused", true)
512           .Case("attribute_overloadable", true)
513           .Case("blocks", LangOpts.Blocks)
514           .Case("cxx_attributes", LangOpts.CPlusPlus0x)
515           .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
516           .Case("cxx_decltype", LangOpts.CPlusPlus0x)
517           .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
518           .Case("cxx_exceptions", LangOpts.Exceptions)
519           .Case("cxx_rtti", LangOpts.RTTI)
520           .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
521           .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
522           .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
523           .Case("ownership_holds", true)
524           .Case("ownership_returns", true)
525           .Case("ownership_takes", true)
526           .Case("cxx_inline_namespaces", true)
527         //.Case("cxx_concepts", false)
528         //.Case("cxx_lambdas", false)
529         //.Case("cxx_nullptr", false)
530         //.Case("cxx_rvalue_references", false)
531         //.Case("cxx_variadic_templates", false)
532           .Case("tls", PP.getTargetInfo().isTLSSupported())
533           .Default(false);
534}
535
536/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
537/// or '__has_include_next("path")' expression.
538/// Returns true if successful.
539static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
540        IdentifierInfo *II, Preprocessor &PP,
541        const DirectoryLookup *LookupFrom) {
542  SourceLocation LParenLoc;
543
544  // Get '('.
545  PP.LexNonComment(Tok);
546
547  // Ensure we have a '('.
548  if (Tok.isNot(tok::l_paren)) {
549    PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
550    return false;
551  }
552
553  // Save '(' location for possible missing ')' message.
554  LParenLoc = Tok.getLocation();
555
556  // Get the file name.
557  PP.getCurrentLexer()->LexIncludeFilename(Tok);
558
559  // Reserve a buffer to get the spelling.
560  llvm::SmallString<128> FilenameBuffer;
561  llvm::StringRef Filename;
562
563  switch (Tok.getKind()) {
564  case tok::eom:
565    // If the token kind is EOM, the error has already been diagnosed.
566    return false;
567
568  case tok::angle_string_literal:
569  case tok::string_literal: {
570    bool Invalid = false;
571    Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
572    if (Invalid)
573      return false;
574    break;
575  }
576
577  case tok::less:
578    // This could be a <foo/bar.h> file coming from a macro expansion.  In this
579    // case, glue the tokens together into FilenameBuffer and interpret those.
580    FilenameBuffer.push_back('<');
581    if (PP.ConcatenateIncludeName(FilenameBuffer))
582      return false;   // Found <eom> but no ">"?  Diagnostic already emitted.
583    Filename = FilenameBuffer.str();
584    break;
585  default:
586    PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
587    return false;
588  }
589
590  bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
591  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
592  // error.
593  if (Filename.empty())
594    return false;
595
596  // Search include directories.
597  const DirectoryLookup *CurDir;
598  const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
599
600  // Get the result value.  Result = true means the file exists.
601  Result = File != 0;
602
603  // Get ')'.
604  PP.LexNonComment(Tok);
605
606  // Ensure we have a trailing ).
607  if (Tok.isNot(tok::r_paren)) {
608    PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
609    PP.Diag(LParenLoc, diag::note_matching) << "(";
610    return false;
611  }
612
613  return true;
614}
615
616/// EvaluateHasInclude - Process a '__has_include("path")' expression.
617/// Returns true if successful.
618static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
619                               Preprocessor &PP) {
620  return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
621}
622
623/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
624/// Returns true if successful.
625static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
626                                   IdentifierInfo *II, Preprocessor &PP) {
627  // __has_include_next is like __has_include, except that we start
628  // searching after the current found directory.  If we can't do this,
629  // issue a diagnostic.
630  const DirectoryLookup *Lookup = PP.GetCurDirLookup();
631  if (PP.isInPrimaryFile()) {
632    Lookup = 0;
633    PP.Diag(Tok, diag::pp_include_next_in_primary);
634  } else if (Lookup == 0) {
635    PP.Diag(Tok, diag::pp_include_next_absolute_path);
636  } else {
637    // Start looking up in the next directory.
638    ++Lookup;
639  }
640
641  return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
642}
643
644/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
645/// as a builtin macro, handle it and return the next token as 'Tok'.
646void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
647  // Figure out which token this is.
648  IdentifierInfo *II = Tok.getIdentifierInfo();
649  assert(II && "Can't be a macro without id info!");
650
651  // If this is an _Pragma or Microsoft __pragma directive, expand it,
652  // invoke the pragma handler, then lex the token after it.
653  if (II == Ident_Pragma)
654    return Handle_Pragma(Tok);
655  else if (II == Ident__pragma) // in non-MS mode this is null
656    return HandleMicrosoft__pragma(Tok);
657
658  ++NumBuiltinMacroExpanded;
659
660  llvm::SmallString<128> TmpBuffer;
661  llvm::raw_svector_ostream OS(TmpBuffer);
662
663  // Set up the return result.
664  Tok.setIdentifierInfo(0);
665  Tok.clearFlag(Token::NeedsCleaning);
666
667  if (II == Ident__LINE__) {
668    // C99 6.10.8: "__LINE__: The presumed line number (within the current
669    // source file) of the current source line (an integer constant)".  This can
670    // be affected by #line.
671    SourceLocation Loc = Tok.getLocation();
672
673    // Advance to the location of the first _, this might not be the first byte
674    // of the token if it starts with an escaped newline.
675    Loc = AdvanceToTokenCharacter(Loc, 0);
676
677    // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
678    // a macro instantiation.  This doesn't matter for object-like macros, but
679    // can matter for a function-like macro that expands to contain __LINE__.
680    // Skip down through instantiation points until we find a file loc for the
681    // end of the instantiation history.
682    Loc = SourceMgr.getInstantiationRange(Loc).second;
683    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
684
685    // __LINE__ expands to a simple numeric value.
686    OS << PLoc.getLine();
687    Tok.setKind(tok::numeric_constant);
688  } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
689    // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
690    // character string literal)". This can be affected by #line.
691    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
692
693    // __BASE_FILE__ is a GNU extension that returns the top of the presumed
694    // #include stack instead of the current file.
695    if (II == Ident__BASE_FILE__) {
696      SourceLocation NextLoc = PLoc.getIncludeLoc();
697      while (NextLoc.isValid()) {
698        PLoc = SourceMgr.getPresumedLoc(NextLoc);
699        NextLoc = PLoc.getIncludeLoc();
700      }
701    }
702
703    // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
704    llvm::SmallString<128> FN;
705    FN += PLoc.getFilename();
706    Lexer::Stringify(FN);
707    OS << '"' << FN.str() << '"';
708    Tok.setKind(tok::string_literal);
709  } else if (II == Ident__DATE__) {
710    if (!DATELoc.isValid())
711      ComputeDATE_TIME(DATELoc, TIMELoc, *this);
712    Tok.setKind(tok::string_literal);
713    Tok.setLength(strlen("\"Mmm dd yyyy\""));
714    Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
715                                                     Tok.getLocation(),
716                                                     Tok.getLength()));
717    return;
718  } else if (II == Ident__TIME__) {
719    if (!TIMELoc.isValid())
720      ComputeDATE_TIME(DATELoc, TIMELoc, *this);
721    Tok.setKind(tok::string_literal);
722    Tok.setLength(strlen("\"hh:mm:ss\""));
723    Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
724                                                     Tok.getLocation(),
725                                                     Tok.getLength()));
726    return;
727  } else if (II == Ident__INCLUDE_LEVEL__) {
728    // Compute the presumed include depth of this token.  This can be affected
729    // by GNU line markers.
730    unsigned Depth = 0;
731
732    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
733    PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
734    for (; PLoc.isValid(); ++Depth)
735      PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
736
737    // __INCLUDE_LEVEL__ expands to a simple numeric value.
738    OS << Depth;
739    Tok.setKind(tok::numeric_constant);
740  } else if (II == Ident__TIMESTAMP__) {
741    // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
742    // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
743
744    // Get the file that we are lexing out of.  If we're currently lexing from
745    // a macro, dig into the include stack.
746    const FileEntry *CurFile = 0;
747    PreprocessorLexer *TheLexer = getCurrentFileLexer();
748
749    if (TheLexer)
750      CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
751
752    const char *Result;
753    if (CurFile) {
754      time_t TT = CurFile->getModificationTime();
755      struct tm *TM = localtime(&TT);
756      Result = asctime(TM);
757    } else {
758      Result = "??? ??? ?? ??:??:?? ????\n";
759    }
760    // Surround the string with " and strip the trailing newline.
761    OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
762    Tok.setKind(tok::string_literal);
763  } else if (II == Ident__COUNTER__) {
764    // __COUNTER__ expands to a simple numeric value.
765    OS << CounterValue++;
766    Tok.setKind(tok::numeric_constant);
767  } else if (II == Ident__has_feature ||
768             II == Ident__has_builtin) {
769    // The argument to these two builtins should be a parenthesized identifier.
770    SourceLocation StartLoc = Tok.getLocation();
771
772    bool IsValid = false;
773    IdentifierInfo *FeatureII = 0;
774
775    // Read the '('.
776    Lex(Tok);
777    if (Tok.is(tok::l_paren)) {
778      // Read the identifier
779      Lex(Tok);
780      if (Tok.is(tok::identifier)) {
781        FeatureII = Tok.getIdentifierInfo();
782
783        // Read the ')'.
784        Lex(Tok);
785        if (Tok.is(tok::r_paren))
786          IsValid = true;
787      }
788    }
789
790    bool Value = false;
791    if (!IsValid)
792      Diag(StartLoc, diag::err_feature_check_malformed);
793    else if (II == Ident__has_builtin) {
794      // Check for a builtin is trivial.
795      Value = FeatureII->getBuiltinID() != 0;
796    } else {
797      assert(II == Ident__has_feature && "Must be feature check");
798      Value = HasFeature(*this, FeatureII);
799    }
800
801    OS << (int)Value;
802    Tok.setKind(tok::numeric_constant);
803  } else if (II == Ident__has_include ||
804             II == Ident__has_include_next) {
805    // The argument to these two builtins should be a parenthesized
806    // file name string literal using angle brackets (<>) or
807    // double-quotes ("").
808    bool Value = false;
809    bool IsValid;
810    if (II == Ident__has_include)
811      IsValid = EvaluateHasInclude(Value, Tok, II, *this);
812    else
813      IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
814    OS << (int)Value;
815    Tok.setKind(tok::numeric_constant);
816  } else {
817    assert(0 && "Unknown identifier!");
818  }
819  CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
820}
821