]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Lex/Lexer.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303197, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Lex / Lexer.cpp
1 //===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
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 the Lexer and Token interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Lex/Lexer.h"
15 #include "UnicodeCharSets.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/ConvertUTF.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/UnicodeCharRanges.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <cstring>
34 #include <string>
35 #include <tuple>
36 #include <utility>
37
38 using namespace clang;
39
40 //===----------------------------------------------------------------------===//
41 // Token Class Implementation
42 //===----------------------------------------------------------------------===//
43
44 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
45 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
46   if (IdentifierInfo *II = getIdentifierInfo())
47     return II->getObjCKeywordID() == objcKey;
48   return false;
49 }
50
51 /// getObjCKeywordID - Return the ObjC keyword kind.
52 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53   IdentifierInfo *specId = getIdentifierInfo();
54   return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
55 }
56
57 //===----------------------------------------------------------------------===//
58 // Lexer Class Implementation
59 //===----------------------------------------------------------------------===//
60
61 void Lexer::anchor() { }
62
63 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
64                       const char *BufEnd) {
65   BufferStart = BufStart;
66   BufferPtr = BufPtr;
67   BufferEnd = BufEnd;
68
69   assert(BufEnd[0] == 0 &&
70          "We assume that the input buffer has a null character at the end"
71          " to simplify lexing!");
72
73   // Check whether we have a BOM in the beginning of the buffer. If yes - act
74   // accordingly. Right now we support only UTF-8 with and without BOM, so, just
75   // skip the UTF-8 BOM if it's present.
76   if (BufferStart == BufferPtr) {
77     // Determine the size of the BOM.
78     StringRef Buf(BufferStart, BufferEnd - BufferStart);
79     size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
80       .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
81       .Default(0);
82
83     // Skip the BOM.
84     BufferPtr += BOMLength;
85   }
86
87   Is_PragmaLexer = false;
88   CurrentConflictMarkerState = CMK_None;
89
90   // Start of the file is a start of line.
91   IsAtStartOfLine = true;
92   IsAtPhysicalStartOfLine = true;
93
94   HasLeadingSpace = false;
95   HasLeadingEmptyMacro = false;
96
97   // We are not after parsing a #.
98   ParsingPreprocessorDirective = false;
99
100   // We are not after parsing #include.
101   ParsingFilename = false;
102
103   // We are not in raw mode.  Raw mode disables diagnostics and interpretation
104   // of tokens (e.g. identifiers, thus disabling macro expansion).  It is used
105   // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106   // or otherwise skipping over tokens.
107   LexingRawMode = false;
108
109   // Default to not keeping comments.
110   ExtendedTokenMode = 0;
111 }
112
113 /// Lexer constructor - Create a new lexer object for the specified buffer
114 /// with the specified preprocessor managing the lexing process.  This lexer
115 /// assumes that the associated file buffer and Preprocessor objects will
116 /// outlive it, so it doesn't take ownership of either of them.
117 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
118   : PreprocessorLexer(&PP, FID),
119     FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
120     LangOpts(PP.getLangOpts()) {
121
122   InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123             InputFile->getBufferEnd());
124
125   resetExtendedTokenMode();
126 }
127
128 void Lexer::resetExtendedTokenMode() {
129   assert(PP && "Cannot reset token mode without a preprocessor");
130   if (LangOpts.TraditionalCPP)
131     SetKeepWhitespaceMode(true);
132   else
133     SetCommentRetentionState(PP->getCommentRetentionState());
134 }
135
136 /// Lexer constructor - Create a new raw lexer object.  This object is only
137 /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
138 /// range will outlive it, so it doesn't take ownership of it.
139 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
140              const char *BufStart, const char *BufPtr, const char *BufEnd)
141   : FileLoc(fileloc), LangOpts(langOpts) {
142
143   InitLexer(BufStart, BufPtr, BufEnd);
144
145   // We *are* in raw mode.
146   LexingRawMode = true;
147 }
148
149 /// Lexer constructor - Create a new raw lexer object.  This object is only
150 /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
151 /// range will outlive it, so it doesn't take ownership of it.
152 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
153              const SourceManager &SM, const LangOptions &langOpts)
154     : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
155             FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
156
157 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
158 /// _Pragma expansion.  This has a variety of magic semantics that this method
159 /// sets up.  It returns a new'd Lexer that must be delete'd when done.
160 ///
161 /// On entrance to this routine, TokStartLoc is a macro location which has a
162 /// spelling loc that indicates the bytes to be lexed for the token and an
163 /// expansion location that indicates where all lexed tokens should be
164 /// "expanded from".
165 ///
166 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
167 /// normal lexer that remaps tokens as they fly by.  This would require making
168 /// Preprocessor::Lex virtual.  Given that, we could just dump in a magic lexer
169 /// interface that could handle this stuff.  This would pull GetMappedTokenLoc
170 /// out of the critical path of the lexer!
171 ///
172 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
173                                  SourceLocation ExpansionLocStart,
174                                  SourceLocation ExpansionLocEnd,
175                                  unsigned TokLen, Preprocessor &PP) {
176   SourceManager &SM = PP.getSourceManager();
177
178   // Create the lexer as if we were going to lex the file normally.
179   FileID SpellingFID = SM.getFileID(SpellingLoc);
180   const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
181   Lexer *L = new Lexer(SpellingFID, InputFile, PP);
182
183   // Now that the lexer is created, change the start/end locations so that we
184   // just lex the subsection of the file that we want.  This is lexing from a
185   // scratch buffer.
186   const char *StrData = SM.getCharacterData(SpellingLoc);
187
188   L->BufferPtr = StrData;
189   L->BufferEnd = StrData+TokLen;
190   assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
191
192   // Set the SourceLocation with the remapping information.  This ensures that
193   // GetMappedTokenLoc will remap the tokens as they are lexed.
194   L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
195                                      ExpansionLocStart,
196                                      ExpansionLocEnd, TokLen);
197
198   // Ensure that the lexer thinks it is inside a directive, so that end \n will
199   // return an EOD token.
200   L->ParsingPreprocessorDirective = true;
201
202   // This lexer really is for _Pragma.
203   L->Is_PragmaLexer = true;
204   return L;
205 }
206
207 /// Stringify - Convert the specified string into a C string, with surrounding
208 /// ""'s, and with escaped \ and " characters.
209 std::string Lexer::Stringify(StringRef Str, bool Charify) {
210   std::string Result = Str;
211   char Quote = Charify ? '\'' : '"';
212   for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213     if (Result[i] == '\\' || Result[i] == Quote) {
214       Result.insert(Result.begin()+i, '\\');
215       ++i; ++e;
216     }
217   }
218   return Result;
219 }
220
221 /// Stringify - Convert the specified string into a C string by escaping '\'
222 /// and " characters.  This does not add surrounding ""'s to the string.
223 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
224   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225     if (Str[i] == '\\' || Str[i] == '"') {
226       Str.insert(Str.begin()+i, '\\');
227       ++i; ++e;
228     }
229   }
230 }
231
232 //===----------------------------------------------------------------------===//
233 // Token Spelling
234 //===----------------------------------------------------------------------===//
235
236 /// \brief Slow case of getSpelling. Extract the characters comprising the
237 /// spelling of this token from the provided input buffer.
238 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239                               const LangOptions &LangOpts, char *Spelling) {
240   assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
241
242   size_t Length = 0;
243   const char *BufEnd = BufPtr + Tok.getLength();
244
245   if (tok::isStringLiteral(Tok.getKind())) {
246     // Munch the encoding-prefix and opening double-quote.
247     while (BufPtr < BufEnd) {
248       unsigned Size;
249       Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
250       BufPtr += Size;
251
252       if (Spelling[Length - 1] == '"')
253         break;
254     }
255
256     // Raw string literals need special handling; trigraph expansion and line
257     // splicing do not occur within their d-char-sequence nor within their
258     // r-char-sequence.
259     if (Length >= 2 &&
260         Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261       // Search backwards from the end of the token to find the matching closing
262       // quote.
263       const char *RawEnd = BufEnd;
264       do --RawEnd; while (*RawEnd != '"');
265       size_t RawLength = RawEnd - BufPtr + 1;
266
267       // Everything between the quotes is included verbatim in the spelling.
268       memcpy(Spelling + Length, BufPtr, RawLength);
269       Length += RawLength;
270       BufPtr += RawLength;
271
272       // The rest of the token is lexed normally.
273     }
274   }
275
276   while (BufPtr < BufEnd) {
277     unsigned Size;
278     Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
279     BufPtr += Size;
280   }
281
282   assert(Length < Tok.getLength() &&
283          "NeedsCleaning flag set on token that didn't need cleaning!");
284   return Length;
285 }
286
287 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
288 /// token are the characters used to represent the token in the source file
289 /// after trigraph expansion and escaped-newline folding.  In particular, this
290 /// wants to get the true, uncanonicalized, spelling of things like digraphs
291 /// UCNs, etc.
292 StringRef Lexer::getSpelling(SourceLocation loc,
293                              SmallVectorImpl<char> &buffer,
294                              const SourceManager &SM,
295                              const LangOptions &options,
296                              bool *invalid) {
297   // Break down the source location.
298   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
299
300   // Try to the load the file buffer.
301   bool invalidTemp = false;
302   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
303   if (invalidTemp) {
304     if (invalid) *invalid = true;
305     return StringRef();
306   }
307
308   const char *tokenBegin = file.data() + locInfo.second;
309
310   // Lex from the start of the given location.
311   Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312               file.begin(), tokenBegin, file.end());
313   Token token;
314   lexer.LexFromRawLexer(token);
315
316   unsigned length = token.getLength();
317
318   // Common case:  no need for cleaning.
319   if (!token.needsCleaning())
320     return StringRef(tokenBegin, length);
321
322   // Hard case, we need to relex the characters into the string.
323   buffer.resize(length);
324   buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
325   return StringRef(buffer.data(), buffer.size());
326 }
327
328 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
329 /// token are the characters used to represent the token in the source file
330 /// after trigraph expansion and escaped-newline folding.  In particular, this
331 /// wants to get the true, uncanonicalized, spelling of things like digraphs
332 /// UCNs, etc.
333 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
334                                const LangOptions &LangOpts, bool *Invalid) {
335   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
336
337   bool CharDataInvalid = false;
338   const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
339                                                     &CharDataInvalid);
340   if (Invalid)
341     *Invalid = CharDataInvalid;
342   if (CharDataInvalid)
343     return std::string();
344
345   // If this token contains nothing interesting, return it directly.
346   if (!Tok.needsCleaning())
347     return std::string(TokStart, TokStart + Tok.getLength());
348
349   std::string Result;
350   Result.resize(Tok.getLength());
351   Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
352   return Result;
353 }
354
355 /// getSpelling - This method is used to get the spelling of a token into a
356 /// preallocated buffer, instead of as an std::string.  The caller is required
357 /// to allocate enough space for the token, which is guaranteed to be at least
358 /// Tok.getLength() bytes long.  The actual length of the token is returned.
359 ///
360 /// Note that this method may do two possible things: it may either fill in
361 /// the buffer specified with characters, or it may *change the input pointer*
362 /// to point to a constant buffer with the data already in it (avoiding a
363 /// copy).  The caller is not allowed to modify the returned buffer pointer
364 /// if an internal buffer is returned.
365 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer, 
366                             const SourceManager &SourceMgr,
367                             const LangOptions &LangOpts, bool *Invalid) {
368   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
369
370   const char *TokStart = nullptr;
371   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372   if (Tok.is(tok::raw_identifier))
373     TokStart = Tok.getRawIdentifier().data();
374   else if (!Tok.hasUCN()) {
375     if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
376       // Just return the string from the identifier table, which is very quick.
377       Buffer = II->getNameStart();
378       return II->getLength();
379     }
380   }
381
382   // NOTE: this can be checked even after testing for an IdentifierInfo.
383   if (Tok.isLiteral())
384     TokStart = Tok.getLiteralData();
385
386   if (!TokStart) {
387     // Compute the start of the token in the input lexer buffer.
388     bool CharDataInvalid = false;
389     TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
390     if (Invalid)
391       *Invalid = CharDataInvalid;
392     if (CharDataInvalid) {
393       Buffer = "";
394       return 0;
395     }
396   }
397
398   // If this token contains nothing interesting, return it directly.
399   if (!Tok.needsCleaning()) {
400     Buffer = TokStart;
401     return Tok.getLength();
402   }
403
404   // Otherwise, hard case, relex the characters into the string.
405   return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
406 }
407
408 /// MeasureTokenLength - Relex the token at the specified location and return
409 /// its length in bytes in the input file.  If the token needs cleaning (e.g.
410 /// includes a trigraph or an escaped newline) then this count includes bytes
411 /// that are part of that.
412 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
413                                    const SourceManager &SM,
414                                    const LangOptions &LangOpts) {
415   Token TheTok;
416   if (getRawToken(Loc, TheTok, SM, LangOpts))
417     return 0;
418   return TheTok.getLength();
419 }
420
421 /// \brief Relex the token at the specified location.
422 /// \returns true if there was a failure, false on success.
423 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
424                         const SourceManager &SM,
425                         const LangOptions &LangOpts,
426                         bool IgnoreWhiteSpace) {
427   // TODO: this could be special cased for common tokens like identifiers, ')',
428   // etc to make this faster, if it mattered.  Just look at StrData[0] to handle
429   // all obviously single-char tokens.  This could use
430   // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
431   // something.
432
433   // If this comes from a macro expansion, we really do want the macro name, not
434   // the token this macro expanded to.
435   Loc = SM.getExpansionLoc(Loc);
436   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
437   bool Invalid = false;
438   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
439   if (Invalid)
440     return true;
441
442   const char *StrData = Buffer.data()+LocInfo.second;
443
444   if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
445     return true;
446
447   // Create a lexer starting at the beginning of this token.
448   Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449                  Buffer.begin(), StrData, Buffer.end());
450   TheLexer.SetCommentRetentionState(true);
451   TheLexer.LexFromRawLexer(Result);
452   return false;
453 }
454
455 /// Returns the pointer that points to the beginning of line that contains
456 /// the given offset, or null if the offset if invalid.
457 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
458   const char *BufStart = Buffer.data();
459   if (Offset >= Buffer.size())
460     return nullptr;
461   const char *StrData = BufStart + Offset;
462
463   if (StrData[0] == '\n' || StrData[0] == '\r')
464     return StrData;
465
466   const char *LexStart = StrData;
467   while (LexStart != BufStart) {
468     if (LexStart[0] == '\n' || LexStart[0] == '\r') {
469       ++LexStart;
470       break;
471     }
472
473     --LexStart;
474   }
475   return LexStart;
476 }
477
478 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
479                                               const SourceManager &SM,
480                                               const LangOptions &LangOpts) {
481   assert(Loc.isFileID());
482   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
483   if (LocInfo.first.isInvalid())
484     return Loc;
485   
486   bool Invalid = false;
487   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
488   if (Invalid)
489     return Loc;
490
491   // Back up from the current location until we hit the beginning of a line
492   // (or the buffer). We'll relex from that point.
493   const char *StrData = Buffer.data() + LocInfo.second;
494   const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
495   if (!LexStart || LexStart == StrData)
496     return Loc;
497   
498   // Create a lexer starting at the beginning of this token.
499   SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
500   Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
501                  Buffer.end());
502   TheLexer.SetCommentRetentionState(true);
503   
504   // Lex tokens until we find the token that contains the source location.
505   Token TheTok;
506   do {
507     TheLexer.LexFromRawLexer(TheTok);
508     
509     if (TheLexer.getBufferLocation() > StrData) {
510       // Lexing this token has taken the lexer past the source location we're
511       // looking for. If the current token encompasses our source location,
512       // return the beginning of that token.
513       if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
514         return TheTok.getLocation();
515       
516       // We ended up skipping over the source location entirely, which means
517       // that it points into whitespace. We're done here.
518       break;
519     }
520   } while (TheTok.getKind() != tok::eof);
521   
522   // We've passed our source location; just return the original source location.
523   return Loc;
524 }
525
526 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
527                                           const SourceManager &SM,
528                                           const LangOptions &LangOpts) {
529  if (Loc.isFileID())
530    return getBeginningOfFileToken(Loc, SM, LangOpts);
531  
532  if (!SM.isMacroArgExpansion(Loc))
533    return Loc;
534
535  SourceLocation FileLoc = SM.getSpellingLoc(Loc);
536  SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
537  std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
538  std::pair<FileID, unsigned> BeginFileLocInfo
539    = SM.getDecomposedLoc(BeginFileLoc);
540  assert(FileLocInfo.first == BeginFileLocInfo.first &&
541         FileLocInfo.second >= BeginFileLocInfo.second);
542  return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
543 }
544
545 namespace {
546
547   enum PreambleDirectiveKind {
548     PDK_Skipped,
549     PDK_StartIf,
550     PDK_EndIf,
551     PDK_Unknown
552   };
553
554 } // end anonymous namespace
555
556 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
557                                                  const LangOptions &LangOpts,
558                                                  unsigned MaxLines) {
559   // Create a lexer starting at the beginning of the file. Note that we use a
560   // "fake" file source location at offset 1 so that the lexer will track our
561   // position within the file.
562   const unsigned StartOffset = 1;
563   SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
564   Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
565                  Buffer.end());
566   TheLexer.SetCommentRetentionState(true);
567
568   // StartLoc will differ from FileLoc if there is a BOM that was skipped.
569   SourceLocation StartLoc = TheLexer.getSourceLocation();
570
571   bool InPreprocessorDirective = false;
572   Token TheTok;
573   Token IfStartTok;
574   unsigned IfCount = 0;
575   SourceLocation ActiveCommentLoc;
576
577   unsigned MaxLineOffset = 0;
578   if (MaxLines) {
579     const char *CurPtr = Buffer.begin();
580     unsigned CurLine = 0;
581     while (CurPtr != Buffer.end()) {
582       char ch = *CurPtr++;
583       if (ch == '\n') {
584         ++CurLine;
585         if (CurLine == MaxLines)
586           break;
587       }
588     }
589     if (CurPtr != Buffer.end())
590       MaxLineOffset = CurPtr - Buffer.begin();
591   }
592
593   do {
594     TheLexer.LexFromRawLexer(TheTok);
595
596     if (InPreprocessorDirective) {
597       // If we've hit the end of the file, we're done.
598       if (TheTok.getKind() == tok::eof) {
599         break;
600       }
601       
602       // If we haven't hit the end of the preprocessor directive, skip this
603       // token.
604       if (!TheTok.isAtStartOfLine())
605         continue;
606         
607       // We've passed the end of the preprocessor directive, and will look
608       // at this token again below.
609       InPreprocessorDirective = false;
610     }
611     
612     // Keep track of the # of lines in the preamble.
613     if (TheTok.isAtStartOfLine()) {
614       unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
615
616       // If we were asked to limit the number of lines in the preamble,
617       // and we're about to exceed that limit, we're done.
618       if (MaxLineOffset && TokOffset >= MaxLineOffset)
619         break;
620     }
621
622     // Comments are okay; skip over them.
623     if (TheTok.getKind() == tok::comment) {
624       if (ActiveCommentLoc.isInvalid())
625         ActiveCommentLoc = TheTok.getLocation();
626       continue;
627     }
628     
629     if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
630       // This is the start of a preprocessor directive. 
631       Token HashTok = TheTok;
632       InPreprocessorDirective = true;
633       ActiveCommentLoc = SourceLocation();
634       
635       // Figure out which directive this is. Since we're lexing raw tokens,
636       // we don't have an identifier table available. Instead, just look at
637       // the raw identifier to recognize and categorize preprocessor directives.
638       TheLexer.LexFromRawLexer(TheTok);
639       if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
640         StringRef Keyword = TheTok.getRawIdentifier();
641         PreambleDirectiveKind PDK
642           = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
643               .Case("include", PDK_Skipped)
644               .Case("__include_macros", PDK_Skipped)
645               .Case("define", PDK_Skipped)
646               .Case("undef", PDK_Skipped)
647               .Case("line", PDK_Skipped)
648               .Case("error", PDK_Skipped)
649               .Case("pragma", PDK_Skipped)
650               .Case("import", PDK_Skipped)
651               .Case("include_next", PDK_Skipped)
652               .Case("warning", PDK_Skipped)
653               .Case("ident", PDK_Skipped)
654               .Case("sccs", PDK_Skipped)
655               .Case("assert", PDK_Skipped)
656               .Case("unassert", PDK_Skipped)
657               .Case("if", PDK_StartIf)
658               .Case("ifdef", PDK_StartIf)
659               .Case("ifndef", PDK_StartIf)
660               .Case("elif", PDK_Skipped)
661               .Case("else", PDK_Skipped)
662               .Case("endif", PDK_EndIf)
663               .Default(PDK_Unknown);
664
665         switch (PDK) {
666         case PDK_Skipped:
667           continue;
668
669         case PDK_StartIf:
670           if (IfCount == 0)
671             IfStartTok = HashTok;
672             
673           ++IfCount;
674           continue;
675             
676         case PDK_EndIf:
677           // Mismatched #endif. The preamble ends here.
678           if (IfCount == 0)
679             break;
680
681           --IfCount;
682           continue;
683             
684         case PDK_Unknown:
685           // We don't know what this directive is; stop at the '#'.
686           break;
687         }
688       }
689       
690       // We only end up here if we didn't recognize the preprocessor
691       // directive or it was one that can't occur in the preamble at this
692       // point. Roll back the current token to the location of the '#'.
693       InPreprocessorDirective = false;
694       TheTok = HashTok;
695     }
696
697     // We hit a token that we don't recognize as being in the
698     // "preprocessing only" part of the file, so we're no longer in
699     // the preamble.
700     break;
701   } while (true);
702   
703   SourceLocation End;
704   if (IfCount)
705     End = IfStartTok.getLocation();
706   else if (ActiveCommentLoc.isValid())
707     End = ActiveCommentLoc; // don't truncate a decl comment.
708   else
709     End = TheTok.getLocation();
710
711   return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
712                         IfCount? IfStartTok.isAtStartOfLine()
713                                : TheTok.isAtStartOfLine());
714 }
715
716 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
717 /// token, return a new location that specifies a character within the token.
718 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
719                                               unsigned CharNo,
720                                               const SourceManager &SM,
721                                               const LangOptions &LangOpts) {
722   // Figure out how many physical characters away the specified expansion
723   // character is.  This needs to take into consideration newlines and
724   // trigraphs.
725   bool Invalid = false;
726   const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
727   
728   // If they request the first char of the token, we're trivially done.
729   if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
730     return TokStart;
731   
732   unsigned PhysOffset = 0;
733   
734   // The usual case is that tokens don't contain anything interesting.  Skip
735   // over the uninteresting characters.  If a token only consists of simple
736   // chars, this method is extremely fast.
737   while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
738     if (CharNo == 0)
739       return TokStart.getLocWithOffset(PhysOffset);
740     ++TokPtr;
741     --CharNo;
742     ++PhysOffset;
743   }
744   
745   // If we have a character that may be a trigraph or escaped newline, use a
746   // lexer to parse it correctly.
747   for (; CharNo; --CharNo) {
748     unsigned Size;
749     Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
750     TokPtr += Size;
751     PhysOffset += Size;
752   }
753   
754   // Final detail: if we end up on an escaped newline, we want to return the
755   // location of the actual byte of the token.  For example foo\<newline>bar
756   // advanced by 3 should return the location of b, not of \\.  One compounding
757   // detail of this is that the escape may be made by a trigraph.
758   if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
759     PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
760   
761   return TokStart.getLocWithOffset(PhysOffset);
762 }
763
764 /// \brief Computes the source location just past the end of the
765 /// token at this source location.
766 ///
767 /// This routine can be used to produce a source location that
768 /// points just past the end of the token referenced by \p Loc, and
769 /// is generally used when a diagnostic needs to point just after a
770 /// token where it expected something different that it received. If
771 /// the returned source location would not be meaningful (e.g., if
772 /// it points into a macro), this routine returns an invalid
773 /// source location.
774 ///
775 /// \param Offset an offset from the end of the token, where the source
776 /// location should refer to. The default offset (0) produces a source
777 /// location pointing just past the end of the token; an offset of 1 produces
778 /// a source location pointing to the last character in the token, etc.
779 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
780                                           const SourceManager &SM,
781                                           const LangOptions &LangOpts) {
782   if (Loc.isInvalid())
783     return SourceLocation();
784
785   if (Loc.isMacroID()) {
786     if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
787       return SourceLocation(); // Points inside the macro expansion.
788   }
789
790   unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
791   if (Len > Offset)
792     Len = Len - Offset;
793   else
794     return Loc;
795   
796   return Loc.getLocWithOffset(Len);
797 }
798
799 /// \brief Returns true if the given MacroID location points at the first
800 /// token of the macro expansion.
801 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
802                                       const SourceManager &SM,
803                                       const LangOptions &LangOpts,
804                                       SourceLocation *MacroBegin) {
805   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
806
807   SourceLocation expansionLoc;
808   if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
809     return false;
810
811   if (expansionLoc.isFileID()) {
812     // No other macro expansions, this is the first.
813     if (MacroBegin)
814       *MacroBegin = expansionLoc;
815     return true;
816   }
817
818   return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
819 }
820
821 /// \brief Returns true if the given MacroID location points at the last
822 /// token of the macro expansion.
823 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
824                                     const SourceManager &SM,
825                                     const LangOptions &LangOpts,
826                                     SourceLocation *MacroEnd) {
827   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
828
829   SourceLocation spellLoc = SM.getSpellingLoc(loc);
830   unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
831   if (tokLen == 0)
832     return false;
833
834   SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
835   SourceLocation expansionLoc;
836   if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
837     return false;
838
839   if (expansionLoc.isFileID()) {
840     // No other macro expansions.
841     if (MacroEnd)
842       *MacroEnd = expansionLoc;
843     return true;
844   }
845
846   return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
847 }
848
849 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
850                                              const SourceManager &SM,
851                                              const LangOptions &LangOpts) {
852   SourceLocation Begin = Range.getBegin();
853   SourceLocation End = Range.getEnd();
854   assert(Begin.isFileID() && End.isFileID());
855   if (Range.isTokenRange()) {
856     End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
857     if (End.isInvalid())
858       return CharSourceRange();
859   }
860
861   // Break down the source locations.
862   FileID FID;
863   unsigned BeginOffs;
864   std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
865   if (FID.isInvalid())
866     return CharSourceRange();
867
868   unsigned EndOffs;
869   if (!SM.isInFileID(End, FID, &EndOffs) ||
870       BeginOffs > EndOffs)
871     return CharSourceRange();
872
873   return CharSourceRange::getCharRange(Begin, End);
874 }
875
876 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
877                                          const SourceManager &SM,
878                                          const LangOptions &LangOpts) {
879   SourceLocation Begin = Range.getBegin();
880   SourceLocation End = Range.getEnd();
881   if (Begin.isInvalid() || End.isInvalid())
882     return CharSourceRange();
883
884   if (Begin.isFileID() && End.isFileID())
885     return makeRangeFromFileLocs(Range, SM, LangOpts);
886
887   if (Begin.isMacroID() && End.isFileID()) {
888     if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
889       return CharSourceRange();
890     Range.setBegin(Begin);
891     return makeRangeFromFileLocs(Range, SM, LangOpts);
892   }
893
894   if (Begin.isFileID() && End.isMacroID()) {
895     if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
896                                                           &End)) ||
897         (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
898                                                            &End)))
899       return CharSourceRange();
900     Range.setEnd(End);
901     return makeRangeFromFileLocs(Range, SM, LangOpts);
902   }
903
904   assert(Begin.isMacroID() && End.isMacroID());
905   SourceLocation MacroBegin, MacroEnd;
906   if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
907       ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
908                                                         &MacroEnd)) ||
909        (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
910                                                          &MacroEnd)))) {
911     Range.setBegin(MacroBegin);
912     Range.setEnd(MacroEnd);
913     return makeRangeFromFileLocs(Range, SM, LangOpts);
914   }
915
916   bool Invalid = false;
917   const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
918                                                         &Invalid);
919   if (Invalid)
920     return CharSourceRange();
921
922   if (BeginEntry.getExpansion().isMacroArgExpansion()) {
923     const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
924                                                         &Invalid);
925     if (Invalid)
926       return CharSourceRange();
927
928     if (EndEntry.getExpansion().isMacroArgExpansion() &&
929         BeginEntry.getExpansion().getExpansionLocStart() ==
930             EndEntry.getExpansion().getExpansionLocStart()) {
931       Range.setBegin(SM.getImmediateSpellingLoc(Begin));
932       Range.setEnd(SM.getImmediateSpellingLoc(End));
933       return makeFileCharRange(Range, SM, LangOpts);
934     }
935   }
936
937   return CharSourceRange();
938 }
939
940 StringRef Lexer::getSourceText(CharSourceRange Range,
941                                const SourceManager &SM,
942                                const LangOptions &LangOpts,
943                                bool *Invalid) {
944   Range = makeFileCharRange(Range, SM, LangOpts);
945   if (Range.isInvalid()) {
946     if (Invalid) *Invalid = true;
947     return StringRef();
948   }
949
950   // Break down the source location.
951   std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
952   if (beginInfo.first.isInvalid()) {
953     if (Invalid) *Invalid = true;
954     return StringRef();
955   }
956
957   unsigned EndOffs;
958   if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
959       beginInfo.second > EndOffs) {
960     if (Invalid) *Invalid = true;
961     return StringRef();
962   }
963
964   // Try to the load the file buffer.
965   bool invalidTemp = false;
966   StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
967   if (invalidTemp) {
968     if (Invalid) *Invalid = true;
969     return StringRef();
970   }
971
972   if (Invalid) *Invalid = false;
973   return file.substr(beginInfo.second, EndOffs - beginInfo.second);
974 }
975
976 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
977                                        const SourceManager &SM,
978                                        const LangOptions &LangOpts) {
979   assert(Loc.isMacroID() && "Only reasonble to call this on macros");
980
981   // Find the location of the immediate macro expansion.
982   while (true) {
983     FileID FID = SM.getFileID(Loc);
984     const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
985     const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
986     Loc = Expansion.getExpansionLocStart();
987     if (!Expansion.isMacroArgExpansion())
988       break;
989
990     // For macro arguments we need to check that the argument did not come
991     // from an inner macro, e.g: "MAC1( MAC2(foo) )"
992     
993     // Loc points to the argument id of the macro definition, move to the
994     // macro expansion.
995     Loc = SM.getImmediateExpansionRange(Loc).first;
996     SourceLocation SpellLoc = Expansion.getSpellingLoc();
997     if (SpellLoc.isFileID())
998       break; // No inner macro.
999
1000     // If spelling location resides in the same FileID as macro expansion
1001     // location, it means there is no inner macro.
1002     FileID MacroFID = SM.getFileID(Loc);
1003     if (SM.isInFileID(SpellLoc, MacroFID))
1004       break;
1005
1006     // Argument came from inner macro.
1007     Loc = SpellLoc;
1008   }
1009
1010   // Find the spelling location of the start of the non-argument expansion
1011   // range. This is where the macro name was spelled in order to begin
1012   // expanding this macro.
1013   Loc = SM.getSpellingLoc(Loc);
1014
1015   // Dig out the buffer where the macro name was spelled and the extents of the
1016   // name so that we can render it into the expansion note.
1017   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1018   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1019   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1020   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1021 }
1022
1023 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1024     SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1025   assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1026   // Walk past macro argument expanions.
1027   while (SM.isMacroArgExpansion(Loc))
1028     Loc = SM.getImmediateExpansionRange(Loc).first;
1029
1030   // If the macro's spelling has no FileID, then it's actually a token paste
1031   // or stringization (or similar) and not a macro at all.
1032   if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1033     return StringRef();
1034
1035   // Find the spelling location of the start of the non-argument expansion
1036   // range. This is where the macro name was spelled in order to begin
1037   // expanding this macro.
1038   Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1039
1040   // Dig out the buffer where the macro name was spelled and the extents of the
1041   // name so that we can render it into the expansion note.
1042   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1043   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1044   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1045   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1046 }
1047
1048 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1049   return isIdentifierBody(c, LangOpts.DollarIdents);
1050 }
1051
1052 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1053                                        const SourceManager &SM) {
1054   if (Loc.isInvalid() || Loc.isMacroID())
1055     return "";
1056   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1057   if (LocInfo.first.isInvalid())
1058     return "";
1059   bool Invalid = false;
1060   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1061   if (Invalid)
1062     return "";
1063   const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1064   if (!Line)
1065     return "";
1066   StringRef Rest = Buffer.substr(Line - Buffer.data());
1067   size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1068   return NumWhitespaceChars == StringRef::npos
1069              ? ""
1070              : Rest.take_front(NumWhitespaceChars);
1071 }
1072
1073 //===----------------------------------------------------------------------===//
1074 // Diagnostics forwarding code.
1075 //===----------------------------------------------------------------------===//
1076
1077 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1078 /// lexer buffer was all expanded at a single point, perform the mapping.
1079 /// This is currently only used for _Pragma implementation, so it is the slow
1080 /// path of the hot getSourceLocation method.  Do not allow it to be inlined.
1081 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1082     Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1083 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1084                                         SourceLocation FileLoc,
1085                                         unsigned CharNo, unsigned TokLen) {
1086   assert(FileLoc.isMacroID() && "Must be a macro expansion");
1087
1088   // Otherwise, we're lexing "mapped tokens".  This is used for things like
1089   // _Pragma handling.  Combine the expansion location of FileLoc with the
1090   // spelling location.
1091   SourceManager &SM = PP.getSourceManager();
1092
1093   // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1094   // characters come from spelling(FileLoc)+Offset.
1095   SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1096   SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1097
1098   // Figure out the expansion loc range, which is the range covered by the
1099   // original _Pragma(...) sequence.
1100   std::pair<SourceLocation,SourceLocation> II =
1101     SM.getImmediateExpansionRange(FileLoc);
1102
1103   return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1104 }
1105
1106 /// getSourceLocation - Return a source location identifier for the specified
1107 /// offset in the current file.
1108 SourceLocation Lexer::getSourceLocation(const char *Loc,
1109                                         unsigned TokLen) const {
1110   assert(Loc >= BufferStart && Loc <= BufferEnd &&
1111          "Location out of range for this buffer!");
1112
1113   // In the normal case, we're just lexing from a simple file buffer, return
1114   // the file id from FileLoc with the offset specified.
1115   unsigned CharNo = Loc-BufferStart;
1116   if (FileLoc.isFileID())
1117     return FileLoc.getLocWithOffset(CharNo);
1118
1119   // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1120   // tokens are lexed from where the _Pragma was defined.
1121   assert(PP && "This doesn't work on raw lexers");
1122   return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1123 }
1124
1125 /// Diag - Forwarding function for diagnostics.  This translate a source
1126 /// position in the current buffer into a SourceLocation object for rendering.
1127 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1128   return PP->Diag(getSourceLocation(Loc), DiagID);
1129 }
1130
1131 //===----------------------------------------------------------------------===//
1132 // Trigraph and Escaped Newline Handling Code.
1133 //===----------------------------------------------------------------------===//
1134
1135 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1136 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1137 static char GetTrigraphCharForLetter(char Letter) {
1138   switch (Letter) {
1139   default:   return 0;
1140   case '=':  return '#';
1141   case ')':  return ']';
1142   case '(':  return '[';
1143   case '!':  return '|';
1144   case '\'': return '^';
1145   case '>':  return '}';
1146   case '/':  return '\\';
1147   case '<':  return '{';
1148   case '-':  return '~';
1149   }
1150 }
1151
1152 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1153 /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
1154 /// return the result character.  Finally, emit a warning about trigraph use
1155 /// whether trigraphs are enabled or not.
1156 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1157   char Res = GetTrigraphCharForLetter(*CP);
1158   if (!Res || !L) return Res;
1159
1160   if (!L->getLangOpts().Trigraphs) {
1161     if (!L->isLexingRawMode())
1162       L->Diag(CP-2, diag::trigraph_ignored);
1163     return 0;
1164   }
1165
1166   if (!L->isLexingRawMode())
1167     L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1168   return Res;
1169 }
1170
1171 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1172 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1173 /// trigraph equivalent on entry to this function.
1174 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1175   unsigned Size = 0;
1176   while (isWhitespace(Ptr[Size])) {
1177     ++Size;
1178
1179     if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1180       continue;
1181
1182     // If this is a \r\n or \n\r, skip the other half.
1183     if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1184         Ptr[Size-1] != Ptr[Size])
1185       ++Size;
1186
1187     return Size;
1188   }
1189
1190   // Not an escaped newline, must be a \t or something else.
1191   return 0;
1192 }
1193
1194 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1195 /// them), skip over them and return the first non-escaped-newline found,
1196 /// otherwise return P.
1197 const char *Lexer::SkipEscapedNewLines(const char *P) {
1198   while (true) {
1199     const char *AfterEscape;
1200     if (*P == '\\') {
1201       AfterEscape = P+1;
1202     } else if (*P == '?') {
1203       // If not a trigraph for escape, bail out.
1204       if (P[1] != '?' || P[2] != '/')
1205         return P;
1206       // FIXME: Take LangOpts into account; the language might not
1207       // support trigraphs.
1208       AfterEscape = P+3;
1209     } else {
1210       return P;
1211     }
1212
1213     unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1214     if (NewLineSize == 0) return P;
1215     P = AfterEscape+NewLineSize;
1216   }
1217 }
1218
1219 /// \brief Checks that the given token is the first token that occurs after the
1220 /// given location (this excludes comments and whitespace). Returns the location
1221 /// immediately after the specified token. If the token is not found or the
1222 /// location is inside a macro, the returned source location will be invalid.
1223 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1224                                         tok::TokenKind TKind,
1225                                         const SourceManager &SM,
1226                                         const LangOptions &LangOpts,
1227                                         bool SkipTrailingWhitespaceAndNewLine) {
1228   if (Loc.isMacroID()) {
1229     if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1230       return SourceLocation();
1231   }
1232   Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1233
1234   // Break down the source location.
1235   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1236
1237   // Try to load the file buffer.
1238   bool InvalidTemp = false;
1239   StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1240   if (InvalidTemp)
1241     return SourceLocation();
1242
1243   const char *TokenBegin = File.data() + LocInfo.second;
1244
1245   // Lex from the start of the given location.
1246   Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1247                                       TokenBegin, File.end());
1248   // Find the token.
1249   Token Tok;
1250   lexer.LexFromRawLexer(Tok);
1251   if (Tok.isNot(TKind))
1252     return SourceLocation();
1253   SourceLocation TokenLoc = Tok.getLocation();
1254
1255   // Calculate how much whitespace needs to be skipped if any.
1256   unsigned NumWhitespaceChars = 0;
1257   if (SkipTrailingWhitespaceAndNewLine) {
1258     const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1259                            Tok.getLength();
1260     unsigned char C = *TokenEnd;
1261     while (isHorizontalWhitespace(C)) {
1262       C = *(++TokenEnd);
1263       NumWhitespaceChars++;
1264     }
1265
1266     // Skip \r, \n, \r\n, or \n\r
1267     if (C == '\n' || C == '\r') {
1268       char PrevC = C;
1269       C = *(++TokenEnd);
1270       NumWhitespaceChars++;
1271       if ((C == '\n' || C == '\r') && C != PrevC)
1272         NumWhitespaceChars++;
1273     }
1274   }
1275
1276   return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1277 }
1278
1279 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1280 /// get its size, and return it.  This is tricky in several cases:
1281 ///   1. If currently at the start of a trigraph, we warn about the trigraph,
1282 ///      then either return the trigraph (skipping 3 chars) or the '?',
1283 ///      depending on whether trigraphs are enabled or not.
1284 ///   2. If this is an escaped newline (potentially with whitespace between
1285 ///      the backslash and newline), implicitly skip the newline and return
1286 ///      the char after it.
1287 ///
1288 /// This handles the slow/uncommon case of the getCharAndSize method.  Here we
1289 /// know that we can accumulate into Size, and that we have already incremented
1290 /// Ptr by Size bytes.
1291 ///
1292 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1293 /// be updated to match.
1294 ///
1295 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1296                                Token *Tok) {
1297   // If we have a slash, look for an escaped newline.
1298   if (Ptr[0] == '\\') {
1299     ++Size;
1300     ++Ptr;
1301 Slash:
1302     // Common case, backslash-char where the char is not whitespace.
1303     if (!isWhitespace(Ptr[0])) return '\\';
1304
1305     // See if we have optional whitespace characters between the slash and
1306     // newline.
1307     if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1308       // Remember that this token needs to be cleaned.
1309       if (Tok) Tok->setFlag(Token::NeedsCleaning);
1310
1311       // Warn if there was whitespace between the backslash and newline.
1312       if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1313         Diag(Ptr, diag::backslash_newline_space);
1314
1315       // Found backslash<whitespace><newline>.  Parse the char after it.
1316       Size += EscapedNewLineSize;
1317       Ptr  += EscapedNewLineSize;
1318
1319       // Use slow version to accumulate a correct size field.
1320       return getCharAndSizeSlow(Ptr, Size, Tok);
1321     }
1322
1323     // Otherwise, this is not an escaped newline, just return the slash.
1324     return '\\';
1325   }
1326
1327   // If this is a trigraph, process it.
1328   if (Ptr[0] == '?' && Ptr[1] == '?') {
1329     // If this is actually a legal trigraph (not something like "??x"), emit
1330     // a trigraph warning.  If so, and if trigraphs are enabled, return it.
1331     if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1332       // Remember that this token needs to be cleaned.
1333       if (Tok) Tok->setFlag(Token::NeedsCleaning);
1334
1335       Ptr += 3;
1336       Size += 3;
1337       if (C == '\\') goto Slash;
1338       return C;
1339     }
1340   }
1341
1342   // If this is neither, return a single character.
1343   ++Size;
1344   return *Ptr;
1345 }
1346
1347 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1348 /// getCharAndSizeNoWarn method.  Here we know that we can accumulate into Size,
1349 /// and that we have already incremented Ptr by Size bytes.
1350 ///
1351 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1352 /// be updated to match.
1353 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1354                                      const LangOptions &LangOpts) {
1355   // If we have a slash, look for an escaped newline.
1356   if (Ptr[0] == '\\') {
1357     ++Size;
1358     ++Ptr;
1359 Slash:
1360     // Common case, backslash-char where the char is not whitespace.
1361     if (!isWhitespace(Ptr[0])) return '\\';
1362
1363     // See if we have optional whitespace characters followed by a newline.
1364     if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1365       // Found backslash<whitespace><newline>.  Parse the char after it.
1366       Size += EscapedNewLineSize;
1367       Ptr  += EscapedNewLineSize;
1368
1369       // Use slow version to accumulate a correct size field.
1370       return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1371     }
1372
1373     // Otherwise, this is not an escaped newline, just return the slash.
1374     return '\\';
1375   }
1376
1377   // If this is a trigraph, process it.
1378   if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1379     // If this is actually a legal trigraph (not something like "??x"), return
1380     // it.
1381     if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1382       Ptr += 3;
1383       Size += 3;
1384       if (C == '\\') goto Slash;
1385       return C;
1386     }
1387   }
1388
1389   // If this is neither, return a single character.
1390   ++Size;
1391   return *Ptr;
1392 }
1393
1394 //===----------------------------------------------------------------------===//
1395 // Helper methods for lexing.
1396 //===----------------------------------------------------------------------===//
1397
1398 /// \brief Routine that indiscriminately skips bytes in the source file.
1399 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1400   BufferPtr += Bytes;
1401   if (BufferPtr > BufferEnd)
1402     BufferPtr = BufferEnd;
1403   // FIXME: What exactly does the StartOfLine bit mean?  There are two
1404   // possible meanings for the "start" of the line: the first token on the
1405   // unexpanded line, or the first token on the expanded line.
1406   IsAtStartOfLine = StartOfLine;
1407   IsAtPhysicalStartOfLine = StartOfLine;
1408 }
1409
1410 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1411   if (LangOpts.AsmPreprocessor) {
1412     return false;
1413   } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1414     static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1415         C11AllowedIDCharRanges);
1416     return C11AllowedIDChars.contains(C);
1417   } else if (LangOpts.CPlusPlus) {
1418     static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1419         CXX03AllowedIDCharRanges);
1420     return CXX03AllowedIDChars.contains(C);
1421   } else {
1422     static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1423         C99AllowedIDCharRanges);
1424     return C99AllowedIDChars.contains(C);
1425   }
1426 }
1427
1428 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1429   assert(isAllowedIDChar(C, LangOpts));
1430   if (LangOpts.AsmPreprocessor) {
1431     return false;
1432   } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1433     static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1434         C11DisallowedInitialIDCharRanges);
1435     return !C11DisallowedInitialIDChars.contains(C);
1436   } else if (LangOpts.CPlusPlus) {
1437     return true;
1438   } else {
1439     static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1440         C99DisallowedInitialIDCharRanges);
1441     return !C99DisallowedInitialIDChars.contains(C);
1442   }
1443 }
1444
1445 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1446                                             const char *End) {
1447   return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1448                                        L.getSourceLocation(End));
1449 }
1450
1451 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1452                                       CharSourceRange Range, bool IsFirst) {
1453   // Check C99 compatibility.
1454   if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1455     enum {
1456       CannotAppearInIdentifier = 0,
1457       CannotStartIdentifier
1458     };
1459
1460     static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1461         C99AllowedIDCharRanges);
1462     static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1463         C99DisallowedInitialIDCharRanges);
1464     if (!C99AllowedIDChars.contains(C)) {
1465       Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1466         << Range
1467         << CannotAppearInIdentifier;
1468     } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1469       Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1470         << Range
1471         << CannotStartIdentifier;
1472     }
1473   }
1474
1475   // Check C++98 compatibility.
1476   if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1477     static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1478         CXX03AllowedIDCharRanges);
1479     if (!CXX03AllowedIDChars.contains(C)) {
1480       Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1481         << Range;
1482     }
1483   }
1484 }
1485
1486 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1487                                     Token &Result) {
1488   const char *UCNPtr = CurPtr + Size;
1489   uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1490   if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1491     return false;
1492
1493   if (!isLexingRawMode())
1494     maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1495                               makeCharRange(*this, CurPtr, UCNPtr),
1496                               /*IsFirst=*/false);
1497
1498   Result.setFlag(Token::HasUCN);
1499   if ((UCNPtr - CurPtr ==  6 && CurPtr[1] == 'u') ||
1500       (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1501     CurPtr = UCNPtr;
1502   else
1503     while (CurPtr != UCNPtr)
1504       (void)getAndAdvanceChar(CurPtr, Result);
1505   return true;
1506 }
1507
1508 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1509   const char *UnicodePtr = CurPtr;
1510   llvm::UTF32 CodePoint;
1511   llvm::ConversionResult Result =
1512       llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1513                                 (const llvm::UTF8 *)BufferEnd,
1514                                 &CodePoint,
1515                                 llvm::strictConversion);
1516   if (Result != llvm::conversionOK ||
1517       !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1518     return false;
1519
1520   if (!isLexingRawMode())
1521     maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1522                               makeCharRange(*this, CurPtr, UnicodePtr),
1523                               /*IsFirst=*/false);
1524
1525   CurPtr = UnicodePtr;
1526   return true;
1527 }
1528
1529 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1530   // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1531   unsigned Size;
1532   unsigned char C = *CurPtr++;
1533   while (isIdentifierBody(C))
1534     C = *CurPtr++;
1535
1536   --CurPtr;   // Back up over the skipped character.
1537
1538   // Fast path, no $,\,? in identifier found.  '\' might be an escaped newline
1539   // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1540   //
1541   // TODO: Could merge these checks into an InfoTable flag to make the
1542   // comparison cheaper
1543   if (isASCII(C) && C != '\\' && C != '?' &&
1544       (C != '$' || !LangOpts.DollarIdents)) {
1545 FinishIdentifier:
1546     const char *IdStart = BufferPtr;
1547     FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1548     Result.setRawIdentifierData(IdStart);
1549
1550     // If we are in raw mode, return this identifier raw.  There is no need to
1551     // look up identifier information or attempt to macro expand it.
1552     if (LexingRawMode)
1553       return true;
1554
1555     // Fill in Result.IdentifierInfo and update the token kind,
1556     // looking up the identifier in the identifier table.
1557     IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1558
1559     // Finally, now that we know we have an identifier, pass this off to the
1560     // preprocessor, which may macro expand it or something.
1561     if (II->isHandleIdentifierCase())
1562       return PP->HandleIdentifier(Result);
1563
1564     if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1565         && II->getPPKeywordID() == tok::pp_not_keyword
1566         && II->getObjCKeywordID() == tok::objc_not_keyword) {
1567       // Return the code-completion token.
1568       Result.setKind(tok::code_completion);
1569       cutOffLexing();
1570       return true;
1571     }
1572     return true;
1573   }
1574
1575   // Otherwise, $,\,? in identifier found.  Enter slower path.
1576
1577   C = getCharAndSize(CurPtr, Size);
1578   while (true) {
1579     if (C == '$') {
1580       // If we hit a $ and they are not supported in identifiers, we are done.
1581       if (!LangOpts.DollarIdents) goto FinishIdentifier;
1582
1583       // Otherwise, emit a diagnostic and continue.
1584       if (!isLexingRawMode())
1585         Diag(CurPtr, diag::ext_dollar_in_identifier);
1586       CurPtr = ConsumeChar(CurPtr, Size, Result);
1587       C = getCharAndSize(CurPtr, Size);
1588       continue;
1589
1590     } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1591       C = getCharAndSize(CurPtr, Size);
1592       continue;
1593     } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1594       C = getCharAndSize(CurPtr, Size);
1595       continue;
1596     } else if (!isIdentifierBody(C)) {
1597       goto FinishIdentifier;
1598     }
1599
1600     // Otherwise, this character is good, consume it.
1601     CurPtr = ConsumeChar(CurPtr, Size, Result);
1602
1603     C = getCharAndSize(CurPtr, Size);
1604     while (isIdentifierBody(C)) {
1605       CurPtr = ConsumeChar(CurPtr, Size, Result);
1606       C = getCharAndSize(CurPtr, Size);
1607     }
1608   }
1609 }
1610
1611 /// isHexaLiteral - Return true if Start points to a hex constant.
1612 /// in microsoft mode (where this is supposed to be several different tokens).
1613 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1614   unsigned Size;
1615   char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1616   if (C1 != '0')
1617     return false;
1618   char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1619   return (C2 == 'x' || C2 == 'X');
1620 }
1621
1622 /// LexNumericConstant - Lex the remainder of a integer or floating point
1623 /// constant. From[-1] is the first character lexed.  Return the end of the
1624 /// constant.
1625 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1626   unsigned Size;
1627   char C = getCharAndSize(CurPtr, Size);
1628   char PrevCh = 0;
1629   while (isPreprocessingNumberBody(C)) {
1630     CurPtr = ConsumeChar(CurPtr, Size, Result);
1631     PrevCh = C;
1632     C = getCharAndSize(CurPtr, Size);
1633   }
1634
1635   // If we fell out, check for a sign, due to 1e+12.  If we have one, continue.
1636   if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1637     // If we are in Microsoft mode, don't continue if the constant is hex.
1638     // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1639     if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1640       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1641   }
1642
1643   // If we have a hex FP constant, continue.
1644   if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1645     // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1646     // not-quite-conforming extension. Only do so if this looks like it's
1647     // actually meant to be a hexfloat, and not if it has a ud-suffix.
1648     bool IsHexFloat = true;
1649     if (!LangOpts.C99) {
1650       if (!isHexaLiteral(BufferPtr, LangOpts))
1651         IsHexFloat = false;
1652       else if (!getLangOpts().CPlusPlus1z &&
1653                std::find(BufferPtr, CurPtr, '_') != CurPtr)
1654         IsHexFloat = false;
1655     }
1656     if (IsHexFloat)
1657       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1658   }
1659
1660   // If we have a digit separator, continue.
1661   if (C == '\'' && getLangOpts().CPlusPlus14) {
1662     unsigned NextSize;
1663     char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1664     if (isIdentifierBody(Next)) {
1665       if (!isLexingRawMode())
1666         Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1667       CurPtr = ConsumeChar(CurPtr, Size, Result);
1668       CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1669       return LexNumericConstant(Result, CurPtr);
1670     }
1671   }
1672
1673   // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1674   if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1675     return LexNumericConstant(Result, CurPtr);
1676   if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1677     return LexNumericConstant(Result, CurPtr);
1678
1679   // Update the location of token as well as BufferPtr.
1680   const char *TokStart = BufferPtr;
1681   FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1682   Result.setLiteralData(TokStart);
1683   return true;
1684 }
1685
1686 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1687 /// in C++11, or warn on a ud-suffix in C++98.
1688 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1689                                bool IsStringLiteral) {
1690   assert(getLangOpts().CPlusPlus);
1691
1692   // Maximally munch an identifier.
1693   unsigned Size;
1694   char C = getCharAndSize(CurPtr, Size);
1695   bool Consumed = false;
1696
1697   if (!isIdentifierHead(C)) {
1698     if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1699       Consumed = true;
1700     else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1701       Consumed = true;
1702     else
1703       return CurPtr;
1704   }
1705
1706   if (!getLangOpts().CPlusPlus11) {
1707     if (!isLexingRawMode())
1708       Diag(CurPtr,
1709            C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1710                     : diag::warn_cxx11_compat_reserved_user_defined_literal)
1711         << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1712     return CurPtr;
1713   }
1714
1715   // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1716   // that does not start with an underscore is ill-formed. As a conforming
1717   // extension, we treat all such suffixes as if they had whitespace before
1718   // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1719   // likely to be a ud-suffix than a macro, however, and accept that.
1720   if (!Consumed) {
1721     bool IsUDSuffix = false;
1722     if (C == '_')
1723       IsUDSuffix = true;
1724     else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1725       // In C++1y, we need to look ahead a few characters to see if this is a
1726       // valid suffix for a string literal or a numeric literal (this could be
1727       // the 'operator""if' defining a numeric literal operator).
1728       const unsigned MaxStandardSuffixLength = 3;
1729       char Buffer[MaxStandardSuffixLength] = { C };
1730       unsigned Consumed = Size;
1731       unsigned Chars = 1;
1732       while (true) {
1733         unsigned NextSize;
1734         char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1735                                          getLangOpts());
1736         if (!isIdentifierBody(Next)) {
1737           // End of suffix. Check whether this is on the whitelist.
1738           const StringRef CompleteSuffix(Buffer, Chars);
1739           IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1740                                                             CompleteSuffix);
1741           break;
1742         }
1743
1744         if (Chars == MaxStandardSuffixLength)
1745           // Too long: can't be a standard suffix.
1746           break;
1747
1748         Buffer[Chars++] = Next;
1749         Consumed += NextSize;
1750       }
1751     }
1752
1753     if (!IsUDSuffix) {
1754       if (!isLexingRawMode())
1755         Diag(CurPtr, getLangOpts().MSVCCompat
1756                          ? diag::ext_ms_reserved_user_defined_literal
1757                          : diag::ext_reserved_user_defined_literal)
1758           << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1759       return CurPtr;
1760     }
1761
1762     CurPtr = ConsumeChar(CurPtr, Size, Result);
1763   }
1764
1765   Result.setFlag(Token::HasUDSuffix);
1766   while (true) {
1767     C = getCharAndSize(CurPtr, Size);
1768     if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1769     else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1770     else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1771     else break;
1772   }
1773
1774   return CurPtr;
1775 }
1776
1777 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1778 /// either " or L" or u8" or u" or U".
1779 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1780                              tok::TokenKind Kind) {
1781   // Does this string contain the \0 character?
1782   const char *NulCharacter = nullptr;
1783
1784   if (!isLexingRawMode() &&
1785       (Kind == tok::utf8_string_literal ||
1786        Kind == tok::utf16_string_literal ||
1787        Kind == tok::utf32_string_literal))
1788     Diag(BufferPtr, getLangOpts().CPlusPlus
1789            ? diag::warn_cxx98_compat_unicode_literal
1790            : diag::warn_c99_compat_unicode_literal);
1791
1792   char C = getAndAdvanceChar(CurPtr, Result);
1793   while (C != '"') {
1794     // Skip escaped characters.  Escaped newlines will already be processed by
1795     // getAndAdvanceChar.
1796     if (C == '\\')
1797       C = getAndAdvanceChar(CurPtr, Result);
1798     
1799     if (C == '\n' || C == '\r' ||             // Newline.
1800         (C == 0 && CurPtr-1 == BufferEnd)) {  // End of file.
1801       if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1802         Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1803       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1804       return true;
1805     }
1806     
1807     if (C == 0) {
1808       if (isCodeCompletionPoint(CurPtr-1)) {
1809         PP->CodeCompleteNaturalLanguage();
1810         FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1811         cutOffLexing();
1812         return true;
1813       }
1814
1815       NulCharacter = CurPtr-1;
1816     }
1817     C = getAndAdvanceChar(CurPtr, Result);
1818   }
1819
1820   // If we are in C++11, lex the optional ud-suffix.
1821   if (getLangOpts().CPlusPlus)
1822     CurPtr = LexUDSuffix(Result, CurPtr, true);
1823
1824   // If a nul character existed in the string, warn about it.
1825   if (NulCharacter && !isLexingRawMode())
1826     Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1827
1828   // Update the location of the token as well as the BufferPtr instance var.
1829   const char *TokStart = BufferPtr;
1830   FormTokenWithChars(Result, CurPtr, Kind);
1831   Result.setLiteralData(TokStart);
1832   return true;
1833 }
1834
1835 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1836 /// having lexed R", LR", u8R", uR", or UR".
1837 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1838                                 tok::TokenKind Kind) {
1839   // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1840   //  Between the initial and final double quote characters of the raw string,
1841   //  any transformations performed in phases 1 and 2 (trigraphs,
1842   //  universal-character-names, and line splicing) are reverted.
1843
1844   if (!isLexingRawMode())
1845     Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1846
1847   unsigned PrefixLen = 0;
1848
1849   while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1850     ++PrefixLen;
1851
1852   // If the last character was not a '(', then we didn't lex a valid delimiter.
1853   if (CurPtr[PrefixLen] != '(') {
1854     if (!isLexingRawMode()) {
1855       const char *PrefixEnd = &CurPtr[PrefixLen];
1856       if (PrefixLen == 16) {
1857         Diag(PrefixEnd, diag::err_raw_delim_too_long);
1858       } else {
1859         Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1860           << StringRef(PrefixEnd, 1);
1861       }
1862     }
1863
1864     // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1865     // it's possible the '"' was intended to be part of the raw string, but
1866     // there's not much we can do about that.
1867     while (true) {
1868       char C = *CurPtr++;
1869
1870       if (C == '"')
1871         break;
1872       if (C == 0 && CurPtr-1 == BufferEnd) {
1873         --CurPtr;
1874         break;
1875       }
1876     }
1877
1878     FormTokenWithChars(Result, CurPtr, tok::unknown);
1879     return true;
1880   }
1881
1882   // Save prefix and move CurPtr past it
1883   const char *Prefix = CurPtr;
1884   CurPtr += PrefixLen + 1; // skip over prefix and '('
1885
1886   while (true) {
1887     char C = *CurPtr++;
1888
1889     if (C == ')') {
1890       // Check for prefix match and closing quote.
1891       if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1892         CurPtr += PrefixLen + 1; // skip over prefix and '"'
1893         break;
1894       }
1895     } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1896       if (!isLexingRawMode())
1897         Diag(BufferPtr, diag::err_unterminated_raw_string)
1898           << StringRef(Prefix, PrefixLen);
1899       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1900       return true;
1901     }
1902   }
1903
1904   // If we are in C++11, lex the optional ud-suffix.
1905   if (getLangOpts().CPlusPlus)
1906     CurPtr = LexUDSuffix(Result, CurPtr, true);
1907
1908   // Update the location of token as well as BufferPtr.
1909   const char *TokStart = BufferPtr;
1910   FormTokenWithChars(Result, CurPtr, Kind);
1911   Result.setLiteralData(TokStart);
1912   return true;
1913 }
1914
1915 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1916 /// after having lexed the '<' character.  This is used for #include filenames.
1917 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1918   // Does this string contain the \0 character?
1919   const char *NulCharacter = nullptr;
1920   const char *AfterLessPos = CurPtr;
1921   char C = getAndAdvanceChar(CurPtr, Result);
1922   while (C != '>') {
1923     // Skip escaped characters.
1924     if (C == '\\' && CurPtr < BufferEnd) {
1925       // Skip the escaped character.
1926       getAndAdvanceChar(CurPtr, Result);
1927     } else if (C == '\n' || C == '\r' ||             // Newline.
1928                (C == 0 && (CurPtr-1 == BufferEnd ||  // End of file.
1929                            isCodeCompletionPoint(CurPtr-1)))) {
1930       // If the filename is unterminated, then it must just be a lone <
1931       // character.  Return this as such.
1932       FormTokenWithChars(Result, AfterLessPos, tok::less);
1933       return true;
1934     } else if (C == 0) {
1935       NulCharacter = CurPtr-1;
1936     }
1937     C = getAndAdvanceChar(CurPtr, Result);
1938   }
1939
1940   // If a nul character existed in the string, warn about it.
1941   if (NulCharacter && !isLexingRawMode())
1942     Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1943
1944   // Update the location of token as well as BufferPtr.
1945   const char *TokStart = BufferPtr;
1946   FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1947   Result.setLiteralData(TokStart);
1948   return true;
1949 }
1950
1951 /// LexCharConstant - Lex the remainder of a character constant, after having
1952 /// lexed either ' or L' or u8' or u' or U'.
1953 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1954                             tok::TokenKind Kind) {
1955   // Does this character contain the \0 character?
1956   const char *NulCharacter = nullptr;
1957
1958   if (!isLexingRawMode()) {
1959     if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1960       Diag(BufferPtr, getLangOpts().CPlusPlus
1961                           ? diag::warn_cxx98_compat_unicode_literal
1962                           : diag::warn_c99_compat_unicode_literal);
1963     else if (Kind == tok::utf8_char_constant)
1964       Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1965   }
1966
1967   char C = getAndAdvanceChar(CurPtr, Result);
1968   if (C == '\'') {
1969     if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1970       Diag(BufferPtr, diag::ext_empty_character);
1971     FormTokenWithChars(Result, CurPtr, tok::unknown);
1972     return true;
1973   }
1974
1975   while (C != '\'') {
1976     // Skip escaped characters.
1977     if (C == '\\')
1978       C = getAndAdvanceChar(CurPtr, Result);
1979
1980     if (C == '\n' || C == '\r' ||             // Newline.
1981         (C == 0 && CurPtr-1 == BufferEnd)) {  // End of file.
1982       if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1983         Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1984       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1985       return true;
1986     }
1987
1988     if (C == 0) {
1989       if (isCodeCompletionPoint(CurPtr-1)) {
1990         PP->CodeCompleteNaturalLanguage();
1991         FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1992         cutOffLexing();
1993         return true;
1994       }
1995
1996       NulCharacter = CurPtr-1;
1997     }
1998     C = getAndAdvanceChar(CurPtr, Result);
1999   }
2000
2001   // If we are in C++11, lex the optional ud-suffix.
2002   if (getLangOpts().CPlusPlus)
2003     CurPtr = LexUDSuffix(Result, CurPtr, false);
2004
2005   // If a nul character existed in the character, warn about it.
2006   if (NulCharacter && !isLexingRawMode())
2007     Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2008
2009   // Update the location of token as well as BufferPtr.
2010   const char *TokStart = BufferPtr;
2011   FormTokenWithChars(Result, CurPtr, Kind);
2012   Result.setLiteralData(TokStart);
2013   return true;
2014 }
2015
2016 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2017 /// Update BufferPtr to point to the next non-whitespace character and return.
2018 ///
2019 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2020 ///
2021 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2022                            bool &TokAtPhysicalStartOfLine) {
2023   // Whitespace - Skip it, then return the token after the whitespace.
2024   bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2025
2026   unsigned char Char = *CurPtr;
2027
2028   // Skip consecutive spaces efficiently.
2029   while (true) {
2030     // Skip horizontal whitespace very aggressively.
2031     while (isHorizontalWhitespace(Char))
2032       Char = *++CurPtr;
2033
2034     // Otherwise if we have something other than whitespace, we're done.
2035     if (!isVerticalWhitespace(Char))
2036       break;
2037
2038     if (ParsingPreprocessorDirective) {
2039       // End of preprocessor directive line, let LexTokenInternal handle this.
2040       BufferPtr = CurPtr;
2041       return false;
2042     }
2043
2044     // OK, but handle newline.
2045     SawNewline = true;
2046     Char = *++CurPtr;
2047   }
2048
2049   // If the client wants us to return whitespace, return it now.
2050   if (isKeepWhitespaceMode()) {
2051     FormTokenWithChars(Result, CurPtr, tok::unknown);
2052     if (SawNewline) {
2053       IsAtStartOfLine = true;
2054       IsAtPhysicalStartOfLine = true;
2055     }
2056     // FIXME: The next token will not have LeadingSpace set.
2057     return true;
2058   }
2059
2060   // If this isn't immediately after a newline, there is leading space.
2061   char PrevChar = CurPtr[-1];
2062   bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2063
2064   Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2065   if (SawNewline) {
2066     Result.setFlag(Token::StartOfLine);
2067     TokAtPhysicalStartOfLine = true;
2068   }
2069
2070   BufferPtr = CurPtr;
2071   return false;
2072 }
2073
2074 /// We have just read the // characters from input.  Skip until we find the
2075 /// newline character thats terminate the comment.  Then update BufferPtr and
2076 /// return.
2077 ///
2078 /// If we're in KeepCommentMode or any CommentHandler has inserted
2079 /// some tokens, this will store the first token and return true.
2080 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2081                             bool &TokAtPhysicalStartOfLine) {
2082   // If Line comments aren't explicitly enabled for this language, emit an
2083   // extension warning.
2084   if (!LangOpts.LineComment && !isLexingRawMode()) {
2085     Diag(BufferPtr, diag::ext_line_comment);
2086
2087     // Mark them enabled so we only emit one warning for this translation
2088     // unit.
2089     LangOpts.LineComment = true;
2090   }
2091
2092   // Scan over the body of the comment.  The common case, when scanning, is that
2093   // the comment contains normal ascii characters with nothing interesting in
2094   // them.  As such, optimize for this case with the inner loop.
2095   //
2096   // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2097   // character that ends the line comment.
2098   char C;
2099   while (true) {
2100     C = *CurPtr;
2101     // Skip over characters in the fast loop.
2102     while (C != 0 &&                // Potentially EOF.
2103            C != '\n' && C != '\r')  // Newline or DOS-style newline.
2104       C = *++CurPtr;
2105
2106     const char *NextLine = CurPtr;
2107     if (C != 0) {
2108       // We found a newline, see if it's escaped.
2109       const char *EscapePtr = CurPtr-1;
2110       bool HasSpace = false;
2111       while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2112         --EscapePtr;
2113         HasSpace = true;
2114       }
2115
2116       if (*EscapePtr == '\\')
2117         // Escaped newline.
2118         CurPtr = EscapePtr;
2119       else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2120                EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2121         // Trigraph-escaped newline.
2122         CurPtr = EscapePtr-2;
2123       else
2124         break; // This is a newline, we're done.
2125
2126       // If there was space between the backslash and newline, warn about it.
2127       if (HasSpace && !isLexingRawMode())
2128         Diag(EscapePtr, diag::backslash_newline_space);
2129     }
2130
2131     // Otherwise, this is a hard case.  Fall back on getAndAdvanceChar to
2132     // properly decode the character.  Read it in raw mode to avoid emitting
2133     // diagnostics about things like trigraphs.  If we see an escaped newline,
2134     // we'll handle it below.
2135     const char *OldPtr = CurPtr;
2136     bool OldRawMode = isLexingRawMode();
2137     LexingRawMode = true;
2138     C = getAndAdvanceChar(CurPtr, Result);
2139     LexingRawMode = OldRawMode;
2140
2141     // If we only read only one character, then no special handling is needed.
2142     // We're done and can skip forward to the newline.
2143     if (C != 0 && CurPtr == OldPtr+1) {
2144       CurPtr = NextLine;
2145       break;
2146     }
2147
2148     // If we read multiple characters, and one of those characters was a \r or
2149     // \n, then we had an escaped newline within the comment.  Emit diagnostic
2150     // unless the next line is also a // comment.
2151     if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2152       for (; OldPtr != CurPtr; ++OldPtr)
2153         if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2154           // Okay, we found a // comment that ends in a newline, if the next
2155           // line is also a // comment, but has spaces, don't emit a diagnostic.
2156           if (isWhitespace(C)) {
2157             const char *ForwardPtr = CurPtr;
2158             while (isWhitespace(*ForwardPtr))  // Skip whitespace.
2159               ++ForwardPtr;
2160             if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2161               break;
2162           }
2163
2164           if (!isLexingRawMode())
2165             Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2166           break;
2167         }
2168     }
2169
2170     if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2171       --CurPtr;
2172       break;
2173     }
2174
2175     if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2176       PP->CodeCompleteNaturalLanguage();
2177       cutOffLexing();
2178       return false;
2179     }
2180   }
2181
2182   // Found but did not consume the newline.  Notify comment handlers about the
2183   // comment unless we're in a #if 0 block.
2184   if (PP && !isLexingRawMode() &&
2185       PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2186                                             getSourceLocation(CurPtr)))) {
2187     BufferPtr = CurPtr;
2188     return true; // A token has to be returned.
2189   }
2190
2191   // If we are returning comments as tokens, return this comment as a token.
2192   if (inKeepCommentMode())
2193     return SaveLineComment(Result, CurPtr);
2194
2195   // If we are inside a preprocessor directive and we see the end of line,
2196   // return immediately, so that the lexer can return this as an EOD token.
2197   if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2198     BufferPtr = CurPtr;
2199     return false;
2200   }
2201
2202   // Otherwise, eat the \n character.  We don't care if this is a \n\r or
2203   // \r\n sequence.  This is an efficiency hack (because we know the \n can't
2204   // contribute to another token), it isn't needed for correctness.  Note that
2205   // this is ok even in KeepWhitespaceMode, because we would have returned the
2206   /// comment above in that mode.
2207   ++CurPtr;
2208
2209   // The next returned token is at the start of the line.
2210   Result.setFlag(Token::StartOfLine);
2211   TokAtPhysicalStartOfLine = true;
2212   // No leading whitespace seen so far.
2213   Result.clearFlag(Token::LeadingSpace);
2214   BufferPtr = CurPtr;
2215   return false;
2216 }
2217
2218 /// If in save-comment mode, package up this Line comment in an appropriate
2219 /// way and return it.
2220 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2221   // If we're not in a preprocessor directive, just return the // comment
2222   // directly.
2223   FormTokenWithChars(Result, CurPtr, tok::comment);
2224
2225   if (!ParsingPreprocessorDirective || LexingRawMode)
2226     return true;
2227
2228   // If this Line-style comment is in a macro definition, transmogrify it into
2229   // a C-style block comment.
2230   bool Invalid = false;
2231   std::string Spelling = PP->getSpelling(Result, &Invalid);
2232   if (Invalid)
2233     return true;
2234   
2235   assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2236   Spelling[1] = '*';   // Change prefix to "/*".
2237   Spelling += "*/";    // add suffix.
2238
2239   Result.setKind(tok::comment);
2240   PP->CreateString(Spelling, Result,
2241                    Result.getLocation(), Result.getLocation());
2242   return true;
2243 }
2244
2245 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2246 /// character (either \\n or \\r) is part of an escaped newline sequence.  Issue
2247 /// a diagnostic if so.  We know that the newline is inside of a block comment.
2248 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2249                                                   Lexer *L) {
2250   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2251
2252   // Back up off the newline.
2253   --CurPtr;
2254
2255   // If this is a two-character newline sequence, skip the other character.
2256   if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2257     // \n\n or \r\r -> not escaped newline.
2258     if (CurPtr[0] == CurPtr[1])
2259       return false;
2260     // \n\r or \r\n -> skip the newline.
2261     --CurPtr;
2262   }
2263
2264   // If we have horizontal whitespace, skip over it.  We allow whitespace
2265   // between the slash and newline.
2266   bool HasSpace = false;
2267   while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2268     --CurPtr;
2269     HasSpace = true;
2270   }
2271
2272   // If we have a slash, we know this is an escaped newline.
2273   if (*CurPtr == '\\') {
2274     if (CurPtr[-1] != '*') return false;
2275   } else {
2276     // It isn't a slash, is it the ?? / trigraph?
2277     if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2278         CurPtr[-3] != '*')
2279       return false;
2280
2281     // This is the trigraph ending the comment.  Emit a stern warning!
2282     CurPtr -= 2;
2283
2284     // If no trigraphs are enabled, warn that we ignored this trigraph and
2285     // ignore this * character.
2286     if (!L->getLangOpts().Trigraphs) {
2287       if (!L->isLexingRawMode())
2288         L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2289       return false;
2290     }
2291     if (!L->isLexingRawMode())
2292       L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2293   }
2294
2295   // Warn about having an escaped newline between the */ characters.
2296   if (!L->isLexingRawMode())
2297     L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2298
2299   // If there was space between the backslash and newline, warn about it.
2300   if (HasSpace && !L->isLexingRawMode())
2301     L->Diag(CurPtr, diag::backslash_newline_space);
2302
2303   return true;
2304 }
2305
2306 #ifdef __SSE2__
2307 #include <emmintrin.h>
2308 #elif __ALTIVEC__
2309 #include <altivec.h>
2310 #undef bool
2311 #endif
2312
2313 /// We have just read from input the / and * characters that started a comment.
2314 /// Read until we find the * and / characters that terminate the comment.
2315 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2316 /// comments, because they cannot cause the comment to end.  The only thing
2317 /// that can happen is the comment could end with an escaped newline between
2318 /// the terminating * and /.
2319 ///
2320 /// If we're in KeepCommentMode or any CommentHandler has inserted
2321 /// some tokens, this will store the first token and return true.
2322 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2323                              bool &TokAtPhysicalStartOfLine) {
2324   // Scan one character past where we should, looking for a '/' character.  Once
2325   // we find it, check to see if it was preceded by a *.  This common
2326   // optimization helps people who like to put a lot of * characters in their
2327   // comments.
2328
2329   // The first character we get with newlines and trigraphs skipped to handle
2330   // the degenerate /*/ case below correctly if the * has an escaped newline
2331   // after it.
2332   unsigned CharSize;
2333   unsigned char C = getCharAndSize(CurPtr, CharSize);
2334   CurPtr += CharSize;
2335   if (C == 0 && CurPtr == BufferEnd+1) {
2336     if (!isLexingRawMode())
2337       Diag(BufferPtr, diag::err_unterminated_block_comment);
2338     --CurPtr;
2339
2340     // KeepWhitespaceMode should return this broken comment as a token.  Since
2341     // it isn't a well formed comment, just return it as an 'unknown' token.
2342     if (isKeepWhitespaceMode()) {
2343       FormTokenWithChars(Result, CurPtr, tok::unknown);
2344       return true;
2345     }
2346
2347     BufferPtr = CurPtr;
2348     return false;
2349   }
2350
2351   // Check to see if the first character after the '/*' is another /.  If so,
2352   // then this slash does not end the block comment, it is part of it.
2353   if (C == '/')
2354     C = *CurPtr++;
2355
2356   while (true) {
2357     // Skip over all non-interesting characters until we find end of buffer or a
2358     // (probably ending) '/' character.
2359     if (CurPtr + 24 < BufferEnd &&
2360         // If there is a code-completion point avoid the fast scan because it
2361         // doesn't check for '\0'.
2362         !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2363       // While not aligned to a 16-byte boundary.
2364       while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2365         C = *CurPtr++;
2366
2367       if (C == '/') goto FoundSlash;
2368
2369 #ifdef __SSE2__
2370       __m128i Slashes = _mm_set1_epi8('/');
2371       while (CurPtr+16 <= BufferEnd) {
2372         int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2373                                     Slashes));
2374         if (cmp != 0) {
2375           // Adjust the pointer to point directly after the first slash. It's
2376           // not necessary to set C here, it will be overwritten at the end of
2377           // the outer loop.
2378           CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2379           goto FoundSlash;
2380         }
2381         CurPtr += 16;
2382       }
2383 #elif __ALTIVEC__
2384       __vector unsigned char Slashes = {
2385         '/', '/', '/', '/',  '/', '/', '/', '/',
2386         '/', '/', '/', '/',  '/', '/', '/', '/'
2387       };
2388       while (CurPtr+16 <= BufferEnd &&
2389              !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2390         CurPtr += 16;
2391 #else
2392       // Scan for '/' quickly.  Many block comments are very large.
2393       while (CurPtr[0] != '/' &&
2394              CurPtr[1] != '/' &&
2395              CurPtr[2] != '/' &&
2396              CurPtr[3] != '/' &&
2397              CurPtr+4 < BufferEnd) {
2398         CurPtr += 4;
2399       }
2400 #endif
2401
2402       // It has to be one of the bytes scanned, increment to it and read one.
2403       C = *CurPtr++;
2404     }
2405
2406     // Loop to scan the remainder.
2407     while (C != '/' && C != '\0')
2408       C = *CurPtr++;
2409
2410     if (C == '/') {
2411   FoundSlash:
2412       if (CurPtr[-2] == '*')  // We found the final */.  We're done!
2413         break;
2414
2415       if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2416         if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2417           // We found the final */, though it had an escaped newline between the
2418           // * and /.  We're done!
2419           break;
2420         }
2421       }
2422       if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2423         // If this is a /* inside of the comment, emit a warning.  Don't do this
2424         // if this is a /*/, which will end the comment.  This misses cases with
2425         // embedded escaped newlines, but oh well.
2426         if (!isLexingRawMode())
2427           Diag(CurPtr-1, diag::warn_nested_block_comment);
2428       }
2429     } else if (C == 0 && CurPtr == BufferEnd+1) {
2430       if (!isLexingRawMode())
2431         Diag(BufferPtr, diag::err_unterminated_block_comment);
2432       // Note: the user probably forgot a */.  We could continue immediately
2433       // after the /*, but this would involve lexing a lot of what really is the
2434       // comment, which surely would confuse the parser.
2435       --CurPtr;
2436
2437       // KeepWhitespaceMode should return this broken comment as a token.  Since
2438       // it isn't a well formed comment, just return it as an 'unknown' token.
2439       if (isKeepWhitespaceMode()) {
2440         FormTokenWithChars(Result, CurPtr, tok::unknown);
2441         return true;
2442       }
2443
2444       BufferPtr = CurPtr;
2445       return false;
2446     } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2447       PP->CodeCompleteNaturalLanguage();
2448       cutOffLexing();
2449       return false;
2450     }
2451
2452     C = *CurPtr++;
2453   }
2454
2455   // Notify comment handlers about the comment unless we're in a #if 0 block.
2456   if (PP && !isLexingRawMode() &&
2457       PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2458                                             getSourceLocation(CurPtr)))) {
2459     BufferPtr = CurPtr;
2460     return true; // A token has to be returned.
2461   }
2462
2463   // If we are returning comments as tokens, return this comment as a token.
2464   if (inKeepCommentMode()) {
2465     FormTokenWithChars(Result, CurPtr, tok::comment);
2466     return true;
2467   }
2468
2469   // It is common for the tokens immediately after a /**/ comment to be
2470   // whitespace.  Instead of going through the big switch, handle it
2471   // efficiently now.  This is safe even in KeepWhitespaceMode because we would
2472   // have already returned above with the comment as a token.
2473   if (isHorizontalWhitespace(*CurPtr)) {
2474     SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2475     return false;
2476   }
2477
2478   // Otherwise, just return so that the next character will be lexed as a token.
2479   BufferPtr = CurPtr;
2480   Result.setFlag(Token::LeadingSpace);
2481   return false;
2482 }
2483
2484 //===----------------------------------------------------------------------===//
2485 // Primary Lexing Entry Points
2486 //===----------------------------------------------------------------------===//
2487
2488 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2489 /// uninterpreted string.  This switches the lexer out of directive mode.
2490 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2491   assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2492          "Must be in a preprocessing directive!");
2493   Token Tmp;
2494
2495   // CurPtr - Cache BufferPtr in an automatic variable.
2496   const char *CurPtr = BufferPtr;
2497   while (true) {
2498     char Char = getAndAdvanceChar(CurPtr, Tmp);
2499     switch (Char) {
2500     default:
2501       if (Result)
2502         Result->push_back(Char);
2503       break;
2504     case 0:  // Null.
2505       // Found end of file?
2506       if (CurPtr-1 != BufferEnd) {
2507         if (isCodeCompletionPoint(CurPtr-1)) {
2508           PP->CodeCompleteNaturalLanguage();
2509           cutOffLexing();
2510           return;
2511         }
2512
2513         // Nope, normal character, continue.
2514         if (Result)
2515           Result->push_back(Char);
2516         break;
2517       }
2518       // FALL THROUGH.
2519     case '\r':
2520     case '\n':
2521       // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2522       assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2523       BufferPtr = CurPtr-1;
2524
2525       // Next, lex the character, which should handle the EOD transition.
2526       Lex(Tmp);
2527       if (Tmp.is(tok::code_completion)) {
2528         if (PP)
2529           PP->CodeCompleteNaturalLanguage();
2530         Lex(Tmp);
2531       }
2532       assert(Tmp.is(tok::eod) && "Unexpected token!");
2533
2534       // Finally, we're done;
2535       return;
2536     }
2537   }
2538 }
2539
2540 /// LexEndOfFile - CurPtr points to the end of this file.  Handle this
2541 /// condition, reporting diagnostics and handling other edge cases as required.
2542 /// This returns true if Result contains a token, false if PP.Lex should be
2543 /// called again.
2544 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2545   // If we hit the end of the file while parsing a preprocessor directive,
2546   // end the preprocessor directive first.  The next token returned will
2547   // then be the end of file.
2548   if (ParsingPreprocessorDirective) {
2549     // Done parsing the "line".
2550     ParsingPreprocessorDirective = false;
2551     // Update the location of token as well as BufferPtr.
2552     FormTokenWithChars(Result, CurPtr, tok::eod);
2553
2554     // Restore comment saving mode, in case it was disabled for directive.
2555     if (PP)
2556       resetExtendedTokenMode();
2557     return true;  // Have a token.
2558   }
2559  
2560   // If we are in raw mode, return this event as an EOF token.  Let the caller
2561   // that put us in raw mode handle the event.
2562   if (isLexingRawMode()) {
2563     Result.startToken();
2564     BufferPtr = BufferEnd;
2565     FormTokenWithChars(Result, BufferEnd, tok::eof);
2566     return true;
2567   }
2568   
2569   // Issue diagnostics for unterminated #if and missing newline.
2570
2571   // If we are in a #if directive, emit an error.
2572   while (!ConditionalStack.empty()) {
2573     if (PP->getCodeCompletionFileLoc() != FileLoc)
2574       PP->Diag(ConditionalStack.back().IfLoc,
2575                diag::err_pp_unterminated_conditional);
2576     ConditionalStack.pop_back();
2577   }
2578
2579   // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2580   // a pedwarn.
2581   if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2582     DiagnosticsEngine &Diags = PP->getDiagnostics();
2583     SourceLocation EndLoc = getSourceLocation(BufferEnd);
2584     unsigned DiagID;
2585
2586     if (LangOpts.CPlusPlus11) {
2587       // C++11 [lex.phases] 2.2 p2
2588       // Prefer the C++98 pedantic compatibility warning over the generic,
2589       // non-extension, user-requested "missing newline at EOF" warning.
2590       if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2591         DiagID = diag::warn_cxx98_compat_no_newline_eof;
2592       } else {
2593         DiagID = diag::warn_no_newline_eof;
2594       }
2595     } else {
2596       DiagID = diag::ext_no_newline_eof;
2597     }
2598
2599     Diag(BufferEnd, DiagID)
2600       << FixItHint::CreateInsertion(EndLoc, "\n");
2601   }
2602
2603   BufferPtr = CurPtr;
2604
2605   // Finally, let the preprocessor handle this.
2606   return PP->HandleEndOfFile(Result, isPragmaLexer());
2607 }
2608
2609 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2610 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2611 /// else and 2 if there are no more tokens in the buffer controlled by the
2612 /// lexer.
2613 unsigned Lexer::isNextPPTokenLParen() {
2614   assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2615
2616   // Switch to 'skipping' mode.  This will ensure that we can lex a token
2617   // without emitting diagnostics, disables macro expansion, and will cause EOF
2618   // to return an EOF token instead of popping the include stack.
2619   LexingRawMode = true;
2620
2621   // Save state that can be changed while lexing so that we can restore it.
2622   const char *TmpBufferPtr = BufferPtr;
2623   bool inPPDirectiveMode = ParsingPreprocessorDirective;
2624   bool atStartOfLine = IsAtStartOfLine;
2625   bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2626   bool leadingSpace = HasLeadingSpace;
2627
2628   Token Tok;
2629   Lex(Tok);
2630
2631   // Restore state that may have changed.
2632   BufferPtr = TmpBufferPtr;
2633   ParsingPreprocessorDirective = inPPDirectiveMode;
2634   HasLeadingSpace = leadingSpace;
2635   IsAtStartOfLine = atStartOfLine;
2636   IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2637
2638   // Restore the lexer back to non-skipping mode.
2639   LexingRawMode = false;
2640
2641   if (Tok.is(tok::eof))
2642     return 2;
2643   return Tok.is(tok::l_paren);
2644 }
2645
2646 /// \brief Find the end of a version control conflict marker.
2647 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2648                                    ConflictMarkerKind CMK) {
2649   const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2650   size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2651   auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2652   size_t Pos = RestOfBuffer.find(Terminator);
2653   while (Pos != StringRef::npos) {
2654     // Must occur at start of line.
2655     if (Pos == 0 ||
2656         (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2657       RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2658       Pos = RestOfBuffer.find(Terminator);
2659       continue;
2660     }
2661     return RestOfBuffer.data()+Pos;
2662   }
2663   return nullptr;
2664 }
2665
2666 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2667 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2668 /// and recover nicely.  This returns true if it is a conflict marker and false
2669 /// if not.
2670 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2671   // Only a conflict marker if it starts at the beginning of a line.
2672   if (CurPtr != BufferStart &&
2673       CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2674     return false;
2675   
2676   // Check to see if we have <<<<<<< or >>>>.
2677   if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2678       !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2679     return false;
2680
2681   // If we have a situation where we don't care about conflict markers, ignore
2682   // it.
2683   if (CurrentConflictMarkerState || isLexingRawMode())
2684     return false;
2685   
2686   ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2687
2688   // Check to see if there is an ending marker somewhere in the buffer at the
2689   // start of a line to terminate this conflict marker.
2690   if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2691     // We found a match.  We are really in a conflict marker.
2692     // Diagnose this, and ignore to the end of line.
2693     Diag(CurPtr, diag::err_conflict_marker);
2694     CurrentConflictMarkerState = Kind;
2695     
2696     // Skip ahead to the end of line.  We know this exists because the
2697     // end-of-conflict marker starts with \r or \n.
2698     while (*CurPtr != '\r' && *CurPtr != '\n') {
2699       assert(CurPtr != BufferEnd && "Didn't find end of line");
2700       ++CurPtr;
2701     }
2702     BufferPtr = CurPtr;
2703     return true;
2704   }
2705   
2706   // No end of conflict marker found.
2707   return false;
2708 }
2709
2710 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2711 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2712 /// is the end of a conflict marker.  Handle it by ignoring up until the end of
2713 /// the line.  This returns true if it is a conflict marker and false if not.
2714 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2715   // Only a conflict marker if it starts at the beginning of a line.
2716   if (CurPtr != BufferStart &&
2717       CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2718     return false;
2719   
2720   // If we have a situation where we don't care about conflict markers, ignore
2721   // it.
2722   if (!CurrentConflictMarkerState || isLexingRawMode())
2723     return false;
2724   
2725   // Check to see if we have the marker (4 characters in a row).
2726   for (unsigned i = 1; i != 4; ++i)
2727     if (CurPtr[i] != CurPtr[0])
2728       return false;
2729   
2730   // If we do have it, search for the end of the conflict marker.  This could
2731   // fail if it got skipped with a '#if 0' or something.  Note that CurPtr might
2732   // be the end of conflict marker.
2733   if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2734                                         CurrentConflictMarkerState)) {
2735     CurPtr = End;
2736     
2737     // Skip ahead to the end of line.
2738     while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2739       ++CurPtr;
2740     
2741     BufferPtr = CurPtr;
2742     
2743     // No longer in the conflict marker.
2744     CurrentConflictMarkerState = CMK_None;
2745     return true;
2746   }
2747   
2748   return false;
2749 }
2750
2751 static const char *findPlaceholderEnd(const char *CurPtr,
2752                                       const char *BufferEnd) {
2753   if (CurPtr == BufferEnd)
2754     return nullptr;
2755   BufferEnd -= 1; // Scan until the second last character.
2756   for (; CurPtr != BufferEnd; ++CurPtr) {
2757     if (CurPtr[0] == '#' && CurPtr[1] == '>')
2758       return CurPtr + 2;
2759   }
2760   return nullptr;
2761 }
2762
2763 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2764   assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2765   if (!PP || LexingRawMode)
2766     return false;
2767   const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2768   if (!End)
2769     return false;
2770   const char *Start = CurPtr - 1;
2771   if (!LangOpts.AllowEditorPlaceholders)
2772     Diag(Start, diag::err_placeholder_in_source);
2773   Result.startToken();
2774   FormTokenWithChars(Result, End, tok::raw_identifier);
2775   Result.setRawIdentifierData(Start);
2776   PP->LookUpIdentifierInfo(Result);
2777   Result.setFlag(Token::IsEditorPlaceholder);
2778   BufferPtr = End;
2779   return true;
2780 }
2781
2782 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2783   if (PP && PP->isCodeCompletionEnabled()) {
2784     SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2785     return Loc == PP->getCodeCompletionLoc();
2786   }
2787
2788   return false;
2789 }
2790
2791 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2792                            Token *Result) {
2793   unsigned CharSize;
2794   char Kind = getCharAndSize(StartPtr, CharSize);
2795
2796   unsigned NumHexDigits;
2797   if (Kind == 'u')
2798     NumHexDigits = 4;
2799   else if (Kind == 'U')
2800     NumHexDigits = 8;
2801   else
2802     return 0;
2803
2804   if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2805     if (Result && !isLexingRawMode())
2806       Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2807     return 0;
2808   }
2809
2810   const char *CurPtr = StartPtr + CharSize;
2811   const char *KindLoc = &CurPtr[-1];
2812
2813   uint32_t CodePoint = 0;
2814   for (unsigned i = 0; i < NumHexDigits; ++i) {
2815     char C = getCharAndSize(CurPtr, CharSize);
2816
2817     unsigned Value = llvm::hexDigitValue(C);
2818     if (Value == -1U) {
2819       if (Result && !isLexingRawMode()) {
2820         if (i == 0) {
2821           Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2822             << StringRef(KindLoc, 1);
2823         } else {
2824           Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2825
2826           // If the user wrote \U1234, suggest a fixit to \u.
2827           if (i == 4 && NumHexDigits == 8) {
2828             CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2829             Diag(KindLoc, diag::note_ucn_four_not_eight)
2830               << FixItHint::CreateReplacement(URange, "u");
2831           }
2832         }
2833       }
2834
2835       return 0;
2836     }
2837
2838     CodePoint <<= 4;
2839     CodePoint += Value;
2840
2841     CurPtr += CharSize;
2842   }
2843
2844   if (Result) {
2845     Result->setFlag(Token::HasUCN);
2846     if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2847       StartPtr = CurPtr;
2848     else
2849       while (StartPtr != CurPtr)
2850         (void)getAndAdvanceChar(StartPtr, *Result);
2851   } else {
2852     StartPtr = CurPtr;
2853   }
2854
2855   // Don't apply C family restrictions to UCNs in assembly mode
2856   if (LangOpts.AsmPreprocessor)
2857     return CodePoint;
2858
2859   // C99 6.4.3p2: A universal character name shall not specify a character whose
2860   //   short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2861   //   0060 (`), nor one in the range D800 through DFFF inclusive.)
2862   // C++11 [lex.charset]p2: If the hexadecimal value for a
2863   //   universal-character-name corresponds to a surrogate code point (in the
2864   //   range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2865   //   if the hexadecimal value for a universal-character-name outside the
2866   //   c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2867   //   string literal corresponds to a control character (in either of the
2868   //   ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2869   //   basic source character set, the program is ill-formed.
2870   if (CodePoint < 0xA0) {
2871     if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2872       return CodePoint;
2873
2874     // We don't use isLexingRawMode() here because we need to warn about bad
2875     // UCNs even when skipping preprocessing tokens in a #if block.
2876     if (Result && PP) {
2877       if (CodePoint < 0x20 || CodePoint >= 0x7F)
2878         Diag(BufferPtr, diag::err_ucn_control_character);
2879       else {
2880         char C = static_cast<char>(CodePoint);
2881         Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2882       }
2883     }
2884
2885     return 0;
2886
2887   } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2888     // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2889     // We don't use isLexingRawMode() here because we need to diagnose bad
2890     // UCNs even when skipping preprocessing tokens in a #if block.
2891     if (Result && PP) {
2892       if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2893         Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2894       else
2895         Diag(BufferPtr, diag::err_ucn_escape_invalid);
2896     }
2897     return 0;
2898   }
2899
2900   return CodePoint;
2901 }
2902
2903 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2904                                    const char *CurPtr) {
2905   static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2906       UnicodeWhitespaceCharRanges);
2907   if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2908       UnicodeWhitespaceChars.contains(C)) {
2909     Diag(BufferPtr, diag::ext_unicode_whitespace)
2910       << makeCharRange(*this, BufferPtr, CurPtr);
2911
2912     Result.setFlag(Token::LeadingSpace);
2913     return true;
2914   }
2915   return false;
2916 }
2917
2918 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2919   if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2920     if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2921         !PP->isPreprocessedOutput()) {
2922       maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2923                                 makeCharRange(*this, BufferPtr, CurPtr),
2924                                 /*IsFirst=*/true);
2925     }
2926
2927     MIOpt.ReadToken();
2928     return LexIdentifier(Result, CurPtr);
2929   }
2930
2931   if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2932       !PP->isPreprocessedOutput() &&
2933       !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2934     // Non-ASCII characters tend to creep into source code unintentionally.
2935     // Instead of letting the parser complain about the unknown token,
2936     // just drop the character.
2937     // Note that we can /only/ do this when the non-ASCII character is actually
2938     // spelled as Unicode, not written as a UCN. The standard requires that
2939     // we not throw away any possible preprocessor tokens, but there's a
2940     // loophole in the mapping of Unicode characters to basic character set
2941     // characters that allows us to map these particular characters to, say,
2942     // whitespace.
2943     Diag(BufferPtr, diag::err_non_ascii)
2944       << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2945
2946     BufferPtr = CurPtr;
2947     return false;
2948   }
2949
2950   // Otherwise, we have an explicit UCN or a character that's unlikely to show
2951   // up by accident.
2952   MIOpt.ReadToken();
2953   FormTokenWithChars(Result, CurPtr, tok::unknown);
2954   return true;
2955 }
2956
2957 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2958   IsAtStartOfLine = Result.isAtStartOfLine();
2959   HasLeadingSpace = Result.hasLeadingSpace();
2960   HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2961   // Note that this doesn't affect IsAtPhysicalStartOfLine.
2962 }
2963
2964 bool Lexer::Lex(Token &Result) {
2965   // Start a new token.
2966   Result.startToken();
2967
2968   // Set up misc whitespace flags for LexTokenInternal.
2969   if (IsAtStartOfLine) {
2970     Result.setFlag(Token::StartOfLine);
2971     IsAtStartOfLine = false;
2972   }
2973
2974   if (HasLeadingSpace) {
2975     Result.setFlag(Token::LeadingSpace);
2976     HasLeadingSpace = false;
2977   }
2978
2979   if (HasLeadingEmptyMacro) {
2980     Result.setFlag(Token::LeadingEmptyMacro);
2981     HasLeadingEmptyMacro = false;
2982   }
2983
2984   bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2985   IsAtPhysicalStartOfLine = false;
2986   bool isRawLex = isLexingRawMode();
2987   (void) isRawLex;
2988   bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2989   // (After the LexTokenInternal call, the lexer might be destroyed.)
2990   assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2991   return returnedToken;
2992 }
2993
2994 /// LexTokenInternal - This implements a simple C family lexer.  It is an
2995 /// extremely performance critical piece of code.  This assumes that the buffer
2996 /// has a null character at the end of the file.  This returns a preprocessing
2997 /// token, not a normal token, as such, it is an internal interface.  It assumes
2998 /// that the Flags of result have been cleared before calling this.
2999 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3000 LexNextToken:
3001   // New token, can't need cleaning yet.
3002   Result.clearFlag(Token::NeedsCleaning);
3003   Result.setIdentifierInfo(nullptr);
3004
3005   // CurPtr - Cache BufferPtr in an automatic variable.
3006   const char *CurPtr = BufferPtr;
3007
3008   // Small amounts of horizontal whitespace is very common between tokens.
3009   if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3010     ++CurPtr;
3011     while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3012       ++CurPtr;
3013
3014     // If we are keeping whitespace and other tokens, just return what we just
3015     // skipped.  The next lexer invocation will return the token after the
3016     // whitespace.
3017     if (isKeepWhitespaceMode()) {
3018       FormTokenWithChars(Result, CurPtr, tok::unknown);
3019       // FIXME: The next token will not have LeadingSpace set.
3020       return true;
3021     }
3022
3023     BufferPtr = CurPtr;
3024     Result.setFlag(Token::LeadingSpace);
3025   }
3026
3027   unsigned SizeTmp, SizeTmp2;   // Temporaries for use in cases below.
3028
3029   // Read a character, advancing over it.
3030   char Char = getAndAdvanceChar(CurPtr, Result);
3031   tok::TokenKind Kind;
3032
3033   switch (Char) {
3034   case 0:  // Null.
3035     // Found end of file?
3036     if (CurPtr-1 == BufferEnd)
3037       return LexEndOfFile(Result, CurPtr-1);
3038
3039     // Check if we are performing code completion.
3040     if (isCodeCompletionPoint(CurPtr-1)) {
3041       // Return the code-completion token.
3042       Result.startToken();
3043       FormTokenWithChars(Result, CurPtr, tok::code_completion);
3044       return true;
3045     }
3046
3047     if (!isLexingRawMode())
3048       Diag(CurPtr-1, diag::null_in_file);
3049     Result.setFlag(Token::LeadingSpace);
3050     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3051       return true; // KeepWhitespaceMode
3052
3053     // We know the lexer hasn't changed, so just try again with this lexer.
3054     // (We manually eliminate the tail call to avoid recursion.)
3055     goto LexNextToken;
3056       
3057   case 26:  // DOS & CP/M EOF: "^Z".
3058     // If we're in Microsoft extensions mode, treat this as end of file.
3059     if (LangOpts.MicrosoftExt) {
3060       if (!isLexingRawMode())
3061         Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3062       return LexEndOfFile(Result, CurPtr-1);
3063     }
3064
3065     // If Microsoft extensions are disabled, this is just random garbage.
3066     Kind = tok::unknown;
3067     break;
3068       
3069   case '\n':
3070   case '\r':
3071     // If we are inside a preprocessor directive and we see the end of line,
3072     // we know we are done with the directive, so return an EOD token.
3073     if (ParsingPreprocessorDirective) {
3074       // Done parsing the "line".
3075       ParsingPreprocessorDirective = false;
3076
3077       // Restore comment saving mode, in case it was disabled for directive.
3078       if (PP)
3079         resetExtendedTokenMode();
3080
3081       // Since we consumed a newline, we are back at the start of a line.
3082       IsAtStartOfLine = true;
3083       IsAtPhysicalStartOfLine = true;
3084
3085       Kind = tok::eod;
3086       break;
3087     }
3088
3089     // No leading whitespace seen so far.
3090     Result.clearFlag(Token::LeadingSpace);
3091
3092     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3093       return true; // KeepWhitespaceMode
3094
3095     // We only saw whitespace, so just try again with this lexer.
3096     // (We manually eliminate the tail call to avoid recursion.)
3097     goto LexNextToken;
3098   case ' ':
3099   case '\t':
3100   case '\f':
3101   case '\v':
3102   SkipHorizontalWhitespace:
3103     Result.setFlag(Token::LeadingSpace);
3104     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3105       return true; // KeepWhitespaceMode
3106
3107   SkipIgnoredUnits:
3108     CurPtr = BufferPtr;
3109
3110     // If the next token is obviously a // or /* */ comment, skip it efficiently
3111     // too (without going through the big switch stmt).
3112     if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3113         LangOpts.LineComment &&
3114         (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3115       if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3116         return true; // There is a token to return.
3117       goto SkipIgnoredUnits;
3118     } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3119       if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3120         return true; // There is a token to return.
3121       goto SkipIgnoredUnits;
3122     } else if (isHorizontalWhitespace(*CurPtr)) {
3123       goto SkipHorizontalWhitespace;
3124     }
3125     // We only saw whitespace, so just try again with this lexer.
3126     // (We manually eliminate the tail call to avoid recursion.)
3127     goto LexNextToken;
3128       
3129   // C99 6.4.4.1: Integer Constants.
3130   // C99 6.4.4.2: Floating Constants.
3131   case '0': case '1': case '2': case '3': case '4':
3132   case '5': case '6': case '7': case '8': case '9':
3133     // Notify MIOpt that we read a non-whitespace/non-comment token.
3134     MIOpt.ReadToken();
3135     return LexNumericConstant(Result, CurPtr);
3136
3137   case 'u':   // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3138     // Notify MIOpt that we read a non-whitespace/non-comment token.
3139     MIOpt.ReadToken();
3140
3141     if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3142       Char = getCharAndSize(CurPtr, SizeTmp);
3143
3144       // UTF-16 string literal
3145       if (Char == '"')
3146         return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3147                                 tok::utf16_string_literal);
3148
3149       // UTF-16 character constant
3150       if (Char == '\'')
3151         return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3152                                tok::utf16_char_constant);
3153
3154       // UTF-16 raw string literal
3155       if (Char == 'R' && LangOpts.CPlusPlus11 &&
3156           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3157         return LexRawStringLiteral(Result,
3158                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3159                                            SizeTmp2, Result),
3160                                tok::utf16_string_literal);
3161
3162       if (Char == '8') {
3163         char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3164
3165         // UTF-8 string literal
3166         if (Char2 == '"')
3167           return LexStringLiteral(Result,
3168                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3169                                            SizeTmp2, Result),
3170                                tok::utf8_string_literal);
3171         if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3172           return LexCharConstant(
3173               Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3174                                   SizeTmp2, Result),
3175               tok::utf8_char_constant);
3176
3177         if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3178           unsigned SizeTmp3;
3179           char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3180           // UTF-8 raw string literal
3181           if (Char3 == '"') {
3182             return LexRawStringLiteral(Result,
3183                    ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3184                                            SizeTmp2, Result),
3185                                SizeTmp3, Result),
3186                    tok::utf8_string_literal);
3187           }
3188         }
3189       }
3190     }
3191
3192     // treat u like the start of an identifier.
3193     return LexIdentifier(Result, CurPtr);
3194
3195   case 'U':   // Identifier (Uber) or C11/C++11 UTF-32 string literal
3196     // Notify MIOpt that we read a non-whitespace/non-comment token.
3197     MIOpt.ReadToken();
3198
3199     if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3200       Char = getCharAndSize(CurPtr, SizeTmp);
3201
3202       // UTF-32 string literal
3203       if (Char == '"')
3204         return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3205                                 tok::utf32_string_literal);
3206
3207       // UTF-32 character constant
3208       if (Char == '\'')
3209         return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3210                                tok::utf32_char_constant);
3211
3212       // UTF-32 raw string literal
3213       if (Char == 'R' && LangOpts.CPlusPlus11 &&
3214           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3215         return LexRawStringLiteral(Result,
3216                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3217                                            SizeTmp2, Result),
3218                                tok::utf32_string_literal);
3219     }
3220
3221     // treat U like the start of an identifier.
3222     return LexIdentifier(Result, CurPtr);
3223
3224   case 'R': // Identifier or C++0x raw string literal
3225     // Notify MIOpt that we read a non-whitespace/non-comment token.
3226     MIOpt.ReadToken();
3227
3228     if (LangOpts.CPlusPlus11) {
3229       Char = getCharAndSize(CurPtr, SizeTmp);
3230
3231       if (Char == '"')
3232         return LexRawStringLiteral(Result,
3233                                    ConsumeChar(CurPtr, SizeTmp, Result),
3234                                    tok::string_literal);
3235     }
3236
3237     // treat R like the start of an identifier.
3238     return LexIdentifier(Result, CurPtr);
3239
3240   case 'L':   // Identifier (Loony) or wide literal (L'x' or L"xyz").
3241     // Notify MIOpt that we read a non-whitespace/non-comment token.
3242     MIOpt.ReadToken();
3243     Char = getCharAndSize(CurPtr, SizeTmp);
3244
3245     // Wide string literal.
3246     if (Char == '"')
3247       return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3248                               tok::wide_string_literal);
3249
3250     // Wide raw string literal.
3251     if (LangOpts.CPlusPlus11 && Char == 'R' &&
3252         getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3253       return LexRawStringLiteral(Result,
3254                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3255                                            SizeTmp2, Result),
3256                                tok::wide_string_literal);
3257
3258     // Wide character constant.
3259     if (Char == '\'')
3260       return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3261                              tok::wide_char_constant);
3262     // FALL THROUGH, treating L like the start of an identifier.
3263
3264   // C99 6.4.2: Identifiers.
3265   case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3266   case 'H': case 'I': case 'J': case 'K':    /*'L'*/case 'M': case 'N':
3267   case 'O': case 'P': case 'Q':    /*'R'*/case 'S': case 'T':    /*'U'*/
3268   case 'V': case 'W': case 'X': case 'Y': case 'Z':
3269   case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3270   case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3271   case 'o': case 'p': case 'q': case 'r': case 's': case 't':    /*'u'*/
3272   case 'v': case 'w': case 'x': case 'y': case 'z':
3273   case '_':
3274     // Notify MIOpt that we read a non-whitespace/non-comment token.
3275     MIOpt.ReadToken();
3276     return LexIdentifier(Result, CurPtr);
3277
3278   case '$':   // $ in identifiers.
3279     if (LangOpts.DollarIdents) {
3280       if (!isLexingRawMode())
3281         Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3282       // Notify MIOpt that we read a non-whitespace/non-comment token.
3283       MIOpt.ReadToken();
3284       return LexIdentifier(Result, CurPtr);
3285     }
3286
3287     Kind = tok::unknown;
3288     break;
3289
3290   // C99 6.4.4: Character Constants.
3291   case '\'':
3292     // Notify MIOpt that we read a non-whitespace/non-comment token.
3293     MIOpt.ReadToken();
3294     return LexCharConstant(Result, CurPtr, tok::char_constant);
3295
3296   // C99 6.4.5: String Literals.
3297   case '"':
3298     // Notify MIOpt that we read a non-whitespace/non-comment token.
3299     MIOpt.ReadToken();
3300     return LexStringLiteral(Result, CurPtr, tok::string_literal);
3301
3302   // C99 6.4.6: Punctuators.
3303   case '?':
3304     Kind = tok::question;
3305     break;
3306   case '[':
3307     Kind = tok::l_square;
3308     break;
3309   case ']':
3310     Kind = tok::r_square;
3311     break;
3312   case '(':
3313     Kind = tok::l_paren;
3314     break;
3315   case ')':
3316     Kind = tok::r_paren;
3317     break;
3318   case '{':
3319     Kind = tok::l_brace;
3320     break;
3321   case '}':
3322     Kind = tok::r_brace;
3323     break;
3324   case '.':
3325     Char = getCharAndSize(CurPtr, SizeTmp);
3326     if (Char >= '0' && Char <= '9') {
3327       // Notify MIOpt that we read a non-whitespace/non-comment token.
3328       MIOpt.ReadToken();
3329
3330       return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3331     } else if (LangOpts.CPlusPlus && Char == '*') {
3332       Kind = tok::periodstar;
3333       CurPtr += SizeTmp;
3334     } else if (Char == '.' &&
3335                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3336       Kind = tok::ellipsis;
3337       CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3338                            SizeTmp2, Result);
3339     } else {
3340       Kind = tok::period;
3341     }
3342     break;
3343   case '&':
3344     Char = getCharAndSize(CurPtr, SizeTmp);
3345     if (Char == '&') {
3346       Kind = tok::ampamp;
3347       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3348     } else if (Char == '=') {
3349       Kind = tok::ampequal;
3350       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3351     } else {
3352       Kind = tok::amp;
3353     }
3354     break;
3355   case '*':
3356     if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3357       Kind = tok::starequal;
3358       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3359     } else {
3360       Kind = tok::star;
3361     }
3362     break;
3363   case '+':
3364     Char = getCharAndSize(CurPtr, SizeTmp);
3365     if (Char == '+') {
3366       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3367       Kind = tok::plusplus;
3368     } else if (Char == '=') {
3369       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3370       Kind = tok::plusequal;
3371     } else {
3372       Kind = tok::plus;
3373     }
3374     break;
3375   case '-':
3376     Char = getCharAndSize(CurPtr, SizeTmp);
3377     if (Char == '-') {      // --
3378       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3379       Kind = tok::minusminus;
3380     } else if (Char == '>' && LangOpts.CPlusPlus &&
3381                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {  // C++ ->*
3382       CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3383                            SizeTmp2, Result);
3384       Kind = tok::arrowstar;
3385     } else if (Char == '>') {   // ->
3386       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3387       Kind = tok::arrow;
3388     } else if (Char == '=') {   // -=
3389       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3390       Kind = tok::minusequal;
3391     } else {
3392       Kind = tok::minus;
3393     }
3394     break;
3395   case '~':
3396     Kind = tok::tilde;
3397     break;
3398   case '!':
3399     if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3400       Kind = tok::exclaimequal;
3401       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3402     } else {
3403       Kind = tok::exclaim;
3404     }
3405     break;
3406   case '/':
3407     // 6.4.9: Comments
3408     Char = getCharAndSize(CurPtr, SizeTmp);
3409     if (Char == '/') {         // Line comment.
3410       // Even if Line comments are disabled (e.g. in C89 mode), we generally
3411       // want to lex this as a comment.  There is one problem with this though,
3412       // that in one particular corner case, this can change the behavior of the
3413       // resultant program.  For example, In  "foo //**/ bar", C89 would lex
3414       // this as "foo / bar" and langauges with Line comments would lex it as
3415       // "foo".  Check to see if the character after the second slash is a '*'.
3416       // If so, we will lex that as a "/" instead of the start of a comment.
3417       // However, we never do this if we are just preprocessing.
3418       bool TreatAsComment = LangOpts.LineComment &&
3419                             (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3420       if (!TreatAsComment)
3421         if (!(PP && PP->isPreprocessedOutput()))
3422           TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3423
3424       if (TreatAsComment) {
3425         if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3426                             TokAtPhysicalStartOfLine))
3427           return true; // There is a token to return.
3428
3429         // It is common for the tokens immediately after a // comment to be
3430         // whitespace (indentation for the next line).  Instead of going through
3431         // the big switch, handle it efficiently now.
3432         goto SkipIgnoredUnits;
3433       }
3434     }
3435
3436     if (Char == '*') {  // /**/ comment.
3437       if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3438                            TokAtPhysicalStartOfLine))
3439         return true; // There is a token to return.
3440
3441       // We only saw whitespace, so just try again with this lexer.
3442       // (We manually eliminate the tail call to avoid recursion.)
3443       goto LexNextToken;
3444     }
3445
3446     if (Char == '=') {
3447       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3448       Kind = tok::slashequal;
3449     } else {
3450       Kind = tok::slash;
3451     }
3452     break;
3453   case '%':
3454     Char = getCharAndSize(CurPtr, SizeTmp);
3455     if (Char == '=') {
3456       Kind = tok::percentequal;
3457       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3458     } else if (LangOpts.Digraphs && Char == '>') {
3459       Kind = tok::r_brace;                             // '%>' -> '}'
3460       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3461     } else if (LangOpts.Digraphs && Char == ':') {
3462       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3463       Char = getCharAndSize(CurPtr, SizeTmp);
3464       if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3465         Kind = tok::hashhash;                          // '%:%:' -> '##'
3466         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3467                              SizeTmp2, Result);
3468       } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3469         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3470         if (!isLexingRawMode())
3471           Diag(BufferPtr, diag::ext_charize_microsoft);
3472         Kind = tok::hashat;
3473       } else {                                         // '%:' -> '#'
3474         // We parsed a # character.  If this occurs at the start of the line,
3475         // it's actually the start of a preprocessing directive.  Callback to
3476         // the preprocessor to handle it.
3477         // TODO: -fpreprocessed mode??
3478         if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3479           goto HandleDirective;
3480
3481         Kind = tok::hash;
3482       }
3483     } else {
3484       Kind = tok::percent;
3485     }
3486     break;
3487   case '<':
3488     Char = getCharAndSize(CurPtr, SizeTmp);
3489     if (ParsingFilename) {
3490       return LexAngledStringLiteral(Result, CurPtr);
3491     } else if (Char == '<') {
3492       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3493       if (After == '=') {
3494         Kind = tok::lesslessequal;
3495         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3496                              SizeTmp2, Result);
3497       } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3498         // If this is actually a '<<<<<<<' version control conflict marker,
3499         // recognize it as such and recover nicely.
3500         goto LexNextToken;
3501       } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3502         // If this is '<<<<' and we're in a Perforce-style conflict marker,
3503         // ignore it.
3504         goto LexNextToken;
3505       } else if (LangOpts.CUDA && After == '<') {
3506         Kind = tok::lesslessless;
3507         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3508                              SizeTmp2, Result);
3509       } else {
3510         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3511         Kind = tok::lessless;
3512       }
3513     } else if (Char == '=') {
3514       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3515       Kind = tok::lessequal;
3516     } else if (LangOpts.Digraphs && Char == ':') {     // '<:' -> '['
3517       if (LangOpts.CPlusPlus11 &&
3518           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3519         // C++0x [lex.pptoken]p3:
3520         //  Otherwise, if the next three characters are <:: and the subsequent
3521         //  character is neither : nor >, the < is treated as a preprocessor
3522         //  token by itself and not as the first character of the alternative
3523         //  token <:.
3524         unsigned SizeTmp3;
3525         char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3526         if (After != ':' && After != '>') {
3527           Kind = tok::less;
3528           if (!isLexingRawMode())
3529             Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3530           break;
3531         }
3532       }
3533
3534       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3535       Kind = tok::l_square;
3536     } else if (LangOpts.Digraphs && Char == '%') {     // '<%' -> '{'
3537       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3538       Kind = tok::l_brace;
3539     } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3540       return true;
3541     } else {
3542       Kind = tok::less;
3543     }
3544     break;
3545   case '>':
3546     Char = getCharAndSize(CurPtr, SizeTmp);
3547     if (Char == '=') {
3548       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3549       Kind = tok::greaterequal;
3550     } else if (Char == '>') {
3551       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3552       if (After == '=') {
3553         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3554                              SizeTmp2, Result);
3555         Kind = tok::greatergreaterequal;
3556       } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3557         // If this is actually a '>>>>' conflict marker, recognize it as such
3558         // and recover nicely.
3559         goto LexNextToken;
3560       } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3561         // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3562         goto LexNextToken;
3563       } else if (LangOpts.CUDA && After == '>') {
3564         Kind = tok::greatergreatergreater;
3565         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3566                              SizeTmp2, Result);
3567       } else {
3568         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3569         Kind = tok::greatergreater;
3570       }
3571     } else {
3572       Kind = tok::greater;
3573     }
3574     break;
3575   case '^':
3576     Char = getCharAndSize(CurPtr, SizeTmp);
3577     if (Char == '=') {
3578       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3579       Kind = tok::caretequal;
3580     } else if (LangOpts.OpenCL && Char == '^') {
3581       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3582       Kind = tok::caretcaret;
3583     } else {
3584       Kind = tok::caret;
3585     }
3586     break;
3587   case '|':
3588     Char = getCharAndSize(CurPtr, SizeTmp);
3589     if (Char == '=') {
3590       Kind = tok::pipeequal;
3591       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3592     } else if (Char == '|') {
3593       // If this is '|||||||' and we're in a conflict marker, ignore it.
3594       if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3595         goto LexNextToken;
3596       Kind = tok::pipepipe;
3597       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3598     } else {
3599       Kind = tok::pipe;
3600     }
3601     break;
3602   case ':':
3603     Char = getCharAndSize(CurPtr, SizeTmp);
3604     if (LangOpts.Digraphs && Char == '>') {
3605       Kind = tok::r_square; // ':>' -> ']'
3606       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3607     } else if (LangOpts.CPlusPlus && Char == ':') {
3608       Kind = tok::coloncolon;
3609       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3610     } else {
3611       Kind = tok::colon;
3612     }
3613     break;
3614   case ';':
3615     Kind = tok::semi;
3616     break;
3617   case '=':
3618     Char = getCharAndSize(CurPtr, SizeTmp);
3619     if (Char == '=') {
3620       // If this is '====' and we're in a conflict marker, ignore it.
3621       if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3622         goto LexNextToken;
3623       
3624       Kind = tok::equalequal;
3625       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3626     } else {
3627       Kind = tok::equal;
3628     }
3629     break;
3630   case ',':
3631     Kind = tok::comma;
3632     break;
3633   case '#':
3634     Char = getCharAndSize(CurPtr, SizeTmp);
3635     if (Char == '#') {
3636       Kind = tok::hashhash;
3637       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3638     } else if (Char == '@' && LangOpts.MicrosoftExt) {  // #@ -> Charize
3639       Kind = tok::hashat;
3640       if (!isLexingRawMode())
3641         Diag(BufferPtr, diag::ext_charize_microsoft);
3642       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3643     } else {
3644       // We parsed a # character.  If this occurs at the start of the line,
3645       // it's actually the start of a preprocessing directive.  Callback to
3646       // the preprocessor to handle it.
3647       // TODO: -fpreprocessed mode??
3648       if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3649         goto HandleDirective;
3650
3651       Kind = tok::hash;
3652     }
3653     break;
3654
3655   case '@':
3656     // Objective C support.
3657     if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3658       Kind = tok::at;
3659     else
3660       Kind = tok::unknown;
3661     break;
3662
3663   // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3664   case '\\':
3665     if (!LangOpts.AsmPreprocessor) {
3666       if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3667         if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3668           if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3669             return true; // KeepWhitespaceMode
3670
3671           // We only saw whitespace, so just try again with this lexer.
3672           // (We manually eliminate the tail call to avoid recursion.)
3673           goto LexNextToken;
3674         }
3675
3676         return LexUnicode(Result, CodePoint, CurPtr);
3677       }
3678     }
3679
3680     Kind = tok::unknown;
3681     break;
3682
3683   default: {
3684     if (isASCII(Char)) {
3685       Kind = tok::unknown;
3686       break;
3687     }
3688
3689     llvm::UTF32 CodePoint;
3690
3691     // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3692     // an escaped newline.
3693     --CurPtr;
3694     llvm::ConversionResult Status =
3695         llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3696                                   (const llvm::UTF8 *)BufferEnd,
3697                                   &CodePoint,
3698                                   llvm::strictConversion);
3699     if (Status == llvm::conversionOK) {
3700       if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3701         if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3702           return true; // KeepWhitespaceMode
3703
3704         // We only saw whitespace, so just try again with this lexer.
3705         // (We manually eliminate the tail call to avoid recursion.)
3706         goto LexNextToken;
3707       }
3708       return LexUnicode(Result, CodePoint, CurPtr);
3709     }
3710     
3711     if (isLexingRawMode() || ParsingPreprocessorDirective ||
3712         PP->isPreprocessedOutput()) {
3713       ++CurPtr;
3714       Kind = tok::unknown;
3715       break;
3716     }
3717
3718     // Non-ASCII characters tend to creep into source code unintentionally.
3719     // Instead of letting the parser complain about the unknown token,
3720     // just diagnose the invalid UTF-8, then drop the character.
3721     Diag(CurPtr, diag::err_invalid_utf8);
3722
3723     BufferPtr = CurPtr+1;
3724     // We're pretending the character didn't exist, so just try again with
3725     // this lexer.
3726     // (We manually eliminate the tail call to avoid recursion.)
3727     goto LexNextToken;
3728   }
3729   }
3730
3731   // Notify MIOpt that we read a non-whitespace/non-comment token.
3732   MIOpt.ReadToken();
3733
3734   // Update the location of token as well as BufferPtr.
3735   FormTokenWithChars(Result, CurPtr, Kind);
3736   return true;
3737
3738 HandleDirective:
3739   // We parsed a # character and it's the start of a preprocessing directive.
3740
3741   FormTokenWithChars(Result, CurPtr, tok::hash);
3742   PP->HandleDirective(Result);
3743
3744   if (PP->hadModuleLoaderFatalFailure()) {
3745     // With a fatal failure in the module loader, we abort parsing.
3746     assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3747     return true;
3748   }
3749
3750   // We parsed the directive; lex a token with the new state.
3751   return false;
3752 }