Parse 'ghccc' in .ll files as the GHC convention (cc 10)
[oota-llvm.git] / lib / AsmParser / LLLexer.cpp
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/StringExtras.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/AsmParser/Parser.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <cctype>
27 #include <cstdio>
28 #include <cstdlib>
29 #include <cstring>
30 using namespace llvm;
31
32 bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
33   ErrorInfo = SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
34   return true;
35 }
36
37 void LLLexer::Warning(LocTy WarningLoc, const Twine &Msg) const {
38   SM.PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
39 }
40
41 //===----------------------------------------------------------------------===//
42 // Helper functions.
43 //===----------------------------------------------------------------------===//
44
45 // atoull - Convert an ascii string of decimal digits into the unsigned long
46 // long representation... this does not have to do input error checking,
47 // because we know that the input will be matched by a suitable regex...
48 //
49 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
50   uint64_t Result = 0;
51   for (; Buffer != End; Buffer++) {
52     uint64_t OldRes = Result;
53     Result *= 10;
54     Result += *Buffer-'0';
55     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
56       Error("constant bigger than 64 bits detected!");
57       return 0;
58     }
59   }
60   return Result;
61 }
62
63 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
64   uint64_t Result = 0;
65   for (; Buffer != End; ++Buffer) {
66     uint64_t OldRes = Result;
67     Result *= 16;
68     Result += hexDigitValue(*Buffer);
69
70     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
71       Error("constant bigger than 64 bits detected!");
72       return 0;
73     }
74   }
75   return Result;
76 }
77
78 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
79                            uint64_t Pair[2]) {
80   Pair[0] = 0;
81   for (int i=0; i<16; i++, Buffer++) {
82     assert(Buffer != End);
83     Pair[0] *= 16;
84     Pair[0] += hexDigitValue(*Buffer);
85   }
86   Pair[1] = 0;
87   for (int i=0; i<16 && Buffer != End; i++, Buffer++) {
88     Pair[1] *= 16;
89     Pair[1] += hexDigitValue(*Buffer);
90   }
91   if (Buffer != End)
92     Error("constant bigger than 128 bits detected!");
93 }
94
95 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
96 /// { low64, high16 } as usual for an APInt.
97 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
98                            uint64_t Pair[2]) {
99   Pair[1] = 0;
100   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
101     assert(Buffer != End);
102     Pair[1] *= 16;
103     Pair[1] += hexDigitValue(*Buffer);
104   }
105   Pair[0] = 0;
106   for (int i=0; i<16; i++, Buffer++) {
107     Pair[0] *= 16;
108     Pair[0] += hexDigitValue(*Buffer);
109   }
110   if (Buffer != End)
111     Error("constant bigger than 128 bits detected!");
112 }
113
114 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
115 // appropriate character.
116 static void UnEscapeLexed(std::string &Str) {
117   if (Str.empty()) return;
118
119   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
120   char *BOut = Buffer;
121   for (char *BIn = Buffer; BIn != EndBuffer; ) {
122     if (BIn[0] == '\\') {
123       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
124         *BOut++ = '\\'; // Two \ becomes one
125         BIn += 2;
126       } else if (BIn < EndBuffer-2 &&
127                  isxdigit(static_cast<unsigned char>(BIn[1])) &&
128                  isxdigit(static_cast<unsigned char>(BIn[2]))) {
129         *BOut = hexDigitValue(BIn[1]) * 16 + hexDigitValue(BIn[2]);
130         BIn += 3;                           // Skip over handled chars
131         ++BOut;
132       } else {
133         *BOut++ = *BIn++;
134       }
135     } else {
136       *BOut++ = *BIn++;
137     }
138   }
139   Str.resize(BOut-Buffer);
140 }
141
142 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
143 static bool isLabelChar(char C) {
144   return isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
145          C == '.' || C == '_';
146 }
147
148
149 /// isLabelTail - Return true if this pointer points to a valid end of a label.
150 static const char *isLabelTail(const char *CurPtr) {
151   while (1) {
152     if (CurPtr[0] == ':') return CurPtr+1;
153     if (!isLabelChar(CurPtr[0])) return nullptr;
154     ++CurPtr;
155   }
156 }
157
158
159
160 //===----------------------------------------------------------------------===//
161 // Lexer definition.
162 //===----------------------------------------------------------------------===//
163
164 LLLexer::LLLexer(StringRef StartBuf, SourceMgr &sm, SMDiagnostic &Err,
165                  LLVMContext &C)
166   : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), Context(C), APFloatVal(0.0) {
167   CurPtr = CurBuf.begin();
168 }
169
170 int LLLexer::getNextChar() {
171   char CurChar = *CurPtr++;
172   switch (CurChar) {
173   default: return (unsigned char)CurChar;
174   case 0:
175     // A nul character in the stream is either the end of the current buffer or
176     // a random nul in the file.  Disambiguate that here.
177     if (CurPtr-1 != CurBuf.end())
178       return 0;  // Just whitespace.
179
180     // Otherwise, return end of file.
181     --CurPtr;  // Another call to lex will return EOF again.
182     return EOF;
183   }
184 }
185
186
187 lltok::Kind LLLexer::LexToken() {
188   TokStart = CurPtr;
189
190   int CurChar = getNextChar();
191   switch (CurChar) {
192   default:
193     // Handle letters: [a-zA-Z_]
194     if (isalpha(static_cast<unsigned char>(CurChar)) || CurChar == '_')
195       return LexIdentifier();
196
197     return lltok::Error;
198   case EOF: return lltok::Eof;
199   case 0:
200   case ' ':
201   case '\t':
202   case '\n':
203   case '\r':
204     // Ignore whitespace.
205     return LexToken();
206   case '+': return LexPositive();
207   case '@': return LexAt();
208   case '$': return LexDollar();
209   case '%': return LexPercent();
210   case '"': return LexQuote();
211   case '.':
212     if (const char *Ptr = isLabelTail(CurPtr)) {
213       CurPtr = Ptr;
214       StrVal.assign(TokStart, CurPtr-1);
215       return lltok::LabelStr;
216     }
217     if (CurPtr[0] == '.' && CurPtr[1] == '.') {
218       CurPtr += 2;
219       return lltok::dotdotdot;
220     }
221     return lltok::Error;
222   case ';':
223     SkipLineComment();
224     return LexToken();
225   case '!': return LexExclaim();
226   case '#': return LexHash();
227   case '0': case '1': case '2': case '3': case '4':
228   case '5': case '6': case '7': case '8': case '9':
229   case '-':
230     return LexDigitOrNegative();
231   case '=': return lltok::equal;
232   case '[': return lltok::lsquare;
233   case ']': return lltok::rsquare;
234   case '{': return lltok::lbrace;
235   case '}': return lltok::rbrace;
236   case '<': return lltok::less;
237   case '>': return lltok::greater;
238   case '(': return lltok::lparen;
239   case ')': return lltok::rparen;
240   case ',': return lltok::comma;
241   case '*': return lltok::star;
242   case '\\': return lltok::backslash;
243   }
244 }
245
246 void LLLexer::SkipLineComment() {
247   while (1) {
248     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
249       return;
250   }
251 }
252
253 /// LexAt - 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   // Handle AtStringConstant: @\"[^\"]*\"
259   if (CurPtr[0] == '"') {
260     ++CurPtr;
261
262     while (1) {
263       int CurChar = getNextChar();
264
265       if (CurChar == EOF) {
266         Error("end of file in global variable name");
267         return lltok::Error;
268       }
269       if (CurChar == '"') {
270         StrVal.assign(TokStart+2, CurPtr-1);
271         UnEscapeLexed(StrVal);
272         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
273           Error("Null bytes are not allowed in names");
274           return lltok::Error;
275         }
276         return lltok::GlobalVar;
277       }
278     }
279   }
280
281   // Handle GlobalVarName: @[-a-zA-Z$._][-a-zA-Z$._0-9]*
282   if (ReadVarName())
283     return lltok::GlobalVar;
284
285   // Handle GlobalVarID: @[0-9]+
286   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
287     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
288       /*empty*/;
289
290     uint64_t Val = atoull(TokStart+1, CurPtr);
291     if ((unsigned)Val != Val)
292       Error("invalid value number (too large)!");
293     UIntVal = unsigned(Val);
294     return lltok::GlobalID;
295   }
296
297   return lltok::Error;
298 }
299
300 lltok::Kind LLLexer::LexDollar() {
301   if (const char *Ptr = isLabelTail(TokStart)) {
302     CurPtr = Ptr;
303     StrVal.assign(TokStart, CurPtr - 1);
304     return lltok::LabelStr;
305   }
306
307   // Handle DollarStringConstant: $\"[^\"]*\"
308   if (CurPtr[0] == '"') {
309     ++CurPtr;
310
311     while (1) {
312       int CurChar = getNextChar();
313
314       if (CurChar == EOF) {
315         Error("end of file in COMDAT variable name");
316         return lltok::Error;
317       }
318       if (CurChar == '"') {
319         StrVal.assign(TokStart + 2, CurPtr - 1);
320         UnEscapeLexed(StrVal);
321         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
322           Error("Null bytes are not allowed in names");
323           return lltok::Error;
324         }
325         return lltok::ComdatVar;
326       }
327     }
328   }
329
330   // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
331   if (ReadVarName())
332     return lltok::ComdatVar;
333
334   return lltok::Error;
335 }
336
337 /// ReadString - Read a string until the closing quote.
338 lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
339   const char *Start = CurPtr;
340   while (1) {
341     int CurChar = getNextChar();
342
343     if (CurChar == EOF) {
344       Error("end of file in string constant");
345       return lltok::Error;
346     }
347     if (CurChar == '"') {
348       StrVal.assign(Start, CurPtr-1);
349       UnEscapeLexed(StrVal);
350       return kind;
351     }
352   }
353 }
354
355 /// ReadVarName - Read the rest of a token containing a variable name.
356 bool LLLexer::ReadVarName() {
357   const char *NameStart = CurPtr;
358   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
359       CurPtr[0] == '-' || CurPtr[0] == '$' ||
360       CurPtr[0] == '.' || CurPtr[0] == '_') {
361     ++CurPtr;
362     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
363            CurPtr[0] == '-' || CurPtr[0] == '$' ||
364            CurPtr[0] == '.' || CurPtr[0] == '_')
365       ++CurPtr;
366
367     StrVal.assign(NameStart, CurPtr);
368     return true;
369   }
370   return false;
371 }
372
373 /// LexPercent - Lex all tokens that start with a % character:
374 ///   LocalVar   ::= %\"[^\"]*\"
375 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
376 ///   LocalVarID ::= %[0-9]+
377 lltok::Kind LLLexer::LexPercent() {
378   // Handle LocalVarName: %\"[^\"]*\"
379   if (CurPtr[0] == '"') {
380     ++CurPtr;
381     return ReadString(lltok::LocalVar);
382   }
383
384   // Handle LocalVarName: %[-a-zA-Z$._][-a-zA-Z$._0-9]*
385   if (ReadVarName())
386     return lltok::LocalVar;
387
388   // Handle LocalVarID: %[0-9]+
389   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
390     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
391       /*empty*/;
392
393     uint64_t Val = atoull(TokStart+1, CurPtr);
394     if ((unsigned)Val != Val)
395       Error("invalid value number (too large)!");
396     UIntVal = unsigned(Val);
397     return lltok::LocalVarID;
398   }
399
400   return lltok::Error;
401 }
402
403 /// LexQuote - Lex all tokens that start with a " character:
404 ///   QuoteLabel        "[^"]+":
405 ///   StringConstant    "[^"]*"
406 lltok::Kind LLLexer::LexQuote() {
407   lltok::Kind kind = ReadString(lltok::StringConstant);
408   if (kind == lltok::Error || kind == lltok::Eof)
409     return kind;
410
411   if (CurPtr[0] == ':') {
412     ++CurPtr;
413     kind = lltok::LabelStr;
414   }
415
416   return kind;
417 }
418
419 /// LexExclaim:
420 ///    !foo
421 ///    !
422 lltok::Kind LLLexer::LexExclaim() {
423   // Lex a metadata name as a MetadataVar.
424   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
425       CurPtr[0] == '-' || CurPtr[0] == '$' ||
426       CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
427     ++CurPtr;
428     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
429            CurPtr[0] == '-' || CurPtr[0] == '$' ||
430            CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
431       ++CurPtr;
432
433     StrVal.assign(TokStart+1, CurPtr);   // Skip !
434     UnEscapeLexed(StrVal);
435     return lltok::MetadataVar;
436   }
437   return lltok::exclaim;
438 }
439
440 /// LexHash - Lex all tokens that start with a # character:
441 ///    AttrGrpID ::= #[0-9]+
442 lltok::Kind LLLexer::LexHash() {
443   // Handle AttrGrpID: #[0-9]+
444   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
445     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
446       /*empty*/;
447
448     uint64_t Val = atoull(TokStart+1, CurPtr);
449     if ((unsigned)Val != Val)
450       Error("invalid value number (too large)!");
451     UIntVal = unsigned(Val);
452     return lltok::AttrGrpID;
453   }
454
455   return lltok::Error;
456 }
457
458 /// LexIdentifier: Handle several related productions:
459 ///    Label           [-a-zA-Z$._0-9]+:
460 ///    IntegerType     i[0-9]+
461 ///    Keyword         sdiv, float, ...
462 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
463 lltok::Kind LLLexer::LexIdentifier() {
464   const char *StartChar = CurPtr;
465   const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
466   const char *KeywordEnd = nullptr;
467
468   for (; isLabelChar(*CurPtr); ++CurPtr) {
469     // If we decide this is an integer, remember the end of the sequence.
470     if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
471       IntEnd = CurPtr;
472     if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
473         *CurPtr != '_')
474       KeywordEnd = CurPtr;
475   }
476
477   // If we stopped due to a colon, this really is a label.
478   if (*CurPtr == ':') {
479     StrVal.assign(StartChar-1, CurPtr++);
480     return lltok::LabelStr;
481   }
482
483   // Otherwise, this wasn't a label.  If this was valid as an integer type,
484   // return it.
485   if (!IntEnd) IntEnd = CurPtr;
486   if (IntEnd != StartChar) {
487     CurPtr = IntEnd;
488     uint64_t NumBits = atoull(StartChar, CurPtr);
489     if (NumBits < IntegerType::MIN_INT_BITS ||
490         NumBits > IntegerType::MAX_INT_BITS) {
491       Error("bitwidth for integer type out of range!");
492       return lltok::Error;
493     }
494     TyVal = IntegerType::get(Context, NumBits);
495     return lltok::Type;
496   }
497
498   // Otherwise, this was a letter sequence.  See which keyword this is.
499   if (!KeywordEnd) KeywordEnd = CurPtr;
500   CurPtr = KeywordEnd;
501   --StartChar;
502   unsigned Len = CurPtr-StartChar;
503 #define KEYWORD(STR)                                                    \
504   do {                                                                  \
505     if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR)))  \
506       return lltok::kw_##STR;                                           \
507   } while (0)
508
509   KEYWORD(true);    KEYWORD(false);
510   KEYWORD(declare); KEYWORD(define);
511   KEYWORD(global);  KEYWORD(constant);
512
513   KEYWORD(private);
514   KEYWORD(internal);
515   KEYWORD(available_externally);
516   KEYWORD(linkonce);
517   KEYWORD(linkonce_odr);
518   KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
519   KEYWORD(weak_odr);
520   KEYWORD(appending);
521   KEYWORD(dllimport);
522   KEYWORD(dllexport);
523   KEYWORD(common);
524   KEYWORD(default);
525   KEYWORD(hidden);
526   KEYWORD(protected);
527   KEYWORD(unnamed_addr);
528   KEYWORD(externally_initialized);
529   KEYWORD(extern_weak);
530   KEYWORD(external);
531   KEYWORD(thread_local);
532   KEYWORD(localdynamic);
533   KEYWORD(initialexec);
534   KEYWORD(localexec);
535   KEYWORD(zeroinitializer);
536   KEYWORD(undef);
537   KEYWORD(null);
538   KEYWORD(to);
539   KEYWORD(tail);
540   KEYWORD(musttail);
541   KEYWORD(target);
542   KEYWORD(triple);
543   KEYWORD(unwind);
544   KEYWORD(deplibs);             // FIXME: Remove in 4.0.
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(singlethread);
555
556   KEYWORD(nnan);
557   KEYWORD(ninf);
558   KEYWORD(nsz);
559   KEYWORD(arcp);
560   KEYWORD(fast);
561   KEYWORD(nuw);
562   KEYWORD(nsw);
563   KEYWORD(exact);
564   KEYWORD(inbounds);
565   KEYWORD(align);
566   KEYWORD(addrspace);
567   KEYWORD(section);
568   KEYWORD(alias);
569   KEYWORD(module);
570   KEYWORD(asm);
571   KEYWORD(sideeffect);
572   KEYWORD(alignstack);
573   KEYWORD(inteldialect);
574   KEYWORD(gc);
575   KEYWORD(prefix);
576
577   KEYWORD(ccc);
578   KEYWORD(fastcc);
579   KEYWORD(coldcc);
580   KEYWORD(x86_stdcallcc);
581   KEYWORD(x86_fastcallcc);
582   KEYWORD(x86_thiscallcc);
583   KEYWORD(x86_vectorcallcc);
584   KEYWORD(arm_apcscc);
585   KEYWORD(arm_aapcscc);
586   KEYWORD(arm_aapcs_vfpcc);
587   KEYWORD(msp430_intrcc);
588   KEYWORD(ptx_kernel);
589   KEYWORD(ptx_device);
590   KEYWORD(spir_kernel);
591   KEYWORD(spir_func);
592   KEYWORD(intel_ocl_bicc);
593   KEYWORD(x86_64_sysvcc);
594   KEYWORD(x86_64_win64cc);
595   KEYWORD(webkit_jscc);
596   KEYWORD(anyregcc);
597   KEYWORD(preserve_mostcc);
598   KEYWORD(preserve_allcc);
599   KEYWORD(ghccc);
600
601   KEYWORD(cc);
602   KEYWORD(c);
603
604   KEYWORD(attributes);
605
606   KEYWORD(alwaysinline);
607   KEYWORD(builtin);
608   KEYWORD(byval);
609   KEYWORD(inalloca);
610   KEYWORD(cold);
611   KEYWORD(dereferenceable);
612   KEYWORD(inlinehint);
613   KEYWORD(inreg);
614   KEYWORD(jumptable);
615   KEYWORD(minsize);
616   KEYWORD(naked);
617   KEYWORD(nest);
618   KEYWORD(noalias);
619   KEYWORD(nobuiltin);
620   KEYWORD(nocapture);
621   KEYWORD(noduplicate);
622   KEYWORD(noimplicitfloat);
623   KEYWORD(noinline);
624   KEYWORD(nonlazybind);
625   KEYWORD(nonnull);
626   KEYWORD(noredzone);
627   KEYWORD(noreturn);
628   KEYWORD(nounwind);
629   KEYWORD(optnone);
630   KEYWORD(optsize);
631   KEYWORD(readnone);
632   KEYWORD(readonly);
633   KEYWORD(returned);
634   KEYWORD(returns_twice);
635   KEYWORD(signext);
636   KEYWORD(sret);
637   KEYWORD(ssp);
638   KEYWORD(sspreq);
639   KEYWORD(sspstrong);
640   KEYWORD(sanitize_address);
641   KEYWORD(sanitize_thread);
642   KEYWORD(sanitize_memory);
643   KEYWORD(uwtable);
644   KEYWORD(zeroext);
645
646   KEYWORD(type);
647   KEYWORD(opaque);
648
649   KEYWORD(comdat);
650
651   // Comdat types
652   KEYWORD(any);
653   KEYWORD(exactmatch);
654   KEYWORD(largest);
655   KEYWORD(noduplicates);
656   KEYWORD(samesize);
657
658   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
659   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
660   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
661   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
662
663   KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
664   KEYWORD(umin);
665
666   KEYWORD(x);
667   KEYWORD(blockaddress);
668
669   // Use-list order directives.
670   KEYWORD(uselistorder);
671   KEYWORD(uselistorder_bb);
672
673   KEYWORD(personality);
674   KEYWORD(cleanup);
675   KEYWORD(catch);
676   KEYWORD(filter);
677 #undef KEYWORD
678
679   // Keywords for types.
680 #define TYPEKEYWORD(STR, LLVMTY) \
681   if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
682     TyVal = LLVMTY; return lltok::Type; }
683   TYPEKEYWORD("void",      Type::getVoidTy(Context));
684   TYPEKEYWORD("half",      Type::getHalfTy(Context));
685   TYPEKEYWORD("float",     Type::getFloatTy(Context));
686   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
687   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
688   TYPEKEYWORD("fp128",     Type::getFP128Ty(Context));
689   TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
690   TYPEKEYWORD("label",     Type::getLabelTy(Context));
691   TYPEKEYWORD("metadata",  Type::getMetadataTy(Context));
692   TYPEKEYWORD("x86_mmx",   Type::getX86_MMXTy(Context));
693 #undef TYPEKEYWORD
694
695   // Keywords for instructions.
696 #define INSTKEYWORD(STR, Enum) \
697   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) { \
698     UIntVal = Instruction::Enum; return lltok::kw_##STR; }
699
700   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
701   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
702   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
703   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
704   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
705   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
706   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
707   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
708
709   INSTKEYWORD(phi,         PHI);
710   INSTKEYWORD(call,        Call);
711   INSTKEYWORD(trunc,       Trunc);
712   INSTKEYWORD(zext,        ZExt);
713   INSTKEYWORD(sext,        SExt);
714   INSTKEYWORD(fptrunc,     FPTrunc);
715   INSTKEYWORD(fpext,       FPExt);
716   INSTKEYWORD(uitofp,      UIToFP);
717   INSTKEYWORD(sitofp,      SIToFP);
718   INSTKEYWORD(fptoui,      FPToUI);
719   INSTKEYWORD(fptosi,      FPToSI);
720   INSTKEYWORD(inttoptr,    IntToPtr);
721   INSTKEYWORD(ptrtoint,    PtrToInt);
722   INSTKEYWORD(bitcast,     BitCast);
723   INSTKEYWORD(addrspacecast, AddrSpaceCast);
724   INSTKEYWORD(select,      Select);
725   INSTKEYWORD(va_arg,      VAArg);
726   INSTKEYWORD(ret,         Ret);
727   INSTKEYWORD(br,          Br);
728   INSTKEYWORD(switch,      Switch);
729   INSTKEYWORD(indirectbr,  IndirectBr);
730   INSTKEYWORD(invoke,      Invoke);
731   INSTKEYWORD(resume,      Resume);
732   INSTKEYWORD(unreachable, Unreachable);
733
734   INSTKEYWORD(alloca,      Alloca);
735   INSTKEYWORD(load,        Load);
736   INSTKEYWORD(store,       Store);
737   INSTKEYWORD(cmpxchg,     AtomicCmpXchg);
738   INSTKEYWORD(atomicrmw,   AtomicRMW);
739   INSTKEYWORD(fence,       Fence);
740   INSTKEYWORD(getelementptr, GetElementPtr);
741
742   INSTKEYWORD(extractelement, ExtractElement);
743   INSTKEYWORD(insertelement,  InsertElement);
744   INSTKEYWORD(shufflevector,  ShuffleVector);
745   INSTKEYWORD(extractvalue,   ExtractValue);
746   INSTKEYWORD(insertvalue,    InsertValue);
747   INSTKEYWORD(landingpad,     LandingPad);
748 #undef INSTKEYWORD
749
750   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
751   // the CFE to avoid forcing it to deal with 64-bit numbers.
752   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
753       TokStart[1] == '0' && TokStart[2] == 'x' &&
754       isxdigit(static_cast<unsigned char>(TokStart[3]))) {
755     int len = CurPtr-TokStart-3;
756     uint32_t bits = len * 4;
757     APInt Tmp(bits, StringRef(TokStart+3, len), 16);
758     uint32_t activeBits = Tmp.getActiveBits();
759     if (activeBits > 0 && activeBits < bits)
760       Tmp = Tmp.trunc(activeBits);
761     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
762     return lltok::APSInt;
763   }
764
765   // If this is "cc1234", return this as just "cc".
766   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
767     CurPtr = TokStart+2;
768     return lltok::kw_cc;
769   }
770
771   // Finally, if this isn't known, return an error.
772   CurPtr = TokStart+1;
773   return lltok::Error;
774 }
775
776
777 /// Lex0x: Handle productions that start with 0x, knowing that it matches and
778 /// that this is not a label:
779 ///    HexFPConstant     0x[0-9A-Fa-f]+
780 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
781 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
782 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
783 ///    HexHalfConstant   0xH[0-9A-Fa-f]+
784 lltok::Kind LLLexer::Lex0x() {
785   CurPtr = TokStart + 2;
786
787   char Kind;
788   if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H') {
789     Kind = *CurPtr++;
790   } else {
791     Kind = 'J';
792   }
793
794   if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
795     // Bad token, return it as an error.
796     CurPtr = TokStart+1;
797     return lltok::Error;
798   }
799
800   while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
801     ++CurPtr;
802
803   if (Kind == 'J') {
804     // HexFPConstant - Floating point constant represented in IEEE format as a
805     // hexadecimal number for when exponential notation is not precise enough.
806     // Half, Float, and double only.
807     APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
808     return lltok::APFloat;
809   }
810
811   uint64_t Pair[2];
812   switch (Kind) {
813   default: llvm_unreachable("Unknown kind!");
814   case 'K':
815     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
816     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
817     APFloatVal = APFloat(APFloat::x87DoubleExtended, APInt(80, Pair));
818     return lltok::APFloat;
819   case 'L':
820     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
821     HexToIntPair(TokStart+3, CurPtr, Pair);
822     APFloatVal = APFloat(APFloat::IEEEquad, APInt(128, Pair));
823     return lltok::APFloat;
824   case 'M':
825     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
826     HexToIntPair(TokStart+3, CurPtr, Pair);
827     APFloatVal = APFloat(APFloat::PPCDoubleDouble, APInt(128, Pair));
828     return lltok::APFloat;
829   case 'H':
830     APFloatVal = APFloat(APFloat::IEEEhalf,
831                          APInt(16,HexIntToVal(TokStart+3, CurPtr)));
832     return lltok::APFloat;
833   }
834 }
835
836 /// LexIdentifier: Handle several related productions:
837 ///    Label             [-a-zA-Z$._0-9]+:
838 ///    NInteger          -[0-9]+
839 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
840 ///    PInteger          [0-9]+
841 ///    HexFPConstant     0x[0-9A-Fa-f]+
842 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
843 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
844 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
845 lltok::Kind LLLexer::LexDigitOrNegative() {
846   // If the letter after the negative is not a number, this is probably a label.
847   if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
848       !isdigit(static_cast<unsigned char>(CurPtr[0]))) {
849     // Okay, this is not a number after the -, it's probably a label.
850     if (const char *End = isLabelTail(CurPtr)) {
851       StrVal.assign(TokStart, End-1);
852       CurPtr = End;
853       return lltok::LabelStr;
854     }
855
856     return lltok::Error;
857   }
858
859   // At this point, it is either a label, int or fp constant.
860
861   // Skip digits, we have at least one.
862   for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
863     /*empty*/;
864
865   // Check to see if this really is a label afterall, e.g. "-1:".
866   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
867     if (const char *End = isLabelTail(CurPtr)) {
868       StrVal.assign(TokStart, End-1);
869       CurPtr = End;
870       return lltok::LabelStr;
871     }
872   }
873
874   // If the next character is a '.', then it is a fp value, otherwise its
875   // integer.
876   if (CurPtr[0] != '.') {
877     if (TokStart[0] == '0' && TokStart[1] == 'x')
878       return Lex0x();
879     unsigned Len = CurPtr-TokStart;
880     uint32_t numBits = ((Len * 64) / 19) + 2;
881     APInt Tmp(numBits, StringRef(TokStart, Len), 10);
882     if (TokStart[0] == '-') {
883       uint32_t minBits = Tmp.getMinSignedBits();
884       if (minBits > 0 && minBits < numBits)
885         Tmp = Tmp.trunc(minBits);
886       APSIntVal = APSInt(Tmp, false);
887     } else {
888       uint32_t activeBits = Tmp.getActiveBits();
889       if (activeBits > 0 && activeBits < numBits)
890         Tmp = Tmp.trunc(activeBits);
891       APSIntVal = APSInt(Tmp, true);
892     }
893     return lltok::APSInt;
894   }
895
896   ++CurPtr;
897
898   // Skip over [0-9]*([eE][-+]?[0-9]+)?
899   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
900
901   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
902     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
903         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
904           isdigit(static_cast<unsigned char>(CurPtr[2])))) {
905       CurPtr += 2;
906       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
907     }
908   }
909
910   APFloatVal = APFloat(std::atof(TokStart));
911   return lltok::APFloat;
912 }
913
914 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
915 lltok::Kind LLLexer::LexPositive() {
916   // If the letter after the negative is a number, this is probably not a
917   // label.
918   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
919     return lltok::Error;
920
921   // Skip digits.
922   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
923     /*empty*/;
924
925   // At this point, we need a '.'.
926   if (CurPtr[0] != '.') {
927     CurPtr = TokStart+1;
928     return lltok::Error;
929   }
930
931   ++CurPtr;
932
933   // Skip over [0-9]*([eE][-+]?[0-9]+)?
934   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
935
936   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
937     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
938         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
939         isdigit(static_cast<unsigned char>(CurPtr[2])))) {
940       CurPtr += 2;
941       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
942     }
943   }
944
945   APFloatVal = APFloat(std::atof(TokStart));
946   return lltok::APFloat;
947 }