xref: /freebsd/contrib/llvm-project/llvm/lib/AsmParser/LLLexer.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
1 //===- LLLexer.cpp - Lexer for .ll Files ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the Lexer for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/AsmParser/LLLexer.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include <cassert>
23 #include <cctype>
24 #include <cstdio>
25 
26 using namespace llvm;
27 
28 bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
29   ErrorInfo = SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
30   return true;
31 }
32 
33 void LLLexer::Warning(LocTy WarningLoc, const Twine &Msg) const {
34   SM.PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
35 }
36 
37 //===----------------------------------------------------------------------===//
38 // Helper functions.
39 //===----------------------------------------------------------------------===//
40 
41 // atoull - Convert an ascii string of decimal digits into the unsigned long
42 // long representation... this does not have to do input error checking,
43 // because we know that the input will be matched by a suitable regex...
44 //
45 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
46   uint64_t Result = 0;
47   for (; Buffer != End; Buffer++) {
48     uint64_t OldRes = Result;
49     Result *= 10;
50     Result += *Buffer-'0';
51     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
52       Error("constant bigger than 64 bits detected!");
53       return 0;
54     }
55   }
56   return Result;
57 }
58 
59 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
60   uint64_t Result = 0;
61   for (; Buffer != End; ++Buffer) {
62     uint64_t OldRes = Result;
63     Result *= 16;
64     Result += hexDigitValue(*Buffer);
65 
66     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
67       Error("constant bigger than 64 bits detected!");
68       return 0;
69     }
70   }
71   return Result;
72 }
73 
74 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
75                            uint64_t Pair[2]) {
76   Pair[0] = 0;
77   if (End - Buffer >= 16) {
78     for (int i = 0; i < 16; i++, Buffer++) {
79       assert(Buffer != End);
80       Pair[0] *= 16;
81       Pair[0] += hexDigitValue(*Buffer);
82     }
83   }
84   Pair[1] = 0;
85   for (int i = 0; i < 16 && Buffer != End; i++, Buffer++) {
86     Pair[1] *= 16;
87     Pair[1] += hexDigitValue(*Buffer);
88   }
89   if (Buffer != End)
90     Error("constant bigger than 128 bits detected!");
91 }
92 
93 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
94 /// { low64, high16 } as usual for an APInt.
95 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
96                            uint64_t Pair[2]) {
97   Pair[1] = 0;
98   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
99     assert(Buffer != End);
100     Pair[1] *= 16;
101     Pair[1] += hexDigitValue(*Buffer);
102   }
103   Pair[0] = 0;
104   for (int i = 0; i < 16 && Buffer != End; i++, Buffer++) {
105     Pair[0] *= 16;
106     Pair[0] += hexDigitValue(*Buffer);
107   }
108   if (Buffer != End)
109     Error("constant bigger than 128 bits detected!");
110 }
111 
112 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
113 // appropriate character.
114 static void UnEscapeLexed(std::string &Str) {
115   if (Str.empty()) return;
116 
117   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
118   char *BOut = Buffer;
119   for (char *BIn = Buffer; BIn != EndBuffer; ) {
120     if (BIn[0] == '\\') {
121       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
122         *BOut++ = '\\'; // Two \ becomes one
123         BIn += 2;
124       } else if (BIn < EndBuffer-2 &&
125                  isxdigit(static_cast<unsigned char>(BIn[1])) &&
126                  isxdigit(static_cast<unsigned char>(BIn[2]))) {
127         *BOut = hexDigitValue(BIn[1]) * 16 + hexDigitValue(BIn[2]);
128         BIn += 3;                           // Skip over handled chars
129         ++BOut;
130       } else {
131         *BOut++ = *BIn++;
132       }
133     } else {
134       *BOut++ = *BIn++;
135     }
136   }
137   Str.resize(BOut-Buffer);
138 }
139 
140 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
141 static bool isLabelChar(char C) {
142   return isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
143          C == '.' || C == '_';
144 }
145 
146 /// isLabelTail - Return true if this pointer points to a valid end of a label.
147 static const char *isLabelTail(const char *CurPtr) {
148   while (true) {
149     if (CurPtr[0] == ':') return CurPtr+1;
150     if (!isLabelChar(CurPtr[0])) return nullptr;
151     ++CurPtr;
152   }
153 }
154 
155 //===----------------------------------------------------------------------===//
156 // Lexer definition.
157 //===----------------------------------------------------------------------===//
158 
159 LLLexer::LLLexer(StringRef StartBuf, SourceMgr &SM, SMDiagnostic &Err,
160                  LLVMContext &C)
161     : CurBuf(StartBuf), ErrorInfo(Err), SM(SM), Context(C) {
162   CurPtr = CurBuf.begin();
163 }
164 
165 int LLLexer::getNextChar() {
166   char CurChar = *CurPtr++;
167   switch (CurChar) {
168   default: return (unsigned char)CurChar;
169   case 0:
170     // A nul character in the stream is either the end of the current buffer or
171     // a random nul in the file.  Disambiguate that here.
172     if (CurPtr-1 != CurBuf.end())
173       return 0;  // Just whitespace.
174 
175     // Otherwise, return end of file.
176     --CurPtr;  // Another call to lex will return EOF again.
177     return EOF;
178   }
179 }
180 
181 lltok::Kind LLLexer::LexToken() {
182   while (true) {
183     TokStart = CurPtr;
184 
185     int CurChar = getNextChar();
186     switch (CurChar) {
187     default:
188       // Handle letters: [a-zA-Z_]
189       if (isalpha(static_cast<unsigned char>(CurChar)) || CurChar == '_')
190         return LexIdentifier();
191 
192       return lltok::Error;
193     case EOF: return lltok::Eof;
194     case 0:
195     case ' ':
196     case '\t':
197     case '\n':
198     case '\r':
199       // Ignore whitespace.
200       continue;
201     case '+': return LexPositive();
202     case '@': return LexAt();
203     case '$': return LexDollar();
204     case '%': return LexPercent();
205     case '"': return LexQuote();
206     case '.':
207       if (const char *Ptr = isLabelTail(CurPtr)) {
208         CurPtr = Ptr;
209         StrVal.assign(TokStart, CurPtr-1);
210         return lltok::LabelStr;
211       }
212       if (CurPtr[0] == '.' && CurPtr[1] == '.') {
213         CurPtr += 2;
214         return lltok::dotdotdot;
215       }
216       return lltok::Error;
217     case ';':
218       SkipLineComment();
219       continue;
220     case '!': return LexExclaim();
221     case '^':
222       return LexCaret();
223     case ':':
224       return lltok::colon;
225     case '#': return LexHash();
226     case '0': case '1': case '2': case '3': case '4':
227     case '5': case '6': case '7': case '8': case '9':
228     case '-':
229       return LexDigitOrNegative();
230     case '=': return lltok::equal;
231     case '[': return lltok::lsquare;
232     case ']': return lltok::rsquare;
233     case '{': return lltok::lbrace;
234     case '}': return lltok::rbrace;
235     case '<': return lltok::less;
236     case '>': return lltok::greater;
237     case '(': return lltok::lparen;
238     case ')': return lltok::rparen;
239     case ',': return lltok::comma;
240     case '*': return lltok::star;
241     case '|': return lltok::bar;
242     }
243   }
244 }
245 
246 void LLLexer::SkipLineComment() {
247   while (true) {
248     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
249       return;
250   }
251 }
252 
253 /// Lex all tokens that start with an @ character.
254 ///   GlobalVar   @\"[^\"]*\"
255 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
256 ///   GlobalVarID @[0-9]+
257 lltok::Kind LLLexer::LexAt() {
258   return LexVar(lltok::GlobalVar, lltok::GlobalID);
259 }
260 
261 lltok::Kind LLLexer::LexDollar() {
262   if (const char *Ptr = isLabelTail(TokStart)) {
263     CurPtr = Ptr;
264     StrVal.assign(TokStart, CurPtr - 1);
265     return lltok::LabelStr;
266   }
267 
268   // Handle DollarStringConstant: $\"[^\"]*\"
269   if (CurPtr[0] == '"') {
270     ++CurPtr;
271 
272     while (true) {
273       int CurChar = getNextChar();
274 
275       if (CurChar == EOF) {
276         Error("end of file in COMDAT variable name");
277         return lltok::Error;
278       }
279       if (CurChar == '"') {
280         StrVal.assign(TokStart + 2, CurPtr - 1);
281         UnEscapeLexed(StrVal);
282         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
283           Error("Null bytes are not allowed in names");
284           return lltok::Error;
285         }
286         return lltok::ComdatVar;
287       }
288     }
289   }
290 
291   // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
292   if (ReadVarName())
293     return lltok::ComdatVar;
294 
295   return lltok::Error;
296 }
297 
298 /// ReadString - Read a string until the closing quote.
299 lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
300   const char *Start = CurPtr;
301   while (true) {
302     int CurChar = getNextChar();
303 
304     if (CurChar == EOF) {
305       Error("end of file in string constant");
306       return lltok::Error;
307     }
308     if (CurChar == '"') {
309       StrVal.assign(Start, CurPtr-1);
310       UnEscapeLexed(StrVal);
311       return kind;
312     }
313   }
314 }
315 
316 /// ReadVarName - Read the rest of a token containing a variable name.
317 bool LLLexer::ReadVarName() {
318   const char *NameStart = CurPtr;
319   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
320       CurPtr[0] == '-' || CurPtr[0] == '$' ||
321       CurPtr[0] == '.' || CurPtr[0] == '_') {
322     ++CurPtr;
323     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
324            CurPtr[0] == '-' || CurPtr[0] == '$' ||
325            CurPtr[0] == '.' || CurPtr[0] == '_')
326       ++CurPtr;
327 
328     StrVal.assign(NameStart, CurPtr);
329     return true;
330   }
331   return false;
332 }
333 
334 // Lex an ID: [0-9]+. On success, the ID is stored in UIntVal and Token is
335 // returned, otherwise the Error token is returned.
336 lltok::Kind LLLexer::LexUIntID(lltok::Kind Token) {
337   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
338     return lltok::Error;
339 
340   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
341     /*empty*/;
342 
343   uint64_t Val = atoull(TokStart + 1, CurPtr);
344   if ((unsigned)Val != Val)
345     Error("invalid value number (too large)!");
346   UIntVal = unsigned(Val);
347   return Token;
348 }
349 
350 lltok::Kind LLLexer::LexVar(lltok::Kind Var, lltok::Kind VarID) {
351   // Handle StringConstant: \"[^\"]*\"
352   if (CurPtr[0] == '"') {
353     ++CurPtr;
354 
355     while (true) {
356       int CurChar = getNextChar();
357 
358       if (CurChar == EOF) {
359         Error("end of file in global variable name");
360         return lltok::Error;
361       }
362       if (CurChar == '"') {
363         StrVal.assign(TokStart+2, CurPtr-1);
364         UnEscapeLexed(StrVal);
365         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
366           Error("Null bytes are not allowed in names");
367           return lltok::Error;
368         }
369         return Var;
370       }
371     }
372   }
373 
374   // Handle VarName: [-a-zA-Z$._][-a-zA-Z$._0-9]*
375   if (ReadVarName())
376     return Var;
377 
378   // Handle VarID: [0-9]+
379   return LexUIntID(VarID);
380 }
381 
382 /// Lex all tokens that start with a % character.
383 ///   LocalVar   ::= %\"[^\"]*\"
384 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
385 ///   LocalVarID ::= %[0-9]+
386 lltok::Kind LLLexer::LexPercent() {
387   return LexVar(lltok::LocalVar, lltok::LocalVarID);
388 }
389 
390 /// Lex all tokens that start with a " character.
391 ///   QuoteLabel        "[^"]+":
392 ///   StringConstant    "[^"]*"
393 lltok::Kind LLLexer::LexQuote() {
394   lltok::Kind kind = ReadString(lltok::StringConstant);
395   if (kind == lltok::Error || kind == lltok::Eof)
396     return kind;
397 
398   if (CurPtr[0] == ':') {
399     ++CurPtr;
400     if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
401       Error("Null bytes are not allowed in names");
402       kind = lltok::Error;
403     } else {
404       kind = lltok::LabelStr;
405     }
406   }
407 
408   return kind;
409 }
410 
411 /// Lex all tokens that start with a ! character.
412 ///    !foo
413 ///    !
414 lltok::Kind LLLexer::LexExclaim() {
415   // Lex a metadata name as a MetadataVar.
416   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
417       CurPtr[0] == '-' || CurPtr[0] == '$' ||
418       CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
419     ++CurPtr;
420     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
421            CurPtr[0] == '-' || CurPtr[0] == '$' ||
422            CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
423       ++CurPtr;
424 
425     StrVal.assign(TokStart+1, CurPtr);   // Skip !
426     UnEscapeLexed(StrVal);
427     return lltok::MetadataVar;
428   }
429   return lltok::exclaim;
430 }
431 
432 /// Lex all tokens that start with a ^ character.
433 ///    SummaryID ::= ^[0-9]+
434 lltok::Kind LLLexer::LexCaret() {
435   // Handle SummaryID: ^[0-9]+
436   return LexUIntID(lltok::SummaryID);
437 }
438 
439 /// Lex all tokens that start with a # character.
440 ///    AttrGrpID ::= #[0-9]+
441 lltok::Kind LLLexer::LexHash() {
442   // Handle AttrGrpID: #[0-9]+
443   return LexUIntID(lltok::AttrGrpID);
444 }
445 
446 /// Lex a label, integer type, keyword, or hexadecimal integer constant.
447 ///    Label           [-a-zA-Z$._0-9]+:
448 ///    IntegerType     i[0-9]+
449 ///    Keyword         sdiv, float, ...
450 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
451 lltok::Kind LLLexer::LexIdentifier() {
452   const char *StartChar = CurPtr;
453   const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
454   const char *KeywordEnd = nullptr;
455 
456   for (; isLabelChar(*CurPtr); ++CurPtr) {
457     // If we decide this is an integer, remember the end of the sequence.
458     if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
459       IntEnd = CurPtr;
460     if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
461         *CurPtr != '_')
462       KeywordEnd = CurPtr;
463   }
464 
465   // If we stopped due to a colon, unless we were directed to ignore it,
466   // this really is a label.
467   if (!IgnoreColonInIdentifiers && *CurPtr == ':') {
468     StrVal.assign(StartChar-1, CurPtr++);
469     return lltok::LabelStr;
470   }
471 
472   // Otherwise, this wasn't a label.  If this was valid as an integer type,
473   // return it.
474   if (!IntEnd) IntEnd = CurPtr;
475   if (IntEnd != StartChar) {
476     CurPtr = IntEnd;
477     uint64_t NumBits = atoull(StartChar, CurPtr);
478     if (NumBits < IntegerType::MIN_INT_BITS ||
479         NumBits > IntegerType::MAX_INT_BITS) {
480       Error("bitwidth for integer type out of range!");
481       return lltok::Error;
482     }
483     TyVal = IntegerType::get(Context, NumBits);
484     return lltok::Type;
485   }
486 
487   // Otherwise, this was a letter sequence.  See which keyword this is.
488   if (!KeywordEnd) KeywordEnd = CurPtr;
489   CurPtr = KeywordEnd;
490   --StartChar;
491   StringRef Keyword(StartChar, CurPtr - StartChar);
492 
493 #define KEYWORD(STR)                                                           \
494   do {                                                                         \
495     if (Keyword == #STR)                                                       \
496       return lltok::kw_##STR;                                                  \
497   } while (false)
498 
499   KEYWORD(true);    KEYWORD(false);
500   KEYWORD(declare); KEYWORD(define);
501   KEYWORD(global);  KEYWORD(constant);
502 
503   KEYWORD(dso_local);
504   KEYWORD(dso_preemptable);
505 
506   KEYWORD(private);
507   KEYWORD(internal);
508   KEYWORD(available_externally);
509   KEYWORD(linkonce);
510   KEYWORD(linkonce_odr);
511   KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
512   KEYWORD(weak_odr);
513   KEYWORD(appending);
514   KEYWORD(dllimport);
515   KEYWORD(dllexport);
516   KEYWORD(common);
517   KEYWORD(default);
518   KEYWORD(hidden);
519   KEYWORD(protected);
520   KEYWORD(unnamed_addr);
521   KEYWORD(local_unnamed_addr);
522   KEYWORD(externally_initialized);
523   KEYWORD(extern_weak);
524   KEYWORD(external);
525   KEYWORD(thread_local);
526   KEYWORD(localdynamic);
527   KEYWORD(initialexec);
528   KEYWORD(localexec);
529   KEYWORD(zeroinitializer);
530   KEYWORD(undef);
531   KEYWORD(null);
532   KEYWORD(none);
533   KEYWORD(poison);
534   KEYWORD(to);
535   KEYWORD(caller);
536   KEYWORD(within);
537   KEYWORD(from);
538   KEYWORD(tail);
539   KEYWORD(musttail);
540   KEYWORD(notail);
541   KEYWORD(target);
542   KEYWORD(triple);
543   KEYWORD(source_filename);
544   KEYWORD(unwind);
545   KEYWORD(datalayout);
546   KEYWORD(volatile);
547   KEYWORD(atomic);
548   KEYWORD(unordered);
549   KEYWORD(monotonic);
550   KEYWORD(acquire);
551   KEYWORD(release);
552   KEYWORD(acq_rel);
553   KEYWORD(seq_cst);
554   KEYWORD(syncscope);
555 
556   KEYWORD(nnan);
557   KEYWORD(ninf);
558   KEYWORD(nsz);
559   KEYWORD(arcp);
560   KEYWORD(contract);
561   KEYWORD(reassoc);
562   KEYWORD(afn);
563   KEYWORD(fast);
564   KEYWORD(nuw);
565   KEYWORD(nsw);
566   KEYWORD(exact);
567   KEYWORD(inbounds);
568   KEYWORD(inrange);
569   KEYWORD(addrspace);
570   KEYWORD(section);
571   KEYWORD(partition);
572   KEYWORD(alias);
573   KEYWORD(ifunc);
574   KEYWORD(module);
575   KEYWORD(asm);
576   KEYWORD(sideeffect);
577   KEYWORD(inteldialect);
578   KEYWORD(gc);
579   KEYWORD(prefix);
580   KEYWORD(prologue);
581 
582   KEYWORD(no_sanitize_address);
583   KEYWORD(no_sanitize_hwaddress);
584   KEYWORD(sanitize_address_dyninit);
585 
586   KEYWORD(ccc);
587   KEYWORD(fastcc);
588   KEYWORD(coldcc);
589   KEYWORD(cfguard_checkcc);
590   KEYWORD(x86_stdcallcc);
591   KEYWORD(x86_fastcallcc);
592   KEYWORD(x86_thiscallcc);
593   KEYWORD(x86_vectorcallcc);
594   KEYWORD(arm_apcscc);
595   KEYWORD(arm_aapcscc);
596   KEYWORD(arm_aapcs_vfpcc);
597   KEYWORD(aarch64_vector_pcs);
598   KEYWORD(aarch64_sve_vector_pcs);
599   KEYWORD(aarch64_sme_preservemost_from_x0);
600   KEYWORD(aarch64_sme_preservemost_from_x2);
601   KEYWORD(msp430_intrcc);
602   KEYWORD(avr_intrcc);
603   KEYWORD(avr_signalcc);
604   KEYWORD(ptx_kernel);
605   KEYWORD(ptx_device);
606   KEYWORD(spir_kernel);
607   KEYWORD(spir_func);
608   KEYWORD(intel_ocl_bicc);
609   KEYWORD(x86_64_sysvcc);
610   KEYWORD(win64cc);
611   KEYWORD(x86_regcallcc);
612   KEYWORD(webkit_jscc);
613   KEYWORD(swiftcc);
614   KEYWORD(swifttailcc);
615   KEYWORD(anyregcc);
616   KEYWORD(preserve_mostcc);
617   KEYWORD(preserve_allcc);
618   KEYWORD(ghccc);
619   KEYWORD(x86_intrcc);
620   KEYWORD(hhvmcc);
621   KEYWORD(hhvm_ccc);
622   KEYWORD(cxx_fast_tlscc);
623   KEYWORD(amdgpu_vs);
624   KEYWORD(amdgpu_ls);
625   KEYWORD(amdgpu_hs);
626   KEYWORD(amdgpu_es);
627   KEYWORD(amdgpu_gs);
628   KEYWORD(amdgpu_ps);
629   KEYWORD(amdgpu_cs);
630   KEYWORD(amdgpu_cs_chain);
631   KEYWORD(amdgpu_cs_chain_preserve);
632   KEYWORD(amdgpu_kernel);
633   KEYWORD(amdgpu_gfx);
634   KEYWORD(tailcc);
635 
636   KEYWORD(cc);
637   KEYWORD(c);
638 
639   KEYWORD(attributes);
640   KEYWORD(sync);
641   KEYWORD(async);
642 
643 #define GET_ATTR_NAMES
644 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
645   KEYWORD(DISPLAY_NAME);
646 #include "llvm/IR/Attributes.inc"
647 
648   KEYWORD(read);
649   KEYWORD(write);
650   KEYWORD(readwrite);
651   KEYWORD(argmem);
652   KEYWORD(inaccessiblemem);
653   KEYWORD(argmemonly);
654   KEYWORD(inaccessiblememonly);
655   KEYWORD(inaccessiblemem_or_argmemonly);
656 
657   // nofpclass attribute
658   KEYWORD(all);
659   KEYWORD(nan);
660   KEYWORD(snan);
661   KEYWORD(qnan);
662   KEYWORD(inf);
663   // ninf already a keyword
664   KEYWORD(pinf);
665   KEYWORD(norm);
666   KEYWORD(nnorm);
667   KEYWORD(pnorm);
668   // sub already a keyword
669   KEYWORD(nsub);
670   KEYWORD(psub);
671   KEYWORD(zero);
672   KEYWORD(nzero);
673   KEYWORD(pzero);
674 
675   KEYWORD(type);
676   KEYWORD(opaque);
677 
678   KEYWORD(comdat);
679 
680   // Comdat types
681   KEYWORD(any);
682   KEYWORD(exactmatch);
683   KEYWORD(largest);
684   KEYWORD(nodeduplicate);
685   KEYWORD(samesize);
686 
687   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
688   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
689   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
690   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
691 
692   KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
693   KEYWORD(umin); KEYWORD(fmax); KEYWORD(fmin);
694   KEYWORD(uinc_wrap);
695   KEYWORD(udec_wrap);
696 
697   KEYWORD(vscale);
698   KEYWORD(x);
699   KEYWORD(blockaddress);
700   KEYWORD(dso_local_equivalent);
701   KEYWORD(no_cfi);
702 
703   // Metadata types.
704   KEYWORD(distinct);
705 
706   // Use-list order directives.
707   KEYWORD(uselistorder);
708   KEYWORD(uselistorder_bb);
709 
710   KEYWORD(personality);
711   KEYWORD(cleanup);
712   KEYWORD(catch);
713   KEYWORD(filter);
714 
715   // Summary index keywords.
716   KEYWORD(path);
717   KEYWORD(hash);
718   KEYWORD(gv);
719   KEYWORD(guid);
720   KEYWORD(name);
721   KEYWORD(summaries);
722   KEYWORD(flags);
723   KEYWORD(blockcount);
724   KEYWORD(linkage);
725   KEYWORD(visibility);
726   KEYWORD(notEligibleToImport);
727   KEYWORD(live);
728   KEYWORD(dsoLocal);
729   KEYWORD(canAutoHide);
730   KEYWORD(function);
731   KEYWORD(insts);
732   KEYWORD(funcFlags);
733   KEYWORD(readNone);
734   KEYWORD(readOnly);
735   KEYWORD(noRecurse);
736   KEYWORD(returnDoesNotAlias);
737   KEYWORD(noInline);
738   KEYWORD(alwaysInline);
739   KEYWORD(noUnwind);
740   KEYWORD(mayThrow);
741   KEYWORD(hasUnknownCall);
742   KEYWORD(mustBeUnreachable);
743   KEYWORD(calls);
744   KEYWORD(callee);
745   KEYWORD(params);
746   KEYWORD(param);
747   KEYWORD(hotness);
748   KEYWORD(unknown);
749   KEYWORD(critical);
750   KEYWORD(relbf);
751   KEYWORD(variable);
752   KEYWORD(vTableFuncs);
753   KEYWORD(virtFunc);
754   KEYWORD(aliasee);
755   KEYWORD(refs);
756   KEYWORD(typeIdInfo);
757   KEYWORD(typeTests);
758   KEYWORD(typeTestAssumeVCalls);
759   KEYWORD(typeCheckedLoadVCalls);
760   KEYWORD(typeTestAssumeConstVCalls);
761   KEYWORD(typeCheckedLoadConstVCalls);
762   KEYWORD(vFuncId);
763   KEYWORD(offset);
764   KEYWORD(args);
765   KEYWORD(typeid);
766   KEYWORD(typeidCompatibleVTable);
767   KEYWORD(summary);
768   KEYWORD(typeTestRes);
769   KEYWORD(kind);
770   KEYWORD(unsat);
771   KEYWORD(byteArray);
772   KEYWORD(inline);
773   KEYWORD(single);
774   KEYWORD(allOnes);
775   KEYWORD(sizeM1BitWidth);
776   KEYWORD(alignLog2);
777   KEYWORD(sizeM1);
778   KEYWORD(bitMask);
779   KEYWORD(inlineBits);
780   KEYWORD(vcall_visibility);
781   KEYWORD(wpdResolutions);
782   KEYWORD(wpdRes);
783   KEYWORD(indir);
784   KEYWORD(singleImpl);
785   KEYWORD(branchFunnel);
786   KEYWORD(singleImplName);
787   KEYWORD(resByArg);
788   KEYWORD(byArg);
789   KEYWORD(uniformRetVal);
790   KEYWORD(uniqueRetVal);
791   KEYWORD(virtualConstProp);
792   KEYWORD(info);
793   KEYWORD(byte);
794   KEYWORD(bit);
795   KEYWORD(varFlags);
796   KEYWORD(callsites);
797   KEYWORD(clones);
798   KEYWORD(stackIds);
799   KEYWORD(allocs);
800   KEYWORD(versions);
801   KEYWORD(memProf);
802   KEYWORD(notcold);
803 
804 #undef KEYWORD
805 
806   // Keywords for types.
807 #define TYPEKEYWORD(STR, LLVMTY)                                               \
808   do {                                                                         \
809     if (Keyword == STR) {                                                      \
810       TyVal = LLVMTY;                                                          \
811       return lltok::Type;                                                      \
812     }                                                                          \
813   } while (false)
814 
815   TYPEKEYWORD("void",      Type::getVoidTy(Context));
816   TYPEKEYWORD("half",      Type::getHalfTy(Context));
817   TYPEKEYWORD("bfloat",    Type::getBFloatTy(Context));
818   TYPEKEYWORD("float",     Type::getFloatTy(Context));
819   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
820   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
821   TYPEKEYWORD("fp128",     Type::getFP128Ty(Context));
822   TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
823   TYPEKEYWORD("label",     Type::getLabelTy(Context));
824   TYPEKEYWORD("metadata",  Type::getMetadataTy(Context));
825   TYPEKEYWORD("x86_mmx",   Type::getX86_MMXTy(Context));
826   TYPEKEYWORD("x86_amx",   Type::getX86_AMXTy(Context));
827   TYPEKEYWORD("token",     Type::getTokenTy(Context));
828   TYPEKEYWORD("ptr",       PointerType::getUnqual(Context));
829 
830 #undef TYPEKEYWORD
831 
832   // Keywords for instructions.
833 #define INSTKEYWORD(STR, Enum)                                                 \
834   do {                                                                         \
835     if (Keyword == #STR) {                                                     \
836       UIntVal = Instruction::Enum;                                             \
837       return lltok::kw_##STR;                                                  \
838     }                                                                          \
839   } while (false)
840 
841   INSTKEYWORD(fneg,  FNeg);
842 
843   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
844   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
845   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
846   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
847   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
848   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
849   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
850   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
851 
852   INSTKEYWORD(phi,         PHI);
853   INSTKEYWORD(call,        Call);
854   INSTKEYWORD(trunc,       Trunc);
855   INSTKEYWORD(zext,        ZExt);
856   INSTKEYWORD(sext,        SExt);
857   INSTKEYWORD(fptrunc,     FPTrunc);
858   INSTKEYWORD(fpext,       FPExt);
859   INSTKEYWORD(uitofp,      UIToFP);
860   INSTKEYWORD(sitofp,      SIToFP);
861   INSTKEYWORD(fptoui,      FPToUI);
862   INSTKEYWORD(fptosi,      FPToSI);
863   INSTKEYWORD(inttoptr,    IntToPtr);
864   INSTKEYWORD(ptrtoint,    PtrToInt);
865   INSTKEYWORD(bitcast,     BitCast);
866   INSTKEYWORD(addrspacecast, AddrSpaceCast);
867   INSTKEYWORD(select,      Select);
868   INSTKEYWORD(va_arg,      VAArg);
869   INSTKEYWORD(ret,         Ret);
870   INSTKEYWORD(br,          Br);
871   INSTKEYWORD(switch,      Switch);
872   INSTKEYWORD(indirectbr,  IndirectBr);
873   INSTKEYWORD(invoke,      Invoke);
874   INSTKEYWORD(resume,      Resume);
875   INSTKEYWORD(unreachable, Unreachable);
876   INSTKEYWORD(callbr,      CallBr);
877 
878   INSTKEYWORD(alloca,      Alloca);
879   INSTKEYWORD(load,        Load);
880   INSTKEYWORD(store,       Store);
881   INSTKEYWORD(cmpxchg,     AtomicCmpXchg);
882   INSTKEYWORD(atomicrmw,   AtomicRMW);
883   INSTKEYWORD(fence,       Fence);
884   INSTKEYWORD(getelementptr, GetElementPtr);
885 
886   INSTKEYWORD(extractelement, ExtractElement);
887   INSTKEYWORD(insertelement,  InsertElement);
888   INSTKEYWORD(shufflevector,  ShuffleVector);
889   INSTKEYWORD(extractvalue,   ExtractValue);
890   INSTKEYWORD(insertvalue,    InsertValue);
891   INSTKEYWORD(landingpad,     LandingPad);
892   INSTKEYWORD(cleanupret,     CleanupRet);
893   INSTKEYWORD(catchret,       CatchRet);
894   INSTKEYWORD(catchswitch,  CatchSwitch);
895   INSTKEYWORD(catchpad,     CatchPad);
896   INSTKEYWORD(cleanuppad,   CleanupPad);
897 
898   INSTKEYWORD(freeze,       Freeze);
899 
900 #undef INSTKEYWORD
901 
902 #define DWKEYWORD(TYPE, TOKEN)                                                 \
903   do {                                                                         \
904     if (Keyword.startswith("DW_" #TYPE "_")) {                                 \
905       StrVal.assign(Keyword.begin(), Keyword.end());                           \
906       return lltok::TOKEN;                                                     \
907     }                                                                          \
908   } while (false)
909 
910   DWKEYWORD(TAG, DwarfTag);
911   DWKEYWORD(ATE, DwarfAttEncoding);
912   DWKEYWORD(VIRTUALITY, DwarfVirtuality);
913   DWKEYWORD(LANG, DwarfLang);
914   DWKEYWORD(CC, DwarfCC);
915   DWKEYWORD(OP, DwarfOp);
916   DWKEYWORD(MACINFO, DwarfMacinfo);
917 
918 #undef DWKEYWORD
919 
920   if (Keyword.startswith("DIFlag")) {
921     StrVal.assign(Keyword.begin(), Keyword.end());
922     return lltok::DIFlag;
923   }
924 
925   if (Keyword.startswith("DISPFlag")) {
926     StrVal.assign(Keyword.begin(), Keyword.end());
927     return lltok::DISPFlag;
928   }
929 
930   if (Keyword.startswith("CSK_")) {
931     StrVal.assign(Keyword.begin(), Keyword.end());
932     return lltok::ChecksumKind;
933   }
934 
935   if (Keyword == "NoDebug" || Keyword == "FullDebug" ||
936       Keyword == "LineTablesOnly" || Keyword == "DebugDirectivesOnly") {
937     StrVal.assign(Keyword.begin(), Keyword.end());
938     return lltok::EmissionKind;
939   }
940 
941   if (Keyword == "GNU" || Keyword == "Apple" || Keyword == "None" ||
942       Keyword == "Default") {
943     StrVal.assign(Keyword.begin(), Keyword.end());
944     return lltok::NameTableKind;
945   }
946 
947   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
948   // the CFE to avoid forcing it to deal with 64-bit numbers.
949   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
950       TokStart[1] == '0' && TokStart[2] == 'x' &&
951       isxdigit(static_cast<unsigned char>(TokStart[3]))) {
952     int len = CurPtr-TokStart-3;
953     uint32_t bits = len * 4;
954     StringRef HexStr(TokStart + 3, len);
955     if (!all_of(HexStr, isxdigit)) {
956       // Bad token, return it as an error.
957       CurPtr = TokStart+3;
958       return lltok::Error;
959     }
960     APInt Tmp(bits, HexStr, 16);
961     uint32_t activeBits = Tmp.getActiveBits();
962     if (activeBits > 0 && activeBits < bits)
963       Tmp = Tmp.trunc(activeBits);
964     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
965     return lltok::APSInt;
966   }
967 
968   // If this is "cc1234", return this as just "cc".
969   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
970     CurPtr = TokStart+2;
971     return lltok::kw_cc;
972   }
973 
974   // Finally, if this isn't known, return an error.
975   CurPtr = TokStart+1;
976   return lltok::Error;
977 }
978 
979 /// Lex all tokens that start with a 0x prefix, knowing they match and are not
980 /// labels.
981 ///    HexFPConstant     0x[0-9A-Fa-f]+
982 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
983 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
984 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
985 ///    HexHalfConstant   0xH[0-9A-Fa-f]+
986 ///    HexBFloatConstant 0xR[0-9A-Fa-f]+
987 lltok::Kind LLLexer::Lex0x() {
988   CurPtr = TokStart + 2;
989 
990   char Kind;
991   if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H' ||
992       CurPtr[0] == 'R') {
993     Kind = *CurPtr++;
994   } else {
995     Kind = 'J';
996   }
997 
998   if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
999     // Bad token, return it as an error.
1000     CurPtr = TokStart+1;
1001     return lltok::Error;
1002   }
1003 
1004   while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
1005     ++CurPtr;
1006 
1007   if (Kind == 'J') {
1008     // HexFPConstant - Floating point constant represented in IEEE format as a
1009     // hexadecimal number for when exponential notation is not precise enough.
1010     // Half, BFloat, Float, and double only.
1011     APFloatVal = APFloat(APFloat::IEEEdouble(),
1012                          APInt(64, HexIntToVal(TokStart + 2, CurPtr)));
1013     return lltok::APFloat;
1014   }
1015 
1016   uint64_t Pair[2];
1017   switch (Kind) {
1018   default: llvm_unreachable("Unknown kind!");
1019   case 'K':
1020     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
1021     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
1022     APFloatVal = APFloat(APFloat::x87DoubleExtended(), APInt(80, Pair));
1023     return lltok::APFloat;
1024   case 'L':
1025     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
1026     HexToIntPair(TokStart+3, CurPtr, Pair);
1027     APFloatVal = APFloat(APFloat::IEEEquad(), APInt(128, Pair));
1028     return lltok::APFloat;
1029   case 'M':
1030     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
1031     HexToIntPair(TokStart+3, CurPtr, Pair);
1032     APFloatVal = APFloat(APFloat::PPCDoubleDouble(), APInt(128, Pair));
1033     return lltok::APFloat;
1034   case 'H':
1035     APFloatVal = APFloat(APFloat::IEEEhalf(),
1036                          APInt(16,HexIntToVal(TokStart+3, CurPtr)));
1037     return lltok::APFloat;
1038   case 'R':
1039     // Brain floating point
1040     APFloatVal = APFloat(APFloat::BFloat(),
1041                          APInt(16, HexIntToVal(TokStart + 3, CurPtr)));
1042     return lltok::APFloat;
1043   }
1044 }
1045 
1046 /// Lex tokens for a label or a numeric constant, possibly starting with -.
1047 ///    Label             [-a-zA-Z$._0-9]+:
1048 ///    NInteger          -[0-9]+
1049 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
1050 ///    PInteger          [0-9]+
1051 ///    HexFPConstant     0x[0-9A-Fa-f]+
1052 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
1053 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
1054 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
1055 lltok::Kind LLLexer::LexDigitOrNegative() {
1056   // If the letter after the negative is not a number, this is probably a label.
1057   if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
1058       !isdigit(static_cast<unsigned char>(CurPtr[0]))) {
1059     // Okay, this is not a number after the -, it's probably a label.
1060     if (const char *End = isLabelTail(CurPtr)) {
1061       StrVal.assign(TokStart, End-1);
1062       CurPtr = End;
1063       return lltok::LabelStr;
1064     }
1065 
1066     return lltok::Error;
1067   }
1068 
1069   // At this point, it is either a label, int or fp constant.
1070 
1071   // Skip digits, we have at least one.
1072   for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
1073     /*empty*/;
1074 
1075   // Check if this is a fully-numeric label:
1076   if (isdigit(TokStart[0]) && CurPtr[0] == ':') {
1077     uint64_t Val = atoull(TokStart, CurPtr);
1078     ++CurPtr; // Skip the colon.
1079     if ((unsigned)Val != Val)
1080       Error("invalid value number (too large)!");
1081     UIntVal = unsigned(Val);
1082     return lltok::LabelID;
1083   }
1084 
1085   // Check to see if this really is a string label, e.g. "-1:".
1086   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
1087     if (const char *End = isLabelTail(CurPtr)) {
1088       StrVal.assign(TokStart, End-1);
1089       CurPtr = End;
1090       return lltok::LabelStr;
1091     }
1092   }
1093 
1094   // If the next character is a '.', then it is a fp value, otherwise its
1095   // integer.
1096   if (CurPtr[0] != '.') {
1097     if (TokStart[0] == '0' && TokStart[1] == 'x')
1098       return Lex0x();
1099     APSIntVal = APSInt(StringRef(TokStart, CurPtr - TokStart));
1100     return lltok::APSInt;
1101   }
1102 
1103   ++CurPtr;
1104 
1105   // Skip over [0-9]*([eE][-+]?[0-9]+)?
1106   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1107 
1108   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
1109     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
1110         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
1111           isdigit(static_cast<unsigned char>(CurPtr[2])))) {
1112       CurPtr += 2;
1113       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1114     }
1115   }
1116 
1117   APFloatVal = APFloat(APFloat::IEEEdouble(),
1118                        StringRef(TokStart, CurPtr - TokStart));
1119   return lltok::APFloat;
1120 }
1121 
1122 /// Lex a floating point constant starting with +.
1123 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
1124 lltok::Kind LLLexer::LexPositive() {
1125   // If the letter after the negative is a number, this is probably not a
1126   // label.
1127   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
1128     return lltok::Error;
1129 
1130   // Skip digits.
1131   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
1132     /*empty*/;
1133 
1134   // At this point, we need a '.'.
1135   if (CurPtr[0] != '.') {
1136     CurPtr = TokStart+1;
1137     return lltok::Error;
1138   }
1139 
1140   ++CurPtr;
1141 
1142   // Skip over [0-9]*([eE][-+]?[0-9]+)?
1143   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1144 
1145   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
1146     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
1147         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
1148         isdigit(static_cast<unsigned char>(CurPtr[2])))) {
1149       CurPtr += 2;
1150       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
1151     }
1152   }
1153 
1154   APFloatVal = APFloat(APFloat::IEEEdouble(),
1155                        StringRef(TokStart, CurPtr - TokStart));
1156   return lltok::APFloat;
1157 }
1158