switch the .ll parser to use SourceMgr.
[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/DerivedTypes.h"
16 #include "llvm/Instruction.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Assembly/Parser.h"
22 #include <cstdlib>
23 #include <cstring>
24 using namespace llvm;
25
26 bool LLLexer::Error(LocTy ErrorLoc, const std::string &Msg) const {
27   ErrorInfo = SM.GetMessage(ErrorLoc, Msg, "error");
28   return true;
29 }
30
31 //===----------------------------------------------------------------------===//
32 // Helper functions.
33 //===----------------------------------------------------------------------===//
34
35 // atoull - Convert an ascii string of decimal digits into the unsigned long
36 // long representation... this does not have to do input error checking,
37 // because we know that the input will be matched by a suitable regex...
38 //
39 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
40   uint64_t Result = 0;
41   for (; Buffer != End; Buffer++) {
42     uint64_t OldRes = Result;
43     Result *= 10;
44     Result += *Buffer-'0';
45     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
46       Error("constant bigger than 64 bits detected!");
47       return 0;
48     }
49   }
50   return Result;
51 }
52
53 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
54   uint64_t Result = 0;
55   for (; Buffer != End; ++Buffer) {
56     uint64_t OldRes = Result;
57     Result *= 16;
58     char C = *Buffer;
59     if (C >= '0' && C <= '9')
60       Result += C-'0';
61     else if (C >= 'A' && C <= 'F')
62       Result += C-'A'+10;
63     else if (C >= 'a' && C <= 'f')
64       Result += C-'a'+10;
65
66     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
67       Error("constant bigger than 64 bits detected!");
68       return 0;
69     }
70   }
71   return Result;
72 }
73
74 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
75                            uint64_t Pair[2]) {
76   Pair[0] = 0;
77   for (int i=0; i<16; i++, Buffer++) {
78     assert(Buffer != End);
79     Pair[0] *= 16;
80     char C = *Buffer;
81     if (C >= '0' && C <= '9')
82       Pair[0] += C-'0';
83     else if (C >= 'A' && C <= 'F')
84       Pair[0] += C-'A'+10;
85     else if (C >= 'a' && C <= 'f')
86       Pair[0] += C-'a'+10;
87   }
88   Pair[1] = 0;
89   for (int i=0; i<16 && Buffer != End; i++, Buffer++) {
90     Pair[1] *= 16;
91     char C = *Buffer;
92     if (C >= '0' && C <= '9')
93       Pair[1] += C-'0';
94     else if (C >= 'A' && C <= 'F')
95       Pair[1] += C-'A'+10;
96     else if (C >= 'a' && C <= 'f')
97       Pair[1] += C-'a'+10;
98   }
99   if (Buffer != End)
100     Error("constant bigger than 128 bits detected!");
101 }
102
103 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
104 /// { low64, high16 } as usual for an APInt.
105 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
106                            uint64_t Pair[2]) {
107   Pair[1] = 0;
108   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
109     assert(Buffer != End);
110     Pair[1] *= 16;
111     char C = *Buffer;
112     if (C >= '0' && C <= '9')
113       Pair[1] += C-'0';
114     else if (C >= 'A' && C <= 'F')
115       Pair[1] += C-'A'+10;
116     else if (C >= 'a' && C <= 'f')
117       Pair[1] += C-'a'+10;
118   }
119   Pair[0] = 0;
120   for (int i=0; i<16; i++, Buffer++) {
121     Pair[0] *= 16;
122     char C = *Buffer;
123     if (C >= '0' && C <= '9')
124       Pair[0] += C-'0';
125     else if (C >= 'A' && C <= 'F')
126       Pair[0] += C-'A'+10;
127     else if (C >= 'a' && C <= 'f')
128       Pair[0] += C-'a'+10;
129   }
130   if (Buffer != End)
131     Error("constant bigger than 128 bits detected!");
132 }
133
134 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
135 // appropriate character.
136 static void UnEscapeLexed(std::string &Str) {
137   if (Str.empty()) return;
138
139   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
140   char *BOut = Buffer;
141   for (char *BIn = Buffer; BIn != EndBuffer; ) {
142     if (BIn[0] == '\\') {
143       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
144         *BOut++ = '\\'; // Two \ becomes one
145         BIn += 2;
146       } else if (BIn < EndBuffer-2 && isxdigit(BIn[1]) && isxdigit(BIn[2])) {
147         char Tmp = BIn[3]; BIn[3] = 0;      // Terminate string
148         *BOut = (char)strtol(BIn+1, 0, 16); // Convert to number
149         BIn[3] = Tmp;                       // Restore character
150         BIn += 3;                           // Skip over handled chars
151         ++BOut;
152       } else {
153         *BOut++ = *BIn++;
154       }
155     } else {
156       *BOut++ = *BIn++;
157     }
158   }
159   Str.resize(BOut-Buffer);
160 }
161
162 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
163 static bool isLabelChar(char C) {
164   return isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_';
165 }
166
167
168 /// isLabelTail - Return true if this pointer points to a valid end of a label.
169 static const char *isLabelTail(const char *CurPtr) {
170   while (1) {
171     if (CurPtr[0] == ':') return CurPtr+1;
172     if (!isLabelChar(CurPtr[0])) return 0;
173     ++CurPtr;
174   }
175 }
176
177
178
179 //===----------------------------------------------------------------------===//
180 // Lexer definition.
181 //===----------------------------------------------------------------------===//
182
183 LLLexer::LLLexer(MemoryBuffer *StartBuf, SourceMgr &sm, SMDiagnostic &Err)
184   : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), APFloatVal(0.0) {
185   CurPtr = CurBuf->getBufferStart();
186 }
187
188 std::string LLLexer::getFilename() const {
189   return CurBuf->getBufferIdentifier();
190 }
191
192 int LLLexer::getNextChar() {
193   char CurChar = *CurPtr++;
194   switch (CurChar) {
195   default: return (unsigned char)CurChar;
196   case 0:
197     // A nul character in the stream is either the end of the current buffer or
198     // a random nul in the file.  Disambiguate that here.
199     if (CurPtr-1 != CurBuf->getBufferEnd())
200       return 0;  // Just whitespace.
201
202     // Otherwise, return end of file.
203     --CurPtr;  // Another call to lex will return EOF again.
204     return EOF;
205   }
206 }
207
208
209 lltok::Kind LLLexer::LexToken() {
210   TokStart = CurPtr;
211
212   int CurChar = getNextChar();
213   switch (CurChar) {
214   default:
215     // Handle letters: [a-zA-Z_]
216     if (isalpha(CurChar) || CurChar == '_')
217       return LexIdentifier();
218
219     return lltok::Error;
220   case EOF: return lltok::Eof;
221   case 0:
222   case ' ':
223   case '\t':
224   case '\n':
225   case '\r':
226     // Ignore whitespace.
227     return LexToken();
228   case '+': return LexPositive();
229   case '@': return LexAt();
230   case '%': return LexPercent();
231   case '"': return LexQuote();
232   case '.':
233     if (const char *Ptr = isLabelTail(CurPtr)) {
234       CurPtr = Ptr;
235       StrVal.assign(TokStart, CurPtr-1);
236       return lltok::LabelStr;
237     }
238     if (CurPtr[0] == '.' && CurPtr[1] == '.') {
239       CurPtr += 2;
240       return lltok::dotdotdot;
241     }
242     return lltok::Error;
243   case '$':
244     if (const char *Ptr = isLabelTail(CurPtr)) {
245       CurPtr = Ptr;
246       StrVal.assign(TokStart, CurPtr-1);
247       return lltok::LabelStr;
248     }
249     return lltok::Error;
250   case ';':
251     SkipLineComment();
252     return LexToken();
253   case '!': return lltok::Metadata;
254   case '0': case '1': case '2': case '3': case '4':
255   case '5': case '6': case '7': case '8': case '9':
256   case '-':
257     return LexDigitOrNegative();
258   case '=': return lltok::equal;
259   case '[': return lltok::lsquare;
260   case ']': return lltok::rsquare;
261   case '{': return lltok::lbrace;
262   case '}': return lltok::rbrace;
263   case '<': return lltok::less;
264   case '>': return lltok::greater;
265   case '(': return lltok::lparen;
266   case ')': return lltok::rparen;
267   case ',': return lltok::comma;
268   case '*': return lltok::star;
269   case '\\': return lltok::backslash;
270   }
271 }
272
273 void LLLexer::SkipLineComment() {
274   while (1) {
275     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
276       return;
277   }
278 }
279
280 /// LexAt - Lex all tokens that start with an @ character:
281 ///   GlobalVar   @\"[^\"]*\"
282 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
283 ///   GlobalVarID @[0-9]+
284 lltok::Kind LLLexer::LexAt() {
285   // Handle AtStringConstant: @\"[^\"]*\"
286   if (CurPtr[0] == '"') {
287     ++CurPtr;
288
289     while (1) {
290       int CurChar = getNextChar();
291
292       if (CurChar == EOF) {
293         Error("end of file in global variable name");
294         return lltok::Error;
295       }
296       if (CurChar == '"') {
297         StrVal.assign(TokStart+2, CurPtr-1);
298         UnEscapeLexed(StrVal);
299         return lltok::GlobalVar;
300       }
301     }
302   }
303
304   // Handle GlobalVarName: @[-a-zA-Z$._][-a-zA-Z$._0-9]*
305   if (isalpha(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
306       CurPtr[0] == '.' || CurPtr[0] == '_') {
307     ++CurPtr;
308     while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
309            CurPtr[0] == '.' || CurPtr[0] == '_')
310       ++CurPtr;
311
312     StrVal.assign(TokStart+1, CurPtr);   // Skip @
313     return lltok::GlobalVar;
314   }
315
316   // Handle GlobalVarID: @[0-9]+
317   if (isdigit(CurPtr[0])) {
318     for (++CurPtr; isdigit(CurPtr[0]); ++CurPtr)
319       /*empty*/;
320
321     uint64_t Val = atoull(TokStart+1, CurPtr);
322     if ((unsigned)Val != Val)
323       Error("invalid value number (too large)!");
324     UIntVal = unsigned(Val);
325     return lltok::GlobalID;
326   }
327
328   return lltok::Error;
329 }
330
331
332 /// LexPercent - Lex all tokens that start with a % character:
333 ///   LocalVar   ::= %\"[^\"]*\"
334 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
335 ///   LocalVarID ::= %[0-9]+
336 lltok::Kind LLLexer::LexPercent() {
337   // Handle LocalVarName: %\"[^\"]*\"
338   if (CurPtr[0] == '"') {
339     ++CurPtr;
340
341     while (1) {
342       int CurChar = getNextChar();
343
344       if (CurChar == EOF) {
345         Error("end of file in string constant");
346         return lltok::Error;
347       }
348       if (CurChar == '"') {
349         StrVal.assign(TokStart+2, CurPtr-1);
350         UnEscapeLexed(StrVal);
351         return lltok::LocalVar;
352       }
353     }
354   }
355
356   // Handle LocalVarName: %[-a-zA-Z$._][-a-zA-Z$._0-9]*
357   if (isalpha(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
358       CurPtr[0] == '.' || CurPtr[0] == '_') {
359     ++CurPtr;
360     while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' ||
361            CurPtr[0] == '.' || CurPtr[0] == '_')
362       ++CurPtr;
363
364     StrVal.assign(TokStart+1, CurPtr);   // Skip %
365     return lltok::LocalVar;
366   }
367
368   // Handle LocalVarID: %[0-9]+
369   if (isdigit(CurPtr[0])) {
370     for (++CurPtr; isdigit(CurPtr[0]); ++CurPtr)
371       /*empty*/;
372
373     uint64_t Val = atoull(TokStart+1, CurPtr);
374     if ((unsigned)Val != Val)
375       Error("invalid value number (too large)!");
376     UIntVal = unsigned(Val);
377     return lltok::LocalVarID;
378   }
379
380   return lltok::Error;
381 }
382
383 /// LexQuote - Lex all tokens that start with a " character:
384 ///   QuoteLabel        "[^"]+":
385 ///   StringConstant    "[^"]*"
386 lltok::Kind LLLexer::LexQuote() {
387   while (1) {
388     int CurChar = getNextChar();
389
390     if (CurChar == EOF) {
391       Error("end of file in quoted string");
392       return lltok::Error;
393     }
394
395     if (CurChar != '"') continue;
396
397     if (CurPtr[0] != ':') {
398       StrVal.assign(TokStart+1, CurPtr-1);
399       UnEscapeLexed(StrVal);
400       return lltok::StringConstant;
401     }
402
403     ++CurPtr;
404     StrVal.assign(TokStart+1, CurPtr-2);
405     UnEscapeLexed(StrVal);
406     return lltok::LabelStr;
407   }
408 }
409
410 static bool JustWhitespaceNewLine(const char *&Ptr) {
411   const char *ThisPtr = Ptr;
412   while (*ThisPtr == ' ' || *ThisPtr == '\t')
413     ++ThisPtr;
414   if (*ThisPtr == '\n' || *ThisPtr == '\r') {
415     Ptr = ThisPtr;
416     return true;
417   }
418   return false;
419 }
420
421
422 /// LexIdentifier: Handle several related productions:
423 ///    Label           [-a-zA-Z$._0-9]+:
424 ///    IntegerType     i[0-9]+
425 ///    Keyword         sdiv, float, ...
426 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
427 lltok::Kind LLLexer::LexIdentifier() {
428   const char *StartChar = CurPtr;
429   const char *IntEnd = CurPtr[-1] == 'i' ? 0 : StartChar;
430   const char *KeywordEnd = 0;
431
432   for (; isLabelChar(*CurPtr); ++CurPtr) {
433     // If we decide this is an integer, remember the end of the sequence.
434     if (!IntEnd && !isdigit(*CurPtr)) IntEnd = CurPtr;
435     if (!KeywordEnd && !isalnum(*CurPtr) && *CurPtr != '_') KeywordEnd = CurPtr;
436   }
437
438   // If we stopped due to a colon, this really is a label.
439   if (*CurPtr == ':') {
440     StrVal.assign(StartChar-1, CurPtr++);
441     return lltok::LabelStr;
442   }
443
444   // Otherwise, this wasn't a label.  If this was valid as an integer type,
445   // return it.
446   if (IntEnd == 0) IntEnd = CurPtr;
447   if (IntEnd != StartChar) {
448     CurPtr = IntEnd;
449     uint64_t NumBits = atoull(StartChar, CurPtr);
450     if (NumBits < IntegerType::MIN_INT_BITS ||
451         NumBits > IntegerType::MAX_INT_BITS) {
452       Error("bitwidth for integer type out of range!");
453       return lltok::Error;
454     }
455     TyVal = IntegerType::get(NumBits);
456     return lltok::Type;
457   }
458
459   // Otherwise, this was a letter sequence.  See which keyword this is.
460   if (KeywordEnd == 0) KeywordEnd = CurPtr;
461   CurPtr = KeywordEnd;
462   --StartChar;
463   unsigned Len = CurPtr-StartChar;
464 #define KEYWORD(STR) \
465   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) \
466     return lltok::kw_##STR;
467
468   KEYWORD(begin);   KEYWORD(end);
469   KEYWORD(true);    KEYWORD(false);
470   KEYWORD(declare); KEYWORD(define);
471   KEYWORD(global);  KEYWORD(constant);
472
473   KEYWORD(private);
474   KEYWORD(internal);
475   KEYWORD(available_externally);
476   KEYWORD(linkonce);
477   KEYWORD(linkonce_odr);
478   KEYWORD(weak);
479   KEYWORD(weak_odr);
480   KEYWORD(appending);
481   KEYWORD(dllimport);
482   KEYWORD(dllexport);
483   KEYWORD(common);
484   KEYWORD(default);
485   KEYWORD(hidden);
486   KEYWORD(protected);
487   KEYWORD(extern_weak);
488   KEYWORD(external);
489   KEYWORD(thread_local);
490   KEYWORD(zeroinitializer);
491   KEYWORD(undef);
492   KEYWORD(null);
493   KEYWORD(to);
494   KEYWORD(tail);
495   KEYWORD(target);
496   KEYWORD(triple);
497   KEYWORD(deplibs);
498   KEYWORD(datalayout);
499   KEYWORD(volatile);
500   KEYWORD(align);
501   KEYWORD(addrspace);
502   KEYWORD(section);
503   KEYWORD(alias);
504   KEYWORD(module);
505   KEYWORD(asm);
506   KEYWORD(sideeffect);
507   KEYWORD(gc);
508
509   KEYWORD(ccc);
510   KEYWORD(fastcc);
511   KEYWORD(coldcc);
512   KEYWORD(x86_stdcallcc);
513   KEYWORD(x86_fastcallcc);
514   KEYWORD(arm_apcscc);
515   KEYWORD(arm_aapcscc);
516   KEYWORD(arm_aapcs_vfpcc);
517
518   KEYWORD(cc);
519   KEYWORD(c);
520
521   KEYWORD(signext);
522   KEYWORD(zeroext);
523   KEYWORD(inreg);
524   KEYWORD(sret);
525   KEYWORD(nounwind);
526   KEYWORD(noreturn);
527   KEYWORD(noalias);
528   KEYWORD(nocapture);
529   KEYWORD(byval);
530   KEYWORD(nest);
531   KEYWORD(readnone);
532   KEYWORD(readonly);
533
534   KEYWORD(noinline);
535   KEYWORD(alwaysinline);
536   KEYWORD(optsize);
537   KEYWORD(ssp);
538   KEYWORD(sspreq);
539   KEYWORD(noredzone);
540   KEYWORD(noimplicitfloat);
541
542   KEYWORD(type);
543   KEYWORD(opaque);
544
545   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
546   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
547   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
548   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
549
550   KEYWORD(x);
551 #undef KEYWORD
552
553   // Keywords for types.
554 #define TYPEKEYWORD(STR, LLVMTY) \
555   if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
556     TyVal = LLVMTY; return lltok::Type; }
557   TYPEKEYWORD("void",      Type::VoidTy);
558   TYPEKEYWORD("float",     Type::FloatTy);
559   TYPEKEYWORD("double",    Type::DoubleTy);
560   TYPEKEYWORD("x86_fp80",  Type::X86_FP80Ty);
561   TYPEKEYWORD("fp128",     Type::FP128Ty);
562   TYPEKEYWORD("ppc_fp128", Type::PPC_FP128Ty);
563   TYPEKEYWORD("label",     Type::LabelTy);
564   TYPEKEYWORD("metadata",  Type::MetadataTy);
565 #undef TYPEKEYWORD
566
567   // Handle special forms for autoupgrading.  Drop these in LLVM 3.0.  This is
568   // to avoid conflicting with the sext/zext instructions, below.
569   if (Len == 4 && !memcmp(StartChar, "sext", 4)) {
570     // Scan CurPtr ahead, seeing if there is just whitespace before the newline.
571     if (JustWhitespaceNewLine(CurPtr))
572       return lltok::kw_signext;
573   } else if (Len == 4 && !memcmp(StartChar, "zext", 4)) {
574     // Scan CurPtr ahead, seeing if there is just whitespace before the newline.
575     if (JustWhitespaceNewLine(CurPtr))
576       return lltok::kw_zeroext;
577   }
578
579   // Keywords for instructions.
580 #define INSTKEYWORD(STR, Enum) \
581   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) { \
582     UIntVal = Instruction::Enum; return lltok::kw_##STR; }
583
584   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
585   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
586   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
587   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
588   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
589   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
590   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
591   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
592   INSTKEYWORD(vicmp, VICmp); INSTKEYWORD(vfcmp, VFCmp);
593
594   INSTKEYWORD(phi,         PHI);
595   INSTKEYWORD(call,        Call);
596   INSTKEYWORD(trunc,       Trunc);
597   INSTKEYWORD(zext,        ZExt);
598   INSTKEYWORD(sext,        SExt);
599   INSTKEYWORD(fptrunc,     FPTrunc);
600   INSTKEYWORD(fpext,       FPExt);
601   INSTKEYWORD(uitofp,      UIToFP);
602   INSTKEYWORD(sitofp,      SIToFP);
603   INSTKEYWORD(fptoui,      FPToUI);
604   INSTKEYWORD(fptosi,      FPToSI);
605   INSTKEYWORD(inttoptr,    IntToPtr);
606   INSTKEYWORD(ptrtoint,    PtrToInt);
607   INSTKEYWORD(bitcast,     BitCast);
608   INSTKEYWORD(select,      Select);
609   INSTKEYWORD(va_arg,      VAArg);
610   INSTKEYWORD(ret,         Ret);
611   INSTKEYWORD(br,          Br);
612   INSTKEYWORD(switch,      Switch);
613   INSTKEYWORD(invoke,      Invoke);
614   INSTKEYWORD(unwind,      Unwind);
615   INSTKEYWORD(unreachable, Unreachable);
616
617   INSTKEYWORD(malloc,      Malloc);
618   INSTKEYWORD(alloca,      Alloca);
619   INSTKEYWORD(free,        Free);
620   INSTKEYWORD(load,        Load);
621   INSTKEYWORD(store,       Store);
622   INSTKEYWORD(getelementptr, GetElementPtr);
623
624   INSTKEYWORD(extractelement, ExtractElement);
625   INSTKEYWORD(insertelement,  InsertElement);
626   INSTKEYWORD(shufflevector,  ShuffleVector);
627   INSTKEYWORD(getresult,      ExtractValue);
628   INSTKEYWORD(extractvalue,   ExtractValue);
629   INSTKEYWORD(insertvalue,    InsertValue);
630 #undef INSTKEYWORD
631
632   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
633   // the CFE to avoid forcing it to deal with 64-bit numbers.
634   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
635       TokStart[1] == '0' && TokStart[2] == 'x' && isxdigit(TokStart[3])) {
636     int len = CurPtr-TokStart-3;
637     uint32_t bits = len * 4;
638     APInt Tmp(bits, TokStart+3, len, 16);
639     uint32_t activeBits = Tmp.getActiveBits();
640     if (activeBits > 0 && activeBits < bits)
641       Tmp.trunc(activeBits);
642     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
643     return lltok::APSInt;
644   }
645
646   // If this is "cc1234", return this as just "cc".
647   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
648     CurPtr = TokStart+2;
649     return lltok::kw_cc;
650   }
651
652   // If this starts with "call", return it as CALL.  This is to support old
653   // broken .ll files.  FIXME: remove this with LLVM 3.0.
654   if (CurPtr-TokStart > 4 && !memcmp(TokStart, "call", 4)) {
655     CurPtr = TokStart+4;
656     UIntVal = Instruction::Call;
657     return lltok::kw_call;
658   }
659
660   // Finally, if this isn't known, return an error.
661   CurPtr = TokStart+1;
662   return lltok::Error;
663 }
664
665
666 /// Lex0x: Handle productions that start with 0x, knowing that it matches and
667 /// that this is not a label:
668 ///    HexFPConstant     0x[0-9A-Fa-f]+
669 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
670 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
671 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
672 lltok::Kind LLLexer::Lex0x() {
673   CurPtr = TokStart + 2;
674
675   char Kind;
676   if (CurPtr[0] >= 'K' && CurPtr[0] <= 'M') {
677     Kind = *CurPtr++;
678   } else {
679     Kind = 'J';
680   }
681
682   if (!isxdigit(CurPtr[0])) {
683     // Bad token, return it as an error.
684     CurPtr = TokStart+1;
685     return lltok::Error;
686   }
687
688   while (isxdigit(CurPtr[0]))
689     ++CurPtr;
690
691   if (Kind == 'J') {
692     // HexFPConstant - Floating point constant represented in IEEE format as a
693     // hexadecimal number for when exponential notation is not precise enough.
694     // Float and double only.
695     APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
696     return lltok::APFloat;
697   }
698
699   uint64_t Pair[2];
700   switch (Kind) {
701   default: assert(0 && "Unknown kind!");
702   case 'K':
703     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
704     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
705     APFloatVal = APFloat(APInt(80, 2, Pair));
706     return lltok::APFloat;
707   case 'L':
708     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
709     HexToIntPair(TokStart+3, CurPtr, Pair);
710     APFloatVal = APFloat(APInt(128, 2, Pair), true);
711     return lltok::APFloat;
712   case 'M':
713     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
714     HexToIntPair(TokStart+3, CurPtr, Pair);
715     APFloatVal = APFloat(APInt(128, 2, Pair));
716     return lltok::APFloat;
717   }
718 }
719
720 /// LexIdentifier: Handle several related productions:
721 ///    Label             [-a-zA-Z$._0-9]+:
722 ///    NInteger          -[0-9]+
723 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
724 ///    PInteger          [0-9]+
725 ///    HexFPConstant     0x[0-9A-Fa-f]+
726 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
727 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
728 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
729 lltok::Kind LLLexer::LexDigitOrNegative() {
730   // If the letter after the negative is a number, this is probably a label.
731   if (!isdigit(TokStart[0]) && !isdigit(CurPtr[0])) {
732     // Okay, this is not a number after the -, it's probably a label.
733     if (const char *End = isLabelTail(CurPtr)) {
734       StrVal.assign(TokStart, End-1);
735       CurPtr = End;
736       return lltok::LabelStr;
737     }
738
739     return lltok::Error;
740   }
741
742   // At this point, it is either a label, int or fp constant.
743
744   // Skip digits, we have at least one.
745   for (; isdigit(CurPtr[0]); ++CurPtr)
746     /*empty*/;
747
748   // Check to see if this really is a label afterall, e.g. "-1:".
749   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
750     if (const char *End = isLabelTail(CurPtr)) {
751       StrVal.assign(TokStart, End-1);
752       CurPtr = End;
753       return lltok::LabelStr;
754     }
755   }
756
757   // If the next character is a '.', then it is a fp value, otherwise its
758   // integer.
759   if (CurPtr[0] != '.') {
760     if (TokStart[0] == '0' && TokStart[1] == 'x')
761       return Lex0x();
762     unsigned Len = CurPtr-TokStart;
763     uint32_t numBits = ((Len * 64) / 19) + 2;
764     APInt Tmp(numBits, TokStart, Len, 10);
765     if (TokStart[0] == '-') {
766       uint32_t minBits = Tmp.getMinSignedBits();
767       if (minBits > 0 && minBits < numBits)
768         Tmp.trunc(minBits);
769       APSIntVal = APSInt(Tmp, false);
770     } else {
771       uint32_t activeBits = Tmp.getActiveBits();
772       if (activeBits > 0 && activeBits < numBits)
773         Tmp.trunc(activeBits);
774       APSIntVal = APSInt(Tmp, true);
775     }
776     return lltok::APSInt;
777   }
778
779   ++CurPtr;
780
781   // Skip over [0-9]*([eE][-+]?[0-9]+)?
782   while (isdigit(CurPtr[0])) ++CurPtr;
783
784   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
785     if (isdigit(CurPtr[1]) ||
786         ((CurPtr[1] == '-' || CurPtr[1] == '+') && isdigit(CurPtr[2]))) {
787       CurPtr += 2;
788       while (isdigit(CurPtr[0])) ++CurPtr;
789     }
790   }
791
792   APFloatVal = APFloat(atof(TokStart));
793   return lltok::APFloat;
794 }
795
796 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
797 lltok::Kind LLLexer::LexPositive() {
798   // If the letter after the negative is a number, this is probably not a
799   // label.
800   if (!isdigit(CurPtr[0]))
801     return lltok::Error;
802
803   // Skip digits.
804   for (++CurPtr; isdigit(CurPtr[0]); ++CurPtr)
805     /*empty*/;
806
807   // At this point, we need a '.'.
808   if (CurPtr[0] != '.') {
809     CurPtr = TokStart+1;
810     return lltok::Error;
811   }
812
813   ++CurPtr;
814
815   // Skip over [0-9]*([eE][-+]?[0-9]+)?
816   while (isdigit(CurPtr[0])) ++CurPtr;
817
818   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
819     if (isdigit(CurPtr[1]) ||
820         ((CurPtr[1] == '-' || CurPtr[1] == '+') && isdigit(CurPtr[2]))) {
821       CurPtr += 2;
822       while (isdigit(CurPtr[0])) ++CurPtr;
823     }
824   }
825
826   APFloatVal = APFloat(atof(TokStart));
827   return lltok::APFloat;
828 }