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