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