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