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