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