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