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