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