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