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