clang  9.0.0svn
PPMacroExpansion.cpp
Go to the documentation of this file.
1 //===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the top level handling of macro expansion for the
10 // preprocessor.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/Attributes.h"
17 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/MacroArgs.h"
28 #include "clang/Lex/MacroInfo.h"
29 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Lex/Token.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstddef>
50 #include <cstring>
51 #include <ctime>
52 #include <string>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace clang;
57 
60  if (!II->hadMacroDefinition())
61  return nullptr;
62  auto Pos = CurSubmoduleState->Macros.find(II);
63  return Pos == CurSubmoduleState->Macros.end() ? nullptr
64  : Pos->second.getLatest();
65 }
66 
68  assert(MD && "MacroDirective should be non-zero!");
69  assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
70 
71  MacroState &StoredMD = CurSubmoduleState->Macros[II];
72  auto *OldMD = StoredMD.getLatest();
73  MD->setPrevious(OldMD);
74  StoredMD.setLatest(MD);
75  StoredMD.overrideActiveModuleMacros(*this, II);
76 
77  if (needModuleMacros()) {
78  // Track that we created a new macro directive, so we know we should
79  // consider building a ModuleMacro for it when we get to the end of
80  // the module.
81  PendingModuleMacroNames.push_back(II);
82  }
83 
84  // Set up the identifier as having associated macro history.
85  II->setHasMacroDefinition(true);
86  if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
87  II->setHasMacroDefinition(false);
88  if (II->isFromAST())
90 }
91 
93  MacroDirective *ED,
94  MacroDirective *MD) {
95  // Normally, when a macro is defined, it goes through appendMacroDirective()
96  // above, which chains a macro to previous defines, undefs, etc.
97  // However, in a pch, the whole macro history up to the end of the pch is
98  // stored, so ASTReader goes through this function instead.
99  // However, built-in macros are already registered in the Preprocessor
100  // ctor, and ASTWriter stops writing the macro chain at built-in macros,
101  // so in that case the chain from the pch needs to be spliced to the existing
102  // built-in.
103 
104  assert(II && MD);
105  MacroState &StoredMD = CurSubmoduleState->Macros[II];
106 
107  if (auto *OldMD = StoredMD.getLatest()) {
108  // shouldIgnoreMacro() in ASTWriter also stops at macros from the
109  // predefines buffer in module builds. However, in module builds, modules
110  // are loaded completely before predefines are processed, so StoredMD
111  // will be nullptr for them when they're loaded. StoredMD should only be
112  // non-nullptr for builtins read from a pch file.
113  assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
114  "only built-ins should have an entry here");
115  assert(!OldMD->getPrevious() && "builtin should only have a single entry");
116  ED->setPrevious(OldMD);
117  StoredMD.setLatest(MD);
118  } else {
119  StoredMD = MD;
120  }
121 
122  // Setup the identifier as having associated macro history.
123  II->setHasMacroDefinition(true);
124  if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
125  II->setHasMacroDefinition(false);
126 }
127 
129  MacroInfo *Macro,
130  ArrayRef<ModuleMacro *> Overrides,
131  bool &New) {
132  llvm::FoldingSetNodeID ID;
133  ModuleMacro::Profile(ID, Mod, II);
134 
135  void *InsertPos;
136  if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
137  New = false;
138  return MM;
139  }
140 
141  auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
142  ModuleMacros.InsertNode(MM, InsertPos);
143 
144  // Each overridden macro is now overridden by one more macro.
145  bool HidAny = false;
146  for (auto *O : Overrides) {
147  HidAny |= (O->NumOverriddenBy == 0);
148  ++O->NumOverriddenBy;
149  }
150 
151  // If we were the first overrider for any macro, it's no longer a leaf.
152  auto &LeafMacros = LeafModuleMacros[II];
153  if (HidAny) {
154  LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
155  [](ModuleMacro *MM) {
156  return MM->NumOverriddenBy != 0;
157  }),
158  LeafMacros.end());
159  }
160 
161  // The new macro is always a leaf macro.
162  LeafMacros.push_back(MM);
163  // The identifier now has defined macros (that may or may not be visible).
164  II->setHasMacroDefinition(true);
165 
166  New = true;
167  return MM;
168 }
169 
171  llvm::FoldingSetNodeID ID;
172  ModuleMacro::Profile(ID, Mod, II);
173 
174  void *InsertPos;
175  return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
176 }
177 
178 void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
179  ModuleMacroInfo &Info) {
180  assert(Info.ActiveModuleMacrosGeneration !=
181  CurSubmoduleState->VisibleModules.getGeneration() &&
182  "don't need to update this macro name info");
183  Info.ActiveModuleMacrosGeneration =
184  CurSubmoduleState->VisibleModules.getGeneration();
185 
186  auto Leaf = LeafModuleMacros.find(II);
187  if (Leaf == LeafModuleMacros.end()) {
188  // No imported macros at all: nothing to do.
189  return;
190  }
191 
192  Info.ActiveModuleMacros.clear();
193 
194  // Every macro that's locally overridden is overridden by a visible macro.
195  llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
196  for (auto *O : Info.OverriddenMacros)
197  NumHiddenOverrides[O] = -1;
198 
199  // Collect all macros that are not overridden by a visible macro.
201  for (auto *LeafMM : Leaf->second) {
202  assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
203  if (NumHiddenOverrides.lookup(LeafMM) == 0)
204  Worklist.push_back(LeafMM);
205  }
206  while (!Worklist.empty()) {
207  auto *MM = Worklist.pop_back_val();
208  if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
209  // We only care about collecting definitions; undefinitions only act
210  // to override other definitions.
211  if (MM->getMacroInfo())
212  Info.ActiveModuleMacros.push_back(MM);
213  } else {
214  for (auto *O : MM->overrides())
215  if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
216  Worklist.push_back(O);
217  }
218  }
219  // Our reverse postorder walk found the macros in reverse order.
220  std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
221 
222  // Determine whether the macro name is ambiguous.
223  MacroInfo *MI = nullptr;
224  bool IsSystemMacro = true;
225  bool IsAmbiguous = false;
226  if (auto *MD = Info.MD) {
227  while (MD && isa<VisibilityMacroDirective>(MD))
228  MD = MD->getPrevious();
229  if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
230  MI = DMD->getInfo();
231  IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
232  }
233  }
234  for (auto *Active : Info.ActiveModuleMacros) {
235  auto *NewMI = Active->getMacroInfo();
236 
237  // Before marking the macro as ambiguous, check if this is a case where
238  // both macros are in system headers. If so, we trust that the system
239  // did not get it wrong. This also handles cases where Clang's own
240  // headers have a different spelling of certain system macros:
241  // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
242  // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
243  //
244  // FIXME: Remove the defined-in-system-headers check. clang's limits.h
245  // overrides the system limits.h's macros, so there's no conflict here.
246  if (MI && NewMI != MI &&
247  !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
248  IsAmbiguous = true;
249  IsSystemMacro &= Active->getOwningModule()->IsSystem ||
250  SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
251  MI = NewMI;
252  }
253  Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
254 }
255 
258  auto LeafIt = LeafModuleMacros.find(II);
259  if (LeafIt != LeafModuleMacros.end())
260  Leaf = LeafIt->second;
261  const MacroState *State = nullptr;
262  auto Pos = CurSubmoduleState->Macros.find(II);
263  if (Pos != CurSubmoduleState->Macros.end())
264  State = &Pos->second;
265 
266  llvm::errs() << "MacroState " << State << " " << II->getNameStart();
267  if (State && State->isAmbiguous(*this, II))
268  llvm::errs() << " ambiguous";
269  if (State && !State->getOverriddenMacros().empty()) {
270  llvm::errs() << " overrides";
271  for (auto *O : State->getOverriddenMacros())
272  llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
273  }
274  llvm::errs() << "\n";
275 
276  // Dump local macro directives.
277  for (auto *MD = State ? State->getLatest() : nullptr; MD;
278  MD = MD->getPrevious()) {
279  llvm::errs() << " ";
280  MD->dump();
281  }
282 
283  // Dump module macros.
285  for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
286  Active.insert(MM);
288  llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
289  while (!Worklist.empty()) {
290  auto *MM = Worklist.pop_back_val();
291  llvm::errs() << " ModuleMacro " << MM << " "
292  << MM->getOwningModule()->getFullModuleName();
293  if (!MM->getMacroInfo())
294  llvm::errs() << " undef";
295 
296  if (Active.count(MM))
297  llvm::errs() << " active";
298  else if (!CurSubmoduleState->VisibleModules.isVisible(
299  MM->getOwningModule()))
300  llvm::errs() << " hidden";
301  else if (MM->getMacroInfo())
302  llvm::errs() << " overridden";
303 
304  if (!MM->overrides().empty()) {
305  llvm::errs() << " overrides";
306  for (auto *O : MM->overrides()) {
307  llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
308  if (Visited.insert(O).second)
309  Worklist.push_back(O);
310  }
311  }
312  llvm::errs() << "\n";
313  if (auto *MI = MM->getMacroInfo()) {
314  llvm::errs() << " ";
315  MI->dump();
316  llvm::errs() << "\n";
317  }
318  }
319 }
320 
321 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
322 /// table and mark it as a builtin macro to be expanded.
323 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
324  // Get the identifier.
325  IdentifierInfo *Id = PP.getIdentifierInfo(Name);
326 
327  // Mark it as being a macro that is builtin.
329  MI->setIsBuiltinMacro();
330  PP.appendDefMacroDirective(Id, MI);
331  return Id;
332 }
333 
334 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
335 /// identifier table.
336 void Preprocessor::RegisterBuiltinMacros() {
337  Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
338  Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
339  Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
340  Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
341  Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
342  Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
343 
344  // C++ Standing Document Extensions.
345  if (LangOpts.CPlusPlus)
346  Ident__has_cpp_attribute =
347  RegisterBuiltinMacro(*this, "__has_cpp_attribute");
348  else
349  Ident__has_cpp_attribute = nullptr;
350 
351  // GCC Extensions.
352  Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
353  Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
354  Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
355 
356  // Microsoft Extensions.
357  if (LangOpts.MicrosoftExt) {
358  Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
359  Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
360  } else {
361  Ident__identifier = nullptr;
362  Ident__pragma = nullptr;
363  }
364 
365  // Clang Extensions.
366  Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
367  Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
368  Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
369  Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
370  Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");
371  Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
372  Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
373  Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
374  Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
375  Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
376  Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch");
377  Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");
378  Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
379  Ident__is_target_environment =
380  RegisterBuiltinMacro(*this, "__is_target_environment");
381 
382  // Modules.
383  Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
384  if (!LangOpts.CurrentModule.empty())
385  Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
386  else
387  Ident__MODULE__ = nullptr;
388 }
389 
390 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
391 /// in its expansion, currently expands to that token literally.
393  const IdentifierInfo *MacroIdent,
394  Preprocessor &PP) {
396 
397  // If the token isn't an identifier, it's always literally expanded.
398  if (!II) return true;
399 
400  // If the information about this identifier is out of date, update it from
401  // the external source.
402  if (II->isOutOfDate())
404 
405  // If the identifier is a macro, and if that macro is enabled, it may be
406  // expanded so it's not a trivial expansion.
407  if (auto *ExpansionMI = PP.getMacroInfo(II))
408  if (ExpansionMI->isEnabled() &&
409  // Fast expanding "#define X X" is ok, because X would be disabled.
410  II != MacroIdent)
411  return false;
412 
413  // If this is an object-like macro invocation, it is safe to trivially expand
414  // it.
415  if (MI->isObjectLike()) return true;
416 
417  // If this is a function-like macro invocation, it's safe to trivially expand
418  // as long as the identifier is not a macro argument.
419  return std::find(MI->param_begin(), MI->param_end(), II) == MI->param_end();
420 }
421 
422 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
423 /// lexed is a '('. If so, consume the token and return true, if not, this
424 /// method should have no observable side-effect on the lexed tokens.
425 bool Preprocessor::isNextPPTokenLParen() {
426  // Do some quick tests for rejection cases.
427  unsigned Val;
428  if (CurLexer)
429  Val = CurLexer->isNextPPTokenLParen();
430  else
431  Val = CurTokenLexer->isNextTokenLParen();
432 
433  if (Val == 2) {
434  // We have run off the end. If it's a source file we don't
435  // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
436  // macro stack.
437  if (CurPPLexer)
438  return false;
439  for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
440  if (Entry.TheLexer)
441  Val = Entry.TheLexer->isNextPPTokenLParen();
442  else
443  Val = Entry.TheTokenLexer->isNextTokenLParen();
444 
445  if (Val != 2)
446  break;
447 
448  // Ran off the end of a source file?
449  if (Entry.ThePPLexer)
450  return false;
451  }
452  }
453 
454  // Okay, if we know that the token is a '(', lex it and return. Otherwise we
455  // have found something that isn't a '(' or we found the end of the
456  // translation unit. In either case, return false.
457  return Val == 1;
458 }
459 
460 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
461 /// expanded as a macro, handle it and return the next token as 'Identifier'.
462 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
463  const MacroDefinition &M) {
464  MacroInfo *MI = M.getMacroInfo();
465 
466  // If this is a macro expansion in the "#if !defined(x)" line for the file,
467  // then the macro could expand to different things in other contexts, we need
468  // to disable the optimization in this case.
469  if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
470 
471  // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
472  if (MI->isBuiltinMacro()) {
473  if (Callbacks)
474  Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
475  /*Args=*/nullptr);
476  ExpandBuiltinMacro(Identifier);
477  return true;
478  }
479 
480  /// Args - If this is a function-like macro expansion, this contains,
481  /// for each macro argument, the list of tokens that were provided to the
482  /// invocation.
483  MacroArgs *Args = nullptr;
484 
485  // Remember where the end of the expansion occurred. For an object-like
486  // macro, this is the identifier. For a function-like macro, this is the ')'.
487  SourceLocation ExpansionEnd = Identifier.getLocation();
488 
489  // If this is a function-like macro, read the arguments.
490  if (MI->isFunctionLike()) {
491  // Remember that we are now parsing the arguments to a macro invocation.
492  // Preprocessor directives used inside macro arguments are not portable, and
493  // this enables the warning.
494  InMacroArgs = true;
495  ArgMacro = &Identifier;
496 
497  Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
498 
499  // Finished parsing args.
500  InMacroArgs = false;
501  ArgMacro = nullptr;
502 
503  // If there was an error parsing the arguments, bail out.
504  if (!Args) return true;
505 
506  ++NumFnMacroExpanded;
507  } else {
508  ++NumMacroExpanded;
509  }
510 
511  // Notice that this macro has been used.
512  markMacroAsUsed(MI);
513 
514  // Remember where the token is expanded.
515  SourceLocation ExpandLoc = Identifier.getLocation();
516  SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
517 
518  if (Callbacks) {
519  if (InMacroArgs) {
520  // We can have macro expansion inside a conditional directive while
521  // reading the function macro arguments. To ensure, in that case, that
522  // MacroExpands callbacks still happen in source order, queue this
523  // callback to have it happen after the function macro callback.
524  DelayedMacroExpandsCallbacks.push_back(
525  MacroExpandsInfo(Identifier, M, ExpansionRange));
526  } else {
527  Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
528  if (!DelayedMacroExpandsCallbacks.empty()) {
529  for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
530  // FIXME: We lose macro args info with delayed callback.
531  Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
532  /*Args=*/nullptr);
533  }
534  DelayedMacroExpandsCallbacks.clear();
535  }
536  }
537  }
538 
539  // If the macro definition is ambiguous, complain.
540  if (M.isAmbiguous()) {
541  Diag(Identifier, diag::warn_pp_ambiguous_macro)
542  << Identifier.getIdentifierInfo();
543  Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
544  << Identifier.getIdentifierInfo();
545  M.forAllDefinitions([&](const MacroInfo *OtherMI) {
546  if (OtherMI != MI)
547  Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
548  << Identifier.getIdentifierInfo();
549  });
550  }
551 
552  // If we started lexing a macro, enter the macro expansion body.
553 
554  // If this macro expands to no tokens, don't bother to push it onto the
555  // expansion stack, only to take it right back off.
556  if (MI->getNumTokens() == 0) {
557  // No need for arg info.
558  if (Args) Args->destroy(*this);
559 
560  // Propagate whitespace info as if we had pushed, then popped,
561  // a macro context.
562  Identifier.setFlag(Token::LeadingEmptyMacro);
563  PropagateLineStartLeadingSpaceInfo(Identifier);
564  ++NumFastMacroExpanded;
565  return false;
566  } else if (MI->getNumTokens() == 1 &&
568  *this)) {
569  // Otherwise, if this macro expands into a single trivially-expanded
570  // token: expand it now. This handles common cases like
571  // "#define VAL 42".
572 
573  // No need for arg info.
574  if (Args) Args->destroy(*this);
575 
576  // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
577  // identifier to the expanded token.
578  bool isAtStartOfLine = Identifier.isAtStartOfLine();
579  bool hasLeadingSpace = Identifier.hasLeadingSpace();
580 
581  // Replace the result token.
582  Identifier = MI->getReplacementToken(0);
583 
584  // Restore the StartOfLine/LeadingSpace markers.
585  Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
586  Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
587 
588  // Update the tokens location to include both its expansion and physical
589  // locations.
590  SourceLocation Loc =
591  SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
592  ExpansionEnd,Identifier.getLength());
593  Identifier.setLocation(Loc);
594 
595  // If this is a disabled macro or #define X X, we must mark the result as
596  // unexpandable.
597  if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
598  if (MacroInfo *NewMI = getMacroInfo(NewII))
599  if (!NewMI->isEnabled() || NewMI == MI) {
600  Identifier.setFlag(Token::DisableExpand);
601  // Don't warn for "#define X X" like "#define bool bool" from
602  // stdbool.h.
603  if (NewMI != MI || MI->isFunctionLike())
604  Diag(Identifier, diag::pp_disabled_macro_expansion);
605  }
606  }
607 
608  // Since this is not an identifier token, it can't be macro expanded, so
609  // we're done.
610  ++NumFastMacroExpanded;
611  return true;
612  }
613 
614  // Start expanding the macro.
615  EnterMacro(Identifier, ExpansionEnd, MI, Args);
616  return false;
617 }
618 
619 enum Bracket {
622 };
623 
624 /// CheckMatchedBrackets - Returns true if the braces and parentheses in the
625 /// token vector are properly nested.
626 static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
627  SmallVector<Bracket, 8> Brackets;
628  for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
629  E = Tokens.end();
630  I != E; ++I) {
631  if (I->is(tok::l_paren)) {
632  Brackets.push_back(Paren);
633  } else if (I->is(tok::r_paren)) {
634  if (Brackets.empty() || Brackets.back() == Brace)
635  return false;
636  Brackets.pop_back();
637  } else if (I->is(tok::l_brace)) {
638  Brackets.push_back(Brace);
639  } else if (I->is(tok::r_brace)) {
640  if (Brackets.empty() || Brackets.back() == Paren)
641  return false;
642  Brackets.pop_back();
643  }
644  }
645  return Brackets.empty();
646 }
647 
648 /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
649 /// vector of tokens in NewTokens. The new number of arguments will be placed
650 /// in NumArgs and the ranges which need to surrounded in parentheses will be
651 /// in ParenHints.
652 /// Returns false if the token stream cannot be changed. If this is because
653 /// of an initializer list starting a macro argument, the range of those
654 /// initializer lists will be place in InitLists.
656  SmallVectorImpl<Token> &OldTokens,
657  SmallVectorImpl<Token> &NewTokens,
658  unsigned &NumArgs,
659  SmallVectorImpl<SourceRange> &ParenHints,
660  SmallVectorImpl<SourceRange> &InitLists) {
661  if (!CheckMatchedBrackets(OldTokens))
662  return false;
663 
664  // Once it is known that the brackets are matched, only a simple count of the
665  // braces is needed.
666  unsigned Braces = 0;
667 
668  // First token of a new macro argument.
669  SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
670 
671  // First closing brace in a new macro argument. Used to generate
672  // SourceRanges for InitLists.
673  SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
674  NumArgs = 0;
675  Token TempToken;
676  // Set to true when a macro separator token is found inside a braced list.
677  // If true, the fixed argument spans multiple old arguments and ParenHints
678  // will be updated.
679  bool FoundSeparatorToken = false;
680  for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
681  E = OldTokens.end();
682  I != E; ++I) {
683  if (I->is(tok::l_brace)) {
684  ++Braces;
685  } else if (I->is(tok::r_brace)) {
686  --Braces;
687  if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
688  ClosingBrace = I;
689  } else if (I->is(tok::eof)) {
690  // EOF token is used to separate macro arguments
691  if (Braces != 0) {
692  // Assume comma separator is actually braced list separator and change
693  // it back to a comma.
694  FoundSeparatorToken = true;
695  I->setKind(tok::comma);
696  I->setLength(1);
697  } else { // Braces == 0
698  // Separator token still separates arguments.
699  ++NumArgs;
700 
701  // If the argument starts with a brace, it can't be fixed with
702  // parentheses. A different diagnostic will be given.
703  if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
704  InitLists.push_back(
705  SourceRange(ArgStartIterator->getLocation(),
706  PP.getLocForEndOfToken(ClosingBrace->getLocation())));
707  ClosingBrace = E;
708  }
709 
710  // Add left paren
711  if (FoundSeparatorToken) {
712  TempToken.startToken();
713  TempToken.setKind(tok::l_paren);
714  TempToken.setLocation(ArgStartIterator->getLocation());
715  TempToken.setLength(0);
716  NewTokens.push_back(TempToken);
717  }
718 
719  // Copy over argument tokens
720  NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
721 
722  // Add right paren and store the paren locations in ParenHints
723  if (FoundSeparatorToken) {
724  SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
725  TempToken.startToken();
726  TempToken.setKind(tok::r_paren);
727  TempToken.setLocation(Loc);
728  TempToken.setLength(0);
729  NewTokens.push_back(TempToken);
730  ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
731  Loc));
732  }
733 
734  // Copy separator token
735  NewTokens.push_back(*I);
736 
737  // Reset values
738  ArgStartIterator = I + 1;
739  FoundSeparatorToken = false;
740  }
741  }
742  }
743 
744  return !ParenHints.empty() && InitLists.empty();
745 }
746 
747 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
748 /// token is the '(' of the macro, this method is invoked to read all of the
749 /// actual arguments specified for the macro invocation. This returns null on
750 /// error.
751 MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
752  MacroInfo *MI,
753  SourceLocation &MacroEnd) {
754  // The number of fixed arguments to parse.
755  unsigned NumFixedArgsLeft = MI->getNumParams();
756  bool isVariadic = MI->isVariadic();
757 
758  // Outer loop, while there are more arguments, keep reading them.
759  Token Tok;
760 
761  // Read arguments as unexpanded tokens. This avoids issues, e.g., where
762  // an argument value in a macro could expand to ',' or '(' or ')'.
763  LexUnexpandedToken(Tok);
764  assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
765 
766  // ArgTokens - Build up a list of tokens that make up each argument. Each
767  // argument is separated by an EOF token. Use a SmallVector so we can avoid
768  // heap allocations in the common case.
769  SmallVector<Token, 64> ArgTokens;
770  bool ContainsCodeCompletionTok = false;
771  bool FoundElidedComma = false;
772 
773  SourceLocation TooManyArgsLoc;
774 
775  unsigned NumActuals = 0;
776  while (Tok.isNot(tok::r_paren)) {
777  if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
778  break;
779 
780  assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
781  "only expect argument separators here");
782 
783  size_t ArgTokenStart = ArgTokens.size();
784  SourceLocation ArgStartLoc = Tok.getLocation();
785 
786  // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
787  // that we already consumed the first one.
788  unsigned NumParens = 0;
789 
790  while (true) {
791  // Read arguments as unexpanded tokens. This avoids issues, e.g., where
792  // an argument value in a macro could expand to ',' or '(' or ')'.
793  LexUnexpandedToken(Tok);
794 
795  if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
796  if (!ContainsCodeCompletionTok) {
797  Diag(MacroName, diag::err_unterm_macro_invoc);
798  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
799  << MacroName.getIdentifierInfo();
800  // Do not lose the EOF/EOD. Return it to the client.
801  MacroName = Tok;
802  return nullptr;
803  }
804  // Do not lose the EOF/EOD.
805  auto Toks = llvm::make_unique<Token[]>(1);
806  Toks[0] = Tok;
807  EnterTokenStream(std::move(Toks), 1, true);
808  break;
809  } else if (Tok.is(tok::r_paren)) {
810  // If we found the ) token, the macro arg list is done.
811  if (NumParens-- == 0) {
812  MacroEnd = Tok.getLocation();
813  if (!ArgTokens.empty() &&
814  ArgTokens.back().commaAfterElided()) {
815  FoundElidedComma = true;
816  }
817  break;
818  }
819  } else if (Tok.is(tok::l_paren)) {
820  ++NumParens;
821  } else if (Tok.is(tok::comma) && NumParens == 0 &&
822  !(Tok.getFlags() & Token::IgnoredComma)) {
823  // In Microsoft-compatibility mode, single commas from nested macro
824  // expansions should not be considered as argument separators. We test
825  // for this with the IgnoredComma token flag above.
826 
827  // Comma ends this argument if there are more fixed arguments expected.
828  // However, if this is a variadic macro, and this is part of the
829  // variadic part, then the comma is just an argument token.
830  if (!isVariadic) break;
831  if (NumFixedArgsLeft > 1)
832  break;
833  } else if (Tok.is(tok::comment) && !KeepMacroComments) {
834  // If this is a comment token in the argument list and we're just in
835  // -C mode (not -CC mode), discard the comment.
836  continue;
837  } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
838  // Reading macro arguments can cause macros that we are currently
839  // expanding from to be popped off the expansion stack. Doing so causes
840  // them to be reenabled for expansion. Here we record whether any
841  // identifiers we lex as macro arguments correspond to disabled macros.
842  // If so, we mark the token as noexpand. This is a subtle aspect of
843  // C99 6.10.3.4p2.
844  if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
845  if (!MI->isEnabled())
847  } else if (Tok.is(tok::code_completion)) {
848  ContainsCodeCompletionTok = true;
849  if (CodeComplete)
850  CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
851  MI, NumActuals);
852  // Don't mark that we reached the code-completion point because the
853  // parser is going to handle the token and there will be another
854  // code-completion callback.
855  }
856 
857  ArgTokens.push_back(Tok);
858  }
859 
860  // If this was an empty argument list foo(), don't add this as an empty
861  // argument.
862  if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
863  break;
864 
865  // If this is not a variadic macro, and too many args were specified, emit
866  // an error.
867  if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
868  if (ArgTokens.size() != ArgTokenStart)
869  TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
870  else
871  TooManyArgsLoc = ArgStartLoc;
872  }
873 
874  // Empty arguments are standard in C99 and C++0x, and are supported as an
875  // extension in other modes.
876  if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
877  Diag(Tok, LangOpts.CPlusPlus11 ?
878  diag::warn_cxx98_compat_empty_fnmacro_arg :
879  diag::ext_empty_fnmacro_arg);
880 
881  // Add a marker EOF token to the end of the token list for this argument.
882  Token EOFTok;
883  EOFTok.startToken();
884  EOFTok.setKind(tok::eof);
885  EOFTok.setLocation(Tok.getLocation());
886  EOFTok.setLength(0);
887  ArgTokens.push_back(EOFTok);
888  ++NumActuals;
889  if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
890  --NumFixedArgsLeft;
891  }
892 
893  // Okay, we either found the r_paren. Check to see if we parsed too few
894  // arguments.
895  unsigned MinArgsExpected = MI->getNumParams();
896 
897  // If this is not a variadic macro, and too many args were specified, emit
898  // an error.
899  if (!isVariadic && NumActuals > MinArgsExpected &&
900  !ContainsCodeCompletionTok) {
901  // Emit the diagnostic at the macro name in case there is a missing ).
902  // Emitting it at the , could be far away from the macro name.
903  Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
904  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
905  << MacroName.getIdentifierInfo();
906 
907  // Commas from braced initializer lists will be treated as argument
908  // separators inside macros. Attempt to correct for this with parentheses.
909  // TODO: See if this can be generalized to angle brackets for templates
910  // inside macro arguments.
911 
912  SmallVector<Token, 4> FixedArgTokens;
913  unsigned FixedNumArgs = 0;
914  SmallVector<SourceRange, 4> ParenHints, InitLists;
915  if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
916  ParenHints, InitLists)) {
917  if (!InitLists.empty()) {
918  DiagnosticBuilder DB =
919  Diag(MacroName,
920  diag::note_init_list_at_beginning_of_macro_argument);
921  for (SourceRange Range : InitLists)
922  DB << Range;
923  }
924  return nullptr;
925  }
926  if (FixedNumArgs != MinArgsExpected)
927  return nullptr;
928 
929  DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
930  for (SourceRange ParenLocation : ParenHints) {
931  DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
932  DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
933  }
934  ArgTokens.swap(FixedArgTokens);
935  NumActuals = FixedNumArgs;
936  }
937 
938  // See MacroArgs instance var for description of this.
939  bool isVarargsElided = false;
940 
941  if (ContainsCodeCompletionTok) {
942  // Recover from not-fully-formed macro invocation during code-completion.
943  Token EOFTok;
944  EOFTok.startToken();
945  EOFTok.setKind(tok::eof);
946  EOFTok.setLocation(Tok.getLocation());
947  EOFTok.setLength(0);
948  for (; NumActuals < MinArgsExpected; ++NumActuals)
949  ArgTokens.push_back(EOFTok);
950  }
951 
952  if (NumActuals < MinArgsExpected) {
953  // There are several cases where too few arguments is ok, handle them now.
954  if (NumActuals == 0 && MinArgsExpected == 1) {
955  // #define A(X) or #define A(...) ---> A()
956 
957  // If there is exactly one argument, and that argument is missing,
958  // then we have an empty "()" argument empty list. This is fine, even if
959  // the macro expects one argument (the argument is just empty).
960  isVarargsElided = MI->isVariadic();
961  } else if ((FoundElidedComma || MI->isVariadic()) &&
962  (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
963  (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
964  // Varargs where the named vararg parameter is missing: OK as extension.
965  // #define A(x, ...)
966  // A("blah")
967  //
968  // If the macro contains the comma pasting extension, the diagnostic
969  // is suppressed; we know we'll get another diagnostic later.
970  if (!MI->hasCommaPasting()) {
971  Diag(Tok, diag::ext_missing_varargs_arg);
972  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
973  << MacroName.getIdentifierInfo();
974  }
975 
976  // Remember this occurred, allowing us to elide the comma when used for
977  // cases like:
978  // #define A(x, foo...) blah(a, ## foo)
979  // #define B(x, ...) blah(a, ## __VA_ARGS__)
980  // #define C(...) blah(a, ## __VA_ARGS__)
981  // A(x) B(x) C()
982  isVarargsElided = true;
983  } else if (!ContainsCodeCompletionTok) {
984  // Otherwise, emit the error.
985  Diag(Tok, diag::err_too_few_args_in_macro_invoc);
986  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
987  << MacroName.getIdentifierInfo();
988  return nullptr;
989  }
990 
991  // Add a marker EOF token to the end of the token list for this argument.
992  SourceLocation EndLoc = Tok.getLocation();
993  Tok.startToken();
994  Tok.setKind(tok::eof);
995  Tok.setLocation(EndLoc);
996  Tok.setLength(0);
997  ArgTokens.push_back(Tok);
998 
999  // If we expect two arguments, add both as empty.
1000  if (NumActuals == 0 && MinArgsExpected == 2)
1001  ArgTokens.push_back(Tok);
1002 
1003  } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
1004  !ContainsCodeCompletionTok) {
1005  // Emit the diagnostic at the macro name in case there is a missing ).
1006  // Emitting it at the , could be far away from the macro name.
1007  Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
1008  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1009  << MacroName.getIdentifierInfo();
1010  return nullptr;
1011  }
1012 
1013  return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
1014 }
1015 
1016 /// Keeps macro expanded tokens for TokenLexers.
1017 //
1018 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1019 /// going to lex in the cache and when it finishes the tokens are removed
1020 /// from the end of the cache.
1021 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1022  ArrayRef<Token> tokens) {
1023  assert(tokLexer);
1024  if (tokens.empty())
1025  return nullptr;
1026 
1027  size_t newIndex = MacroExpandedTokens.size();
1028  bool cacheNeedsToGrow = tokens.size() >
1029  MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1030  MacroExpandedTokens.append(tokens.begin(), tokens.end());
1031 
1032  if (cacheNeedsToGrow) {
1033  // Go through all the TokenLexers whose 'Tokens' pointer points in the
1034  // buffer and update the pointers to the (potential) new buffer array.
1035  for (const auto &Lexer : MacroExpandingLexersStack) {
1036  TokenLexer *prevLexer;
1037  size_t tokIndex;
1038  std::tie(prevLexer, tokIndex) = Lexer;
1039  prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1040  }
1041  }
1042 
1043  MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1044  return MacroExpandedTokens.data() + newIndex;
1045 }
1046 
1047 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1048  assert(!MacroExpandingLexersStack.empty());
1049  size_t tokIndex = MacroExpandingLexersStack.back().second;
1050  assert(tokIndex < MacroExpandedTokens.size());
1051  // Pop the cached macro expanded tokens from the end.
1052  MacroExpandedTokens.resize(tokIndex);
1053  MacroExpandingLexersStack.pop_back();
1054 }
1055 
1056 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
1057 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1058 /// the identifier tokens inserted.
1059 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1060  Preprocessor &PP) {
1061  time_t TT = time(nullptr);
1062  struct tm *TM = localtime(&TT);
1063 
1064  static const char * const Months[] = {
1065  "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1066  };
1067 
1068  {
1069  SmallString<32> TmpBuffer;
1070  llvm::raw_svector_ostream TmpStream(TmpBuffer);
1071  TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1072  TM->tm_mday, TM->tm_year + 1900);
1073  Token TmpTok;
1074  TmpTok.startToken();
1075  PP.CreateString(TmpStream.str(), TmpTok);
1076  DATELoc = TmpTok.getLocation();
1077  }
1078 
1079  {
1080  SmallString<32> TmpBuffer;
1081  llvm::raw_svector_ostream TmpStream(TmpBuffer);
1082  TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1083  TM->tm_hour, TM->tm_min, TM->tm_sec);
1084  Token TmpTok;
1085  TmpTok.startToken();
1086  PP.CreateString(TmpStream.str(), TmpTok);
1087  TIMELoc = TmpTok.getLocation();
1088  }
1089 }
1090 
1091 /// HasFeature - Return true if we recognize and implement the feature
1092 /// specified by the identifier as a standard language feature.
1093 static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
1094  const LangOptions &LangOpts = PP.getLangOpts();
1095 
1096  // Normalize the feature name, __foo__ becomes foo.
1097  if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1098  Feature = Feature.substr(2, Feature.size() - 4);
1099 
1100 #define FEATURE(Name, Predicate) .Case(#Name, Predicate)
1101  return llvm::StringSwitch<bool>(Feature)
1102 #include "clang/Basic/Features.def"
1103  .Default(false);
1104 #undef FEATURE
1105 }
1106 
1107 /// HasExtension - Return true if we recognize and implement the feature
1108 /// specified by the identifier, either as an extension or a standard language
1109 /// feature.
1110 static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1111  if (HasFeature(PP, Extension))
1112  return true;
1113 
1114  // If the use of an extension results in an error diagnostic, extensions are
1115  // effectively unavailable, so just return false here.
1118  return false;
1119 
1120  const LangOptions &LangOpts = PP.getLangOpts();
1121 
1122  // Normalize the extension name, __foo__ becomes foo.
1123  if (Extension.startswith("__") && Extension.endswith("__") &&
1124  Extension.size() >= 4)
1125  Extension = Extension.substr(2, Extension.size() - 4);
1126 
1127  // Because we inherit the feature list from HasFeature, this string switch
1128  // must be less restrictive than HasFeature's.
1129 #define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
1130  return llvm::StringSwitch<bool>(Extension)
1131 #include "clang/Basic/Features.def"
1132  .Default(false);
1133 #undef EXTENSION
1134 }
1135 
1136 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1137 /// or '__has_include_next("path")' expression.
1138 /// Returns true if successful.
1140  IdentifierInfo *II, Preprocessor &PP,
1141  const DirectoryLookup *LookupFrom,
1142  const FileEntry *LookupFromFile) {
1143  // Save the location of the current token. If a '(' is later found, use
1144  // that location. If not, use the end of this location instead.
1145  SourceLocation LParenLoc = Tok.getLocation();
1146 
1147  // These expressions are only allowed within a preprocessor directive.
1148  if (!PP.isParsingIfOrElifDirective()) {
1149  PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
1150  // Return a valid identifier token.
1151  assert(Tok.is(tok::identifier));
1152  Tok.setIdentifierInfo(II);
1153  return false;
1154  }
1155 
1156  // Get '('. If we don't have a '(', try to form a header-name token.
1157  do {
1158  if (PP.LexHeaderName(Tok))
1159  return false;
1160  } while (Tok.getKind() == tok::comment);
1161 
1162  // Ensure we have a '('.
1163  if (Tok.isNot(tok::l_paren)) {
1164  // No '(', use end of last token.
1165  LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1166  PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1167  // If the next token looks like a filename or the start of one,
1168  // assume it is and process it as such.
1169  if (Tok.isNot(tok::header_name))
1170  return false;
1171  } else {
1172  // Save '(' location for possible missing ')' message.
1173  LParenLoc = Tok.getLocation();
1174  if (PP.LexHeaderName(Tok))
1175  return false;
1176  }
1177 
1178  if (Tok.isNot(tok::header_name)) {
1179  PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1180  return false;
1181  }
1182 
1183  // Reserve a buffer to get the spelling.
1184  SmallString<128> FilenameBuffer;
1185  bool Invalid = false;
1186  StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1187  if (Invalid)
1188  return false;
1189 
1190  SourceLocation FilenameLoc = Tok.getLocation();
1191 
1192  // Get ')'.
1193  PP.LexNonComment(Tok);
1194 
1195  // Ensure we have a trailing ).
1196  if (Tok.isNot(tok::r_paren)) {
1197  PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1198  << II << tok::r_paren;
1199  PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1200  return false;
1201  }
1202 
1203  bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1204  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1205  // error.
1206  if (Filename.empty())
1207  return false;
1208 
1209  // Search include directories.
1210  const DirectoryLookup *CurDir;
1211  const FileEntry *File =
1212  PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1213  CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
1214 
1215  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1217  if (File)
1218  FileType = PP.getHeaderSearchInfo().getFileDirFlavor(File);
1219  Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
1220  }
1221 
1222  // Get the result value. A result of true means the file exists.
1223  return File != nullptr;
1224 }
1225 
1226 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
1227 /// Returns true if successful.
1229  Preprocessor &PP) {
1230  return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
1231 }
1232 
1233 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1234 /// Returns true if successful.
1236  IdentifierInfo *II, Preprocessor &PP) {
1237  // __has_include_next is like __has_include, except that we start
1238  // searching after the current found directory. If we can't do this,
1239  // issue a diagnostic.
1240  // FIXME: Factor out duplication with
1241  // Preprocessor::HandleIncludeNextDirective.
1242  const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1243  const FileEntry *LookupFromFile = nullptr;
1244  if (PP.isInPrimaryFile() && PP.getLangOpts().IsHeaderFile) {
1245  // If the main file is a header, then it's either for PCH/AST generation,
1246  // or libclang opened it. Either way, handle it as a normal include below
1247  // and do not complain about __has_include_next.
1248  } else if (PP.isInPrimaryFile()) {
1249  Lookup = nullptr;
1250  PP.Diag(Tok, diag::pp_include_next_in_primary);
1251  } else if (PP.getCurrentLexerSubmodule()) {
1252  // Start looking up in the directory *after* the one in which the current
1253  // file would be found, if any.
1254  assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1255  LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1256  Lookup = nullptr;
1257  } else if (!Lookup) {
1258  PP.Diag(Tok, diag::pp_include_next_absolute_path);
1259  } else {
1260  // Start looking up in the next directory.
1261  ++Lookup;
1262  }
1263 
1264  return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
1265 }
1266 
1267 /// Process single-argument builtin feature-like macros that return
1268 /// integer values.
1269 static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1270  Token &Tok, IdentifierInfo *II,
1271  Preprocessor &PP,
1272  llvm::function_ref<
1273  int(Token &Tok,
1274  bool &HasLexedNextTok)> Op) {
1275  // Parse the initial '('.
1276  PP.LexUnexpandedToken(Tok);
1277  if (Tok.isNot(tok::l_paren)) {
1278  PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1279  << tok::l_paren;
1280 
1281  // Provide a dummy '0' value on output stream to elide further errors.
1282  if (!Tok.isOneOf(tok::eof, tok::eod)) {
1283  OS << 0;
1284  Tok.setKind(tok::numeric_constant);
1285  }
1286  return;
1287  }
1288 
1289  unsigned ParenDepth = 1;
1290  SourceLocation LParenLoc = Tok.getLocation();
1292 
1293  Token ResultTok;
1294  bool SuppressDiagnostic = false;
1295  while (true) {
1296  // Parse next token.
1297  PP.LexUnexpandedToken(Tok);
1298 
1299 already_lexed:
1300  switch (Tok.getKind()) {
1301  case tok::eof:
1302  case tok::eod:
1303  // Don't provide even a dummy value if the eod or eof marker is
1304  // reached. Simply provide a diagnostic.
1305  PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1306  return;
1307 
1308  case tok::comma:
1309  if (!SuppressDiagnostic) {
1310  PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1311  SuppressDiagnostic = true;
1312  }
1313  continue;
1314 
1315  case tok::l_paren:
1316  ++ParenDepth;
1317  if (Result.hasValue())
1318  break;
1319  if (!SuppressDiagnostic) {
1320  PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1321  SuppressDiagnostic = true;
1322  }
1323  continue;
1324 
1325  case tok::r_paren:
1326  if (--ParenDepth > 0)
1327  continue;
1328 
1329  // The last ')' has been reached; return the value if one found or
1330  // a diagnostic and a dummy value.
1331  if (Result.hasValue())
1332  OS << Result.getValue();
1333  else {
1334  OS << 0;
1335  if (!SuppressDiagnostic)
1336  PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1337  }
1338  Tok.setKind(tok::numeric_constant);
1339  return;
1340 
1341  default: {
1342  // Parse the macro argument, if one not found so far.
1343  if (Result.hasValue())
1344  break;
1345 
1346  bool HasLexedNextToken = false;
1347  Result = Op(Tok, HasLexedNextToken);
1348  ResultTok = Tok;
1349  if (HasLexedNextToken)
1350  goto already_lexed;
1351  continue;
1352  }
1353  }
1354 
1355  // Diagnose missing ')'.
1356  if (!SuppressDiagnostic) {
1357  if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1358  if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1359  Diag << LastII;
1360  else
1361  Diag << ResultTok.getKind();
1362  Diag << tok::r_paren << ResultTok.getLocation();
1363  }
1364  PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1365  SuppressDiagnostic = true;
1366  }
1367  }
1368 }
1369 
1370 /// Helper function to return the IdentifierInfo structure of a Token
1371 /// or generate a diagnostic if none available.
1373  Preprocessor &PP,
1374  signed DiagID) {
1375  IdentifierInfo *II;
1376  if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1377  return II;
1378 
1379  PP.Diag(Tok.getLocation(), DiagID);
1380  return nullptr;
1381 }
1382 
1383 /// Implements the __is_target_arch builtin macro.
1384 static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
1385  std::string ArchName = II->getName().lower() + "--";
1386  llvm::Triple Arch(ArchName);
1387  const llvm::Triple &TT = TI.getTriple();
1388  if (TT.isThumb()) {
1389  // arm matches thumb or thumbv7. armv7 matches thumbv7.
1390  if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
1391  Arch.getSubArch() == TT.getSubArch()) &&
1392  ((TT.getArch() == llvm::Triple::thumb &&
1393  Arch.getArch() == llvm::Triple::arm) ||
1394  (TT.getArch() == llvm::Triple::thumbeb &&
1395  Arch.getArch() == llvm::Triple::armeb)))
1396  return true;
1397  }
1398  // Check the parsed arch when it has no sub arch to allow Clang to
1399  // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
1400  return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
1401  Arch.getSubArch() == TT.getSubArch()) &&
1402  Arch.getArch() == TT.getArch();
1403 }
1404 
1405 /// Implements the __is_target_vendor builtin macro.
1406 static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
1407  StringRef VendorName = TI.getTriple().getVendorName();
1408  if (VendorName.empty())
1409  VendorName = "unknown";
1410  return VendorName.equals_lower(II->getName());
1411 }
1412 
1413 /// Implements the __is_target_os builtin macro.
1414 static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
1415  std::string OSName =
1416  (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
1417  llvm::Triple OS(OSName);
1418  if (OS.getOS() == llvm::Triple::Darwin) {
1419  // Darwin matches macos, ios, etc.
1420  return TI.getTriple().isOSDarwin();
1421  }
1422  return TI.getTriple().getOS() == OS.getOS();
1423 }
1424 
1425 /// Implements the __is_target_environment builtin macro.
1426 static bool isTargetEnvironment(const TargetInfo &TI,
1427  const IdentifierInfo *II) {
1428  std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
1429  llvm::Triple Env(EnvName);
1430  return TI.getTriple().getEnvironment() == Env.getEnvironment();
1431 }
1432 
1433 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1434 /// as a builtin macro, handle it and return the next token as 'Tok'.
1435 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1436  // Figure out which token this is.
1437  IdentifierInfo *II = Tok.getIdentifierInfo();
1438  assert(II && "Can't be a macro without id info!");
1439 
1440  // If this is an _Pragma or Microsoft __pragma directive, expand it,
1441  // invoke the pragma handler, then lex the token after it.
1442  if (II == Ident_Pragma)
1443  return Handle_Pragma(Tok);
1444  else if (II == Ident__pragma) // in non-MS mode this is null
1445  return HandleMicrosoft__pragma(Tok);
1446 
1447  ++NumBuiltinMacroExpanded;
1448 
1449  SmallString<128> TmpBuffer;
1450  llvm::raw_svector_ostream OS(TmpBuffer);
1451 
1452  // Set up the return result.
1453  Tok.setIdentifierInfo(nullptr);
1455 
1456  if (II == Ident__LINE__) {
1457  // C99 6.10.8: "__LINE__: The presumed line number (within the current
1458  // source file) of the current source line (an integer constant)". This can
1459  // be affected by #line.
1460  SourceLocation Loc = Tok.getLocation();
1461 
1462  // Advance to the location of the first _, this might not be the first byte
1463  // of the token if it starts with an escaped newline.
1464  Loc = AdvanceToTokenCharacter(Loc, 0);
1465 
1466  // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1467  // a macro expansion. This doesn't matter for object-like macros, but
1468  // can matter for a function-like macro that expands to contain __LINE__.
1469  // Skip down through expansion points until we find a file loc for the
1470  // end of the expansion history.
1471  Loc = SourceMgr.getExpansionRange(Loc).getEnd();
1472  PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1473 
1474  // __LINE__ expands to a simple numeric value.
1475  OS << (PLoc.isValid()? PLoc.getLine() : 1);
1476  Tok.setKind(tok::numeric_constant);
1477  } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1478  // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1479  // character string literal)". This can be affected by #line.
1480  PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1481 
1482  // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1483  // #include stack instead of the current file.
1484  if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1485  SourceLocation NextLoc = PLoc.getIncludeLoc();
1486  while (NextLoc.isValid()) {
1487  PLoc = SourceMgr.getPresumedLoc(NextLoc);
1488  if (PLoc.isInvalid())
1489  break;
1490 
1491  NextLoc = PLoc.getIncludeLoc();
1492  }
1493  }
1494 
1495  // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1496  SmallString<128> FN;
1497  if (PLoc.isValid()) {
1498  FN += PLoc.getFilename();
1499  Lexer::Stringify(FN);
1500  OS << '"' << FN << '"';
1501  }
1502  Tok.setKind(tok::string_literal);
1503  } else if (II == Ident__DATE__) {
1504  Diag(Tok.getLocation(), diag::warn_pp_date_time);
1505  if (!DATELoc.isValid())
1506  ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1507  Tok.setKind(tok::string_literal);
1508  Tok.setLength(strlen("\"Mmm dd yyyy\""));
1509  Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1510  Tok.getLocation(),
1511  Tok.getLength()));
1512  return;
1513  } else if (II == Ident__TIME__) {
1514  Diag(Tok.getLocation(), diag::warn_pp_date_time);
1515  if (!TIMELoc.isValid())
1516  ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1517  Tok.setKind(tok::string_literal);
1518  Tok.setLength(strlen("\"hh:mm:ss\""));
1519  Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1520  Tok.getLocation(),
1521  Tok.getLength()));
1522  return;
1523  } else if (II == Ident__INCLUDE_LEVEL__) {
1524  // Compute the presumed include depth of this token. This can be affected
1525  // by GNU line markers.
1526  unsigned Depth = 0;
1527 
1528  PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1529  if (PLoc.isValid()) {
1530  PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1531  for (; PLoc.isValid(); ++Depth)
1532  PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1533  }
1534 
1535  // __INCLUDE_LEVEL__ expands to a simple numeric value.
1536  OS << Depth;
1537  Tok.setKind(tok::numeric_constant);
1538  } else if (II == Ident__TIMESTAMP__) {
1539  Diag(Tok.getLocation(), diag::warn_pp_date_time);
1540  // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1541  // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1542 
1543  // Get the file that we are lexing out of. If we're currently lexing from
1544  // a macro, dig into the include stack.
1545  const FileEntry *CurFile = nullptr;
1546  PreprocessorLexer *TheLexer = getCurrentFileLexer();
1547 
1548  if (TheLexer)
1549  CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1550 
1551  const char *Result;
1552  if (CurFile) {
1553  time_t TT = CurFile->getModificationTime();
1554  struct tm *TM = localtime(&TT);
1555  Result = asctime(TM);
1556  } else {
1557  Result = "??? ??? ?? ??:??:?? ????\n";
1558  }
1559  // Surround the string with " and strip the trailing newline.
1560  OS << '"' << StringRef(Result).drop_back() << '"';
1561  Tok.setKind(tok::string_literal);
1562  } else if (II == Ident__COUNTER__) {
1563  // __COUNTER__ expands to a simple numeric value.
1564  OS << CounterValue++;
1565  Tok.setKind(tok::numeric_constant);
1566  } else if (II == Ident__has_feature) {
1567  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1568  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1570  diag::err_feature_check_malformed);
1571  return II && HasFeature(*this, II->getName());
1572  });
1573  } else if (II == Ident__has_extension) {
1574  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1575  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1577  diag::err_feature_check_malformed);
1578  return II && HasExtension(*this, II->getName());
1579  });
1580  } else if (II == Ident__has_builtin) {
1581  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1582  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1584  diag::err_feature_check_malformed);
1585  const LangOptions &LangOpts = getLangOpts();
1586  if (!II)
1587  return false;
1588  else if (II->getBuiltinID() != 0) {
1589  switch (II->getBuiltinID()) {
1590  case Builtin::BI__builtin_operator_new:
1591  case Builtin::BI__builtin_operator_delete:
1592  // denotes date of behavior change to support calling arbitrary
1593  // usual allocation and deallocation functions. Required by libc++
1594  return 201802;
1595  default:
1596  return true;
1597  }
1598  return true;
1599  } else {
1600  return llvm::StringSwitch<bool>(II->getName())
1601  .Case("__make_integer_seq", LangOpts.CPlusPlus)
1602  .Case("__type_pack_element", LangOpts.CPlusPlus)
1603  .Case("__builtin_available", true)
1604  .Case("__is_target_arch", true)
1605  .Case("__is_target_vendor", true)
1606  .Case("__is_target_os", true)
1607  .Case("__is_target_environment", true)
1608  .Default(false);
1609  }
1610  });
1611  } else if (II == Ident__is_identifier) {
1612  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1613  [](Token &Tok, bool &HasLexedNextToken) -> int {
1614  return Tok.is(tok::identifier);
1615  });
1616  } else if (II == Ident__has_attribute) {
1617  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1618  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1620  diag::err_feature_check_malformed);
1621  return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1622  getTargetInfo(), getLangOpts()) : 0;
1623  });
1624  } else if (II == Ident__has_declspec) {
1625  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1626  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1628  diag::err_feature_check_malformed);
1629  return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II,
1630  getTargetInfo(), getLangOpts()) : 0;
1631  });
1632  } else if (II == Ident__has_cpp_attribute ||
1633  II == Ident__has_c_attribute) {
1634  bool IsCXX = II == Ident__has_cpp_attribute;
1636  OS, Tok, II, *this, [&](Token &Tok, bool &HasLexedNextToken) -> int {
1637  IdentifierInfo *ScopeII = nullptr;
1639  Tok, *this, diag::err_feature_check_malformed);
1640  if (!II)
1641  return false;
1642 
1643  // It is possible to receive a scope token. Read the "::", if it is
1644  // available, and the subsequent identifier.
1645  LexUnexpandedToken(Tok);
1646  if (Tok.isNot(tok::coloncolon))
1647  HasLexedNextToken = true;
1648  else {
1649  ScopeII = II;
1650  LexUnexpandedToken(Tok);
1651  II = ExpectFeatureIdentifierInfo(Tok, *this,
1652  diag::err_feature_check_malformed);
1653  }
1654 
1655  AttrSyntax Syntax = IsCXX ? AttrSyntax::CXX : AttrSyntax::C;
1656  return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
1657  getLangOpts())
1658  : 0;
1659  });
1660  } else if (II == Ident__has_include ||
1661  II == Ident__has_include_next) {
1662  // The argument to these two builtins should be a parenthesized
1663  // file name string literal using angle brackets (<>) or
1664  // double-quotes ("").
1665  bool Value;
1666  if (II == Ident__has_include)
1667  Value = EvaluateHasInclude(Tok, II, *this);
1668  else
1669  Value = EvaluateHasIncludeNext(Tok, II, *this);
1670 
1671  if (Tok.isNot(tok::r_paren))
1672  return;
1673  OS << (int)Value;
1674  Tok.setKind(tok::numeric_constant);
1675  } else if (II == Ident__has_warning) {
1676  // The argument should be a parenthesized string literal.
1677  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1678  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1679  std::string WarningName;
1680  SourceLocation StrStartLoc = Tok.getLocation();
1681 
1682  HasLexedNextToken = Tok.is(tok::string_literal);
1683  if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1684  /*MacroExpansion=*/false))
1685  return false;
1686 
1687  // FIXME: Should we accept "-R..." flags here, or should that be
1688  // handled by a separate __has_remark?
1689  if (WarningName.size() < 3 || WarningName[0] != '-' ||
1690  WarningName[1] != 'W') {
1691  Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1692  return false;
1693  }
1694 
1695  // Finally, check if the warning flags maps to a diagnostic group.
1696  // We construct a SmallVector here to talk to getDiagnosticIDs().
1697  // Although we don't use the result, this isn't a hot path, and not
1698  // worth special casing.
1700  return !getDiagnostics().getDiagnosticIDs()->
1702  WarningName.substr(2), Diags);
1703  });
1704  } else if (II == Ident__building_module) {
1705  // The argument to this builtin should be an identifier. The
1706  // builtin evaluates to 1 when that identifier names the module we are
1707  // currently building.
1708  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1709  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1711  diag::err_expected_id_building_module);
1712  return getLangOpts().isCompilingModule() && II &&
1713  (II->getName() == getLangOpts().CurrentModule);
1714  });
1715  } else if (II == Ident__MODULE__) {
1716  // The current module as an identifier.
1717  OS << getLangOpts().CurrentModule;
1718  IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1719  Tok.setIdentifierInfo(ModuleII);
1720  Tok.setKind(ModuleII->getTokenID());
1721  } else if (II == Ident__identifier) {
1722  SourceLocation Loc = Tok.getLocation();
1723 
1724  // We're expecting '__identifier' '(' identifier ')'. Try to recover
1725  // if the parens are missing.
1726  LexNonComment(Tok);
1727  if (Tok.isNot(tok::l_paren)) {
1728  // No '(', use end of last token.
1729  Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1730  << II << tok::l_paren;
1731  // If the next token isn't valid as our argument, we can't recover.
1732  if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1733  Tok.setKind(tok::identifier);
1734  return;
1735  }
1736 
1737  SourceLocation LParenLoc = Tok.getLocation();
1738  LexNonComment(Tok);
1739 
1740  if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1741  Tok.setKind(tok::identifier);
1742  else {
1743  Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1744  << Tok.getKind();
1745  // Don't walk past anything that's not a real token.
1746  if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
1747  return;
1748  }
1749 
1750  // Discard the ')', preserving 'Tok' as our result.
1751  Token RParen;
1752  LexNonComment(RParen);
1753  if (RParen.isNot(tok::r_paren)) {
1754  Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1755  << Tok.getKind() << tok::r_paren;
1756  Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1757  }
1758  return;
1759  } else if (II == Ident__is_target_arch) {
1761  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1763  Tok, *this, diag::err_feature_check_malformed);
1764  return II && isTargetArch(getTargetInfo(), II);
1765  });
1766  } else if (II == Ident__is_target_vendor) {
1768  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1770  Tok, *this, diag::err_feature_check_malformed);
1771  return II && isTargetVendor(getTargetInfo(), II);
1772  });
1773  } else if (II == Ident__is_target_os) {
1775  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1777  Tok, *this, diag::err_feature_check_malformed);
1778  return II && isTargetOS(getTargetInfo(), II);
1779  });
1780  } else if (II == Ident__is_target_environment) {
1782  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1784  Tok, *this, diag::err_feature_check_malformed);
1785  return II && isTargetEnvironment(getTargetInfo(), II);
1786  });
1787  } else {
1788  llvm_unreachable("Unknown identifier!");
1789  }
1790  CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
1791 }
1792 
1794  // If the 'used' status changed, and the macro requires 'unused' warning,
1795  // remove its SourceLocation from the warn-for-unused-macro locations.
1796  if (MI->isWarnIfUnused() && !MI->isUsed())
1797  WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1798  MI->setIsUsed(true);
1799 }
A diagnostic that indicates a problem or potential problem.
static IdentifierInfo * RegisterBuiltinMacro(Preprocessor &PP, const char *Name)
RegisterBuiltinMacro - Register the specified identifier in the identifier table and mark it as a bui...
StringRef Identifier
Definition: Format.cpp:1714
static bool CheckMatchedBrackets(const SmallVectorImpl< Token > &Tokens)
CheckMatchedBrackets - Returns true if the braces and parentheses in the token vector are properly ne...
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:76
MacroInfo * AllocateMacroInfo(SourceLocation L)
Allocate a new MacroInfo object with the provided SourceLocation.
param_iterator param_begin() const
Definition: MacroInfo.h:180
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition: Token.h:256
Defines the clang::FileManager interface and associated types.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:966
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro *> Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:94
void dumpMacroInfo(const IdentifierInfo *II)
bool isEnabled() const
Return true if this macro is enabled.
Definition: MacroInfo.h:258
Is the identifier known as a __declspec-style attribute?
bool isInPrimaryFile() const
Return true if we&#39;re in the top-level file, not in a #include.
static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile)
EvaluateHasIncludeCommon - Process a &#39;__has_include("path")&#39; or &#39;__has_include_next("path")&#39; expressi...
Defines the clang::MacroInfo and clang::MacroDirective classes.
Is the identifier known as a GNU-style attribute?
Defines types useful for describing an Objective-C runtime.
A description of the current definition of a macro.
Definition: MacroInfo.h:564
static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl< Token > &OldTokens, SmallVectorImpl< Token > &NewTokens, unsigned &NumArgs, SmallVectorImpl< SourceRange > &ParenHints, SmallVectorImpl< SourceRange > &InitLists)
GenerateNewArgTokens - Returns true if OldTokens can be converted to a new vector of tokens in NewTok...
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
static bool isTargetEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_environment builtin macro.
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:233
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
Definition: LangOptions.h:262
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isVariadic() const
Definition: MacroInfo.h:207
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:689
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:77
This interface provides a way to observe the actions of the preprocessor as it does its thing...
Definition: PPCallbacks.h:35
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:117
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:328
tok::TokenKind getKind() const
Definition: Token.h:89
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc)
One of these records is kept for each identifier that is lexed.
Represents a macro directive exported by a module.
Definition: MacroInfo.h:488
static bool HasFeature(const Preprocessor &PP, StringRef Feature)
HasFeature - Return true if we recognize and implement the feature specified by the identifier as a s...
void setHasMacroDefinition(bool Val)
LineState State
static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_os builtin macro.
static bool getDiagnosticsInGroup(diag::Flavor Flavor, const WarningOption *Group, SmallVectorImpl< diag::kind > &Diags)
Return true if any diagnostics were found in this group, even if they were filtered out due to having...
bool hasCommaPasting() const
Definition: MacroInfo.h:217
const TargetInfo & getTargetInfo() const
Definition: Preprocessor.h:901
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
void setKind(tok::TokenKind K)
Definition: Token.h:90
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:900
AttrSyntax
Definition: Attributes.h:19
Describes a module or submodule.
Definition: Module.h:64
static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP)
ComputeDATE_TIME - Compute the current time, enter it into the specified scratch buffer, then return DATELoc/TIMELoc locations with the position of the identifier tokens inserted.
param_iterator param_end() const
Definition: MacroInfo.h:181
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
Module * getCurrentLexerSubmodule() const
Return the submodule owning the file being lexed.
Definition: Preprocessor.h:981
static IdentifierInfo * ExpectFeatureIdentifierInfo(Token &Tok, Preprocessor &PP, signed DiagID)
Helper function to return the IdentifierInfo structure of a Token or generate a diagnostic if none av...
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the &#39;spelling&#39; of the token at the given location; does not go up to the spelling location or ...
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:905
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream &OS, Token &Tok, IdentifierInfo *II, Preprocessor &PP, llvm::function_ref< int(Token &Tok, bool &HasLexedNextTok)> Op)
Process single-argument builtin feature-like macros that return integer values.
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:235
const FormatToken & Tok
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
void LexNonComment(Token &Result)
Lex a token.
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
void ExpandedMacro()
ExpandedMacro - When a macro is expanded with this lexer as the current buffer, this method is called...
static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, Preprocessor &PP)
EvaluateHasInclude - Process a &#39;__has_include("path")&#39; expression.
void destroy(Preprocessor &PP)
destroy - Destroy and deallocate the memory for this object.
Definition: MacroArgs.cpp:78
TokenLexer - This implements a lexer that returns tokens from a macro body or token stream instead of...
Definition: TokenLexer.h:30
Present this diagnostic as an error.
int hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:7
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used. ...
Definition: MacroInfo.h:222
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
return Out str()
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1044
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:226
StringRef Filename
Definition: Format.cpp:1707
unsigned getNumParams() const
Definition: MacroInfo.h:182
Exposes information about the current target.
Definition: TargetInfo.h:161
bool isValid() const
Defines the clang::LangOptions interface.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
int Id
Definition: ASTDiff.cpp:190
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_vendor builtin macro.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
bool isDefined() const
Definition: MacroInfo.h:384
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition: MacroArgs.h:29
unsigned getLine() const
Return the presumed line number of this location.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:123
Defines the clang::Preprocessor interface.
MultipleIncludeOpt MIOpt
A state machine that detects the #ifndef-wrapping a file idiom for the multiple-include optimization...
int Depth
Definition: ASTDiff.cpp:190
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Represents an unpacked "presumed" location which can be presented to the user.
PPCallbacks * getPPCallbacks() const
Definition: Preprocessor.h:991
bool isObjectLike() const
Definition: MacroInfo.h:200
The result type of a method or function.
static bool HasExtension(const Preprocessor &PP, StringRef Extension)
HasExtension - Return true if we recognize and implement the feature specified by the identifier...
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
const DirectoryLookup * GetCurDirLookup()
Get the DirectoryLookup structure used to find the current FileEntry, if CurLexer is non-null and if ...
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition: MacroInfo.h:152
SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File)
Return whether the specified file is a normal header, a system header, or a C++ friendly system heade...
Definition: HeaderSearch.h:434
const char * getFilename() const
Return the presumed filename of this location.
ExternalPreprocessorSource * getExternalSource() const
Definition: Preprocessor.h:917
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
Definition: MacroInfo.h:290
Encodes a location in the source.
static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_arch builtin macro.
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP)
isTrivialSingleTokenExpansion - Return true if MI, which has a single token in its expansion...
void setLength(unsigned Len)
Definition: Token.h:132
SourceLocation createExpansionLoc(SourceLocation Loc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLength, bool ExpansionIsTokenRange=true, int LoadedID=0, unsigned LoadedOffset=0)
Return a new SourceLocation that encodes the fact that a token from SpellingLoc should actually be re...
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
static bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II, Preprocessor &PP)
EvaluateHasIncludeNext - Process &#39;__has_include_next("path")&#39; expression.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:176
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:185
void setIsBuiltinMacro(bool Val=true)
Set or clear the isBuiltinMacro flag.
Definition: MacroInfo.h:149
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:265
PreprocessorLexer * getCurrentLexer() const
Return the current lexer being lexed from.
Definition: Preprocessor.h:971
const FileEntry * LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false)
Given a "foo" or <foo> reference, look up the indicated file.
StringRef getName() const
Return the actual identifier string.
bool isNot(tok::TokenKind K) const
Definition: Token.h:95
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
Dataflow Directional Tag Classes.
bool isWarnIfUnused() const
Return true if we should emit a warning if the macro is unused.
Definition: MacroInfo.h:230
bool isValid() const
Return true if this is a valid SourceLocation object.
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:233
bool isFunctionLike() const
Definition: MacroInfo.h:199
const FileEntry * getFileEntry() const
getFileEntry - Return the FileEntry corresponding to this FileID.
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:96
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i...
Definition: LangOptions.h:250
unsigned getLength() const
Definition: Token.h:126
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
static ModuleMacro * create(Preprocessor &PP, Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro *> Overrides)
Definition: MacroInfo.cpp:241
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)=0
Update an out-of-date identifier.
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token&#39;s location and length to ...
SourceLocation getEnd() const
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:91
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition: MacroInfo.h:123
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:494
Defines the clang::SourceLocation class and associated facilities.
ModuleMacro * getModuleMacro(Module *Mod, IdentifierInfo *II)
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:897
bool isAmbiguous() const
true if the definition is ambiguous, false otherwise.
Definition: MacroInfo.h:589
static MacroArgs * create(const MacroInfo *MI, ArrayRef< Token > UnexpArgTokens, bool VarargsElided, Preprocessor &PP)
MacroArgs ctor function - Create a new MacroArgs object with the specified macro and argument info...
Definition: MacroArgs.cpp:24
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition: MacroInfo.h:215
Defines the clang::TargetInfo interface.
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition: MacroInfo.h:325
void forAllDefinitions(Fn F) const
Definition: MacroInfo.h:600
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition: MacroInfo.h:580
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
void setLocation(SourceLocation L)
Definition: Token.h:131
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or #elif directive.
Definition: Preprocessor.h:929
A trivial tuple used to represent a source range.
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
unsigned getFlags() const
Return the internal represtation of the flags.
Definition: Token.h:251
void clearFlag(TokenFlags Flag)
Unset the specified flag.
Definition: Token.h:243
SourceLocation getIncludeLoc() const
Return the presumed include location of this location.
Defines the PreprocessorLexer interface.
virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex)
Callback invoked when performing code completion inside a function-like macro argument.
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: MacroInfo.h:519
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:269
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void startToken()
Reset all flags to cleared.
Definition: Token.h:168
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping &#39;\&#39; and " characters and ii) ...
Definition: Lexer.cpp:246
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:123