PPDirectives.cpp revision e26224e61c8a3b607c73c52f2cd0344065d7b412
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//  This file implements # directive processing for the Preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Preprocessor.h"
15#include "clang/Lex/LiteralSupport.h"
16#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/LexDiagnostic.h"
19#include "clang/Lex/CodeCompletionHandler.h"
20#include "clang/Lex/Pragma.h"
21#include "clang/Basic/FileManager.h"
22#include "clang/Basic/SourceManager.h"
23#include "llvm/ADT/APInt.h"
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Utility Methods for Preprocessor Directive Handling.
28//===----------------------------------------------------------------------===//
29
30MacroInfo *Preprocessor::AllocateMacroInfo() {
31  MacroInfoChain *MIChain;
32
33  if (MICache) {
34    MIChain = MICache;
35    MICache = MICache->Next;
36  }
37  else {
38    MIChain = BP.Allocate<MacroInfoChain>();
39  }
40
41  MIChain->Next = MIChainHead;
42  MIChain->Prev = 0;
43  if (MIChainHead)
44    MIChainHead->Prev = MIChain;
45  MIChainHead = MIChain;
46
47  return &(MIChain->MI);
48}
49
50MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
51  MacroInfo *MI = AllocateMacroInfo();
52  new (MI) MacroInfo(L);
53  return MI;
54}
55
56MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
57  MacroInfo *MI = AllocateMacroInfo();
58  new (MI) MacroInfo(MacroToClone, BP);
59  return MI;
60}
61
62/// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
63///  be reused for allocating new MacroInfo objects.
64void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
65  MacroInfoChain *MIChain = (MacroInfoChain*) MI;
66  if (MacroInfoChain *Prev = MIChain->Prev) {
67    MacroInfoChain *Next = MIChain->Next;
68    Prev->Next = Next;
69    if (Next)
70      Next->Prev = Prev;
71  }
72  else {
73    assert(MIChainHead == MIChain);
74    MIChainHead = MIChain->Next;
75    MIChainHead->Prev = 0;
76  }
77  MIChain->Next = MICache;
78  MICache = MIChain;
79
80  MI->Destroy();
81}
82
83/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
84/// current line until the tok::eod token is found.
85void Preprocessor::DiscardUntilEndOfDirective() {
86  Token Tmp;
87  do {
88    LexUnexpandedToken(Tmp);
89    assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
90  } while (Tmp.isNot(tok::eod));
91}
92
93/// ReadMacroName - Lex and validate a macro name, which occurs after a
94/// #define or #undef.  This sets the token kind to eod and discards the rest
95/// of the macro line if the macro name is invalid.  isDefineUndef is 1 if
96/// this is due to a a #define, 2 if #undef directive, 0 if it is something
97/// else (e.g. #ifdef).
98void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
99  // Read the token, don't allow macro expansion on it.
100  LexUnexpandedToken(MacroNameTok);
101
102  if (MacroNameTok.is(tok::code_completion)) {
103    if (CodeComplete)
104      CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
105    LexUnexpandedToken(MacroNameTok);
106    return;
107  }
108
109  // Missing macro name?
110  if (MacroNameTok.is(tok::eod)) {
111    Diag(MacroNameTok, diag::err_pp_missing_macro_name);
112    return;
113  }
114
115  IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
116  if (II == 0) {
117    bool Invalid = false;
118    std::string Spelling = getSpelling(MacroNameTok, &Invalid);
119    if (Invalid)
120      return;
121
122    const IdentifierInfo &Info = Identifiers.get(Spelling);
123    if (Info.isCPlusPlusOperatorKeyword())
124      // C++ 2.5p2: Alternative tokens behave the same as its primary token
125      // except for their spellings.
126      Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
127    else
128      Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
129    // Fall through on error.
130  } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
131    // Error if defining "defined": C99 6.10.8.4.
132    Diag(MacroNameTok, diag::err_defined_macro_name);
133  } else if (isDefineUndef && II->hasMacroDefinition() &&
134             getMacroInfo(II)->isBuiltinMacro()) {
135    // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
136    if (isDefineUndef == 1)
137      Diag(MacroNameTok, diag::pp_redef_builtin_macro);
138    else
139      Diag(MacroNameTok, diag::pp_undef_builtin_macro);
140  } else {
141    // Okay, we got a good identifier node.  Return it.
142    return;
143  }
144
145  // Invalid macro name, read and discard the rest of the line.  Then set the
146  // token kind to tok::eod.
147  MacroNameTok.setKind(tok::eod);
148  return DiscardUntilEndOfDirective();
149}
150
151/// CheckEndOfDirective - Ensure that the next token is a tok::eod token.  If
152/// not, emit a diagnostic and consume up until the eod.  If EnableMacros is
153/// true, then we consider macros that expand to zero tokens as being ok.
154void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
155  Token Tmp;
156  // Lex unexpanded tokens for most directives: macros might expand to zero
157  // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
158  // #line) allow empty macros.
159  if (EnableMacros)
160    Lex(Tmp);
161  else
162    LexUnexpandedToken(Tmp);
163
164  // There should be no tokens after the directive, but we allow them as an
165  // extension.
166  while (Tmp.is(tok::comment))  // Skip comments in -C mode.
167    LexUnexpandedToken(Tmp);
168
169  if (Tmp.isNot(tok::eod)) {
170    // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
171    // or if this is a macro-style preprocessing directive, because it is more
172    // trouble than it is worth to insert /**/ and check that there is no /**/
173    // in the range also.
174    FixItHint Hint;
175    if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
176        !CurTokenLexer)
177      Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
178    Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
179    DiscardUntilEndOfDirective();
180  }
181}
182
183
184
185/// SkipExcludedConditionalBlock - We just read a #if or related directive and
186/// decided that the subsequent tokens are in the #if'd out portion of the
187/// file.  Lex the rest of the file, until we see an #endif.  If
188/// FoundNonSkipPortion is true, then we have already emitted code for part of
189/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
190/// is true, then #else directives are ok, if not, then we have already seen one
191/// so a #else directive is a duplicate.  When this returns, the caller can lex
192/// the first valid token.
193void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
194                                                bool FoundNonSkipPortion,
195                                                bool FoundElse) {
196  ++NumSkipped;
197  assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
198
199  CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
200                                 FoundNonSkipPortion, FoundElse);
201
202  if (CurPTHLexer) {
203    PTHSkipExcludedConditionalBlock();
204    return;
205  }
206
207  // Enter raw mode to disable identifier lookup (and thus macro expansion),
208  // disabling warnings, etc.
209  CurPPLexer->LexingRawMode = true;
210  Token Tok;
211  while (1) {
212    CurLexer->Lex(Tok);
213
214    if (Tok.is(tok::code_completion)) {
215      if (CodeComplete)
216        CodeComplete->CodeCompleteInConditionalExclusion();
217      continue;
218    }
219
220    // If this is the end of the buffer, we have an error.
221    if (Tok.is(tok::eof)) {
222      // Emit errors for each unterminated conditional on the stack, including
223      // the current one.
224      while (!CurPPLexer->ConditionalStack.empty()) {
225        if (!isCodeCompletionFile(Tok.getLocation()))
226          Diag(CurPPLexer->ConditionalStack.back().IfLoc,
227               diag::err_pp_unterminated_conditional);
228        CurPPLexer->ConditionalStack.pop_back();
229      }
230
231      // Just return and let the caller lex after this #include.
232      break;
233    }
234
235    // If this token is not a preprocessor directive, just skip it.
236    if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
237      continue;
238
239    // We just parsed a # character at the start of a line, so we're in
240    // directive mode.  Tell the lexer this so any newlines we see will be
241    // converted into an EOD token (this terminates the macro).
242    CurPPLexer->ParsingPreprocessorDirective = true;
243    if (CurLexer) CurLexer->SetCommentRetentionState(false);
244
245
246    // Read the next token, the directive flavor.
247    LexUnexpandedToken(Tok);
248
249    // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
250    // something bogus), skip it.
251    if (Tok.isNot(tok::raw_identifier)) {
252      CurPPLexer->ParsingPreprocessorDirective = false;
253      // Restore comment saving mode.
254      if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
255      continue;
256    }
257
258    // If the first letter isn't i or e, it isn't intesting to us.  We know that
259    // this is safe in the face of spelling differences, because there is no way
260    // to spell an i/e in a strange way that is another letter.  Skipping this
261    // allows us to avoid looking up the identifier info for #define/#undef and
262    // other common directives.
263    const char *RawCharData = Tok.getRawIdentifierData();
264
265    char FirstChar = RawCharData[0];
266    if (FirstChar >= 'a' && FirstChar <= 'z' &&
267        FirstChar != 'i' && FirstChar != 'e') {
268      CurPPLexer->ParsingPreprocessorDirective = false;
269      // Restore comment saving mode.
270      if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
271      continue;
272    }
273
274    // Get the identifier name without trigraphs or embedded newlines.  Note
275    // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
276    // when skipping.
277    char DirectiveBuf[20];
278    llvm::StringRef Directive;
279    if (!Tok.needsCleaning() && Tok.getLength() < 20) {
280      Directive = llvm::StringRef(RawCharData, Tok.getLength());
281    } else {
282      std::string DirectiveStr = getSpelling(Tok);
283      unsigned IdLen = DirectiveStr.size();
284      if (IdLen >= 20) {
285        CurPPLexer->ParsingPreprocessorDirective = false;
286        // Restore comment saving mode.
287        if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
288        continue;
289      }
290      memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
291      Directive = llvm::StringRef(DirectiveBuf, IdLen);
292    }
293
294    if (Directive.startswith("if")) {
295      llvm::StringRef Sub = Directive.substr(2);
296      if (Sub.empty() ||   // "if"
297          Sub == "def" ||   // "ifdef"
298          Sub == "ndef") {  // "ifndef"
299        // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
300        // bother parsing the condition.
301        DiscardUntilEndOfDirective();
302        CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
303                                       /*foundnonskip*/false,
304                                       /*foundelse*/false);
305
306        if (Callbacks)
307          Callbacks->Endif();
308      }
309    } else if (Directive[0] == 'e') {
310      llvm::StringRef Sub = Directive.substr(1);
311      if (Sub == "ndif") {  // "endif"
312        CheckEndOfDirective("endif");
313        PPConditionalInfo CondInfo;
314        CondInfo.WasSkipping = true; // Silence bogus warning.
315        bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
316        (void)InCond;  // Silence warning in no-asserts mode.
317        assert(!InCond && "Can't be skipping if not in a conditional!");
318
319        // If we popped the outermost skipping block, we're done skipping!
320        if (!CondInfo.WasSkipping)
321          break;
322      } else if (Sub == "lse") { // "else".
323        // #else directive in a skipping conditional.  If not in some other
324        // skipping conditional, and if #else hasn't already been seen, enter it
325        // as a non-skipping conditional.
326        PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
327
328        // If this is a #else with a #else before it, report the error.
329        if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
330
331        // Note that we've seen a #else in this conditional.
332        CondInfo.FoundElse = true;
333
334        if (Callbacks)
335          Callbacks->Else();
336
337        // If the conditional is at the top level, and the #if block wasn't
338        // entered, enter the #else block now.
339        if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
340          CondInfo.FoundNonSkip = true;
341          CheckEndOfDirective("else");
342          break;
343        } else {
344          DiscardUntilEndOfDirective();  // C99 6.10p4.
345        }
346      } else if (Sub == "lif") {  // "elif".
347        PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
348
349        bool ShouldEnter;
350        const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
351        // If this is in a skipping block or if we're already handled this #if
352        // block, don't bother parsing the condition.
353        if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
354          DiscardUntilEndOfDirective();
355          ShouldEnter = false;
356        } else {
357          // Restore the value of LexingRawMode so that identifiers are
358          // looked up, etc, inside the #elif expression.
359          assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
360          CurPPLexer->LexingRawMode = false;
361          IdentifierInfo *IfNDefMacro = 0;
362          ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
363          CurPPLexer->LexingRawMode = true;
364        }
365        const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
366
367        // If this is a #elif with a #else before it, report the error.
368        if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
369
370        if (Callbacks)
371          Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
372
373        // If this condition is true, enter it!
374        if (ShouldEnter) {
375          CondInfo.FoundNonSkip = true;
376          break;
377        }
378      }
379    }
380
381    CurPPLexer->ParsingPreprocessorDirective = false;
382    // Restore comment saving mode.
383    if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
384  }
385
386  // Finally, if we are out of the conditional (saw an #endif or ran off the end
387  // of the file, just stop skipping and return to lexing whatever came after
388  // the #if block.
389  CurPPLexer->LexingRawMode = false;
390}
391
392void Preprocessor::PTHSkipExcludedConditionalBlock() {
393
394  while (1) {
395    assert(CurPTHLexer);
396    assert(CurPTHLexer->LexingRawMode == false);
397
398    // Skip to the next '#else', '#elif', or #endif.
399    if (CurPTHLexer->SkipBlock()) {
400      // We have reached an #endif.  Both the '#' and 'endif' tokens
401      // have been consumed by the PTHLexer.  Just pop off the condition level.
402      PPConditionalInfo CondInfo;
403      bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
404      (void)InCond;  // Silence warning in no-asserts mode.
405      assert(!InCond && "Can't be skipping if not in a conditional!");
406      break;
407    }
408
409    // We have reached a '#else' or '#elif'.  Lex the next token to get
410    // the directive flavor.
411    Token Tok;
412    LexUnexpandedToken(Tok);
413
414    // We can actually look up the IdentifierInfo here since we aren't in
415    // raw mode.
416    tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
417
418    if (K == tok::pp_else) {
419      // #else: Enter the else condition.  We aren't in a nested condition
420      //  since we skip those. We're always in the one matching the last
421      //  blocked we skipped.
422      PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
423      // Note that we've seen a #else in this conditional.
424      CondInfo.FoundElse = true;
425
426      // If the #if block wasn't entered then enter the #else block now.
427      if (!CondInfo.FoundNonSkip) {
428        CondInfo.FoundNonSkip = true;
429
430        // Scan until the eod token.
431        CurPTHLexer->ParsingPreprocessorDirective = true;
432        DiscardUntilEndOfDirective();
433        CurPTHLexer->ParsingPreprocessorDirective = false;
434
435        break;
436      }
437
438      // Otherwise skip this block.
439      continue;
440    }
441
442    assert(K == tok::pp_elif);
443    PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
444
445    // If this is a #elif with a #else before it, report the error.
446    if (CondInfo.FoundElse)
447      Diag(Tok, diag::pp_err_elif_after_else);
448
449    // If this is in a skipping block or if we're already handled this #if
450    // block, don't bother parsing the condition.  We just skip this block.
451    if (CondInfo.FoundNonSkip)
452      continue;
453
454    // Evaluate the condition of the #elif.
455    IdentifierInfo *IfNDefMacro = 0;
456    CurPTHLexer->ParsingPreprocessorDirective = true;
457    bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
458    CurPTHLexer->ParsingPreprocessorDirective = false;
459
460    // If this condition is true, enter it!
461    if (ShouldEnter) {
462      CondInfo.FoundNonSkip = true;
463      break;
464    }
465
466    // Otherwise, skip this block and go to the next one.
467    continue;
468  }
469}
470
471/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
472/// return null on failure.  isAngled indicates whether the file reference is
473/// for system #include's or not (i.e. using <> instead of "").
474const FileEntry *Preprocessor::LookupFile(
475    llvm::StringRef Filename,
476    bool isAngled,
477    const DirectoryLookup *FromDir,
478    const DirectoryLookup *&CurDir,
479    llvm::SmallVectorImpl<char> *SearchPath,
480    llvm::SmallVectorImpl<char> *RelativePath) {
481  // If the header lookup mechanism may be relative to the current file, pass in
482  // info about where the current file is.
483  const FileEntry *CurFileEnt = 0;
484  if (!FromDir) {
485    FileID FID = getCurrentFileLexer()->getFileID();
486    CurFileEnt = SourceMgr.getFileEntryForID(FID);
487
488    // If there is no file entry associated with this file, it must be the
489    // predefines buffer.  Any other file is not lexed with a normal lexer, so
490    // it won't be scanned for preprocessor directives.   If we have the
491    // predefines buffer, resolve #include references (which come from the
492    // -include command line argument) as if they came from the main file, this
493    // affects file lookup etc.
494    if (CurFileEnt == 0) {
495      FID = SourceMgr.getMainFileID();
496      CurFileEnt = SourceMgr.getFileEntryForID(FID);
497    }
498  }
499
500  // Do a standard file entry lookup.
501  CurDir = CurDirLookup;
502  const FileEntry *FE = HeaderInfo.LookupFile(
503      Filename, isAngled, FromDir, CurDir, CurFileEnt,
504      SearchPath, RelativePath);
505  if (FE) return FE;
506
507  // Otherwise, see if this is a subframework header.  If so, this is relative
508  // to one of the headers on the #include stack.  Walk the list of the current
509  // headers on the #include stack and pass them to HeaderInfo.
510  if (IsFileLexer()) {
511    if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
512      if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
513                                                    SearchPath, RelativePath)))
514        return FE;
515  }
516
517  for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
518    IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
519    if (IsFileLexer(ISEntry)) {
520      if ((CurFileEnt =
521           SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
522        if ((FE = HeaderInfo.LookupSubframeworkHeader(
523                Filename, CurFileEnt, SearchPath, RelativePath)))
524          return FE;
525    }
526  }
527
528  // Otherwise, we really couldn't find the file.
529  return 0;
530}
531
532
533//===----------------------------------------------------------------------===//
534// Preprocessor Directive Handling.
535//===----------------------------------------------------------------------===//
536
537/// HandleDirective - This callback is invoked when the lexer sees a # token
538/// at the start of a line.  This consumes the directive, modifies the
539/// lexer/preprocessor state, and advances the lexer(s) so that the next token
540/// read is the correct one.
541void Preprocessor::HandleDirective(Token &Result) {
542  // FIXME: Traditional: # with whitespace before it not recognized by K&R?
543
544  // We just parsed a # character at the start of a line, so we're in directive
545  // mode.  Tell the lexer this so any newlines we see will be converted into an
546  // EOD token (which terminates the directive).
547  CurPPLexer->ParsingPreprocessorDirective = true;
548
549  ++NumDirectives;
550
551  // We are about to read a token.  For the multiple-include optimization FA to
552  // work, we have to remember if we had read any tokens *before* this
553  // pp-directive.
554  bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
555
556  // Save the '#' token in case we need to return it later.
557  Token SavedHash = Result;
558
559  // Read the next token, the directive flavor.  This isn't expanded due to
560  // C99 6.10.3p8.
561  LexUnexpandedToken(Result);
562
563  // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
564  //   #define A(x) #x
565  //   A(abc
566  //     #warning blah
567  //   def)
568  // If so, the user is relying on non-portable behavior, emit a diagnostic.
569  if (InMacroArgs)
570    Diag(Result, diag::ext_embedded_directive);
571
572TryAgain:
573  switch (Result.getKind()) {
574  case tok::eod:
575    return;   // null directive.
576  case tok::comment:
577    // Handle stuff like "# /*foo*/ define X" in -E -C mode.
578    LexUnexpandedToken(Result);
579    goto TryAgain;
580  case tok::code_completion:
581    if (CodeComplete)
582      CodeComplete->CodeCompleteDirective(
583                                    CurPPLexer->getConditionalStackDepth() > 0);
584    return;
585  case tok::numeric_constant:  // # 7  GNU line marker directive.
586    if (getLangOptions().AsmPreprocessor)
587      break;  // # 4 is not a preprocessor directive in .S files.
588    return HandleDigitDirective(Result);
589  default:
590    IdentifierInfo *II = Result.getIdentifierInfo();
591    if (II == 0) break;  // Not an identifier.
592
593    // Ask what the preprocessor keyword ID is.
594    switch (II->getPPKeywordID()) {
595    default: break;
596    // C99 6.10.1 - Conditional Inclusion.
597    case tok::pp_if:
598      return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
599    case tok::pp_ifdef:
600      return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
601    case tok::pp_ifndef:
602      return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
603    case tok::pp_elif:
604      return HandleElifDirective(Result);
605    case tok::pp_else:
606      return HandleElseDirective(Result);
607    case tok::pp_endif:
608      return HandleEndifDirective(Result);
609
610    // C99 6.10.2 - Source File Inclusion.
611    case tok::pp_include:
612      // Handle #include.
613      return HandleIncludeDirective(SavedHash.getLocation(), Result);
614    case tok::pp___include_macros:
615      // Handle -imacros.
616      return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
617
618    // C99 6.10.3 - Macro Replacement.
619    case tok::pp_define:
620      return HandleDefineDirective(Result);
621    case tok::pp_undef:
622      return HandleUndefDirective(Result);
623
624    // C99 6.10.4 - Line Control.
625    case tok::pp_line:
626      return HandleLineDirective(Result);
627
628    // C99 6.10.5 - Error Directive.
629    case tok::pp_error:
630      return HandleUserDiagnosticDirective(Result, false);
631
632    // C99 6.10.6 - Pragma Directive.
633    case tok::pp_pragma:
634      return HandlePragmaDirective(PIK_HashPragma);
635
636    // GNU Extensions.
637    case tok::pp_import:
638      return HandleImportDirective(SavedHash.getLocation(), Result);
639    case tok::pp_include_next:
640      return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
641
642    case tok::pp_warning:
643      Diag(Result, diag::ext_pp_warning_directive);
644      return HandleUserDiagnosticDirective(Result, true);
645    case tok::pp_ident:
646      return HandleIdentSCCSDirective(Result);
647    case tok::pp_sccs:
648      return HandleIdentSCCSDirective(Result);
649    case tok::pp_assert:
650      //isExtension = true;  // FIXME: implement #assert
651      break;
652    case tok::pp_unassert:
653      //isExtension = true;  // FIXME: implement #unassert
654      break;
655    }
656    break;
657  }
658
659  // If this is a .S file, treat unknown # directives as non-preprocessor
660  // directives.  This is important because # may be a comment or introduce
661  // various pseudo-ops.  Just return the # token and push back the following
662  // token to be lexed next time.
663  if (getLangOptions().AsmPreprocessor) {
664    Token *Toks = new Token[2];
665    // Return the # and the token after it.
666    Toks[0] = SavedHash;
667    Toks[1] = Result;
668
669    // If the second token is a hashhash token, then we need to translate it to
670    // unknown so the token lexer doesn't try to perform token pasting.
671    if (Result.is(tok::hashhash))
672      Toks[1].setKind(tok::unknown);
673
674    // Enter this token stream so that we re-lex the tokens.  Make sure to
675    // enable macro expansion, in case the token after the # is an identifier
676    // that is expanded.
677    EnterTokenStream(Toks, 2, false, true);
678    return;
679  }
680
681  // If we reached here, the preprocessing token is not valid!
682  Diag(Result, diag::err_pp_invalid_directive);
683
684  // Read the rest of the PP line.
685  DiscardUntilEndOfDirective();
686
687  // Okay, we're done parsing the directive.
688}
689
690/// GetLineValue - Convert a numeric token into an unsigned value, emitting
691/// Diagnostic DiagID if it is invalid, and returning the value in Val.
692static bool GetLineValue(Token &DigitTok, unsigned &Val,
693                         unsigned DiagID, Preprocessor &PP) {
694  if (DigitTok.isNot(tok::numeric_constant)) {
695    PP.Diag(DigitTok, DiagID);
696
697    if (DigitTok.isNot(tok::eod))
698      PP.DiscardUntilEndOfDirective();
699    return true;
700  }
701
702  llvm::SmallString<64> IntegerBuffer;
703  IntegerBuffer.resize(DigitTok.getLength());
704  const char *DigitTokBegin = &IntegerBuffer[0];
705  bool Invalid = false;
706  unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
707  if (Invalid)
708    return true;
709
710  // Verify that we have a simple digit-sequence, and compute the value.  This
711  // is always a simple digit string computed in decimal, so we do this manually
712  // here.
713  Val = 0;
714  for (unsigned i = 0; i != ActualLength; ++i) {
715    if (!isdigit(DigitTokBegin[i])) {
716      PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
717              diag::err_pp_line_digit_sequence);
718      PP.DiscardUntilEndOfDirective();
719      return true;
720    }
721
722    unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
723    if (NextVal < Val) { // overflow.
724      PP.Diag(DigitTok, DiagID);
725      PP.DiscardUntilEndOfDirective();
726      return true;
727    }
728    Val = NextVal;
729  }
730
731  // Reject 0, this is needed both by #line numbers and flags.
732  if (Val == 0) {
733    PP.Diag(DigitTok, DiagID);
734    PP.DiscardUntilEndOfDirective();
735    return true;
736  }
737
738  if (DigitTokBegin[0] == '0')
739    PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
740
741  return false;
742}
743
744/// HandleLineDirective - Handle #line directive: C99 6.10.4.  The two
745/// acceptable forms are:
746///   # line digit-sequence
747///   # line digit-sequence "s-char-sequence"
748void Preprocessor::HandleLineDirective(Token &Tok) {
749  // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
750  // expanded.
751  Token DigitTok;
752  Lex(DigitTok);
753
754  // Validate the number and convert it to an unsigned.
755  unsigned LineNo;
756  if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
757    return;
758
759  // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
760  // number greater than 2147483647".  C90 requires that the line # be <= 32767.
761  unsigned LineLimit = Features.C99 ? 2147483648U : 32768U;
762  if (LineNo >= LineLimit)
763    Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
764
765  int FilenameID = -1;
766  Token StrTok;
767  Lex(StrTok);
768
769  // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
770  // string followed by eod.
771  if (StrTok.is(tok::eod))
772    ; // ok
773  else if (StrTok.isNot(tok::string_literal)) {
774    Diag(StrTok, diag::err_pp_line_invalid_filename);
775    DiscardUntilEndOfDirective();
776    return;
777  } else {
778    // Parse and validate the string, converting it into a unique ID.
779    StringLiteralParser Literal(&StrTok, 1, *this);
780    assert(!Literal.AnyWide && "Didn't allow wide strings in");
781    if (Literal.hadError)
782      return DiscardUntilEndOfDirective();
783    if (Literal.Pascal) {
784      Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
785      return DiscardUntilEndOfDirective();
786    }
787    FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
788                                                  Literal.GetStringLength());
789
790    // Verify that there is nothing after the string, other than EOD.  Because
791    // of C99 6.10.4p5, macros that expand to empty tokens are ok.
792    CheckEndOfDirective("line", true);
793  }
794
795  SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
796
797  if (Callbacks)
798    Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
799                           PPCallbacks::RenameFile,
800                           SrcMgr::C_User);
801}
802
803/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
804/// marker directive.
805static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
806                                bool &IsSystemHeader, bool &IsExternCHeader,
807                                Preprocessor &PP) {
808  unsigned FlagVal;
809  Token FlagTok;
810  PP.Lex(FlagTok);
811  if (FlagTok.is(tok::eod)) return false;
812  if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
813    return true;
814
815  if (FlagVal == 1) {
816    IsFileEntry = true;
817
818    PP.Lex(FlagTok);
819    if (FlagTok.is(tok::eod)) return false;
820    if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
821      return true;
822  } else if (FlagVal == 2) {
823    IsFileExit = true;
824
825    SourceManager &SM = PP.getSourceManager();
826    // If we are leaving the current presumed file, check to make sure the
827    // presumed include stack isn't empty!
828    FileID CurFileID =
829      SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first;
830    PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
831    if (PLoc.isInvalid())
832      return true;
833
834    // If there is no include loc (main file) or if the include loc is in a
835    // different physical file, then we aren't in a "1" line marker flag region.
836    SourceLocation IncLoc = PLoc.getIncludeLoc();
837    if (IncLoc.isInvalid() ||
838        SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) {
839      PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
840      PP.DiscardUntilEndOfDirective();
841      return true;
842    }
843
844    PP.Lex(FlagTok);
845    if (FlagTok.is(tok::eod)) return false;
846    if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
847      return true;
848  }
849
850  // We must have 3 if there are still flags.
851  if (FlagVal != 3) {
852    PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
853    PP.DiscardUntilEndOfDirective();
854    return true;
855  }
856
857  IsSystemHeader = true;
858
859  PP.Lex(FlagTok);
860  if (FlagTok.is(tok::eod)) return false;
861  if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
862    return true;
863
864  // We must have 4 if there is yet another flag.
865  if (FlagVal != 4) {
866    PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
867    PP.DiscardUntilEndOfDirective();
868    return true;
869  }
870
871  IsExternCHeader = true;
872
873  PP.Lex(FlagTok);
874  if (FlagTok.is(tok::eod)) return false;
875
876  // There are no more valid flags here.
877  PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
878  PP.DiscardUntilEndOfDirective();
879  return true;
880}
881
882/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
883/// one of the following forms:
884///
885///     # 42
886///     # 42 "file" ('1' | '2')?
887///     # 42 "file" ('1' | '2')? '3' '4'?
888///
889void Preprocessor::HandleDigitDirective(Token &DigitTok) {
890  // Validate the number and convert it to an unsigned.  GNU does not have a
891  // line # limit other than it fit in 32-bits.
892  unsigned LineNo;
893  if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
894                   *this))
895    return;
896
897  Token StrTok;
898  Lex(StrTok);
899
900  bool IsFileEntry = false, IsFileExit = false;
901  bool IsSystemHeader = false, IsExternCHeader = false;
902  int FilenameID = -1;
903
904  // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
905  // string followed by eod.
906  if (StrTok.is(tok::eod))
907    ; // ok
908  else if (StrTok.isNot(tok::string_literal)) {
909    Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
910    return DiscardUntilEndOfDirective();
911  } else {
912    // Parse and validate the string, converting it into a unique ID.
913    StringLiteralParser Literal(&StrTok, 1, *this);
914    assert(!Literal.AnyWide && "Didn't allow wide strings in");
915    if (Literal.hadError)
916      return DiscardUntilEndOfDirective();
917    if (Literal.Pascal) {
918      Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
919      return DiscardUntilEndOfDirective();
920    }
921    FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(),
922                                                  Literal.GetStringLength());
923
924    // If a filename was present, read any flags that are present.
925    if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
926                            IsSystemHeader, IsExternCHeader, *this))
927      return;
928  }
929
930  // Create a line note with this information.
931  SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
932                        IsFileEntry, IsFileExit,
933                        IsSystemHeader, IsExternCHeader);
934
935  // If the preprocessor has callbacks installed, notify them of the #line
936  // change.  This is used so that the line marker comes out in -E mode for
937  // example.
938  if (Callbacks) {
939    PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
940    if (IsFileEntry)
941      Reason = PPCallbacks::EnterFile;
942    else if (IsFileExit)
943      Reason = PPCallbacks::ExitFile;
944    SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
945    if (IsExternCHeader)
946      FileKind = SrcMgr::C_ExternCSystem;
947    else if (IsSystemHeader)
948      FileKind = SrcMgr::C_System;
949
950    Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
951  }
952}
953
954
955/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
956///
957void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
958                                                 bool isWarning) {
959  // PTH doesn't emit #warning or #error directives.
960  if (CurPTHLexer)
961    return CurPTHLexer->DiscardToEndOfLine();
962
963  // Read the rest of the line raw.  We do this because we don't want macros
964  // to be expanded and we don't require that the tokens be valid preprocessing
965  // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
966  // collapse multiple consequtive white space between tokens, but this isn't
967  // specified by the standard.
968  std::string Message = CurLexer->ReadToEndOfLine();
969  if (isWarning)
970    Diag(Tok, diag::pp_hash_warning) << Message;
971  else
972    Diag(Tok, diag::err_pp_hash_error) << Message;
973}
974
975/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
976///
977void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
978  // Yes, this directive is an extension.
979  Diag(Tok, diag::ext_pp_ident_directive);
980
981  // Read the string argument.
982  Token StrTok;
983  Lex(StrTok);
984
985  // If the token kind isn't a string, it's a malformed directive.
986  if (StrTok.isNot(tok::string_literal) &&
987      StrTok.isNot(tok::wide_string_literal)) {
988    Diag(StrTok, diag::err_pp_malformed_ident);
989    if (StrTok.isNot(tok::eod))
990      DiscardUntilEndOfDirective();
991    return;
992  }
993
994  // Verify that there is nothing after the string, other than EOD.
995  CheckEndOfDirective("ident");
996
997  if (Callbacks) {
998    bool Invalid = false;
999    std::string Str = getSpelling(StrTok, &Invalid);
1000    if (!Invalid)
1001      Callbacks->Ident(Tok.getLocation(), Str);
1002  }
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// Preprocessor Include Directive Handling.
1007//===----------------------------------------------------------------------===//
1008
1009/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1010/// checked and spelled filename, e.g. as an operand of #include. This returns
1011/// true if the input filename was in <>'s or false if it were in ""'s.  The
1012/// caller is expected to provide a buffer that is large enough to hold the
1013/// spelling of the filename, but is also expected to handle the case when
1014/// this method decides to use a different buffer.
1015bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1016                                              llvm::StringRef &Buffer) {
1017  // Get the text form of the filename.
1018  assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1019
1020  // Make sure the filename is <x> or "x".
1021  bool isAngled;
1022  if (Buffer[0] == '<') {
1023    if (Buffer.back() != '>') {
1024      Diag(Loc, diag::err_pp_expects_filename);
1025      Buffer = llvm::StringRef();
1026      return true;
1027    }
1028    isAngled = true;
1029  } else if (Buffer[0] == '"') {
1030    if (Buffer.back() != '"') {
1031      Diag(Loc, diag::err_pp_expects_filename);
1032      Buffer = llvm::StringRef();
1033      return true;
1034    }
1035    isAngled = false;
1036  } else {
1037    Diag(Loc, diag::err_pp_expects_filename);
1038    Buffer = llvm::StringRef();
1039    return true;
1040  }
1041
1042  // Diagnose #include "" as invalid.
1043  if (Buffer.size() <= 2) {
1044    Diag(Loc, diag::err_pp_empty_filename);
1045    Buffer = llvm::StringRef();
1046    return true;
1047  }
1048
1049  // Skip the brackets.
1050  Buffer = Buffer.substr(1, Buffer.size()-2);
1051  return isAngled;
1052}
1053
1054/// ConcatenateIncludeName - Handle cases where the #include name is expanded
1055/// from a macro as multiple tokens, which need to be glued together.  This
1056/// occurs for code like:
1057///    #define FOO <a/b.h>
1058///    #include FOO
1059/// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1060///
1061/// This code concatenates and consumes tokens up to the '>' token.  It returns
1062/// false if the > was found, otherwise it returns true if it finds and consumes
1063/// the EOD marker.
1064bool Preprocessor::ConcatenateIncludeName(
1065                                        llvm::SmallString<128> &FilenameBuffer,
1066                                          SourceLocation &End) {
1067  Token CurTok;
1068
1069  Lex(CurTok);
1070  while (CurTok.isNot(tok::eod)) {
1071    End = CurTok.getLocation();
1072
1073    // FIXME: Provide code completion for #includes.
1074    if (CurTok.is(tok::code_completion)) {
1075      Lex(CurTok);
1076      continue;
1077    }
1078
1079    // Append the spelling of this token to the buffer. If there was a space
1080    // before it, add it now.
1081    if (CurTok.hasLeadingSpace())
1082      FilenameBuffer.push_back(' ');
1083
1084    // Get the spelling of the token, directly into FilenameBuffer if possible.
1085    unsigned PreAppendSize = FilenameBuffer.size();
1086    FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1087
1088    const char *BufPtr = &FilenameBuffer[PreAppendSize];
1089    unsigned ActualLen = getSpelling(CurTok, BufPtr);
1090
1091    // If the token was spelled somewhere else, copy it into FilenameBuffer.
1092    if (BufPtr != &FilenameBuffer[PreAppendSize])
1093      memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1094
1095    // Resize FilenameBuffer to the correct size.
1096    if (CurTok.getLength() != ActualLen)
1097      FilenameBuffer.resize(PreAppendSize+ActualLen);
1098
1099    // If we found the '>' marker, return success.
1100    if (CurTok.is(tok::greater))
1101      return false;
1102
1103    Lex(CurTok);
1104  }
1105
1106  // If we hit the eod marker, emit an error and return true so that the caller
1107  // knows the EOD has been read.
1108  Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1109  return true;
1110}
1111
1112/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1113/// file to be included from the lexer, then include it!  This is a common
1114/// routine with functionality shared between #include, #include_next and
1115/// #import.  LookupFrom is set when this is a #include_next directive, it
1116/// specifies the file to start searching from.
1117void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1118                                          Token &IncludeTok,
1119                                          const DirectoryLookup *LookupFrom,
1120                                          bool isImport) {
1121
1122  Token FilenameTok;
1123  CurPPLexer->LexIncludeFilename(FilenameTok);
1124
1125  // Reserve a buffer to get the spelling.
1126  llvm::SmallString<128> FilenameBuffer;
1127  llvm::StringRef Filename;
1128  SourceLocation End;
1129
1130  switch (FilenameTok.getKind()) {
1131  case tok::eod:
1132    // If the token kind is EOD, the error has already been diagnosed.
1133    return;
1134
1135  case tok::angle_string_literal:
1136  case tok::string_literal:
1137    Filename = getSpelling(FilenameTok, FilenameBuffer);
1138    End = FilenameTok.getLocation();
1139    break;
1140
1141  case tok::less:
1142    // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1143    // case, glue the tokens together into FilenameBuffer and interpret those.
1144    FilenameBuffer.push_back('<');
1145    if (ConcatenateIncludeName(FilenameBuffer, End))
1146      return;   // Found <eod> but no ">"?  Diagnostic already emitted.
1147    Filename = FilenameBuffer.str();
1148    break;
1149  default:
1150    Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1151    DiscardUntilEndOfDirective();
1152    return;
1153  }
1154
1155  bool isAngled =
1156    GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1157  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1158  // error.
1159  if (Filename.empty()) {
1160    DiscardUntilEndOfDirective();
1161    return;
1162  }
1163
1164  // Verify that there is nothing after the filename, other than EOD.  Note that
1165  // we allow macros that expand to nothing after the filename, because this
1166  // falls into the category of "#include pp-tokens new-line" specified in
1167  // C99 6.10.2p4.
1168  CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1169
1170  // Check that we don't have infinite #include recursion.
1171  if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1172    Diag(FilenameTok, diag::err_pp_include_too_deep);
1173    return;
1174  }
1175
1176  // Search include directories.
1177  const DirectoryLookup *CurDir;
1178  llvm::SmallString<1024> SearchPath;
1179  llvm::SmallString<1024> RelativePath;
1180  // We get the raw path only if we have 'Callbacks' to which we later pass
1181  // the path.
1182  const FileEntry *File = LookupFile(
1183      Filename, isAngled, LookupFrom, CurDir,
1184      Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL);
1185  if (File == 0) {
1186    Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1187    return;
1188  }
1189
1190  // Notify the callback object that we've seen an inclusion directive.
1191  if (Callbacks)
1192    Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1193                                  End, SearchPath, RelativePath);
1194
1195  // The #included file will be considered to be a system header if either it is
1196  // in a system include directory, or if the #includer is a system include
1197  // header.
1198  SrcMgr::CharacteristicKind FileCharacter =
1199    std::max(HeaderInfo.getFileDirFlavor(File),
1200             SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
1201
1202  // Ask HeaderInfo if we should enter this #include file.  If not, #including
1203  // this file will have no effect.
1204  if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1205    if (Callbacks)
1206      Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
1207    return;
1208  }
1209
1210  // Look up the file, create a File ID for it.
1211  FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1212                                      FileCharacter);
1213  if (FID.isInvalid()) {
1214    Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1215    return;
1216  }
1217
1218  // Finally, if all is good, enter the new file!
1219  EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
1220}
1221
1222/// HandleIncludeNextDirective - Implements #include_next.
1223///
1224void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1225                                              Token &IncludeNextTok) {
1226  Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1227
1228  // #include_next is like #include, except that we start searching after
1229  // the current found directory.  If we can't do this, issue a
1230  // diagnostic.
1231  const DirectoryLookup *Lookup = CurDirLookup;
1232  if (isInPrimaryFile()) {
1233    Lookup = 0;
1234    Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1235  } else if (Lookup == 0) {
1236    Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1237  } else {
1238    // Start looking up in the next directory.
1239    ++Lookup;
1240  }
1241
1242  return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
1243}
1244
1245/// HandleImportDirective - Implements #import.
1246///
1247void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1248                                         Token &ImportTok) {
1249  if (!Features.ObjC1)  // #import is standard for ObjC.
1250    Diag(ImportTok, diag::ext_pp_import_directive);
1251
1252  return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
1253}
1254
1255/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1256/// pseudo directive in the predefines buffer.  This handles it by sucking all
1257/// tokens through the preprocessor and discarding them (only keeping the side
1258/// effects on the preprocessor).
1259void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1260                                                Token &IncludeMacrosTok) {
1261  // This directive should only occur in the predefines buffer.  If not, emit an
1262  // error and reject it.
1263  SourceLocation Loc = IncludeMacrosTok.getLocation();
1264  if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1265    Diag(IncludeMacrosTok.getLocation(),
1266         diag::pp_include_macros_out_of_predefines);
1267    DiscardUntilEndOfDirective();
1268    return;
1269  }
1270
1271  // Treat this as a normal #include for checking purposes.  If this is
1272  // successful, it will push a new lexer onto the include stack.
1273  HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
1274
1275  Token TmpTok;
1276  do {
1277    Lex(TmpTok);
1278    assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1279  } while (TmpTok.isNot(tok::hashhash));
1280}
1281
1282//===----------------------------------------------------------------------===//
1283// Preprocessor Macro Directive Handling.
1284//===----------------------------------------------------------------------===//
1285
1286/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1287/// definition has just been read.  Lex the rest of the arguments and the
1288/// closing ), updating MI with what we learn.  Return true if an error occurs
1289/// parsing the arg list.
1290bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1291  llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1292
1293  Token Tok;
1294  while (1) {
1295    LexUnexpandedToken(Tok);
1296    switch (Tok.getKind()) {
1297    case tok::r_paren:
1298      // Found the end of the argument list.
1299      if (Arguments.empty())  // #define FOO()
1300        return false;
1301      // Otherwise we have #define FOO(A,)
1302      Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1303      return true;
1304    case tok::ellipsis:  // #define X(... -> C99 varargs
1305      // Warn if use of C99 feature in non-C99 mode.
1306      if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1307
1308      // Lex the token after the identifier.
1309      LexUnexpandedToken(Tok);
1310      if (Tok.isNot(tok::r_paren)) {
1311        Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1312        return true;
1313      }
1314      // Add the __VA_ARGS__ identifier as an argument.
1315      Arguments.push_back(Ident__VA_ARGS__);
1316      MI->setIsC99Varargs();
1317      MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1318      return false;
1319    case tok::eod:  // #define X(
1320      Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1321      return true;
1322    default:
1323      // Handle keywords and identifiers here to accept things like
1324      // #define Foo(for) for.
1325      IdentifierInfo *II = Tok.getIdentifierInfo();
1326      if (II == 0) {
1327        // #define X(1
1328        Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1329        return true;
1330      }
1331
1332      // If this is already used as an argument, it is used multiple times (e.g.
1333      // #define X(A,A.
1334      if (std::find(Arguments.begin(), Arguments.end(), II) !=
1335          Arguments.end()) {  // C99 6.10.3p6
1336        Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
1337        return true;
1338      }
1339
1340      // Add the argument to the macro info.
1341      Arguments.push_back(II);
1342
1343      // Lex the token after the identifier.
1344      LexUnexpandedToken(Tok);
1345
1346      switch (Tok.getKind()) {
1347      default:          // #define X(A B
1348        Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1349        return true;
1350      case tok::r_paren: // #define X(A)
1351        MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1352        return false;
1353      case tok::comma:  // #define X(A,
1354        break;
1355      case tok::ellipsis:  // #define X(A... -> GCC extension
1356        // Diagnose extension.
1357        Diag(Tok, diag::ext_named_variadic_macro);
1358
1359        // Lex the token after the identifier.
1360        LexUnexpandedToken(Tok);
1361        if (Tok.isNot(tok::r_paren)) {
1362          Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1363          return true;
1364        }
1365
1366        MI->setIsGNUVarargs();
1367        MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1368        return false;
1369      }
1370    }
1371  }
1372}
1373
1374/// HandleDefineDirective - Implements #define.  This consumes the entire macro
1375/// line then lets the caller lex the next real token.
1376void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1377  ++NumDefined;
1378
1379  Token MacroNameTok;
1380  ReadMacroName(MacroNameTok, 1);
1381
1382  // Error reading macro name?  If so, diagnostic already issued.
1383  if (MacroNameTok.is(tok::eod))
1384    return;
1385
1386  Token LastTok = MacroNameTok;
1387
1388  // If we are supposed to keep comments in #defines, reenable comment saving
1389  // mode.
1390  if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
1391
1392  // Create the new macro.
1393  MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
1394
1395  Token Tok;
1396  LexUnexpandedToken(Tok);
1397
1398  // If this is a function-like macro definition, parse the argument list,
1399  // marking each of the identifiers as being used as macro arguments.  Also,
1400  // check other constraints on the first token of the macro body.
1401  if (Tok.is(tok::eod)) {
1402    // If there is no body to this macro, we have no special handling here.
1403  } else if (Tok.hasLeadingSpace()) {
1404    // This is a normal token with leading space.  Clear the leading space
1405    // marker on the first token to get proper expansion.
1406    Tok.clearFlag(Token::LeadingSpace);
1407  } else if (Tok.is(tok::l_paren)) {
1408    // This is a function-like macro definition.  Read the argument list.
1409    MI->setIsFunctionLike();
1410    if (ReadMacroDefinitionArgList(MI)) {
1411      // Forget about MI.
1412      ReleaseMacroInfo(MI);
1413      // Throw away the rest of the line.
1414      if (CurPPLexer->ParsingPreprocessorDirective)
1415        DiscardUntilEndOfDirective();
1416      return;
1417    }
1418
1419    // If this is a definition of a variadic C99 function-like macro, not using
1420    // the GNU named varargs extension, enabled __VA_ARGS__.
1421
1422    // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1423    // This gets unpoisoned where it is allowed.
1424    assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1425    if (MI->isC99Varargs())
1426      Ident__VA_ARGS__->setIsPoisoned(false);
1427
1428    // Read the first token after the arg list for down below.
1429    LexUnexpandedToken(Tok);
1430  } else if (Features.C99) {
1431    // C99 requires whitespace between the macro definition and the body.  Emit
1432    // a diagnostic for something like "#define X+".
1433    Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1434  } else {
1435    // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1436    // first character of a replacement list is not a character required by
1437    // subclause 5.2.1, then there shall be white-space separation between the
1438    // identifier and the replacement list.".  5.2.1 lists this set:
1439    //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1440    // is irrelevant here.
1441    bool isInvalid = false;
1442    if (Tok.is(tok::at)) // @ is not in the list above.
1443      isInvalid = true;
1444    else if (Tok.is(tok::unknown)) {
1445      // If we have an unknown token, it is something strange like "`".  Since
1446      // all of valid characters would have lexed into a single character
1447      // token of some sort, we know this is not a valid case.
1448      isInvalid = true;
1449    }
1450    if (isInvalid)
1451      Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1452    else
1453      Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
1454  }
1455
1456  if (!Tok.is(tok::eod))
1457    LastTok = Tok;
1458
1459  // Read the rest of the macro body.
1460  if (MI->isObjectLike()) {
1461    // Object-like macros are very simple, just read their body.
1462    while (Tok.isNot(tok::eod)) {
1463      LastTok = Tok;
1464      MI->AddTokenToBody(Tok);
1465      // Get the next token of the macro.
1466      LexUnexpandedToken(Tok);
1467    }
1468
1469  } else {
1470    // Otherwise, read the body of a function-like macro.  While we are at it,
1471    // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1472    // parameters in function-like macro expansions.
1473    while (Tok.isNot(tok::eod)) {
1474      LastTok = Tok;
1475
1476      if (Tok.isNot(tok::hash)) {
1477        MI->AddTokenToBody(Tok);
1478
1479        // Get the next token of the macro.
1480        LexUnexpandedToken(Tok);
1481        continue;
1482      }
1483
1484      // Get the next token of the macro.
1485      LexUnexpandedToken(Tok);
1486
1487      // Check for a valid macro arg identifier.
1488      if (Tok.getIdentifierInfo() == 0 ||
1489          MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1490
1491        // If this is assembler-with-cpp mode, we accept random gibberish after
1492        // the '#' because '#' is often a comment character.  However, change
1493        // the kind of the token to tok::unknown so that the preprocessor isn't
1494        // confused.
1495        if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
1496          LastTok.setKind(tok::unknown);
1497        } else {
1498          Diag(Tok, diag::err_pp_stringize_not_parameter);
1499          ReleaseMacroInfo(MI);
1500
1501          // Disable __VA_ARGS__ again.
1502          Ident__VA_ARGS__->setIsPoisoned(true);
1503          return;
1504        }
1505      }
1506
1507      // Things look ok, add the '#' and param name tokens to the macro.
1508      MI->AddTokenToBody(LastTok);
1509      MI->AddTokenToBody(Tok);
1510      LastTok = Tok;
1511
1512      // Get the next token of the macro.
1513      LexUnexpandedToken(Tok);
1514    }
1515  }
1516
1517
1518  // Disable __VA_ARGS__ again.
1519  Ident__VA_ARGS__->setIsPoisoned(true);
1520
1521  // Check that there is no paste (##) operator at the beginning or end of the
1522  // replacement list.
1523  unsigned NumTokens = MI->getNumTokens();
1524  if (NumTokens != 0) {
1525    if (MI->getReplacementToken(0).is(tok::hashhash)) {
1526      Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
1527      ReleaseMacroInfo(MI);
1528      return;
1529    }
1530    if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1531      Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
1532      ReleaseMacroInfo(MI);
1533      return;
1534    }
1535  }
1536
1537  MI->setDefinitionEndLoc(LastTok.getLocation());
1538
1539  // Finally, if this identifier already had a macro defined for it, verify that
1540  // the macro bodies are identical and free the old definition.
1541  if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
1542    // It is very common for system headers to have tons of macro redefinitions
1543    // and for warnings to be disabled in system headers.  If this is the case,
1544    // then don't bother calling MacroInfo::isIdenticalTo.
1545    if (!getDiagnostics().getSuppressSystemWarnings() ||
1546        !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1547      if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
1548        Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1549
1550      // Macros must be identical.  This means all tokens and whitespace
1551      // separation must be the same.  C99 6.10.3.2.
1552      if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1553          !MI->isIdenticalTo(*OtherMI, *this)) {
1554        Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1555          << MacroNameTok.getIdentifierInfo();
1556        Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1557      }
1558    }
1559    if (OtherMI->isWarnIfUnused())
1560      WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
1561    ReleaseMacroInfo(OtherMI);
1562  }
1563
1564  setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1565
1566  assert(!MI->isUsed());
1567  // If we need warning for not using the macro, add its location in the
1568  // warn-because-unused-macro set. If it gets used it will be removed from set.
1569  if (isInPrimaryFile() && // don't warn for include'd macros.
1570      Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1571                               MI->getDefinitionLoc()) != Diagnostic::Ignored) {
1572    MI->setIsWarnIfUnused(true);
1573    WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1574  }
1575
1576  // If the callbacks want to know, tell them about the macro definition.
1577  if (Callbacks)
1578    Callbacks->MacroDefined(MacroNameTok, MI);
1579}
1580
1581/// HandleUndefDirective - Implements #undef.
1582///
1583void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1584  ++NumUndefined;
1585
1586  Token MacroNameTok;
1587  ReadMacroName(MacroNameTok, 2);
1588
1589  // Error reading macro name?  If so, diagnostic already issued.
1590  if (MacroNameTok.is(tok::eod))
1591    return;
1592
1593  // Check to see if this is the last token on the #undef line.
1594  CheckEndOfDirective("undef");
1595
1596  // Okay, we finally have a valid identifier to undef.
1597  MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1598
1599  // If the macro is not defined, this is a noop undef, just return.
1600  if (MI == 0) return;
1601
1602  if (!MI->isUsed())
1603    Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1604
1605  // If the callbacks want to know, tell them about the macro #undef.
1606  if (Callbacks)
1607    Callbacks->MacroUndefined(MacroNameTok, MI);
1608
1609  if (MI->isWarnIfUnused())
1610    WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1611
1612  // Free macro definition.
1613  ReleaseMacroInfo(MI);
1614  setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1615}
1616
1617
1618//===----------------------------------------------------------------------===//
1619// Preprocessor Conditional Directive Handling.
1620//===----------------------------------------------------------------------===//
1621
1622/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive.  isIfndef is
1623/// true when this is a #ifndef directive.  ReadAnyTokensBeforeDirective is true
1624/// if any tokens have been returned or pp-directives activated before this
1625/// #ifndef has been lexed.
1626///
1627void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1628                                        bool ReadAnyTokensBeforeDirective) {
1629  ++NumIf;
1630  Token DirectiveTok = Result;
1631
1632  Token MacroNameTok;
1633  ReadMacroName(MacroNameTok);
1634
1635  // Error reading macro name?  If so, diagnostic already issued.
1636  if (MacroNameTok.is(tok::eod)) {
1637    // Skip code until we get to #endif.  This helps with recovery by not
1638    // emitting an error when the #endif is reached.
1639    SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1640                                 /*Foundnonskip*/false, /*FoundElse*/false);
1641    return;
1642  }
1643
1644  // Check to see if this is the last token on the #if[n]def line.
1645  CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
1646
1647  IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1648  MacroInfo *MI = getMacroInfo(MII);
1649
1650  if (CurPPLexer->getConditionalStackDepth() == 0) {
1651    // If the start of a top-level #ifdef and if the macro is not defined,
1652    // inform MIOpt that this might be the start of a proper include guard.
1653    // Otherwise it is some other form of unknown conditional which we can't
1654    // handle.
1655    if (!ReadAnyTokensBeforeDirective && MI == 0) {
1656      assert(isIfndef && "#ifdef shouldn't reach here");
1657      CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
1658    } else
1659      CurPPLexer->MIOpt.EnterTopLevelConditional();
1660  }
1661
1662  // If there is a macro, process it.
1663  if (MI)  // Mark it used.
1664    markMacroAsUsed(MI);
1665
1666  // Should we include the stuff contained by this directive?
1667  if (!MI == isIfndef) {
1668    // Yes, remember that we are inside a conditional, then lex the next token.
1669    CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1670                                     /*wasskip*/false, /*foundnonskip*/true,
1671                                     /*foundelse*/false);
1672  } else {
1673    // No, skip the contents of this block.
1674    SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1675                                 /*Foundnonskip*/false,
1676                                 /*FoundElse*/false);
1677  }
1678
1679  if (Callbacks) {
1680    if (isIfndef)
1681      Callbacks->Ifndef(MacroNameTok);
1682    else
1683      Callbacks->Ifdef(MacroNameTok);
1684  }
1685}
1686
1687/// HandleIfDirective - Implements the #if directive.
1688///
1689void Preprocessor::HandleIfDirective(Token &IfToken,
1690                                     bool ReadAnyTokensBeforeDirective) {
1691  ++NumIf;
1692
1693  // Parse and evaluate the conditional expression.
1694  IdentifierInfo *IfNDefMacro = 0;
1695  const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1696  const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1697  const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1698
1699  // If this condition is equivalent to #ifndef X, and if this is the first
1700  // directive seen, handle it for the multiple-include optimization.
1701  if (CurPPLexer->getConditionalStackDepth() == 0) {
1702    if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
1703      CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1704    else
1705      CurPPLexer->MIOpt.EnterTopLevelConditional();
1706  }
1707
1708  // Should we include the stuff contained by this directive?
1709  if (ConditionalTrue) {
1710    // Yes, remember that we are inside a conditional, then lex the next token.
1711    CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
1712                                   /*foundnonskip*/true, /*foundelse*/false);
1713  } else {
1714    // No, skip the contents of this block.
1715    SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1716                                 /*FoundElse*/false);
1717  }
1718
1719  if (Callbacks)
1720    Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
1721}
1722
1723/// HandleEndifDirective - Implements the #endif directive.
1724///
1725void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1726  ++NumEndif;
1727
1728  // Check that this is the whole directive.
1729  CheckEndOfDirective("endif");
1730
1731  PPConditionalInfo CondInfo;
1732  if (CurPPLexer->popConditionalLevel(CondInfo)) {
1733    // No conditionals on the stack: this is an #endif without an #if.
1734    Diag(EndifToken, diag::err_pp_endif_without_if);
1735    return;
1736  }
1737
1738  // If this the end of a top-level #endif, inform MIOpt.
1739  if (CurPPLexer->getConditionalStackDepth() == 0)
1740    CurPPLexer->MIOpt.ExitTopLevelConditional();
1741
1742  assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
1743         "This code should only be reachable in the non-skipping case!");
1744
1745  if (Callbacks)
1746    Callbacks->Endif();
1747}
1748
1749/// HandleElseDirective - Implements the #else directive.
1750///
1751void Preprocessor::HandleElseDirective(Token &Result) {
1752  ++NumElse;
1753
1754  // #else directive in a non-skipping conditional... start skipping.
1755  CheckEndOfDirective("else");
1756
1757  PPConditionalInfo CI;
1758  if (CurPPLexer->popConditionalLevel(CI)) {
1759    Diag(Result, diag::pp_err_else_without_if);
1760    return;
1761  }
1762
1763  // If this is a top-level #else, inform the MIOpt.
1764  if (CurPPLexer->getConditionalStackDepth() == 0)
1765    CurPPLexer->MIOpt.EnterTopLevelConditional();
1766
1767  // If this is a #else with a #else before it, report the error.
1768  if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1769
1770  // Finally, skip the rest of the contents of this block.
1771  SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1772                               /*FoundElse*/true);
1773
1774  if (Callbacks)
1775    Callbacks->Else();
1776}
1777
1778/// HandleElifDirective - Implements the #elif directive.
1779///
1780void Preprocessor::HandleElifDirective(Token &ElifToken) {
1781  ++NumElse;
1782
1783  // #elif directive in a non-skipping conditional... start skipping.
1784  // We don't care what the condition is, because we will always skip it (since
1785  // the block immediately before it was included).
1786  const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1787  DiscardUntilEndOfDirective();
1788  const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1789
1790  PPConditionalInfo CI;
1791  if (CurPPLexer->popConditionalLevel(CI)) {
1792    Diag(ElifToken, diag::pp_err_elif_without_if);
1793    return;
1794  }
1795
1796  // If this is a top-level #elif, inform the MIOpt.
1797  if (CurPPLexer->getConditionalStackDepth() == 0)
1798    CurPPLexer->MIOpt.EnterTopLevelConditional();
1799
1800  // If this is a #elif with a #else before it, report the error.
1801  if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1802
1803  // Finally, skip the rest of the contents of this block.
1804  SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1805                               /*FoundElse*/CI.FoundElse);
1806
1807  if (Callbacks)
1808    Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
1809}
1810