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