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