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