Clang Project

clang_source_code/lib/Lex/PPMacroExpansion.cpp
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"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
17#include "clang/Basic/LLVM.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/ObjCRuntime.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Lex/CodeCompletionHandler.h"
23#include "clang/Lex/DirectoryLookup.h"
24#include "clang/Lex/ExternalPreprocessorSource.h"
25#include "clang/Lex/HeaderSearch.h"
26#include "clang/Lex/LexDiagnostic.h"
27#include "clang/Lex/MacroArgs.h"
28#include "clang/Lex/MacroInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Lex/PreprocessorLexer.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
56using namespace clang;
57
58MacroDirective *
59Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *IIconst {
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
67void Preprocessor::appendMacroDirective(IdentifierInfo *IIMacroDirective *MD){
68   (0) . __assert_fail ("MD && \"MacroDirective should be non-zero!\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 68, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(MD && "MacroDirective should be non-zero!");
69   (0) . __assert_fail ("!MD->getPrevious() && \"Already attached to a MacroDirective history.\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 69, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">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(*thisII);
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())
89    II->setChangedSinceDeserialization();
90}
91
92void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
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     (0) . __assert_fail ("OldMD->getMacroInfo()->isBuiltinMacro() && \"only built-ins should have an entry here\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 114, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
114 (0) . __assert_fail ("OldMD->getMacroInfo()->isBuiltinMacro() && \"only built-ins should have an entry here\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 114, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "only built-ins should have an entry here");
115     (0) . __assert_fail ("!OldMD->getPrevious() && \"builtin should only have a single entry\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 115, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">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
128ModuleMacro *Preprocessor::addModuleMacro(Module *ModIdentifierInfo *II,
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
170ModuleMacro *Preprocessor::getModuleMacro(Module *ModIdentifierInfo *II) {
171  llvm::FoldingSetNodeID ID;
172  ModuleMacro::Profile(ID, Mod, II);
173
174  void *InsertPos;
175  return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
176}
177
178void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
179                                         ModuleMacroInfo &Info) {
180   (0) . __assert_fail ("Info.ActiveModuleMacrosGeneration != CurSubmoduleState->VisibleModules.getGeneration() && \"don't need to update this macro name info\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 182, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Info.ActiveModuleMacrosGeneration !=
181 (0) . __assert_fail ("Info.ActiveModuleMacrosGeneration != CurSubmoduleState->VisibleModules.getGeneration() && \"don't need to update this macro name info\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 182, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             CurSubmoduleState->VisibleModules.getGeneration() &&
182 (0) . __assert_fail ("Info.ActiveModuleMacrosGeneration != CurSubmoduleState->VisibleModules.getGeneration() && \"don't need to update this macro name info\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 182, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "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.
200  llvm::SmallVector<ModuleMacro *, 16Worklist;
201  for (auto *LeafMM : Leaf->second) {
202     (0) . __assert_fail ("LeafMM->getNumOverridingMacros() == 0 && \"leaf macro overridden\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 202, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">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
256void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
257  ArrayRef<ModuleMacro*> Leaf;
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() : nullptrMD;
278       MD = MD->getPrevious()) {
279    llvm::errs() << " ";
280    MD->dump();
281  }
282
283  // Dump module macros.
284  llvm::DenseSet<ModuleMacro*> Active;
285  for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
286    Active.insert(MM);
287  llvm::DenseSet<ModuleMacro*> Visited;
288  llvm::SmallVector<ModuleMacro *, 16Worklist(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.
323static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PPconst char *Name){
324  // Get the identifier.
325  IdentifierInfo *Id = PP.getIdentifierInfo(Name);
326
327  // Mark it as being a macro that is builtin.
328  MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
329  MI->setIsBuiltinMacro();
330  PP.appendDefMacroDirective(IdMI);
331  return Id;
332}
333
334/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
335/// identifier table.
336void 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.
392static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
393                                          const IdentifierInfo *MacroIdent,
394                                          Preprocessor &PP) {
395  IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
396
397  // If the token isn't an identifier, it's always literally expanded.
398  if (!IIreturn true;
399
400  // If the information about this identifier is out of date, update it from
401  // the external source.
402  if (II->isOutOfDate())
403    PP.getExternalSource()->updateOutOfDateIdentifier(*II);
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.
425bool 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'.
462bool 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 (CurPPLexerCurPPLexer->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(IdentifierMIdentifier.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(IdentifierMIExpansionEnd);
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 (!Argsreturn 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(ExpandLocExpansionEnd);
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(IdentifierMExpansionRangeArgs);
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 (ArgsArgs->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 &&
567             isTrivialSingleTokenExpansion(MIIdentifier.getIdentifierInfo(),
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 (ArgsArgs->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::LeadingSpacehasLeadingSpace);
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(IdentifierExpansionEndMIArgs);
616  return false;
617}
618
619enum Bracket {
620  Brace,
621  Paren
622};
623
624/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
625/// token vector are properly nested.
626static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
627  SmallVector<Bracket8Brackets;
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.
655static bool GenerateNewArgTokens(Preprocessor &PP,
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.
751MacroArgs *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   (0) . __assert_fail ("Tok.is(tok..l_paren) && \"Error computing l-paren-ness?\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 764, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">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<Token64ArgTokens;
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::eoftok::eod))
778      break;
779
780     (0) . __assert_fail ("Tok.isOneOf(tok..l_paren, tok..comma) && \"only expect argument separators here\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 781, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
781 (0) . __assert_fail ("Tok.isOneOf(tok..l_paren, tok..comma) && \"only expect argument separators here\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 781, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "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::eoftok::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), 1true);
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 (!isVariadicbreak;
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())
846            Tok.setFlag(Token::DisableExpand);
847      } else if (Tok.is(tok::code_completion)) {
848        ContainsCodeCompletionTok = true;
849        if (CodeComplete)
850          CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
851                                                  MINumActuals);
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<Token4FixedArgTokens;
913    unsigned FixedNumArgs = 0;
914    SmallVector<SourceRange4ParenHintsInitLists;
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.
1021Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1022                                              ArrayRef<Tokentokens) {
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
1047void 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.
1059static void ComputeDATE_TIME(SourceLocation &DATELocSourceLocation &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<32TmpBuffer;
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<32TmpBuffer;
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.
1093static bool HasFeature(const Preprocessor &PPStringRef 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.
1110static bool HasExtension(const Preprocessor &PPStringRef 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.
1116  if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1117      diag::Severity::Error)
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.
1139static bool EvaluateHasIncludeCommon(Token &Tok,
1140                                     IdentifierInfo *IIPreprocessor &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<128FilenameBuffer;
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, nullptrnullptrnullptrnullptrnullptr);
1214
1215  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1216    SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
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.
1228static bool EvaluateHasInclude(Token &TokIdentifierInfo *II,
1229                               Preprocessor &PP) {
1230  return EvaluateHasIncludeCommon(TokIIPPnullptrnullptr);
1231}
1232
1233/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1234/// Returns true if successful.
1235static bool EvaluateHasIncludeNext(Token &Tok,
1236                                   IdentifierInfo *IIPreprocessor &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     (0) . __assert_fail ("PP.getCurrentLexer() && \"#include_next directive in macro?\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 1254, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">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(TokIIPPLookupLookupFromFile);
1265}
1266
1267/// Process single-argument builtin feature-like macros that return
1268/// integer values.
1269static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1270                                            Token &TokIdentifierInfo *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::eoftok::eod)) {
1283      OS << 0;
1284      Tok.setKind(tok::numeric_constant);
1285    }
1286    return;
1287  }
1288
1289  unsigned ParenDepth = 1;
1290  SourceLocation LParenLoc = Tok.getLocation();
1291  llvm::Optional<intResult;
1292
1293  Token ResultTok;
1294  bool SuppressDiagnostic = false;
1295  while (true) {
1296    // Parse next token.
1297    PP.LexUnexpandedToken(Tok);
1298
1299already_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.
1372static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
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.
1384static bool isTargetArch(const TargetInfo &TIconst 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.
1406static bool isTargetVendor(const TargetInfo &TIconst 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.
1414static bool isTargetOS(const TargetInfo &TIconst 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.
1426static 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'.
1435void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1436  // Figure out which token this is.
1437  IdentifierInfo *II = Tok.getIdentifierInfo();
1438   (0) . __assert_fail ("II && \"Can't be a macro without id info!\"", "/home/seafit/code_projects/clang_source/clang/lib/Lex/PPMacroExpansion.cpp", 1438, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">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<128TmpBuffer;
1450  llvm::raw_svector_ostream OS(TmpBuffer);
1451
1452  // Set up the return result.
1453  Tok.setIdentifierInfo(nullptr);
1454  Tok.clearFlag(Token::NeedsCleaning);
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(Loc0);
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<128FN;
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(DATELocTIMELoc*this);
1507    Tok.setKind(tok::string_literal);
1508    Tok.setLength(strlen("\"Mmm dd yyyy\""));
1509    Tok.setLocation(SourceMgr.createExpansionLoc(DATELocTok.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(DATELocTIMELoc*this);
1517    Tok.setKind(tok::string_literal);
1518    Tok.setLength(strlen("\"hh:mm:ss\""));
1519    Tok.setLocation(SourceMgr.createExpansionLoc(TIMELocTok.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 {
1569        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
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 {
1576        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
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 {
1583        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
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 {
1619        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
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 {
1627        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
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;
1635    EvaluateFeatureLikeBuiltinMacro(
1636        OS, Tok, II, *this, [&](Token &Tok, bool &HasLexedNextToken) -> int {
1637          IdentifierInfo *ScopeII = nullptr;
1638          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
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(TokII*this);
1668    else
1669      Value = EvaluateHasIncludeNext(TokII*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.
1699        SmallVector<diag::kind, 10> Diags;
1700        return !getDiagnostics().getDiagnosticIDs()->
1701                getDiagnosticsInGroup(diag::Flavor::WarningOrError,
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 {
1710        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
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::eoftok::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) {
1760    EvaluateFeatureLikeBuiltinMacro(
1761        OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1762          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1763              Tok, *this, diag::err_feature_check_malformed);
1764          return II && isTargetArch(getTargetInfo(), II);
1765        });
1766  } else if (II == Ident__is_target_vendor) {
1767    EvaluateFeatureLikeBuiltinMacro(
1768        OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1769          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1770              Tok, *this, diag::err_feature_check_malformed);
1771          return II && isTargetVendor(getTargetInfo(), II);
1772        });
1773  } else if (II == Ident__is_target_os) {
1774    EvaluateFeatureLikeBuiltinMacro(
1775        OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1776          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1777              Tok, *this, diag::err_feature_check_malformed);
1778          return II && isTargetOS(getTargetInfo(), II);
1779        });
1780  } else if (II == Ident__is_target_environment) {
1781    EvaluateFeatureLikeBuiltinMacro(
1782        OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1783          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
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
1793void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
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}
1800
clang::Preprocessor::getLocalMacroDirectiveHistory
clang::Preprocessor::appendMacroDirective
clang::Preprocessor::setLoadedMacroDirective
clang::Preprocessor::addModuleMacro
clang::Preprocessor::getModuleMacro
clang::Preprocessor::updateModuleMacroInfo
clang::Preprocessor::dumpMacroInfo
clang::Preprocessor::RegisterBuiltinMacros
clang::Preprocessor::isNextPPTokenLParen
clang::Preprocessor::HandleMacroExpandedIdentifier
clang::Preprocessor::ReadMacroCallArgumentList
clang::Preprocessor::cacheMacroExpandedTokens
clang::Preprocessor::removeCachedMacroExpandedTokensOfLastLexer
clang::Preprocessor::ExpandBuiltinMacro
clang::Preprocessor::markMacroAsUsed