1 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
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 /// \file
10 /// Implements # directive processing for the Preprocessor.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/Module.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/LexDiagnostic.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "clang/Lex/MacroInfo.h"
27 #include "clang/Lex/ModuleLoader.h"
28 #include "clang/Lex/ModuleMap.h"
29 #include "clang/Lex/PPCallbacks.h"
30 #include "clang/Lex/Pragma.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Lex/Token.h"
34 #include "clang/Lex/VariadicMacroSupport.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/ScopeExit.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/AlignOf.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Path.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstring>
48 #include <new>
49 #include <string>
50 #include <utility>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 // Utility Methods for Preprocessor Directive Handling.
56 //===----------------------------------------------------------------------===//
57 
58 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
59   auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
60   MIChainHead = MIChain;
61   return &MIChain->MI;
62 }
63 
64 DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
65                                                            SourceLocation Loc) {
66   return new (BP) DefMacroDirective(MI, Loc);
67 }
68 
69 UndefMacroDirective *
70 Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
71   return new (BP) UndefMacroDirective(UndefLoc);
72 }
73 
74 VisibilityMacroDirective *
75 Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
76                                                bool isPublic) {
77   return new (BP) VisibilityMacroDirective(Loc, isPublic);
78 }
79 
80 /// Read and discard all tokens remaining on the current line until
81 /// the tok::eod token is found.
82 SourceRange Preprocessor::DiscardUntilEndOfDirective() {
83   Token Tmp;
84   SourceRange Res;
85 
86   LexUnexpandedToken(Tmp);
87   Res.setBegin(Tmp.getLocation());
88   while (Tmp.isNot(tok::eod)) {
89     assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
90     LexUnexpandedToken(Tmp);
91   }
92   Res.setEnd(Tmp.getLocation());
93   return Res;
94 }
95 
96 /// Enumerates possible cases of #define/#undef a reserved identifier.
97 enum MacroDiag {
98   MD_NoWarn,        //> Not a reserved identifier
99   MD_KeywordDef,    //> Macro hides keyword, enabled by default
100   MD_ReservedMacro  //> #define of #undef reserved id, disabled by default
101 };
102 
103 /// Enumerates possible %select values for the pp_err_elif_after_else and
104 /// pp_err_elif_without_if diagnostics.
105 enum PPElifDiag {
106   PED_Elif,
107   PED_Elifdef,
108   PED_Elifndef
109 };
110 
111 // The -fmodule-name option tells the compiler to textually include headers in
112 // the specified module, meaning clang won't build the specified module. This is
113 // useful in a number of situations, for instance, when building a library that
114 // vends a module map, one might want to avoid hitting intermediate build
115 // products containimg the module map or avoid finding the system installed
116 // modulemap for that library.
117 static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
118                                 StringRef ModuleName) {
119   StringRef TopLevelName = M->getTopLevelModuleName();
120 
121   // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
122   // are textually included and no modules are built for both.
123   if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
124       !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
125     TopLevelName = TopLevelName.drop_back(8);
126 
127   return TopLevelName == CurrentModule;
128 }
129 
130 static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
131   const LangOptions &Lang = PP.getLangOpts();
132   if (isReservedInAllContexts(II->isReserved(Lang))) {
133     // list from:
134     // - https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html
135     // - https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160
136     // - man 7 feature_test_macros
137     // The list must be sorted for correct binary search.
138     static constexpr StringRef ReservedMacro[] = {
139         "_ATFILE_SOURCE",
140         "_BSD_SOURCE",
141         "_CRT_NONSTDC_NO_WARNINGS",
142         "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES",
143         "_CRT_SECURE_NO_WARNINGS",
144         "_FILE_OFFSET_BITS",
145         "_FORTIFY_SOURCE",
146         "_GLIBCXX_ASSERTIONS",
147         "_GLIBCXX_CONCEPT_CHECKS",
148         "_GLIBCXX_DEBUG",
149         "_GLIBCXX_DEBUG_PEDANTIC",
150         "_GLIBCXX_PARALLEL",
151         "_GLIBCXX_PARALLEL_ASSERTIONS",
152         "_GLIBCXX_SANITIZE_VECTOR",
153         "_GLIBCXX_USE_CXX11_ABI",
154         "_GLIBCXX_USE_DEPRECATED",
155         "_GNU_SOURCE",
156         "_ISOC11_SOURCE",
157         "_ISOC95_SOURCE",
158         "_ISOC99_SOURCE",
159         "_LARGEFILE64_SOURCE",
160         "_POSIX_C_SOURCE",
161         "_REENTRANT",
162         "_SVID_SOURCE",
163         "_THREAD_SAFE",
164         "_XOPEN_SOURCE",
165         "_XOPEN_SOURCE_EXTENDED",
166         "__STDCPP_WANT_MATH_SPEC_FUNCS__",
167         "__STDC_FORMAT_MACROS",
168     };
169     if (std::binary_search(std::begin(ReservedMacro), std::end(ReservedMacro),
170                            II->getName()))
171       return MD_NoWarn;
172 
173     return MD_ReservedMacro;
174   }
175   StringRef Text = II->getName();
176   if (II->isKeyword(Lang))
177     return MD_KeywordDef;
178   if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
179     return MD_KeywordDef;
180   return MD_NoWarn;
181 }
182 
183 static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
184   const LangOptions &Lang = PP.getLangOpts();
185   // Do not warn on keyword undef.  It is generally harmless and widely used.
186   if (isReservedInAllContexts(II->isReserved(Lang)))
187     return MD_ReservedMacro;
188   return MD_NoWarn;
189 }
190 
191 // Return true if we want to issue a diagnostic by default if we
192 // encounter this name in a #include with the wrong case. For now,
193 // this includes the standard C and C++ headers, Posix headers,
194 // and Boost headers. Improper case for these #includes is a
195 // potential portability issue.
196 static bool warnByDefaultOnWrongCase(StringRef Include) {
197   // If the first component of the path is "boost", treat this like a standard header
198   // for the purposes of diagnostics.
199   if (::llvm::sys::path::begin(Include)->equals_insensitive("boost"))
200     return true;
201 
202   // "condition_variable" is the longest standard header name at 18 characters.
203   // If the include file name is longer than that, it can't be a standard header.
204   static const size_t MaxStdHeaderNameLen = 18u;
205   if (Include.size() > MaxStdHeaderNameLen)
206     return false;
207 
208   // Lowercase and normalize the search string.
209   SmallString<32> LowerInclude{Include};
210   for (char &Ch : LowerInclude) {
211     // In the ASCII range?
212     if (static_cast<unsigned char>(Ch) > 0x7f)
213       return false; // Can't be a standard header
214     // ASCII lowercase:
215     if (Ch >= 'A' && Ch <= 'Z')
216       Ch += 'a' - 'A';
217     // Normalize path separators for comparison purposes.
218     else if (::llvm::sys::path::is_separator(Ch))
219       Ch = '/';
220   }
221 
222   // The standard C/C++ and Posix headers
223   return llvm::StringSwitch<bool>(LowerInclude)
224     // C library headers
225     .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
226     .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
227     .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
228     .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
229     .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
230     .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
231 
232     // C++ headers for C library facilities
233     .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
234     .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
235     .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
236     .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
237     .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
238     .Case("cwctype", true)
239 
240     // C++ library headers
241     .Cases("algorithm", "fstream", "list", "regex", "thread", true)
242     .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
243     .Cases("atomic", "future", "map", "set", "type_traits", true)
244     .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
245     .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
246     .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
247     .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
248     .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
249     .Cases("deque", "istream", "queue", "string", "valarray", true)
250     .Cases("exception", "iterator", "random", "strstream", "vector", true)
251     .Cases("forward_list", "limits", "ratio", "system_error", true)
252 
253     // POSIX headers (which aren't also C headers)
254     .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
255     .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
256     .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
257     .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
258     .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
259     .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
260     .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
261     .Cases("sys/resource.h", "sys/select.h",  "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
262     .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
263     .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
264     .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
265     .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
266     .Default(false);
267 }
268 
269 bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
270                                   bool *ShadowFlag) {
271   // Missing macro name?
272   if (MacroNameTok.is(tok::eod))
273     return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
274 
275   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
276   if (!II)
277     return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
278 
279   if (II->isCPlusPlusOperatorKeyword()) {
280     // C++ 2.5p2: Alternative tokens behave the same as its primary token
281     // except for their spellings.
282     Diag(MacroNameTok, getLangOpts().MicrosoftExt
283                            ? diag::ext_pp_operator_used_as_macro_name
284                            : diag::err_pp_operator_used_as_macro_name)
285         << II << MacroNameTok.getKind();
286     // Allow #defining |and| and friends for Microsoft compatibility or
287     // recovery when legacy C headers are included in C++.
288   }
289 
290   if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
291     // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
292     return Diag(MacroNameTok, diag::err_defined_macro_name);
293   }
294 
295   if (isDefineUndef == MU_Undef) {
296     auto *MI = getMacroInfo(II);
297     if (MI && MI->isBuiltinMacro()) {
298       // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
299       // and C++ [cpp.predefined]p4], but allow it as an extension.
300       Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
301     }
302   }
303 
304   // If defining/undefining reserved identifier or a keyword, we need to issue
305   // a warning.
306   SourceLocation MacroNameLoc = MacroNameTok.getLocation();
307   if (ShadowFlag)
308     *ShadowFlag = false;
309   if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
310       (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
311     MacroDiag D = MD_NoWarn;
312     if (isDefineUndef == MU_Define) {
313       D = shouldWarnOnMacroDef(*this, II);
314     }
315     else if (isDefineUndef == MU_Undef)
316       D = shouldWarnOnMacroUndef(*this, II);
317     if (D == MD_KeywordDef) {
318       // We do not want to warn on some patterns widely used in configuration
319       // scripts.  This requires analyzing next tokens, so do not issue warnings
320       // now, only inform caller.
321       if (ShadowFlag)
322         *ShadowFlag = true;
323     }
324     if (D == MD_ReservedMacro)
325       Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
326   }
327 
328   // Okay, we got a good identifier.
329   return false;
330 }
331 
332 /// Lex and validate a macro name, which occurs after a
333 /// \#define or \#undef.
334 ///
335 /// This sets the token kind to eod and discards the rest of the macro line if
336 /// the macro name is invalid.
337 ///
338 /// \param MacroNameTok Token that is expected to be a macro name.
339 /// \param isDefineUndef Context in which macro is used.
340 /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
341 void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
342                                  bool *ShadowFlag) {
343   // Read the token, don't allow macro expansion on it.
344   LexUnexpandedToken(MacroNameTok);
345 
346   if (MacroNameTok.is(tok::code_completion)) {
347     if (CodeComplete)
348       CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
349     setCodeCompletionReached();
350     LexUnexpandedToken(MacroNameTok);
351   }
352 
353   if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
354     return;
355 
356   // Invalid macro name, read and discard the rest of the line and set the
357   // token kind to tok::eod if necessary.
358   if (MacroNameTok.isNot(tok::eod)) {
359     MacroNameTok.setKind(tok::eod);
360     DiscardUntilEndOfDirective();
361   }
362 }
363 
364 /// Ensure that the next token is a tok::eod token.
365 ///
366 /// If not, emit a diagnostic and consume up until the eod.  If EnableMacros is
367 /// true, then we consider macros that expand to zero tokens as being ok.
368 ///
369 /// Returns the location of the end of the directive.
370 SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
371                                                  bool EnableMacros) {
372   Token Tmp;
373   // Lex unexpanded tokens for most directives: macros might expand to zero
374   // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
375   // #line) allow empty macros.
376   if (EnableMacros)
377     Lex(Tmp);
378   else
379     LexUnexpandedToken(Tmp);
380 
381   // There should be no tokens after the directive, but we allow them as an
382   // extension.
383   while (Tmp.is(tok::comment))  // Skip comments in -C mode.
384     LexUnexpandedToken(Tmp);
385 
386   if (Tmp.is(tok::eod))
387     return Tmp.getLocation();
388 
389   // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
390   // or if this is a macro-style preprocessing directive, because it is more
391   // trouble than it is worth to insert /**/ and check that there is no /**/
392   // in the range also.
393   FixItHint Hint;
394   if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
395       !CurTokenLexer)
396     Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
397   Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
398   return DiscardUntilEndOfDirective().getEnd();
399 }
400 
401 Optional<unsigned> Preprocessor::getSkippedRangeForExcludedConditionalBlock(
402     SourceLocation HashLoc) {
403   if (!ExcludedConditionalDirectiveSkipMappings)
404     return None;
405   if (!HashLoc.isFileID())
406     return None;
407 
408   std::pair<FileID, unsigned> HashFileOffset =
409       SourceMgr.getDecomposedLoc(HashLoc);
410   Optional<llvm::MemoryBufferRef> Buf =
411       SourceMgr.getBufferOrNone(HashFileOffset.first);
412   if (!Buf)
413     return None;
414   auto It =
415       ExcludedConditionalDirectiveSkipMappings->find(Buf->getBufferStart());
416   if (It == ExcludedConditionalDirectiveSkipMappings->end())
417     return None;
418 
419   const PreprocessorSkippedRangeMapping &SkippedRanges = *It->getSecond();
420   // Check if the offset of '#' is mapped in the skipped ranges.
421   auto MappingIt = SkippedRanges.find(HashFileOffset.second);
422   if (MappingIt == SkippedRanges.end())
423     return None;
424 
425   unsigned BytesToSkip = MappingIt->getSecond();
426   unsigned CurLexerBufferOffset = CurLexer->getCurrentBufferOffset();
427   assert(CurLexerBufferOffset >= HashFileOffset.second &&
428          "lexer is before the hash?");
429   // Take into account the fact that the lexer has already advanced, so the
430   // number of bytes to skip must be adjusted.
431   unsigned LengthDiff = CurLexerBufferOffset - HashFileOffset.second;
432   assert(BytesToSkip >= LengthDiff && "lexer is after the skipped range?");
433   return BytesToSkip - LengthDiff;
434 }
435 
436 /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
437 /// decided that the subsequent tokens are in the \#if'd out portion of the
438 /// file.  Lex the rest of the file, until we see an \#endif.  If
439 /// FoundNonSkipPortion is true, then we have already emitted code for part of
440 /// this \#if directive, so \#else/\#elif blocks should never be entered.
441 /// If ElseOk is true, then \#else directives are ok, if not, then we have
442 /// already seen one so a \#else directive is a duplicate.  When this returns,
443 /// the caller can lex the first valid token.
444 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
445                                                 SourceLocation IfTokenLoc,
446                                                 bool FoundNonSkipPortion,
447                                                 bool FoundElse,
448                                                 SourceLocation ElseLoc) {
449   ++NumSkipped;
450   assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
451 
452   if (PreambleConditionalStack.reachedEOFWhileSkipping())
453     PreambleConditionalStack.clearSkipInfo();
454   else
455     CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
456                                      FoundNonSkipPortion, FoundElse);
457 
458   // Enter raw mode to disable identifier lookup (and thus macro expansion),
459   // disabling warnings, etc.
460   CurPPLexer->LexingRawMode = true;
461   Token Tok;
462   if (auto SkipLength =
463           getSkippedRangeForExcludedConditionalBlock(HashTokenLoc)) {
464     // Skip to the next '#endif' / '#else' / '#elif'.
465     CurLexer->skipOver(*SkipLength);
466   }
467   SourceLocation endLoc;
468   while (true) {
469     CurLexer->Lex(Tok);
470 
471     if (Tok.is(tok::code_completion)) {
472       setCodeCompletionReached();
473       if (CodeComplete)
474         CodeComplete->CodeCompleteInConditionalExclusion();
475       continue;
476     }
477 
478     // If this is the end of the buffer, we have an error.
479     if (Tok.is(tok::eof)) {
480       // We don't emit errors for unterminated conditionals here,
481       // Lexer::LexEndOfFile can do that properly.
482       // Just return and let the caller lex after this #include.
483       if (PreambleConditionalStack.isRecording())
484         PreambleConditionalStack.SkipInfo.emplace(
485             HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
486       break;
487     }
488 
489     // If this token is not a preprocessor directive, just skip it.
490     if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
491       continue;
492 
493     // We just parsed a # character at the start of a line, so we're in
494     // directive mode.  Tell the lexer this so any newlines we see will be
495     // converted into an EOD token (this terminates the macro).
496     CurPPLexer->ParsingPreprocessorDirective = true;
497     if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
498 
499 
500     // Read the next token, the directive flavor.
501     LexUnexpandedToken(Tok);
502 
503     // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
504     // something bogus), skip it.
505     if (Tok.isNot(tok::raw_identifier)) {
506       CurPPLexer->ParsingPreprocessorDirective = false;
507       // Restore comment saving mode.
508       if (CurLexer) CurLexer->resetExtendedTokenMode();
509       continue;
510     }
511 
512     // If the first letter isn't i or e, it isn't intesting to us.  We know that
513     // this is safe in the face of spelling differences, because there is no way
514     // to spell an i/e in a strange way that is another letter.  Skipping this
515     // allows us to avoid looking up the identifier info for #define/#undef and
516     // other common directives.
517     StringRef RI = Tok.getRawIdentifier();
518 
519     char FirstChar = RI[0];
520     if (FirstChar >= 'a' && FirstChar <= 'z' &&
521         FirstChar != 'i' && FirstChar != 'e') {
522       CurPPLexer->ParsingPreprocessorDirective = false;
523       // Restore comment saving mode.
524       if (CurLexer) CurLexer->resetExtendedTokenMode();
525       continue;
526     }
527 
528     // Get the identifier name without trigraphs or embedded newlines.  Note
529     // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
530     // when skipping.
531     char DirectiveBuf[20];
532     StringRef Directive;
533     if (!Tok.needsCleaning() && RI.size() < 20) {
534       Directive = RI;
535     } else {
536       std::string DirectiveStr = getSpelling(Tok);
537       size_t IdLen = DirectiveStr.size();
538       if (IdLen >= 20) {
539         CurPPLexer->ParsingPreprocessorDirective = false;
540         // Restore comment saving mode.
541         if (CurLexer) CurLexer->resetExtendedTokenMode();
542         continue;
543       }
544       memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
545       Directive = StringRef(DirectiveBuf, IdLen);
546     }
547 
548     if (Directive.startswith("if")) {
549       StringRef Sub = Directive.substr(2);
550       if (Sub.empty() ||   // "if"
551           Sub == "def" ||   // "ifdef"
552           Sub == "ndef") {  // "ifndef"
553         // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
554         // bother parsing the condition.
555         DiscardUntilEndOfDirective();
556         CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
557                                        /*foundnonskip*/false,
558                                        /*foundelse*/false);
559       }
560     } else if (Directive[0] == 'e') {
561       StringRef Sub = Directive.substr(1);
562       if (Sub == "ndif") {  // "endif"
563         PPConditionalInfo CondInfo;
564         CondInfo.WasSkipping = true; // Silence bogus warning.
565         bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
566         (void)InCond;  // Silence warning in no-asserts mode.
567         assert(!InCond && "Can't be skipping if not in a conditional!");
568 
569         // If we popped the outermost skipping block, we're done skipping!
570         if (!CondInfo.WasSkipping) {
571           // Restore the value of LexingRawMode so that trailing comments
572           // are handled correctly, if we've reached the outermost block.
573           CurPPLexer->LexingRawMode = false;
574           endLoc = CheckEndOfDirective("endif");
575           CurPPLexer->LexingRawMode = true;
576           if (Callbacks)
577             Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
578           break;
579         } else {
580           DiscardUntilEndOfDirective();
581         }
582       } else if (Sub == "lse") { // "else".
583         // #else directive in a skipping conditional.  If not in some other
584         // skipping conditional, and if #else hasn't already been seen, enter it
585         // as a non-skipping conditional.
586         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
587 
588         // If this is a #else with a #else before it, report the error.
589         if (CondInfo.FoundElse)
590           Diag(Tok, diag::pp_err_else_after_else);
591 
592         // Note that we've seen a #else in this conditional.
593         CondInfo.FoundElse = true;
594 
595         // If the conditional is at the top level, and the #if block wasn't
596         // entered, enter the #else block now.
597         if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
598           CondInfo.FoundNonSkip = true;
599           // Restore the value of LexingRawMode so that trailing comments
600           // are handled correctly.
601           CurPPLexer->LexingRawMode = false;
602           endLoc = CheckEndOfDirective("else");
603           CurPPLexer->LexingRawMode = true;
604           if (Callbacks)
605             Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
606           break;
607         } else {
608           DiscardUntilEndOfDirective();  // C99 6.10p4.
609         }
610       } else if (Sub == "lif") {  // "elif".
611         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
612 
613         // If this is a #elif with a #else before it, report the error.
614         if (CondInfo.FoundElse)
615           Diag(Tok, diag::pp_err_elif_after_else) << PED_Elif;
616 
617         // If this is in a skipping block or if we're already handled this #if
618         // block, don't bother parsing the condition.
619         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
620           // FIXME: We should probably do at least some minimal parsing of the
621           // condition to verify that it is well-formed. The current state
622           // allows #elif* directives with completely malformed (or missing)
623           // conditions.
624           DiscardUntilEndOfDirective();
625         } else {
626           // Restore the value of LexingRawMode so that identifiers are
627           // looked up, etc, inside the #elif expression.
628           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
629           CurPPLexer->LexingRawMode = false;
630           IdentifierInfo *IfNDefMacro = nullptr;
631           DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
632           // Stop if Lexer became invalid after hitting code completion token.
633           if (!CurPPLexer)
634             return;
635           const bool CondValue = DER.Conditional;
636           CurPPLexer->LexingRawMode = true;
637           if (Callbacks) {
638             Callbacks->Elif(
639                 Tok.getLocation(), DER.ExprRange,
640                 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
641                 CondInfo.IfLoc);
642           }
643           // If this condition is true, enter it!
644           if (CondValue) {
645             CondInfo.FoundNonSkip = true;
646             break;
647           }
648         }
649       } else if (Sub == "lifdef" ||  // "elifdef"
650                  Sub == "lifndef") { // "elifndef"
651         bool IsElifDef = Sub == "lifdef";
652         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
653         Token DirectiveToken = Tok;
654 
655         // Warn if using `#elifdef` & `#elifndef` in not C2x & C++2b mode even
656         // if this branch is in a skipping block.
657         unsigned DiagID;
658         if (LangOpts.CPlusPlus)
659           DiagID = LangOpts.CPlusPlus2b ? diag::warn_cxx2b_compat_pp_directive
660                                         : diag::ext_cxx2b_pp_directive;
661         else
662           DiagID = LangOpts.C2x ? diag::warn_c2x_compat_pp_directive
663                                 : diag::ext_c2x_pp_directive;
664         Diag(Tok, DiagID) << (IsElifDef ? PED_Elifdef : PED_Elifndef);
665 
666         // If this is a #elif with a #else before it, report the error.
667         if (CondInfo.FoundElse)
668           Diag(Tok, diag::pp_err_elif_after_else)
669               << (IsElifDef ? PED_Elifdef : PED_Elifndef);
670 
671         // If this is in a skipping block or if we're already handled this #if
672         // block, don't bother parsing the condition.
673         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
674           // FIXME: We should probably do at least some minimal parsing of the
675           // condition to verify that it is well-formed. The current state
676           // allows #elif* directives with completely malformed (or missing)
677           // conditions.
678           DiscardUntilEndOfDirective();
679         } else {
680           // Restore the value of LexingRawMode so that identifiers are
681           // looked up, etc, inside the #elif[n]def expression.
682           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
683           CurPPLexer->LexingRawMode = false;
684           Token MacroNameTok;
685           ReadMacroName(MacroNameTok);
686           CurPPLexer->LexingRawMode = true;
687 
688           // If the macro name token is tok::eod, there was an error that was
689           // already reported.
690           if (MacroNameTok.is(tok::eod)) {
691             // Skip code until we get to #endif.  This helps with recovery by
692             // not emitting an error when the #endif is reached.
693             continue;
694           }
695 
696           emitMacroExpansionWarnings(MacroNameTok);
697 
698           CheckEndOfDirective(IsElifDef ? "elifdef" : "elifndef");
699 
700           IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
701           auto MD = getMacroDefinition(MII);
702           MacroInfo *MI = MD.getMacroInfo();
703 
704           if (Callbacks) {
705             if (IsElifDef) {
706               Callbacks->Elifdef(DirectiveToken.getLocation(), MacroNameTok,
707                                  MD);
708             } else {
709               Callbacks->Elifndef(DirectiveToken.getLocation(), MacroNameTok,
710                                   MD);
711             }
712           }
713           // If this condition is true, enter it!
714           if (static_cast<bool>(MI) == IsElifDef) {
715             CondInfo.FoundNonSkip = true;
716             break;
717           }
718         }
719       }
720     }
721 
722     CurPPLexer->ParsingPreprocessorDirective = false;
723     // Restore comment saving mode.
724     if (CurLexer) CurLexer->resetExtendedTokenMode();
725   }
726 
727   // Finally, if we are out of the conditional (saw an #endif or ran off the end
728   // of the file, just stop skipping and return to lexing whatever came after
729   // the #if block.
730   CurPPLexer->LexingRawMode = false;
731 
732   // The last skipped range isn't actually skipped yet if it's truncated
733   // by the end of the preamble; we'll resume parsing after the preamble.
734   if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
735     Callbacks->SourceRangeSkipped(
736         SourceRange(HashTokenLoc, endLoc.isValid()
737                                       ? endLoc
738                                       : CurPPLexer->getSourceLocation()),
739         Tok.getLocation());
740 }
741 
742 Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
743   if (!SourceMgr.isInMainFile(Loc)) {
744     // Try to determine the module of the include directive.
745     // FIXME: Look into directly passing the FileEntry from LookupFile instead.
746     FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
747     if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
748       // The include comes from an included file.
749       return HeaderInfo.getModuleMap()
750           .findModuleForHeader(EntryOfIncl)
751           .getModule();
752     }
753   }
754 
755   // This is either in the main file or not in a file at all. It belongs
756   // to the current module, if there is one.
757   return getLangOpts().CurrentModule.empty()
758              ? nullptr
759              : HeaderInfo.lookupModule(getLangOpts().CurrentModule, Loc);
760 }
761 
762 const FileEntry *
763 Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
764                                                SourceLocation Loc) {
765   Module *IncM = getModuleForLocation(IncLoc);
766 
767   // Walk up through the include stack, looking through textual headers of M
768   // until we hit a non-textual header that we can #include. (We assume textual
769   // headers of a module with non-textual headers aren't meant to be used to
770   // import entities from the module.)
771   auto &SM = getSourceManager();
772   while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
773     auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
774     auto *FE = SM.getFileEntryForID(ID);
775     if (!FE)
776       break;
777 
778     // We want to find all possible modules that might contain this header, so
779     // search all enclosing directories for module maps and load them.
780     HeaderInfo.hasModuleMap(FE->getName(), /*Root*/ nullptr,
781                             SourceMgr.isInSystemHeader(Loc));
782 
783     bool InPrivateHeader = false;
784     for (auto Header : HeaderInfo.findAllModulesForHeader(FE)) {
785       if (!Header.isAccessibleFrom(IncM)) {
786         // It's in a private header; we can't #include it.
787         // FIXME: If there's a public header in some module that re-exports it,
788         // then we could suggest including that, but it's not clear that's the
789         // expected way to make this entity visible.
790         InPrivateHeader = true;
791         continue;
792       }
793 
794       // We'll suggest including textual headers below if they're
795       // include-guarded.
796       if (Header.getRole() & ModuleMap::TextualHeader)
797         continue;
798 
799       // If we have a module import syntax, we shouldn't include a header to
800       // make a particular module visible. Let the caller know they should
801       // suggest an import instead.
802       if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
803           getLangOpts().ModulesTS)
804         return nullptr;
805 
806       // If this is an accessible, non-textual header of M's top-level module
807       // that transitively includes the given location and makes the
808       // corresponding module visible, this is the thing to #include.
809       return FE;
810     }
811 
812     // FIXME: If we're bailing out due to a private header, we shouldn't suggest
813     // an import either.
814     if (InPrivateHeader)
815       return nullptr;
816 
817     // If the header is includable and has an include guard, assume the
818     // intended way to expose its contents is by #include, not by importing a
819     // module that transitively includes it.
820     if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
821       return FE;
822 
823     Loc = SM.getIncludeLoc(ID);
824   }
825 
826   return nullptr;
827 }
828 
829 Optional<FileEntryRef> Preprocessor::LookupFile(
830     SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
831     ConstSearchDirIterator FromDir, const FileEntry *FromFile,
832     ConstSearchDirIterator *CurDirArg, SmallVectorImpl<char> *SearchPath,
833     SmallVectorImpl<char> *RelativePath,
834     ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
835     bool *IsFrameworkFound, bool SkipCache) {
836   ConstSearchDirIterator CurDirLocal = nullptr;
837   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
838 
839   Module *RequestingModule = getModuleForLocation(FilenameLoc);
840   bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
841 
842   // If the header lookup mechanism may be relative to the current inclusion
843   // stack, record the parent #includes.
844   SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
845       Includers;
846   bool BuildSystemModule = false;
847   if (!FromDir && !FromFile) {
848     FileID FID = getCurrentFileLexer()->getFileID();
849     const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
850 
851     // If there is no file entry associated with this file, it must be the
852     // predefines buffer or the module includes buffer. Any other file is not
853     // lexed with a normal lexer, so it won't be scanned for preprocessor
854     // directives.
855     //
856     // If we have the predefines buffer, resolve #include references (which come
857     // from the -include command line argument) from the current working
858     // directory instead of relative to the main file.
859     //
860     // If we have the module includes buffer, resolve #include references (which
861     // come from header declarations in the module map) relative to the module
862     // map file.
863     if (!FileEnt) {
864       if (FID == SourceMgr.getMainFileID() && MainFileDir) {
865         Includers.push_back(std::make_pair(nullptr, MainFileDir));
866         BuildSystemModule = getCurrentModule()->IsSystem;
867       } else if ((FileEnt =
868                     SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
869         Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
870     } else {
871       Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
872     }
873 
874     // MSVC searches the current include stack from top to bottom for
875     // headers included by quoted include directives.
876     // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
877     if (LangOpts.MSVCCompat && !isAngled) {
878       for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
879         if (IsFileLexer(ISEntry))
880           if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
881             Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
882       }
883     }
884   }
885 
886   CurDir = CurDirLookup;
887 
888   if (FromFile) {
889     // We're supposed to start looking from after a particular file. Search
890     // the include path until we find that file or run out of files.
891     ConstSearchDirIterator TmpCurDir = CurDir;
892     ConstSearchDirIterator TmpFromDir = nullptr;
893     while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
894                Filename, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
895                Includers, SearchPath, RelativePath, RequestingModule,
896                SuggestedModule, /*IsMapped=*/nullptr,
897                /*IsFrameworkFound=*/nullptr, SkipCache)) {
898       // Keep looking as if this file did a #include_next.
899       TmpFromDir = TmpCurDir;
900       ++TmpFromDir;
901       if (&FE->getFileEntry() == FromFile) {
902         // Found it.
903         FromDir = TmpFromDir;
904         CurDir = TmpCurDir;
905         break;
906       }
907     }
908   }
909 
910   // Do a standard file entry lookup.
911   Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
912       Filename, FilenameLoc, isAngled, FromDir, &CurDir, Includers, SearchPath,
913       RelativePath, RequestingModule, SuggestedModule, IsMapped,
914       IsFrameworkFound, SkipCache, BuildSystemModule);
915   if (FE) {
916     if (SuggestedModule && !LangOpts.AsmPreprocessor)
917       HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
918           RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
919           Filename, *FE);
920     return FE;
921   }
922 
923   const FileEntry *CurFileEnt;
924   // Otherwise, see if this is a subframework header.  If so, this is relative
925   // to one of the headers on the #include stack.  Walk the list of the current
926   // headers on the #include stack and pass them to HeaderInfo.
927   if (IsFileLexer()) {
928     if ((CurFileEnt = CurPPLexer->getFileEntry())) {
929       if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
930               Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
931               SuggestedModule)) {
932         if (SuggestedModule && !LangOpts.AsmPreprocessor)
933           HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
934               RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
935               Filename, *FE);
936         return FE;
937       }
938     }
939   }
940 
941   for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
942     if (IsFileLexer(ISEntry)) {
943       if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
944         if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
945                 Filename, CurFileEnt, SearchPath, RelativePath,
946                 RequestingModule, SuggestedModule)) {
947           if (SuggestedModule && !LangOpts.AsmPreprocessor)
948             HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
949                 RequestingModule, RequestingModuleIsModuleInterface,
950                 FilenameLoc, Filename, *FE);
951           return FE;
952         }
953       }
954     }
955   }
956 
957   // Otherwise, we really couldn't find the file.
958   return None;
959 }
960 
961 //===----------------------------------------------------------------------===//
962 // Preprocessor Directive Handling.
963 //===----------------------------------------------------------------------===//
964 
965 class Preprocessor::ResetMacroExpansionHelper {
966 public:
967   ResetMacroExpansionHelper(Preprocessor *pp)
968     : PP(pp), save(pp->DisableMacroExpansion) {
969     if (pp->MacroExpansionInDirectivesOverride)
970       pp->DisableMacroExpansion = false;
971   }
972 
973   ~ResetMacroExpansionHelper() {
974     PP->DisableMacroExpansion = save;
975   }
976 
977 private:
978   Preprocessor *PP;
979   bool save;
980 };
981 
982 /// Process a directive while looking for the through header or a #pragma
983 /// hdrstop. The following directives are handled:
984 /// #include (to check if it is the through header)
985 /// #define (to warn about macros that don't match the PCH)
986 /// #pragma (to check for pragma hdrstop).
987 /// All other directives are completely discarded.
988 void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
989                                                        SourceLocation HashLoc) {
990   if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
991     if (II->getPPKeywordID() == tok::pp_define) {
992       return HandleDefineDirective(Result,
993                                    /*ImmediatelyAfterHeaderGuard=*/false);
994     }
995     if (SkippingUntilPCHThroughHeader &&
996         II->getPPKeywordID() == tok::pp_include) {
997       return HandleIncludeDirective(HashLoc, Result);
998     }
999     if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
1000       Lex(Result);
1001       auto *II = Result.getIdentifierInfo();
1002       if (II && II->getName() == "hdrstop")
1003         return HandlePragmaHdrstop(Result);
1004     }
1005   }
1006   DiscardUntilEndOfDirective();
1007 }
1008 
1009 /// HandleDirective - This callback is invoked when the lexer sees a # token
1010 /// at the start of a line.  This consumes the directive, modifies the
1011 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
1012 /// read is the correct one.
1013 void Preprocessor::HandleDirective(Token &Result) {
1014   // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1015 
1016   // We just parsed a # character at the start of a line, so we're in directive
1017   // mode.  Tell the lexer this so any newlines we see will be converted into an
1018   // EOD token (which terminates the directive).
1019   CurPPLexer->ParsingPreprocessorDirective = true;
1020   if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
1021 
1022   bool ImmediatelyAfterTopLevelIfndef =
1023       CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
1024   CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
1025 
1026   ++NumDirectives;
1027 
1028   // We are about to read a token.  For the multiple-include optimization FA to
1029   // work, we have to remember if we had read any tokens *before* this
1030   // pp-directive.
1031   bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
1032 
1033   // Save the '#' token in case we need to return it later.
1034   Token SavedHash = Result;
1035 
1036   // Read the next token, the directive flavor.  This isn't expanded due to
1037   // C99 6.10.3p8.
1038   LexUnexpandedToken(Result);
1039 
1040   // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
1041   //   #define A(x) #x
1042   //   A(abc
1043   //     #warning blah
1044   //   def)
1045   // If so, the user is relying on undefined behavior, emit a diagnostic. Do
1046   // not support this for #include-like directives, since that can result in
1047   // terrible diagnostics, and does not work in GCC.
1048   if (InMacroArgs) {
1049     if (IdentifierInfo *II = Result.getIdentifierInfo()) {
1050       switch (II->getPPKeywordID()) {
1051       case tok::pp_include:
1052       case tok::pp_import:
1053       case tok::pp_include_next:
1054       case tok::pp___include_macros:
1055       case tok::pp_pragma:
1056         Diag(Result, diag::err_embedded_directive) << II->getName();
1057         Diag(*ArgMacro, diag::note_macro_expansion_here)
1058             << ArgMacro->getIdentifierInfo();
1059         DiscardUntilEndOfDirective();
1060         return;
1061       default:
1062         break;
1063       }
1064     }
1065     Diag(Result, diag::ext_embedded_directive);
1066   }
1067 
1068   // Temporarily enable macro expansion if set so
1069   // and reset to previous state when returning from this function.
1070   ResetMacroExpansionHelper helper(this);
1071 
1072   if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
1073     return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
1074 
1075   switch (Result.getKind()) {
1076   case tok::eod:
1077     return;   // null directive.
1078   case tok::code_completion:
1079     setCodeCompletionReached();
1080     if (CodeComplete)
1081       CodeComplete->CodeCompleteDirective(
1082                                     CurPPLexer->getConditionalStackDepth() > 0);
1083     return;
1084   case tok::numeric_constant:  // # 7  GNU line marker directive.
1085     if (getLangOpts().AsmPreprocessor)
1086       break;  // # 4 is not a preprocessor directive in .S files.
1087     return HandleDigitDirective(Result);
1088   default:
1089     IdentifierInfo *II = Result.getIdentifierInfo();
1090     if (!II) break; // Not an identifier.
1091 
1092     // Ask what the preprocessor keyword ID is.
1093     switch (II->getPPKeywordID()) {
1094     default: break;
1095     // C99 6.10.1 - Conditional Inclusion.
1096     case tok::pp_if:
1097       return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
1098     case tok::pp_ifdef:
1099       return HandleIfdefDirective(Result, SavedHash, false,
1100                                   true /*not valid for miopt*/);
1101     case tok::pp_ifndef:
1102       return HandleIfdefDirective(Result, SavedHash, true,
1103                                   ReadAnyTokensBeforeDirective);
1104     case tok::pp_elif:
1105     case tok::pp_elifdef:
1106     case tok::pp_elifndef:
1107       return HandleElifFamilyDirective(Result, SavedHash, II->getPPKeywordID());
1108 
1109     case tok::pp_else:
1110       return HandleElseDirective(Result, SavedHash);
1111     case tok::pp_endif:
1112       return HandleEndifDirective(Result);
1113 
1114     // C99 6.10.2 - Source File Inclusion.
1115     case tok::pp_include:
1116       // Handle #include.
1117       return HandleIncludeDirective(SavedHash.getLocation(), Result);
1118     case tok::pp___include_macros:
1119       // Handle -imacros.
1120       return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
1121 
1122     // C99 6.10.3 - Macro Replacement.
1123     case tok::pp_define:
1124       return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
1125     case tok::pp_undef:
1126       return HandleUndefDirective();
1127 
1128     // C99 6.10.4 - Line Control.
1129     case tok::pp_line:
1130       return HandleLineDirective();
1131 
1132     // C99 6.10.5 - Error Directive.
1133     case tok::pp_error:
1134       return HandleUserDiagnosticDirective(Result, false);
1135 
1136     // C99 6.10.6 - Pragma Directive.
1137     case tok::pp_pragma:
1138       return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
1139 
1140     // GNU Extensions.
1141     case tok::pp_import:
1142       return HandleImportDirective(SavedHash.getLocation(), Result);
1143     case tok::pp_include_next:
1144       return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
1145 
1146     case tok::pp_warning:
1147       Diag(Result, diag::ext_pp_warning_directive);
1148       return HandleUserDiagnosticDirective(Result, true);
1149     case tok::pp_ident:
1150       return HandleIdentSCCSDirective(Result);
1151     case tok::pp_sccs:
1152       return HandleIdentSCCSDirective(Result);
1153     case tok::pp_assert:
1154       //isExtension = true;  // FIXME: implement #assert
1155       break;
1156     case tok::pp_unassert:
1157       //isExtension = true;  // FIXME: implement #unassert
1158       break;
1159 
1160     case tok::pp___public_macro:
1161       if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
1162         return HandleMacroPublicDirective(Result);
1163       break;
1164 
1165     case tok::pp___private_macro:
1166       if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
1167         return HandleMacroPrivateDirective();
1168       break;
1169     }
1170     break;
1171   }
1172 
1173   // If this is a .S file, treat unknown # directives as non-preprocessor
1174   // directives.  This is important because # may be a comment or introduce
1175   // various pseudo-ops.  Just return the # token and push back the following
1176   // token to be lexed next time.
1177   if (getLangOpts().AsmPreprocessor) {
1178     auto Toks = std::make_unique<Token[]>(2);
1179     // Return the # and the token after it.
1180     Toks[0] = SavedHash;
1181     Toks[1] = Result;
1182 
1183     // If the second token is a hashhash token, then we need to translate it to
1184     // unknown so the token lexer doesn't try to perform token pasting.
1185     if (Result.is(tok::hashhash))
1186       Toks[1].setKind(tok::unknown);
1187 
1188     // Enter this token stream so that we re-lex the tokens.  Make sure to
1189     // enable macro expansion, in case the token after the # is an identifier
1190     // that is expanded.
1191     EnterTokenStream(std::move(Toks), 2, false, /*IsReinject*/false);
1192     return;
1193   }
1194 
1195   // If we reached here, the preprocessing token is not valid!
1196   Diag(Result, diag::err_pp_invalid_directive);
1197 
1198   // Read the rest of the PP line.
1199   DiscardUntilEndOfDirective();
1200 
1201   // Okay, we're done parsing the directive.
1202 }
1203 
1204 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
1205 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
1206 static bool GetLineValue(Token &DigitTok, unsigned &Val,
1207                          unsigned DiagID, Preprocessor &PP,
1208                          bool IsGNULineDirective=false) {
1209   if (DigitTok.isNot(tok::numeric_constant)) {
1210     PP.Diag(DigitTok, DiagID);
1211 
1212     if (DigitTok.isNot(tok::eod))
1213       PP.DiscardUntilEndOfDirective();
1214     return true;
1215   }
1216 
1217   SmallString<64> IntegerBuffer;
1218   IntegerBuffer.resize(DigitTok.getLength());
1219   const char *DigitTokBegin = &IntegerBuffer[0];
1220   bool Invalid = false;
1221   unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1222   if (Invalid)
1223     return true;
1224 
1225   // Verify that we have a simple digit-sequence, and compute the value.  This
1226   // is always a simple digit string computed in decimal, so we do this manually
1227   // here.
1228   Val = 0;
1229   for (unsigned i = 0; i != ActualLength; ++i) {
1230     // C++1y [lex.fcon]p1:
1231     //   Optional separating single quotes in a digit-sequence are ignored
1232     if (DigitTokBegin[i] == '\'')
1233       continue;
1234 
1235     if (!isDigit(DigitTokBegin[i])) {
1236       PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
1237               diag::err_pp_line_digit_sequence) << IsGNULineDirective;
1238       PP.DiscardUntilEndOfDirective();
1239       return true;
1240     }
1241 
1242     unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1243     if (NextVal < Val) { // overflow.
1244       PP.Diag(DigitTok, DiagID);
1245       PP.DiscardUntilEndOfDirective();
1246       return true;
1247     }
1248     Val = NextVal;
1249   }
1250 
1251   if (DigitTokBegin[0] == '0' && Val)
1252     PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1253       << IsGNULineDirective;
1254 
1255   return false;
1256 }
1257 
1258 /// Handle a \#line directive: C99 6.10.4.
1259 ///
1260 /// The two acceptable forms are:
1261 /// \verbatim
1262 ///   # line digit-sequence
1263 ///   # line digit-sequence "s-char-sequence"
1264 /// \endverbatim
1265 void Preprocessor::HandleLineDirective() {
1266   // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
1267   // expanded.
1268   Token DigitTok;
1269   Lex(DigitTok);
1270 
1271   // Validate the number and convert it to an unsigned.
1272   unsigned LineNo;
1273   if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
1274     return;
1275 
1276   if (LineNo == 0)
1277     Diag(DigitTok, diag::ext_pp_line_zero);
1278 
1279   // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1280   // number greater than 2147483647".  C90 requires that the line # be <= 32767.
1281   unsigned LineLimit = 32768U;
1282   if (LangOpts.C99 || LangOpts.CPlusPlus11)
1283     LineLimit = 2147483648U;
1284   if (LineNo >= LineLimit)
1285     Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
1286   else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
1287     Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
1288 
1289   int FilenameID = -1;
1290   Token StrTok;
1291   Lex(StrTok);
1292 
1293   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
1294   // string followed by eod.
1295   if (StrTok.is(tok::eod))
1296     ; // ok
1297   else if (StrTok.isNot(tok::string_literal)) {
1298     Diag(StrTok, diag::err_pp_line_invalid_filename);
1299     DiscardUntilEndOfDirective();
1300     return;
1301   } else if (StrTok.hasUDSuffix()) {
1302     Diag(StrTok, diag::err_invalid_string_udl);
1303     DiscardUntilEndOfDirective();
1304     return;
1305   } else {
1306     // Parse and validate the string, converting it into a unique ID.
1307     StringLiteralParser Literal(StrTok, *this);
1308     assert(Literal.isAscii() && "Didn't allow wide strings in");
1309     if (Literal.hadError) {
1310       DiscardUntilEndOfDirective();
1311       return;
1312     }
1313     if (Literal.Pascal) {
1314       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1315       DiscardUntilEndOfDirective();
1316       return;
1317     }
1318     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1319 
1320     // Verify that there is nothing after the string, other than EOD.  Because
1321     // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1322     CheckEndOfDirective("line", true);
1323   }
1324 
1325   // Take the file kind of the file containing the #line directive. #line
1326   // directives are often used for generated sources from the same codebase, so
1327   // the new file should generally be classified the same way as the current
1328   // file. This is visible in GCC's pre-processed output, which rewrites #line
1329   // to GNU line markers.
1330   SrcMgr::CharacteristicKind FileKind =
1331       SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1332 
1333   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1334                         false, FileKind);
1335 
1336   if (Callbacks)
1337     Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1338                            PPCallbacks::RenameFile, FileKind);
1339 }
1340 
1341 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1342 /// marker directive.
1343 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1344                                 SrcMgr::CharacteristicKind &FileKind,
1345                                 Preprocessor &PP) {
1346   unsigned FlagVal;
1347   Token FlagTok;
1348   PP.Lex(FlagTok);
1349   if (FlagTok.is(tok::eod)) return false;
1350   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1351     return true;
1352 
1353   if (FlagVal == 1) {
1354     IsFileEntry = true;
1355 
1356     PP.Lex(FlagTok);
1357     if (FlagTok.is(tok::eod)) return false;
1358     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1359       return true;
1360   } else if (FlagVal == 2) {
1361     IsFileExit = true;
1362 
1363     SourceManager &SM = PP.getSourceManager();
1364     // If we are leaving the current presumed file, check to make sure the
1365     // presumed include stack isn't empty!
1366     FileID CurFileID =
1367       SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
1368     PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
1369     if (PLoc.isInvalid())
1370       return true;
1371 
1372     // If there is no include loc (main file) or if the include loc is in a
1373     // different physical file, then we aren't in a "1" line marker flag region.
1374     SourceLocation IncLoc = PLoc.getIncludeLoc();
1375     if (IncLoc.isInvalid() ||
1376         SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
1377       PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1378       PP.DiscardUntilEndOfDirective();
1379       return true;
1380     }
1381 
1382     PP.Lex(FlagTok);
1383     if (FlagTok.is(tok::eod)) return false;
1384     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1385       return true;
1386   }
1387 
1388   // We must have 3 if there are still flags.
1389   if (FlagVal != 3) {
1390     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1391     PP.DiscardUntilEndOfDirective();
1392     return true;
1393   }
1394 
1395   FileKind = SrcMgr::C_System;
1396 
1397   PP.Lex(FlagTok);
1398   if (FlagTok.is(tok::eod)) return false;
1399   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1400     return true;
1401 
1402   // We must have 4 if there is yet another flag.
1403   if (FlagVal != 4) {
1404     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1405     PP.DiscardUntilEndOfDirective();
1406     return true;
1407   }
1408 
1409   FileKind = SrcMgr::C_ExternCSystem;
1410 
1411   PP.Lex(FlagTok);
1412   if (FlagTok.is(tok::eod)) return false;
1413 
1414   // There are no more valid flags here.
1415   PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1416   PP.DiscardUntilEndOfDirective();
1417   return true;
1418 }
1419 
1420 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1421 /// one of the following forms:
1422 ///
1423 ///     # 42
1424 ///     # 42 "file" ('1' | '2')?
1425 ///     # 42 "file" ('1' | '2')? '3' '4'?
1426 ///
1427 void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1428   // Validate the number and convert it to an unsigned.  GNU does not have a
1429   // line # limit other than it fit in 32-bits.
1430   unsigned LineNo;
1431   if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
1432                    *this, true))
1433     return;
1434 
1435   Token StrTok;
1436   Lex(StrTok);
1437 
1438   bool IsFileEntry = false, IsFileExit = false;
1439   int FilenameID = -1;
1440   SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1441 
1442   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
1443   // string followed by eod.
1444   if (StrTok.is(tok::eod)) {
1445     Diag(StrTok, diag::ext_pp_gnu_line_directive);
1446     // Treat this like "#line NN", which doesn't change file characteristics.
1447     FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1448   } else if (StrTok.isNot(tok::string_literal)) {
1449     Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1450     DiscardUntilEndOfDirective();
1451     return;
1452   } else if (StrTok.hasUDSuffix()) {
1453     Diag(StrTok, diag::err_invalid_string_udl);
1454     DiscardUntilEndOfDirective();
1455     return;
1456   } else {
1457     // Parse and validate the string, converting it into a unique ID.
1458     StringLiteralParser Literal(StrTok, *this);
1459     assert(Literal.isAscii() && "Didn't allow wide strings in");
1460     if (Literal.hadError) {
1461       DiscardUntilEndOfDirective();
1462       return;
1463     }
1464     if (Literal.Pascal) {
1465       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1466       DiscardUntilEndOfDirective();
1467       return;
1468     }
1469 
1470     // If a filename was present, read any flags that are present.
1471     if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
1472       return;
1473     if (!SourceMgr.isWrittenInBuiltinFile(DigitTok.getLocation()) &&
1474         !SourceMgr.isWrittenInCommandLineFile(DigitTok.getLocation()))
1475       Diag(StrTok, diag::ext_pp_gnu_line_directive);
1476 
1477     // Exiting to an empty string means pop to the including file, so leave
1478     // FilenameID as -1 in that case.
1479     if (!(IsFileExit && Literal.GetString().empty()))
1480       FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1481   }
1482 
1483   // Create a line note with this information.
1484   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1485                         IsFileExit, FileKind);
1486 
1487   // If the preprocessor has callbacks installed, notify them of the #line
1488   // change.  This is used so that the line marker comes out in -E mode for
1489   // example.
1490   if (Callbacks) {
1491     PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1492     if (IsFileEntry)
1493       Reason = PPCallbacks::EnterFile;
1494     else if (IsFileExit)
1495       Reason = PPCallbacks::ExitFile;
1496 
1497     Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
1498   }
1499 }
1500 
1501 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1502 ///
1503 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1504                                                  bool isWarning) {
1505   // Read the rest of the line raw.  We do this because we don't want macros
1506   // to be expanded and we don't require that the tokens be valid preprocessing
1507   // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
1508   // collapse multiple consecutive white space between tokens, but this isn't
1509   // specified by the standard.
1510   SmallString<128> Message;
1511   CurLexer->ReadToEndOfLine(&Message);
1512 
1513   // Find the first non-whitespace character, so that we can make the
1514   // diagnostic more succinct.
1515   StringRef Msg = Message.str().ltrim(' ');
1516 
1517   if (isWarning)
1518     Diag(Tok, diag::pp_hash_warning) << Msg;
1519   else
1520     Diag(Tok, diag::err_pp_hash_error) << Msg;
1521 }
1522 
1523 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1524 ///
1525 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1526   // Yes, this directive is an extension.
1527   Diag(Tok, diag::ext_pp_ident_directive);
1528 
1529   // Read the string argument.
1530   Token StrTok;
1531   Lex(StrTok);
1532 
1533   // If the token kind isn't a string, it's a malformed directive.
1534   if (StrTok.isNot(tok::string_literal) &&
1535       StrTok.isNot(tok::wide_string_literal)) {
1536     Diag(StrTok, diag::err_pp_malformed_ident);
1537     if (StrTok.isNot(tok::eod))
1538       DiscardUntilEndOfDirective();
1539     return;
1540   }
1541 
1542   if (StrTok.hasUDSuffix()) {
1543     Diag(StrTok, diag::err_invalid_string_udl);
1544     DiscardUntilEndOfDirective();
1545     return;
1546   }
1547 
1548   // Verify that there is nothing after the string, other than EOD.
1549   CheckEndOfDirective("ident");
1550 
1551   if (Callbacks) {
1552     bool Invalid = false;
1553     std::string Str = getSpelling(StrTok, &Invalid);
1554     if (!Invalid)
1555       Callbacks->Ident(Tok.getLocation(), Str);
1556   }
1557 }
1558 
1559 /// Handle a #public directive.
1560 void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
1561   Token MacroNameTok;
1562   ReadMacroName(MacroNameTok, MU_Undef);
1563 
1564   // Error reading macro name?  If so, diagnostic already issued.
1565   if (MacroNameTok.is(tok::eod))
1566     return;
1567 
1568   // Check to see if this is the last token on the #__public_macro line.
1569   CheckEndOfDirective("__public_macro");
1570 
1571   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1572   // Okay, we finally have a valid identifier to undef.
1573   MacroDirective *MD = getLocalMacroDirective(II);
1574 
1575   // If the macro is not defined, this is an error.
1576   if (!MD) {
1577     Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1578     return;
1579   }
1580 
1581   // Note that this macro has now been exported.
1582   appendMacroDirective(II, AllocateVisibilityMacroDirective(
1583                                 MacroNameTok.getLocation(), /*isPublic=*/true));
1584 }
1585 
1586 /// Handle a #private directive.
1587 void Preprocessor::HandleMacroPrivateDirective() {
1588   Token MacroNameTok;
1589   ReadMacroName(MacroNameTok, MU_Undef);
1590 
1591   // Error reading macro name?  If so, diagnostic already issued.
1592   if (MacroNameTok.is(tok::eod))
1593     return;
1594 
1595   // Check to see if this is the last token on the #__private_macro line.
1596   CheckEndOfDirective("__private_macro");
1597 
1598   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1599   // Okay, we finally have a valid identifier to undef.
1600   MacroDirective *MD = getLocalMacroDirective(II);
1601 
1602   // If the macro is not defined, this is an error.
1603   if (!MD) {
1604     Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1605     return;
1606   }
1607 
1608   // Note that this macro has now been marked private.
1609   appendMacroDirective(II, AllocateVisibilityMacroDirective(
1610                                MacroNameTok.getLocation(), /*isPublic=*/false));
1611 }
1612 
1613 //===----------------------------------------------------------------------===//
1614 // Preprocessor Include Directive Handling.
1615 //===----------------------------------------------------------------------===//
1616 
1617 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1618 /// checked and spelled filename, e.g. as an operand of \#include. This returns
1619 /// true if the input filename was in <>'s or false if it were in ""'s.  The
1620 /// caller is expected to provide a buffer that is large enough to hold the
1621 /// spelling of the filename, but is also expected to handle the case when
1622 /// this method decides to use a different buffer.
1623 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1624                                               StringRef &Buffer) {
1625   // Get the text form of the filename.
1626   assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1627 
1628   // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
1629   // C++20 [lex.header]/2:
1630   //
1631   // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
1632   //   in C: behavior is undefined
1633   //   in C++: program is conditionally-supported with implementation-defined
1634   //           semantics
1635 
1636   // Make sure the filename is <x> or "x".
1637   bool isAngled;
1638   if (Buffer[0] == '<') {
1639     if (Buffer.back() != '>') {
1640       Diag(Loc, diag::err_pp_expects_filename);
1641       Buffer = StringRef();
1642       return true;
1643     }
1644     isAngled = true;
1645   } else if (Buffer[0] == '"') {
1646     if (Buffer.back() != '"') {
1647       Diag(Loc, diag::err_pp_expects_filename);
1648       Buffer = StringRef();
1649       return true;
1650     }
1651     isAngled = false;
1652   } else {
1653     Diag(Loc, diag::err_pp_expects_filename);
1654     Buffer = StringRef();
1655     return true;
1656   }
1657 
1658   // Diagnose #include "" as invalid.
1659   if (Buffer.size() <= 2) {
1660     Diag(Loc, diag::err_pp_empty_filename);
1661     Buffer = StringRef();
1662     return true;
1663   }
1664 
1665   // Skip the brackets.
1666   Buffer = Buffer.substr(1, Buffer.size()-2);
1667   return isAngled;
1668 }
1669 
1670 /// Push a token onto the token stream containing an annotation.
1671 void Preprocessor::EnterAnnotationToken(SourceRange Range,
1672                                         tok::TokenKind Kind,
1673                                         void *AnnotationVal) {
1674   // FIXME: Produce this as the current token directly, rather than
1675   // allocating a new token for it.
1676   auto Tok = std::make_unique<Token[]>(1);
1677   Tok[0].startToken();
1678   Tok[0].setKind(Kind);
1679   Tok[0].setLocation(Range.getBegin());
1680   Tok[0].setAnnotationEndLoc(Range.getEnd());
1681   Tok[0].setAnnotationValue(AnnotationVal);
1682   EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
1683 }
1684 
1685 /// Produce a diagnostic informing the user that a #include or similar
1686 /// was implicitly treated as a module import.
1687 static void diagnoseAutoModuleImport(
1688     Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1689     ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1690     SourceLocation PathEnd) {
1691   StringRef ImportKeyword;
1692   if (PP.getLangOpts().ObjC)
1693     ImportKeyword = "@import";
1694   else if (PP.getLangOpts().ModulesTS || PP.getLangOpts().CPlusPlusModules)
1695     ImportKeyword = "import";
1696   else
1697     return; // no import syntax available
1698 
1699   SmallString<128> PathString;
1700   for (size_t I = 0, N = Path.size(); I != N; ++I) {
1701     if (I)
1702       PathString += '.';
1703     PathString += Path[I].first->getName();
1704   }
1705   int IncludeKind = 0;
1706 
1707   switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1708   case tok::pp_include:
1709     IncludeKind = 0;
1710     break;
1711 
1712   case tok::pp_import:
1713     IncludeKind = 1;
1714     break;
1715 
1716   case tok::pp_include_next:
1717     IncludeKind = 2;
1718     break;
1719 
1720   case tok::pp___include_macros:
1721     IncludeKind = 3;
1722     break;
1723 
1724   default:
1725     llvm_unreachable("unknown include directive kind");
1726   }
1727 
1728   CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1729                                /*IsTokenRange=*/false);
1730   PP.Diag(HashLoc, diag::warn_auto_module_import)
1731       << IncludeKind << PathString
1732       << FixItHint::CreateReplacement(
1733              ReplaceRange, (ImportKeyword + " " + PathString + ";").str());
1734 }
1735 
1736 // Given a vector of path components and a string containing the real
1737 // path to the file, build a properly-cased replacement in the vector,
1738 // and return true if the replacement should be suggested.
1739 static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1740                             StringRef RealPathName) {
1741   auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1742   auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1743   int Cnt = 0;
1744   bool SuggestReplacement = false;
1745   // Below is a best-effort to handle ".." in paths. It is admittedly
1746   // not 100% correct in the presence of symlinks.
1747   for (auto &Component : llvm::reverse(Components)) {
1748     if ("." == Component) {
1749     } else if (".." == Component) {
1750       ++Cnt;
1751     } else if (Cnt) {
1752       --Cnt;
1753     } else if (RealPathComponentIter != RealPathComponentEnd) {
1754       if (Component != *RealPathComponentIter) {
1755         // If these path components differ by more than just case, then we
1756         // may be looking at symlinked paths. Bail on this diagnostic to avoid
1757         // noisy false positives.
1758         SuggestReplacement =
1759             RealPathComponentIter->equals_insensitive(Component);
1760         if (!SuggestReplacement)
1761           break;
1762         Component = *RealPathComponentIter;
1763       }
1764       ++RealPathComponentIter;
1765     }
1766   }
1767   return SuggestReplacement;
1768 }
1769 
1770 bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1771                                           const TargetInfo &TargetInfo,
1772                                           DiagnosticsEngine &Diags, Module *M) {
1773   Module::Requirement Requirement;
1774   Module::UnresolvedHeaderDirective MissingHeader;
1775   Module *ShadowingModule = nullptr;
1776   if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1777                      ShadowingModule))
1778     return false;
1779 
1780   if (MissingHeader.FileNameLoc.isValid()) {
1781     Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1782         << MissingHeader.IsUmbrella << MissingHeader.FileName;
1783   } else if (ShadowingModule) {
1784     Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1785     Diags.Report(ShadowingModule->DefinitionLoc,
1786                  diag::note_previous_definition);
1787   } else {
1788     // FIXME: Track the location at which the requirement was specified, and
1789     // use it here.
1790     Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1791         << M->getFullModuleName() << Requirement.second << Requirement.first;
1792   }
1793   return true;
1794 }
1795 
1796 std::pair<ConstSearchDirIterator, const FileEntry *>
1797 Preprocessor::getIncludeNextStart(const Token &IncludeNextTok) const {
1798   // #include_next is like #include, except that we start searching after
1799   // the current found directory.  If we can't do this, issue a
1800   // diagnostic.
1801   ConstSearchDirIterator Lookup = CurDirLookup;
1802   const FileEntry *LookupFromFile = nullptr;
1803 
1804   if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
1805     // If the main file is a header, then it's either for PCH/AST generation,
1806     // or libclang opened it. Either way, handle it as a normal include below
1807     // and do not complain about include_next.
1808   } else if (isInPrimaryFile()) {
1809     Lookup = nullptr;
1810     Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1811   } else if (CurLexerSubmodule) {
1812     // Start looking up in the directory *after* the one in which the current
1813     // file would be found, if any.
1814     assert(CurPPLexer && "#include_next directive in macro?");
1815     LookupFromFile = CurPPLexer->getFileEntry();
1816     Lookup = nullptr;
1817   } else if (!Lookup) {
1818     // The current file was not found by walking the include path. Either it
1819     // is the primary file (handled above), or it was found by absolute path,
1820     // or it was found relative to such a file.
1821     // FIXME: Track enough information so we know which case we're in.
1822     Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1823   } else {
1824     // Start looking up in the next directory.
1825     ++Lookup;
1826   }
1827 
1828   return {Lookup, LookupFromFile};
1829 }
1830 
1831 /// HandleIncludeDirective - The "\#include" tokens have just been read, read
1832 /// the file to be included from the lexer, then include it!  This is a common
1833 /// routine with functionality shared between \#include, \#include_next and
1834 /// \#import.  LookupFrom is set when this is a \#include_next directive, it
1835 /// specifies the file to start searching from.
1836 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1837                                           Token &IncludeTok,
1838                                           ConstSearchDirIterator LookupFrom,
1839                                           const FileEntry *LookupFromFile) {
1840   Token FilenameTok;
1841   if (LexHeaderName(FilenameTok))
1842     return;
1843 
1844   if (FilenameTok.isNot(tok::header_name)) {
1845     Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1846     if (FilenameTok.isNot(tok::eod))
1847       DiscardUntilEndOfDirective();
1848     return;
1849   }
1850 
1851   // Verify that there is nothing after the filename, other than EOD.  Note
1852   // that we allow macros that expand to nothing after the filename, because
1853   // this falls into the category of "#include pp-tokens new-line" specified
1854   // in C99 6.10.2p4.
1855   SourceLocation EndLoc =
1856       CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1857 
1858   auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
1859                                             EndLoc, LookupFrom, LookupFromFile);
1860   switch (Action.Kind) {
1861   case ImportAction::None:
1862   case ImportAction::SkippedModuleImport:
1863     break;
1864   case ImportAction::ModuleBegin:
1865     EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1866                          tok::annot_module_begin, Action.ModuleForHeader);
1867     break;
1868   case ImportAction::ModuleImport:
1869     EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1870                          tok::annot_module_include, Action.ModuleForHeader);
1871     break;
1872   case ImportAction::Failure:
1873     assert(TheModuleLoader.HadFatalFailure &&
1874            "This should be an early exit only to a fatal error");
1875     TheModuleLoader.HadFatalFailure = true;
1876     IncludeTok.setKind(tok::eof);
1877     CurLexer->cutOffLexing();
1878     return;
1879   }
1880 }
1881 
1882 Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
1883     ConstSearchDirIterator *CurDir, StringRef &Filename,
1884     SourceLocation FilenameLoc, CharSourceRange FilenameRange,
1885     const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
1886     bool &IsMapped, ConstSearchDirIterator LookupFrom,
1887     const FileEntry *LookupFromFile, StringRef &LookupFilename,
1888     SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
1889     ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
1890   Optional<FileEntryRef> File = LookupFile(
1891       FilenameLoc, LookupFilename,
1892       isAngled, LookupFrom, LookupFromFile, CurDir,
1893       Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1894       &SuggestedModule, &IsMapped, &IsFrameworkFound);
1895   if (File)
1896     return File;
1897 
1898   if (SuppressIncludeNotFoundError)
1899     return None;
1900 
1901   // If the file could not be located and it was included via angle
1902   // brackets, we can attempt a lookup as though it were a quoted path to
1903   // provide the user with a possible fixit.
1904   if (isAngled) {
1905     Optional<FileEntryRef> File = LookupFile(
1906         FilenameLoc, LookupFilename,
1907         false, LookupFrom, LookupFromFile, CurDir,
1908         Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1909         &SuggestedModule, &IsMapped,
1910         /*IsFrameworkFound=*/nullptr);
1911     if (File) {
1912       Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
1913           << Filename << IsImportDecl
1914           << FixItHint::CreateReplacement(FilenameRange,
1915                                           "\"" + Filename.str() + "\"");
1916       return File;
1917     }
1918   }
1919 
1920   // Check for likely typos due to leading or trailing non-isAlphanumeric
1921   // characters
1922   StringRef OriginalFilename = Filename;
1923   if (LangOpts.SpellChecking) {
1924     // A heuristic to correct a typo file name by removing leading and
1925     // trailing non-isAlphanumeric characters.
1926     auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1927       Filename = Filename.drop_until(isAlphanumeric);
1928       while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1929         Filename = Filename.drop_back();
1930       }
1931       return Filename;
1932     };
1933     StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
1934     StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename);
1935 
1936     Optional<FileEntryRef> File = LookupFile(
1937         FilenameLoc, TypoCorrectionLookupName, isAngled, LookupFrom, LookupFromFile,
1938         CurDir, Callbacks ? &SearchPath : nullptr,
1939         Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1940         /*IsFrameworkFound=*/nullptr);
1941     if (File) {
1942       auto Hint =
1943           isAngled ? FixItHint::CreateReplacement(
1944                          FilenameRange, "<" + TypoCorrectionName.str() + ">")
1945                    : FixItHint::CreateReplacement(
1946                          FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
1947       Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
1948           << OriginalFilename << TypoCorrectionName << Hint;
1949       // We found the file, so set the Filename to the name after typo
1950       // correction.
1951       Filename = TypoCorrectionName;
1952       LookupFilename = TypoCorrectionLookupName;
1953       return File;
1954     }
1955   }
1956 
1957   // If the file is still not found, just go with the vanilla diagnostic
1958   assert(!File.hasValue() && "expected missing file");
1959   Diag(FilenameTok, diag::err_pp_file_not_found)
1960       << OriginalFilename << FilenameRange;
1961   if (IsFrameworkFound) {
1962     size_t SlashPos = OriginalFilename.find('/');
1963     assert(SlashPos != StringRef::npos &&
1964            "Include with framework name should have '/' in the filename");
1965     StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
1966     FrameworkCacheEntry &CacheEntry =
1967         HeaderInfo.LookupFrameworkCache(FrameworkName);
1968     assert(CacheEntry.Directory && "Found framework should be in cache");
1969     Diag(FilenameTok, diag::note_pp_framework_without_header)
1970         << OriginalFilename.substr(SlashPos + 1) << FrameworkName
1971         << CacheEntry.Directory->getName();
1972   }
1973 
1974   return None;
1975 }
1976 
1977 /// Handle either a #include-like directive or an import declaration that names
1978 /// a header file.
1979 ///
1980 /// \param HashLoc The location of the '#' token for an include, or
1981 ///        SourceLocation() for an import declaration.
1982 /// \param IncludeTok The include / include_next / import token.
1983 /// \param FilenameTok The header-name token.
1984 /// \param EndLoc The location at which any imported macros become visible.
1985 /// \param LookupFrom For #include_next, the starting directory for the
1986 ///        directory lookup.
1987 /// \param LookupFromFile For #include_next, the starting file for the directory
1988 ///        lookup.
1989 Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
1990     SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
1991     SourceLocation EndLoc, ConstSearchDirIterator LookupFrom,
1992     const FileEntry *LookupFromFile) {
1993   SmallString<128> FilenameBuffer;
1994   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
1995   SourceLocation CharEnd = FilenameTok.getEndLoc();
1996 
1997   CharSourceRange FilenameRange
1998     = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
1999   StringRef OriginalFilename = Filename;
2000   bool isAngled =
2001     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
2002 
2003   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
2004   // error.
2005   if (Filename.empty())
2006     return {ImportAction::None};
2007 
2008   bool IsImportDecl = HashLoc.isInvalid();
2009   SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
2010 
2011   // Complain about attempts to #include files in an audit pragma.
2012   if (PragmaARCCFCodeAuditedInfo.second.isValid()) {
2013     Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
2014     Diag(PragmaARCCFCodeAuditedInfo.second, diag::note_pragma_entered_here);
2015 
2016     // Immediately leave the pragma.
2017     PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
2018   }
2019 
2020   // Complain about attempts to #include files in an assume-nonnull pragma.
2021   if (PragmaAssumeNonNullLoc.isValid()) {
2022     Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
2023     Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
2024 
2025     // Immediately leave the pragma.
2026     PragmaAssumeNonNullLoc = SourceLocation();
2027   }
2028 
2029   if (HeaderInfo.HasIncludeAliasMap()) {
2030     // Map the filename with the brackets still attached.  If the name doesn't
2031     // map to anything, fall back on the filename we've already gotten the
2032     // spelling for.
2033     StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
2034     if (!NewName.empty())
2035       Filename = NewName;
2036   }
2037 
2038   // Search include directories.
2039   bool IsMapped = false;
2040   bool IsFrameworkFound = false;
2041   ConstSearchDirIterator CurDir = nullptr;
2042   SmallString<1024> SearchPath;
2043   SmallString<1024> RelativePath;
2044   // We get the raw path only if we have 'Callbacks' to which we later pass
2045   // the path.
2046   ModuleMap::KnownHeader SuggestedModule;
2047   SourceLocation FilenameLoc = FilenameTok.getLocation();
2048   StringRef LookupFilename = Filename;
2049 
2050   // Normalize slashes when compiling with -fms-extensions on non-Windows. This
2051   // is unnecessary on Windows since the filesystem there handles backslashes.
2052   SmallString<128> NormalizedPath;
2053   llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::native;
2054   if (is_style_posix(BackslashStyle) && LangOpts.MicrosoftExt) {
2055     NormalizedPath = Filename.str();
2056     llvm::sys::path::native(NormalizedPath);
2057     LookupFilename = NormalizedPath;
2058     BackslashStyle = llvm::sys::path::Style::windows;
2059   }
2060 
2061   Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
2062       &CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
2063       IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
2064       LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
2065 
2066   if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
2067     if (File && isPCHThroughHeader(&File->getFileEntry()))
2068       SkippingUntilPCHThroughHeader = false;
2069     return {ImportAction::None};
2070   }
2071 
2072   // Should we enter the source file? Set to Skip if either the source file is
2073   // known to have no effect beyond its effect on module visibility -- that is,
2074   // if it's got an include guard that is already defined, set to Import if it
2075   // is a modular header we've already built and should import.
2076   enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
2077 
2078   if (PPOpts->SingleFileParseMode)
2079     Action = IncludeLimitReached;
2080 
2081   // If we've reached the max allowed include depth, it is usually due to an
2082   // include cycle. Don't enter already processed files again as it can lead to
2083   // reaching the max allowed include depth again.
2084   if (Action == Enter && HasReachedMaxIncludeDepth && File &&
2085       alreadyIncluded(*File))
2086     Action = IncludeLimitReached;
2087 
2088   // Determine whether we should try to import the module for this #include, if
2089   // there is one. Don't do so if precompiled module support is disabled or we
2090   // are processing this module textually (because we're building the module).
2091   if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
2092       !isForModuleBuilding(SuggestedModule.getModule(),
2093                            getLangOpts().CurrentModule,
2094                            getLangOpts().ModuleName)) {
2095     // If this include corresponds to a module but that module is
2096     // unavailable, diagnose the situation and bail out.
2097     // FIXME: Remove this; loadModule does the same check (but produces
2098     // slightly worse diagnostics).
2099     if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
2100                                SuggestedModule.getModule())) {
2101       Diag(FilenameTok.getLocation(),
2102            diag::note_implicit_top_level_module_import_here)
2103           << SuggestedModule.getModule()->getTopLevelModuleName();
2104       return {ImportAction::None};
2105     }
2106 
2107     // Compute the module access path corresponding to this module.
2108     // FIXME: Should we have a second loadModule() overload to avoid this
2109     // extra lookup step?
2110     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2111     for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
2112       Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
2113                                     FilenameTok.getLocation()));
2114     std::reverse(Path.begin(), Path.end());
2115 
2116     // Warn that we're replacing the include/import with a module import.
2117     if (!IsImportDecl)
2118       diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
2119 
2120     // Load the module to import its macros. We'll make the declarations
2121     // visible when the parser gets here.
2122     // FIXME: Pass SuggestedModule in here rather than converting it to a path
2123     // and making the module loader convert it back again.
2124     ModuleLoadResult Imported = TheModuleLoader.loadModule(
2125         IncludeTok.getLocation(), Path, Module::Hidden,
2126         /*IsInclusionDirective=*/true);
2127     assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
2128            "the imported module is different than the suggested one");
2129 
2130     if (Imported) {
2131       Action = Import;
2132     } else if (Imported.isMissingExpected()) {
2133       // We failed to find a submodule that we assumed would exist (because it
2134       // was in the directory of an umbrella header, for instance), but no
2135       // actual module containing it exists (because the umbrella header is
2136       // incomplete).  Treat this as a textual inclusion.
2137       SuggestedModule = ModuleMap::KnownHeader();
2138     } else if (Imported.isConfigMismatch()) {
2139       // On a configuration mismatch, enter the header textually. We still know
2140       // that it's part of the corresponding module.
2141     } else {
2142       // We hit an error processing the import. Bail out.
2143       if (hadModuleLoaderFatalFailure()) {
2144         // With a fatal failure in the module loader, we abort parsing.
2145         Token &Result = IncludeTok;
2146         assert(CurLexer && "#include but no current lexer set!");
2147         Result.startToken();
2148         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
2149         CurLexer->cutOffLexing();
2150       }
2151       return {ImportAction::None};
2152     }
2153   }
2154 
2155   // The #included file will be considered to be a system header if either it is
2156   // in a system include directory, or if the #includer is a system include
2157   // header.
2158   SrcMgr::CharacteristicKind FileCharacter =
2159       SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
2160   if (File)
2161     FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
2162                              FileCharacter);
2163 
2164   // If this is a '#import' or an import-declaration, don't re-enter the file.
2165   //
2166   // FIXME: If we have a suggested module for a '#include', and we've already
2167   // visited this file, don't bother entering it again. We know it has no
2168   // further effect.
2169   bool EnterOnce =
2170       IsImportDecl ||
2171       IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
2172 
2173   bool IsFirstIncludeOfFile = false;
2174 
2175   // Ask HeaderInfo if we should enter this #include file.  If not, #including
2176   // this file will have no effect.
2177   if (Action == Enter && File &&
2178       !HeaderInfo.ShouldEnterIncludeFile(
2179           *this, &File->getFileEntry(), EnterOnce, getLangOpts().Modules,
2180           SuggestedModule.getModule(), IsFirstIncludeOfFile)) {
2181     // Even if we've already preprocessed this header once and know that we
2182     // don't need to see its contents again, we still need to import it if it's
2183     // modular because we might not have imported it from this submodule before.
2184     //
2185     // FIXME: We don't do this when compiling a PCH because the AST
2186     // serialization layer can't cope with it. This means we get local
2187     // submodule visibility semantics wrong in that case.
2188     Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
2189   }
2190 
2191   // Check for circular inclusion of the main file.
2192   // We can't generate a consistent preamble with regard to the conditional
2193   // stack if the main file is included again as due to the preamble bounds
2194   // some directives (e.g. #endif of a header guard) will never be seen.
2195   // Since this will lead to confusing errors, avoid the inclusion.
2196   if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
2197       SourceMgr.isMainFile(File->getFileEntry())) {
2198     Diag(FilenameTok.getLocation(),
2199          diag::err_pp_including_mainfile_in_preamble);
2200     return {ImportAction::None};
2201   }
2202 
2203   if (Callbacks && !IsImportDecl) {
2204     // Notify the callback object that we've seen an inclusion directive.
2205     // FIXME: Use a different callback for a pp-import?
2206     Callbacks->InclusionDirective(HashLoc, IncludeTok, LookupFilename, isAngled,
2207                                   FilenameRange, File, SearchPath, RelativePath,
2208                                   Action == Import ? SuggestedModule.getModule()
2209                                                    : nullptr,
2210                                   FileCharacter);
2211     if (Action == Skip && File)
2212       Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
2213   }
2214 
2215   if (!File)
2216     return {ImportAction::None};
2217 
2218   // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2219   // module corresponding to the named header.
2220   if (IsImportDecl && !SuggestedModule) {
2221     Diag(FilenameTok, diag::err_header_import_not_header_unit)
2222       << OriginalFilename << File->getName();
2223     return {ImportAction::None};
2224   }
2225 
2226   // Issue a diagnostic if the name of the file on disk has a different case
2227   // than the one we're about to open.
2228   const bool CheckIncludePathPortability =
2229       !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
2230 
2231   if (CheckIncludePathPortability) {
2232     StringRef Name = LookupFilename;
2233     StringRef NameWithoriginalSlashes = Filename;
2234 #if defined(_WIN32)
2235     // Skip UNC prefix if present. (tryGetRealPathName() always
2236     // returns a path with the prefix skipped.)
2237     bool NameWasUNC = Name.consume_front("\\\\?\\");
2238     NameWithoriginalSlashes.consume_front("\\\\?\\");
2239 #endif
2240     StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
2241     SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2242                                           llvm::sys::path::end(Name));
2243 #if defined(_WIN32)
2244     // -Wnonportable-include-path is designed to diagnose includes using
2245     // case even on systems with a case-insensitive file system.
2246     // On Windows, RealPathName always starts with an upper-case drive
2247     // letter for absolute paths, but Name might start with either
2248     // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell.
2249     // ("foo" will always have on-disk case, no matter which case was
2250     // used in the cd command). To not emit this warning solely for
2251     // the drive letter, whose case is dependent on if `cd` is used
2252     // with upper- or lower-case drive letters, always consider the
2253     // given drive letter case as correct for the purpose of this warning.
2254     SmallString<128> FixedDriveRealPath;
2255     if (llvm::sys::path::is_absolute(Name) &&
2256         llvm::sys::path::is_absolute(RealPathName) &&
2257         toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
2258         isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
2259       assert(Components.size() >= 3 && "should have drive, backslash, name");
2260       assert(Components[0].size() == 2 && "should start with drive");
2261       assert(Components[0][1] == ':' && "should have colon");
2262       FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
2263       RealPathName = FixedDriveRealPath;
2264     }
2265 #endif
2266 
2267     if (trySimplifyPath(Components, RealPathName)) {
2268       SmallString<128> Path;
2269       Path.reserve(Name.size()+2);
2270       Path.push_back(isAngled ? '<' : '"');
2271 
2272       const auto IsSep = [BackslashStyle](char c) {
2273         return llvm::sys::path::is_separator(c, BackslashStyle);
2274       };
2275 
2276       for (auto Component : Components) {
2277         // On POSIX, Components will contain a single '/' as first element
2278         // exactly if Name is an absolute path.
2279         // On Windows, it will contain "C:" followed by '\' for absolute paths.
2280         // The drive letter is optional for absolute paths on Windows, but
2281         // clang currently cannot process absolute paths in #include lines that
2282         // don't have a drive.
2283         // If the first entry in Components is a directory separator,
2284         // then the code at the bottom of this loop that keeps the original
2285         // directory separator style copies it. If the second entry is
2286         // a directory separator (the C:\ case), then that separator already
2287         // got copied when the C: was processed and we want to skip that entry.
2288         if (!(Component.size() == 1 && IsSep(Component[0])))
2289           Path.append(Component);
2290         else if (!Path.empty())
2291           continue;
2292 
2293         // Append the separator(s) the user used, or the close quote
2294         if (Path.size() > NameWithoriginalSlashes.size()) {
2295           Path.push_back(isAngled ? '>' : '"');
2296           continue;
2297         }
2298         assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
2299         do
2300           Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
2301         while (Path.size() <= NameWithoriginalSlashes.size() &&
2302                IsSep(NameWithoriginalSlashes[Path.size()-1]));
2303       }
2304 
2305 #if defined(_WIN32)
2306       // Restore UNC prefix if it was there.
2307       if (NameWasUNC)
2308         Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
2309 #endif
2310 
2311       // For user files and known standard headers, issue a diagnostic.
2312       // For other system headers, don't. They can be controlled separately.
2313       auto DiagId =
2314           (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
2315               ? diag::pp_nonportable_path
2316               : diag::pp_nonportable_system_path;
2317       Diag(FilenameTok, DiagId) << Path <<
2318         FixItHint::CreateReplacement(FilenameRange, Path);
2319     }
2320   }
2321 
2322   switch (Action) {
2323   case Skip:
2324     // If we don't need to enter the file, stop now.
2325     if (Module *M = SuggestedModule.getModule())
2326       return {ImportAction::SkippedModuleImport, M};
2327     return {ImportAction::None};
2328 
2329   case IncludeLimitReached:
2330     // If we reached our include limit and don't want to enter any more files,
2331     // don't go any further.
2332     return {ImportAction::None};
2333 
2334   case Import: {
2335     // If this is a module import, make it visible if needed.
2336     Module *M = SuggestedModule.getModule();
2337     assert(M && "no module to import");
2338 
2339     makeModuleVisible(M, EndLoc);
2340 
2341     if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
2342         tok::pp___include_macros)
2343       return {ImportAction::None};
2344 
2345     return {ImportAction::ModuleImport, M};
2346   }
2347 
2348   case Enter:
2349     break;
2350   }
2351 
2352   // Check that we don't have infinite #include recursion.
2353   if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2354     Diag(FilenameTok, diag::err_pp_include_too_deep);
2355     HasReachedMaxIncludeDepth = true;
2356     return {ImportAction::None};
2357   }
2358 
2359   // Look up the file, create a File ID for it.
2360   SourceLocation IncludePos = FilenameTok.getLocation();
2361   // If the filename string was the result of macro expansions, set the include
2362   // position on the file where it will be included and after the expansions.
2363   if (IncludePos.isMacroID())
2364     IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
2365   FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
2366   if (!FID.isValid()) {
2367     TheModuleLoader.HadFatalFailure = true;
2368     return ImportAction::Failure;
2369   }
2370 
2371   // If all is good, enter the new file!
2372   if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation(),
2373                       IsFirstIncludeOfFile))
2374     return {ImportAction::None};
2375 
2376   // Determine if we're switching to building a new submodule, and which one.
2377   if (auto *M = SuggestedModule.getModule()) {
2378     if (M->getTopLevelModule()->ShadowingModule) {
2379       // We are building a submodule that belongs to a shadowed module. This
2380       // means we find header files in the shadowed module.
2381       Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2382         << M->getFullModuleName();
2383       Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2384            diag::note_previous_definition);
2385       return {ImportAction::None};
2386     }
2387     // When building a pch, -fmodule-name tells the compiler to textually
2388     // include headers in the specified module. We are not building the
2389     // specified module.
2390     //
2391     // FIXME: This is the wrong way to handle this. We should produce a PCH
2392     // that behaves the same as the header would behave in a compilation using
2393     // that PCH, which means we should enter the submodule. We need to teach
2394     // the AST serialization layer to deal with the resulting AST.
2395     if (getLangOpts().CompilingPCH &&
2396         isForModuleBuilding(M, getLangOpts().CurrentModule,
2397                             getLangOpts().ModuleName))
2398       return {ImportAction::None};
2399 
2400     assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2401     CurLexerSubmodule = M;
2402 
2403     // Let the macro handling code know that any future macros are within
2404     // the new submodule.
2405     EnterSubmodule(M, EndLoc, /*ForPragma*/false);
2406 
2407     // Let the parser know that any future declarations are within the new
2408     // submodule.
2409     // FIXME: There's no point doing this if we're handling a #__include_macros
2410     // directive.
2411     return {ImportAction::ModuleBegin, M};
2412   }
2413 
2414   assert(!IsImportDecl && "failed to diagnose missing module for import decl");
2415   return {ImportAction::None};
2416 }
2417 
2418 /// HandleIncludeNextDirective - Implements \#include_next.
2419 ///
2420 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2421                                               Token &IncludeNextTok) {
2422   Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
2423 
2424   ConstSearchDirIterator Lookup = nullptr;
2425   const FileEntry *LookupFromFile;
2426   std::tie(Lookup, LookupFromFile) = getIncludeNextStart(IncludeNextTok);
2427 
2428   return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2429                                 LookupFromFile);
2430 }
2431 
2432 /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
2433 void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2434   // The Microsoft #import directive takes a type library and generates header
2435   // files from it, and includes those.  This is beyond the scope of what clang
2436   // does, so we ignore it and error out.  However, #import can optionally have
2437   // trailing attributes that span multiple lines.  We're going to eat those
2438   // so we can continue processing from there.
2439   Diag(Tok, diag::err_pp_import_directive_ms );
2440 
2441   // Read tokens until we get to the end of the directive.  Note that the
2442   // directive can be split over multiple lines using the backslash character.
2443   DiscardUntilEndOfDirective();
2444 }
2445 
2446 /// HandleImportDirective - Implements \#import.
2447 ///
2448 void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2449                                          Token &ImportTok) {
2450   if (!LangOpts.ObjC) {  // #import is standard for ObjC.
2451     if (LangOpts.MSVCCompat)
2452       return HandleMicrosoftImportDirective(ImportTok);
2453     Diag(ImportTok, diag::ext_pp_import_directive);
2454   }
2455   return HandleIncludeDirective(HashLoc, ImportTok);
2456 }
2457 
2458 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2459 /// pseudo directive in the predefines buffer.  This handles it by sucking all
2460 /// tokens through the preprocessor and discarding them (only keeping the side
2461 /// effects on the preprocessor).
2462 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2463                                                 Token &IncludeMacrosTok) {
2464   // This directive should only occur in the predefines buffer.  If not, emit an
2465   // error and reject it.
2466   SourceLocation Loc = IncludeMacrosTok.getLocation();
2467   if (SourceMgr.getBufferName(Loc) != "<built-in>") {
2468     Diag(IncludeMacrosTok.getLocation(),
2469          diag::pp_include_macros_out_of_predefines);
2470     DiscardUntilEndOfDirective();
2471     return;
2472   }
2473 
2474   // Treat this as a normal #include for checking purposes.  If this is
2475   // successful, it will push a new lexer onto the include stack.
2476   HandleIncludeDirective(HashLoc, IncludeMacrosTok);
2477 
2478   Token TmpTok;
2479   do {
2480     Lex(TmpTok);
2481     assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2482   } while (TmpTok.isNot(tok::hashhash));
2483 }
2484 
2485 //===----------------------------------------------------------------------===//
2486 // Preprocessor Macro Directive Handling.
2487 //===----------------------------------------------------------------------===//
2488 
2489 /// ReadMacroParameterList - The ( starting a parameter list of a macro
2490 /// definition has just been read.  Lex the rest of the parameters and the
2491 /// closing ), updating MI with what we learn.  Return true if an error occurs
2492 /// parsing the param list.
2493 bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
2494   SmallVector<IdentifierInfo*, 32> Parameters;
2495 
2496   while (true) {
2497     LexUnexpandedToken(Tok);
2498     switch (Tok.getKind()) {
2499     case tok::r_paren:
2500       // Found the end of the parameter list.
2501       if (Parameters.empty())  // #define FOO()
2502         return false;
2503       // Otherwise we have #define FOO(A,)
2504       Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2505       return true;
2506     case tok::ellipsis:  // #define X(... -> C99 varargs
2507       if (!LangOpts.C99)
2508         Diag(Tok, LangOpts.CPlusPlus11 ?
2509              diag::warn_cxx98_compat_variadic_macro :
2510              diag::ext_variadic_macro);
2511 
2512       // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2513       if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) {
2514         Diag(Tok, diag::ext_pp_opencl_variadic_macros);
2515       }
2516 
2517       // Lex the token after the identifier.
2518       LexUnexpandedToken(Tok);
2519       if (Tok.isNot(tok::r_paren)) {
2520         Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2521         return true;
2522       }
2523       // Add the __VA_ARGS__ identifier as a parameter.
2524       Parameters.push_back(Ident__VA_ARGS__);
2525       MI->setIsC99Varargs();
2526       MI->setParameterList(Parameters, BP);
2527       return false;
2528     case tok::eod:  // #define X(
2529       Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2530       return true;
2531     default:
2532       // Handle keywords and identifiers here to accept things like
2533       // #define Foo(for) for.
2534       IdentifierInfo *II = Tok.getIdentifierInfo();
2535       if (!II) {
2536         // #define X(1
2537         Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2538         return true;
2539       }
2540 
2541       // If this is already used as a parameter, it is used multiple times (e.g.
2542       // #define X(A,A.
2543       if (llvm::is_contained(Parameters, II)) { // C99 6.10.3p6
2544         Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
2545         return true;
2546       }
2547 
2548       // Add the parameter to the macro info.
2549       Parameters.push_back(II);
2550 
2551       // Lex the token after the identifier.
2552       LexUnexpandedToken(Tok);
2553 
2554       switch (Tok.getKind()) {
2555       default:          // #define X(A B
2556         Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2557         return true;
2558       case tok::r_paren: // #define X(A)
2559         MI->setParameterList(Parameters, BP);
2560         return false;
2561       case tok::comma:  // #define X(A,
2562         break;
2563       case tok::ellipsis:  // #define X(A... -> GCC extension
2564         // Diagnose extension.
2565         Diag(Tok, diag::ext_named_variadic_macro);
2566 
2567         // Lex the token after the identifier.
2568         LexUnexpandedToken(Tok);
2569         if (Tok.isNot(tok::r_paren)) {
2570           Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2571           return true;
2572         }
2573 
2574         MI->setIsGNUVarargs();
2575         MI->setParameterList(Parameters, BP);
2576         return false;
2577       }
2578     }
2579   }
2580 }
2581 
2582 static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2583                                    const LangOptions &LOptions) {
2584   if (MI->getNumTokens() == 1) {
2585     const Token &Value = MI->getReplacementToken(0);
2586 
2587     // Macro that is identity, like '#define inline inline' is a valid pattern.
2588     if (MacroName.getKind() == Value.getKind())
2589       return true;
2590 
2591     // Macro that maps a keyword to the same keyword decorated with leading/
2592     // trailing underscores is a valid pattern:
2593     //    #define inline __inline
2594     //    #define inline __inline__
2595     //    #define inline _inline (in MS compatibility mode)
2596     StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2597     if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2598       if (!II->isKeyword(LOptions))
2599         return false;
2600       StringRef ValueText = II->getName();
2601       StringRef TrimmedValue = ValueText;
2602       if (!ValueText.startswith("__")) {
2603         if (ValueText.startswith("_"))
2604           TrimmedValue = TrimmedValue.drop_front(1);
2605         else
2606           return false;
2607       } else {
2608         TrimmedValue = TrimmedValue.drop_front(2);
2609         if (TrimmedValue.endswith("__"))
2610           TrimmedValue = TrimmedValue.drop_back(2);
2611       }
2612       return TrimmedValue.equals(MacroText);
2613     } else {
2614       return false;
2615     }
2616   }
2617 
2618   // #define inline
2619   return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2620                            tok::kw_const) &&
2621          MI->getNumTokens() == 0;
2622 }
2623 
2624 // ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2625 // entire line) of the macro's tokens and adds them to MacroInfo, and while
2626 // doing so performs certain validity checks including (but not limited to):
2627 //   - # (stringization) is followed by a macro parameter
2628 //
2629 //  Returns a nullptr if an invalid sequence of tokens is encountered or returns
2630 //  a pointer to a MacroInfo object.
2631 
2632 MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2633     const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
2634 
2635   Token LastTok = MacroNameTok;
2636   // Create the new macro.
2637   MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
2638 
2639   Token Tok;
2640   LexUnexpandedToken(Tok);
2641 
2642   // Ensure we consume the rest of the macro body if errors occur.
2643   auto _ = llvm::make_scope_exit([&]() {
2644     // The flag indicates if we are still waiting for 'eod'.
2645     if (CurLexer->ParsingPreprocessorDirective)
2646       DiscardUntilEndOfDirective();
2647   });
2648 
2649   // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2650   // within their appropriate context.
2651   VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2652 
2653   // If this is a function-like macro definition, parse the argument list,
2654   // marking each of the identifiers as being used as macro arguments.  Also,
2655   // check other constraints on the first token of the macro body.
2656   if (Tok.is(tok::eod)) {
2657     if (ImmediatelyAfterHeaderGuard) {
2658       // Save this macro information since it may part of a header guard.
2659       CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2660                                         MacroNameTok.getLocation());
2661     }
2662     // If there is no body to this macro, we have no special handling here.
2663   } else if (Tok.hasLeadingSpace()) {
2664     // This is a normal token with leading space.  Clear the leading space
2665     // marker on the first token to get proper expansion.
2666     Tok.clearFlag(Token::LeadingSpace);
2667   } else if (Tok.is(tok::l_paren)) {
2668     // This is a function-like macro definition.  Read the argument list.
2669     MI->setIsFunctionLike();
2670     if (ReadMacroParameterList(MI, LastTok))
2671       return nullptr;
2672 
2673     // If this is a definition of an ISO C/C++ variadic function-like macro (not
2674     // using the GNU named varargs extension) inform our variadic scope guard
2675     // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2676     // allowed only within the definition of a variadic macro.
2677 
2678     if (MI->isC99Varargs()) {
2679       VariadicMacroScopeGuard.enterScope();
2680     }
2681 
2682     // Read the first token after the arg list for down below.
2683     LexUnexpandedToken(Tok);
2684   } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
2685     // C99 requires whitespace between the macro definition and the body.  Emit
2686     // a diagnostic for something like "#define X+".
2687     Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2688   } else {
2689     // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2690     // first character of a replacement list is not a character required by
2691     // subclause 5.2.1, then there shall be white-space separation between the
2692     // identifier and the replacement list.".  5.2.1 lists this set:
2693     //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2694     // is irrelevant here.
2695     bool isInvalid = false;
2696     if (Tok.is(tok::at)) // @ is not in the list above.
2697       isInvalid = true;
2698     else if (Tok.is(tok::unknown)) {
2699       // If we have an unknown token, it is something strange like "`".  Since
2700       // all of valid characters would have lexed into a single character
2701       // token of some sort, we know this is not a valid case.
2702       isInvalid = true;
2703     }
2704     if (isInvalid)
2705       Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2706     else
2707       Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
2708   }
2709 
2710   if (!Tok.is(tok::eod))
2711     LastTok = Tok;
2712 
2713   SmallVector<Token, 16> Tokens;
2714 
2715   // Read the rest of the macro body.
2716   if (MI->isObjectLike()) {
2717     // Object-like macros are very simple, just read their body.
2718     while (Tok.isNot(tok::eod)) {
2719       LastTok = Tok;
2720       Tokens.push_back(Tok);
2721       // Get the next token of the macro.
2722       LexUnexpandedToken(Tok);
2723     }
2724   } else {
2725     // Otherwise, read the body of a function-like macro.  While we are at it,
2726     // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2727     // parameters in function-like macro expansions.
2728 
2729     VAOptDefinitionContext VAOCtx(*this);
2730 
2731     while (Tok.isNot(tok::eod)) {
2732       LastTok = Tok;
2733 
2734       if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
2735         Tokens.push_back(Tok);
2736 
2737         if (VAOCtx.isVAOptToken(Tok)) {
2738           // If we're already within a VAOPT, emit an error.
2739           if (VAOCtx.isInVAOpt()) {
2740             Diag(Tok, diag::err_pp_vaopt_nested_use);
2741             return nullptr;
2742           }
2743           // Ensure VAOPT is followed by a '(' .
2744           LexUnexpandedToken(Tok);
2745           if (Tok.isNot(tok::l_paren)) {
2746             Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2747             return nullptr;
2748           }
2749           Tokens.push_back(Tok);
2750           VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2751           LexUnexpandedToken(Tok);
2752           if (Tok.is(tok::hashhash)) {
2753             Diag(Tok, diag::err_vaopt_paste_at_start);
2754             return nullptr;
2755           }
2756           continue;
2757         } else if (VAOCtx.isInVAOpt()) {
2758           if (Tok.is(tok::r_paren)) {
2759             if (VAOCtx.sawClosingParen()) {
2760               assert(Tokens.size() >= 3 &&
2761                      "Must have seen at least __VA_OPT__( "
2762                      "and a subsequent tok::r_paren");
2763               if (Tokens[Tokens.size() - 2].is(tok::hashhash)) {
2764                 Diag(Tok, diag::err_vaopt_paste_at_end);
2765                 return nullptr;
2766               }
2767             }
2768           } else if (Tok.is(tok::l_paren)) {
2769             VAOCtx.sawOpeningParen(Tok.getLocation());
2770           }
2771         }
2772         // Get the next token of the macro.
2773         LexUnexpandedToken(Tok);
2774         continue;
2775       }
2776 
2777       // If we're in -traditional mode, then we should ignore stringification
2778       // and token pasting. Mark the tokens as unknown so as not to confuse
2779       // things.
2780       if (getLangOpts().TraditionalCPP) {
2781         Tok.setKind(tok::unknown);
2782         Tokens.push_back(Tok);
2783 
2784         // Get the next token of the macro.
2785         LexUnexpandedToken(Tok);
2786         continue;
2787       }
2788 
2789       if (Tok.is(tok::hashhash)) {
2790         // If we see token pasting, check if it looks like the gcc comma
2791         // pasting extension.  We'll use this information to suppress
2792         // diagnostics later on.
2793 
2794         // Get the next token of the macro.
2795         LexUnexpandedToken(Tok);
2796 
2797         if (Tok.is(tok::eod)) {
2798           Tokens.push_back(LastTok);
2799           break;
2800         }
2801 
2802         if (!Tokens.empty() && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2803             Tokens[Tokens.size() - 1].is(tok::comma))
2804           MI->setHasCommaPasting();
2805 
2806         // Things look ok, add the '##' token to the macro.
2807         Tokens.push_back(LastTok);
2808         continue;
2809       }
2810 
2811       // Our Token is a stringization operator.
2812       // Get the next token of the macro.
2813       LexUnexpandedToken(Tok);
2814 
2815       // Check for a valid macro arg identifier or __VA_OPT__.
2816       if (!VAOCtx.isVAOptToken(Tok) &&
2817           (Tok.getIdentifierInfo() == nullptr ||
2818            MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
2819 
2820         // If this is assembler-with-cpp mode, we accept random gibberish after
2821         // the '#' because '#' is often a comment character.  However, change
2822         // the kind of the token to tok::unknown so that the preprocessor isn't
2823         // confused.
2824         if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
2825           LastTok.setKind(tok::unknown);
2826           Tokens.push_back(LastTok);
2827           continue;
2828         } else {
2829           Diag(Tok, diag::err_pp_stringize_not_parameter)
2830             << LastTok.is(tok::hashat);
2831           return nullptr;
2832         }
2833       }
2834 
2835       // Things look ok, add the '#' and param name tokens to the macro.
2836       Tokens.push_back(LastTok);
2837 
2838       // If the token following '#' is VAOPT, let the next iteration handle it
2839       // and check it for correctness, otherwise add the token and prime the
2840       // loop with the next one.
2841       if (!VAOCtx.isVAOptToken(Tok)) {
2842         Tokens.push_back(Tok);
2843         LastTok = Tok;
2844 
2845         // Get the next token of the macro.
2846         LexUnexpandedToken(Tok);
2847       }
2848     }
2849     if (VAOCtx.isInVAOpt()) {
2850       assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2851       Diag(Tok, diag::err_pp_expected_after)
2852         << LastTok.getKind() << tok::r_paren;
2853       Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2854       return nullptr;
2855     }
2856   }
2857   MI->setDefinitionEndLoc(LastTok.getLocation());
2858 
2859   MI->setTokens(Tokens, BP);
2860   return MI;
2861 }
2862 /// HandleDefineDirective - Implements \#define.  This consumes the entire macro
2863 /// line then lets the caller lex the next real token.
2864 void Preprocessor::HandleDefineDirective(
2865     Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2866   ++NumDefined;
2867 
2868   Token MacroNameTok;
2869   bool MacroShadowsKeyword;
2870   ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2871 
2872   // Error reading macro name?  If so, diagnostic already issued.
2873   if (MacroNameTok.is(tok::eod))
2874     return;
2875 
2876   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
2877   // Issue a final pragma warning if we're defining a macro that was has been
2878   // undefined and is being redefined.
2879   if (!II->hasMacroDefinition() && II->hadMacroDefinition() && II->isFinal())
2880     emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
2881 
2882   // If we are supposed to keep comments in #defines, reenable comment saving
2883   // mode.
2884   if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2885 
2886   MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2887       MacroNameTok, ImmediatelyAfterHeaderGuard);
2888 
2889   if (!MI) return;
2890 
2891   if (MacroShadowsKeyword &&
2892       !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2893     Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2894   }
2895   // Check that there is no paste (##) operator at the beginning or end of the
2896   // replacement list.
2897   unsigned NumTokens = MI->getNumTokens();
2898   if (NumTokens != 0) {
2899     if (MI->getReplacementToken(0).is(tok::hashhash)) {
2900       Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2901       return;
2902     }
2903     if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2904       Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2905       return;
2906     }
2907   }
2908 
2909   // When skipping just warn about macros that do not match.
2910   if (SkippingUntilPCHThroughHeader) {
2911     const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2912     if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2913                              /*Syntactic=*/LangOpts.MicrosoftExt))
2914       Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2915           << MacroNameTok.getIdentifierInfo();
2916     // Issue the diagnostic but allow the change if msvc extensions are enabled
2917     if (!LangOpts.MicrosoftExt)
2918       return;
2919   }
2920 
2921   // Finally, if this identifier already had a macro defined for it, verify that
2922   // the macro bodies are identical, and issue diagnostics if they are not.
2923   if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
2924     // Final macros are hard-mode: they always warn. Even if the bodies are
2925     // identical. Even if they are in system headers. Even if they are things we
2926     // would silently allow in the past.
2927     if (MacroNameTok.getIdentifierInfo()->isFinal())
2928       emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
2929 
2930     // In Objective-C, ignore attempts to directly redefine the builtin
2931     // definitions of the ownership qualifiers.  It's still possible to
2932     // #undef them.
2933     auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2934       return II->isStr("__strong") ||
2935              II->isStr("__weak") ||
2936              II->isStr("__unsafe_unretained") ||
2937              II->isStr("__autoreleasing");
2938     };
2939    if (getLangOpts().ObjC &&
2940         SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2941           == getPredefinesFileID() &&
2942         isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2943       // Warn if it changes the tokens.
2944       if ((!getDiagnostics().getSuppressSystemWarnings() ||
2945            !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2946           !MI->isIdenticalTo(*OtherMI, *this,
2947                              /*Syntactic=*/LangOpts.MicrosoftExt)) {
2948         Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2949       }
2950       assert(!OtherMI->isWarnIfUnused());
2951       return;
2952     }
2953 
2954     // It is very common for system headers to have tons of macro redefinitions
2955     // and for warnings to be disabled in system headers.  If this is the case,
2956     // then don't bother calling MacroInfo::isIdenticalTo.
2957     if (!getDiagnostics().getSuppressSystemWarnings() ||
2958         !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
2959 
2960       if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
2961         Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2962 
2963       // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2964       // C++ [cpp.predefined]p4, but allow it as an extension.
2965       if (OtherMI->isBuiltinMacro())
2966         Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
2967       // Macros must be identical.  This means all tokens and whitespace
2968       // separation must be the same.  C99 6.10.3p2.
2969       else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
2970                !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
2971         Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2972           << MacroNameTok.getIdentifierInfo();
2973         Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2974       }
2975     }
2976     if (OtherMI->isWarnIfUnused())
2977       WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
2978   }
2979 
2980   DefMacroDirective *MD =
2981       appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
2982 
2983   assert(!MI->isUsed());
2984   // If we need warning for not using the macro, add its location in the
2985   // warn-because-unused-macro set. If it gets used it will be removed from set.
2986   if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
2987       !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
2988       !MacroExpansionInDirectivesOverride &&
2989       getSourceManager().getFileID(MI->getDefinitionLoc()) !=
2990           getPredefinesFileID()) {
2991     MI->setIsWarnIfUnused(true);
2992     WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2993   }
2994 
2995   // If the callbacks want to know, tell them about the macro definition.
2996   if (Callbacks)
2997     Callbacks->MacroDefined(MacroNameTok, MD);
2998 
2999   // If we're in MS compatibility mode and the macro being defined is the
3000   // assert macro, implicitly add a macro definition for static_assert to work
3001   // around their broken assert.h header file in C. Only do so if there isn't
3002   // already a static_assert macro defined.
3003   if (!getLangOpts().CPlusPlus && getLangOpts().MSVCCompat &&
3004       MacroNameTok.getIdentifierInfo()->isStr("assert") &&
3005       !isMacroDefined("static_assert")) {
3006     MacroInfo *MI = AllocateMacroInfo(SourceLocation());
3007 
3008     Token Tok;
3009     Tok.startToken();
3010     Tok.setKind(tok::kw__Static_assert);
3011     Tok.setIdentifierInfo(getIdentifierInfo("_Static_assert"));
3012     MI->setTokens({Tok}, BP);
3013     (void)appendDefMacroDirective(getIdentifierInfo("static_assert"), MI);
3014   }
3015 }
3016 
3017 /// HandleUndefDirective - Implements \#undef.
3018 ///
3019 void Preprocessor::HandleUndefDirective() {
3020   ++NumUndefined;
3021 
3022   Token MacroNameTok;
3023   ReadMacroName(MacroNameTok, MU_Undef);
3024 
3025   // Error reading macro name?  If so, diagnostic already issued.
3026   if (MacroNameTok.is(tok::eod))
3027     return;
3028 
3029   // Check to see if this is the last token on the #undef line.
3030   CheckEndOfDirective("undef");
3031 
3032   // Okay, we have a valid identifier to undef.
3033   auto *II = MacroNameTok.getIdentifierInfo();
3034   auto MD = getMacroDefinition(II);
3035   UndefMacroDirective *Undef = nullptr;
3036 
3037   if (II->isFinal())
3038     emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/true);
3039 
3040   // If the macro is not defined, this is a noop undef.
3041   if (const MacroInfo *MI = MD.getMacroInfo()) {
3042     if (!MI->isUsed() && MI->isWarnIfUnused())
3043       Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
3044 
3045     if (MI->isWarnIfUnused())
3046       WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
3047 
3048     Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
3049   }
3050 
3051   // If the callbacks want to know, tell them about the macro #undef.
3052   // Note: no matter if the macro was defined or not.
3053   if (Callbacks)
3054     Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
3055 
3056   if (Undef)
3057     appendMacroDirective(II, Undef);
3058 }
3059 
3060 //===----------------------------------------------------------------------===//
3061 // Preprocessor Conditional Directive Handling.
3062 //===----------------------------------------------------------------------===//
3063 
3064 /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive.  isIfndef
3065 /// is true when this is a \#ifndef directive.  ReadAnyTokensBeforeDirective is
3066 /// true if any tokens have been returned or pp-directives activated before this
3067 /// \#ifndef has been lexed.
3068 ///
3069 void Preprocessor::HandleIfdefDirective(Token &Result,
3070                                         const Token &HashToken,
3071                                         bool isIfndef,
3072                                         bool ReadAnyTokensBeforeDirective) {
3073   ++NumIf;
3074   Token DirectiveTok = Result;
3075 
3076   Token MacroNameTok;
3077   ReadMacroName(MacroNameTok);
3078 
3079   // Error reading macro name?  If so, diagnostic already issued.
3080   if (MacroNameTok.is(tok::eod)) {
3081     // Skip code until we get to #endif.  This helps with recovery by not
3082     // emitting an error when the #endif is reached.
3083     SkipExcludedConditionalBlock(HashToken.getLocation(),
3084                                  DirectiveTok.getLocation(),
3085                                  /*Foundnonskip*/ false, /*FoundElse*/ false);
3086     return;
3087   }
3088 
3089   emitMacroExpansionWarnings(MacroNameTok);
3090 
3091   // Check to see if this is the last token on the #if[n]def line.
3092   CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
3093 
3094   IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
3095   auto MD = getMacroDefinition(MII);
3096   MacroInfo *MI = MD.getMacroInfo();
3097 
3098   if (CurPPLexer->getConditionalStackDepth() == 0) {
3099     // If the start of a top-level #ifdef and if the macro is not defined,
3100     // inform MIOpt that this might be the start of a proper include guard.
3101     // Otherwise it is some other form of unknown conditional which we can't
3102     // handle.
3103     if (!ReadAnyTokensBeforeDirective && !MI) {
3104       assert(isIfndef && "#ifdef shouldn't reach here");
3105       CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
3106     } else
3107       CurPPLexer->MIOpt.EnterTopLevelConditional();
3108   }
3109 
3110   // If there is a macro, process it.
3111   if (MI)  // Mark it used.
3112     markMacroAsUsed(MI);
3113 
3114   if (Callbacks) {
3115     if (isIfndef)
3116       Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
3117     else
3118       Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
3119   }
3120 
3121   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3122     getSourceManager().isInMainFile(DirectiveTok.getLocation());
3123 
3124   // Should we include the stuff contained by this directive?
3125   if (PPOpts->SingleFileParseMode && !MI) {
3126     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3127     // the directive blocks.
3128     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3129                                      /*wasskip*/false, /*foundnonskip*/false,
3130                                      /*foundelse*/false);
3131   } else if (!MI == isIfndef || RetainExcludedCB) {
3132     // Yes, remember that we are inside a conditional, then lex the next token.
3133     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3134                                      /*wasskip*/false, /*foundnonskip*/true,
3135                                      /*foundelse*/false);
3136   } else {
3137     // No, skip the contents of this block.
3138     SkipExcludedConditionalBlock(HashToken.getLocation(),
3139                                  DirectiveTok.getLocation(),
3140                                  /*Foundnonskip*/ false,
3141                                  /*FoundElse*/ false);
3142   }
3143 }
3144 
3145 /// HandleIfDirective - Implements the \#if directive.
3146 ///
3147 void Preprocessor::HandleIfDirective(Token &IfToken,
3148                                      const Token &HashToken,
3149                                      bool ReadAnyTokensBeforeDirective) {
3150   ++NumIf;
3151 
3152   // Parse and evaluate the conditional expression.
3153   IdentifierInfo *IfNDefMacro = nullptr;
3154   const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
3155   const bool ConditionalTrue = DER.Conditional;
3156   // Lexer might become invalid if we hit code completion point while evaluating
3157   // expression.
3158   if (!CurPPLexer)
3159     return;
3160 
3161   // If this condition is equivalent to #ifndef X, and if this is the first
3162   // directive seen, handle it for the multiple-include optimization.
3163   if (CurPPLexer->getConditionalStackDepth() == 0) {
3164     if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
3165       // FIXME: Pass in the location of the macro name, not the 'if' token.
3166       CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
3167     else
3168       CurPPLexer->MIOpt.EnterTopLevelConditional();
3169   }
3170 
3171   if (Callbacks)
3172     Callbacks->If(
3173         IfToken.getLocation(), DER.ExprRange,
3174         (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
3175 
3176   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3177     getSourceManager().isInMainFile(IfToken.getLocation());
3178 
3179   // Should we include the stuff contained by this directive?
3180   if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
3181     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3182     // the directive blocks.
3183     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3184                                      /*foundnonskip*/false, /*foundelse*/false);
3185   } else if (ConditionalTrue || RetainExcludedCB) {
3186     // Yes, remember that we are inside a conditional, then lex the next token.
3187     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3188                                    /*foundnonskip*/true, /*foundelse*/false);
3189   } else {
3190     // No, skip the contents of this block.
3191     SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
3192                                  /*Foundnonskip*/ false,
3193                                  /*FoundElse*/ false);
3194   }
3195 }
3196 
3197 /// HandleEndifDirective - Implements the \#endif directive.
3198 ///
3199 void Preprocessor::HandleEndifDirective(Token &EndifToken) {
3200   ++NumEndif;
3201 
3202   // Check that this is the whole directive.
3203   CheckEndOfDirective("endif");
3204 
3205   PPConditionalInfo CondInfo;
3206   if (CurPPLexer->popConditionalLevel(CondInfo)) {
3207     // No conditionals on the stack: this is an #endif without an #if.
3208     Diag(EndifToken, diag::err_pp_endif_without_if);
3209     return;
3210   }
3211 
3212   // If this the end of a top-level #endif, inform MIOpt.
3213   if (CurPPLexer->getConditionalStackDepth() == 0)
3214     CurPPLexer->MIOpt.ExitTopLevelConditional();
3215 
3216   assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
3217          "This code should only be reachable in the non-skipping case!");
3218 
3219   if (Callbacks)
3220     Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
3221 }
3222 
3223 /// HandleElseDirective - Implements the \#else directive.
3224 ///
3225 void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
3226   ++NumElse;
3227 
3228   // #else directive in a non-skipping conditional... start skipping.
3229   CheckEndOfDirective("else");
3230 
3231   PPConditionalInfo CI;
3232   if (CurPPLexer->popConditionalLevel(CI)) {
3233     Diag(Result, diag::pp_err_else_without_if);
3234     return;
3235   }
3236 
3237   // If this is a top-level #else, inform the MIOpt.
3238   if (CurPPLexer->getConditionalStackDepth() == 0)
3239     CurPPLexer->MIOpt.EnterTopLevelConditional();
3240 
3241   // If this is a #else with a #else before it, report the error.
3242   if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
3243 
3244   if (Callbacks)
3245     Callbacks->Else(Result.getLocation(), CI.IfLoc);
3246 
3247   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3248     getSourceManager().isInMainFile(Result.getLocation());
3249 
3250   if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3251     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3252     // the directive blocks.
3253     CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
3254                                      /*foundnonskip*/false, /*foundelse*/true);
3255     return;
3256   }
3257 
3258   // Finally, skip the rest of the contents of this block.
3259   SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
3260                                /*Foundnonskip*/ true,
3261                                /*FoundElse*/ true, Result.getLocation());
3262 }
3263 
3264 /// Implements the \#elif, \#elifdef, and \#elifndef directives.
3265 void Preprocessor::HandleElifFamilyDirective(Token &ElifToken,
3266                                              const Token &HashToken,
3267                                              tok::PPKeywordKind Kind) {
3268   PPElifDiag DirKind = Kind == tok::pp_elif      ? PED_Elif
3269                        : Kind == tok::pp_elifdef ? PED_Elifdef
3270                                                  : PED_Elifndef;
3271   ++NumElse;
3272 
3273   // Warn if using `#elifdef` & `#elifndef` in not C2x & C++2b mode.
3274   switch (DirKind) {
3275   case PED_Elifdef:
3276   case PED_Elifndef:
3277     unsigned DiagID;
3278     if (LangOpts.CPlusPlus)
3279       DiagID = LangOpts.CPlusPlus2b ? diag::warn_cxx2b_compat_pp_directive
3280                                     : diag::ext_cxx2b_pp_directive;
3281     else
3282       DiagID = LangOpts.C2x ? diag::warn_c2x_compat_pp_directive
3283                             : diag::ext_c2x_pp_directive;
3284     Diag(ElifToken, DiagID) << DirKind;
3285     break;
3286   default:
3287     break;
3288   }
3289 
3290   // #elif directive in a non-skipping conditional... start skipping.
3291   // We don't care what the condition is, because we will always skip it (since
3292   // the block immediately before it was included).
3293   SourceRange ConditionRange = DiscardUntilEndOfDirective();
3294 
3295   PPConditionalInfo CI;
3296   if (CurPPLexer->popConditionalLevel(CI)) {
3297     Diag(ElifToken, diag::pp_err_elif_without_if) << DirKind;
3298     return;
3299   }
3300 
3301   // If this is a top-level #elif, inform the MIOpt.
3302   if (CurPPLexer->getConditionalStackDepth() == 0)
3303     CurPPLexer->MIOpt.EnterTopLevelConditional();
3304 
3305   // If this is a #elif with a #else before it, report the error.
3306   if (CI.FoundElse)
3307     Diag(ElifToken, diag::pp_err_elif_after_else) << DirKind;
3308 
3309   if (Callbacks) {
3310     switch (Kind) {
3311     case tok::pp_elif:
3312       Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
3313                       PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
3314       break;
3315     case tok::pp_elifdef:
3316       Callbacks->Elifdef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3317       break;
3318     case tok::pp_elifndef:
3319       Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3320       break;
3321     default:
3322       assert(false && "unexpected directive kind");
3323       break;
3324     }
3325   }
3326 
3327   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3328     getSourceManager().isInMainFile(ElifToken.getLocation());
3329 
3330   if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3331     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3332     // the directive blocks.
3333     CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
3334                                      /*foundnonskip*/false, /*foundelse*/false);
3335     return;
3336   }
3337 
3338   // Finally, skip the rest of the contents of this block.
3339   SkipExcludedConditionalBlock(
3340       HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3341       /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
3342 }
3343