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