LLVM API Documentation

LLLexer.cpp
Go to the documentation of this file.
00001 //===- LLLexer.cpp - Lexer for .ll Files ----------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Implement the Lexer for .ll files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "LLLexer.h"
00015 #include "llvm/ADT/StringExtras.h"
00016 #include "llvm/ADT/Twine.h"
00017 #include "llvm/AsmParser/Parser.h"
00018 #include "llvm/IR/DerivedTypes.h"
00019 #include "llvm/IR/Instruction.h"
00020 #include "llvm/IR/LLVMContext.h"
00021 #include "llvm/Support/ErrorHandling.h"
00022 #include "llvm/Support/MathExtras.h"
00023 #include "llvm/Support/MemoryBuffer.h"
00024 #include "llvm/Support/SourceMgr.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include <cctype>
00027 #include <cstdio>
00028 #include <cstdlib>
00029 #include <cstring>
00030 using namespace llvm;
00031 
00032 bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
00033   ErrorInfo = SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
00034   return true;
00035 }
00036 
00037 void LLLexer::Warning(LocTy WarningLoc, const Twine &Msg) const {
00038   SM.PrintMessage(WarningLoc, SourceMgr::DK_Warning, Msg);
00039 }
00040 
00041 //===----------------------------------------------------------------------===//
00042 // Helper functions.
00043 //===----------------------------------------------------------------------===//
00044 
00045 // atoull - Convert an ascii string of decimal digits into the unsigned long
00046 // long representation... this does not have to do input error checking,
00047 // because we know that the input will be matched by a suitable regex...
00048 //
00049 uint64_t LLLexer::atoull(const char *Buffer, const char *End) {
00050   uint64_t Result = 0;
00051   for (; Buffer != End; Buffer++) {
00052     uint64_t OldRes = Result;
00053     Result *= 10;
00054     Result += *Buffer-'0';
00055     if (Result < OldRes) {  // Uh, oh, overflow detected!!!
00056       Error("constant bigger than 64 bits detected!");
00057       return 0;
00058     }
00059   }
00060   return Result;
00061 }
00062 
00063 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
00064   uint64_t Result = 0;
00065   for (; Buffer != End; ++Buffer) {
00066     uint64_t OldRes = Result;
00067     Result *= 16;
00068     Result += hexDigitValue(*Buffer);
00069 
00070     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
00071       Error("constant bigger than 64 bits detected!");
00072       return 0;
00073     }
00074   }
00075   return Result;
00076 }
00077 
00078 void LLLexer::HexToIntPair(const char *Buffer, const char *End,
00079                            uint64_t Pair[2]) {
00080   Pair[0] = 0;
00081   for (int i=0; i<16; i++, Buffer++) {
00082     assert(Buffer != End);
00083     Pair[0] *= 16;
00084     Pair[0] += hexDigitValue(*Buffer);
00085   }
00086   Pair[1] = 0;
00087   for (int i=0; i<16 && Buffer != End; i++, Buffer++) {
00088     Pair[1] *= 16;
00089     Pair[1] += hexDigitValue(*Buffer);
00090   }
00091   if (Buffer != End)
00092     Error("constant bigger than 128 bits detected!");
00093 }
00094 
00095 /// FP80HexToIntPair - translate an 80 bit FP80 number (20 hexits) into
00096 /// { low64, high16 } as usual for an APInt.
00097 void LLLexer::FP80HexToIntPair(const char *Buffer, const char *End,
00098                            uint64_t Pair[2]) {
00099   Pair[1] = 0;
00100   for (int i=0; i<4 && Buffer != End; i++, Buffer++) {
00101     assert(Buffer != End);
00102     Pair[1] *= 16;
00103     Pair[1] += hexDigitValue(*Buffer);
00104   }
00105   Pair[0] = 0;
00106   for (int i=0; i<16; i++, Buffer++) {
00107     Pair[0] *= 16;
00108     Pair[0] += hexDigitValue(*Buffer);
00109   }
00110   if (Buffer != End)
00111     Error("constant bigger than 128 bits detected!");
00112 }
00113 
00114 // UnEscapeLexed - Run through the specified buffer and change \xx codes to the
00115 // appropriate character.
00116 static void UnEscapeLexed(std::string &Str) {
00117   if (Str.empty()) return;
00118 
00119   char *Buffer = &Str[0], *EndBuffer = Buffer+Str.size();
00120   char *BOut = Buffer;
00121   for (char *BIn = Buffer; BIn != EndBuffer; ) {
00122     if (BIn[0] == '\\') {
00123       if (BIn < EndBuffer-1 && BIn[1] == '\\') {
00124         *BOut++ = '\\'; // Two \ becomes one
00125         BIn += 2;
00126       } else if (BIn < EndBuffer-2 &&
00127                  isxdigit(static_cast<unsigned char>(BIn[1])) &&
00128                  isxdigit(static_cast<unsigned char>(BIn[2]))) {
00129         *BOut = hexDigitValue(BIn[1]) * 16 + hexDigitValue(BIn[2]);
00130         BIn += 3;                           // Skip over handled chars
00131         ++BOut;
00132       } else {
00133         *BOut++ = *BIn++;
00134       }
00135     } else {
00136       *BOut++ = *BIn++;
00137     }
00138   }
00139   Str.resize(BOut-Buffer);
00140 }
00141 
00142 /// isLabelChar - Return true for [-a-zA-Z$._0-9].
00143 static bool isLabelChar(char C) {
00144   return isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
00145          C == '.' || C == '_';
00146 }
00147 
00148 
00149 /// isLabelTail - Return true if this pointer points to a valid end of a label.
00150 static const char *isLabelTail(const char *CurPtr) {
00151   while (1) {
00152     if (CurPtr[0] == ':') return CurPtr+1;
00153     if (!isLabelChar(CurPtr[0])) return nullptr;
00154     ++CurPtr;
00155   }
00156 }
00157 
00158 
00159 
00160 //===----------------------------------------------------------------------===//
00161 // Lexer definition.
00162 //===----------------------------------------------------------------------===//
00163 
00164 LLLexer::LLLexer(StringRef StartBuf, SourceMgr &sm, SMDiagnostic &Err,
00165                  LLVMContext &C)
00166   : CurBuf(StartBuf), ErrorInfo(Err), SM(sm), Context(C), APFloatVal(0.0) {
00167   CurPtr = CurBuf.begin();
00168 }
00169 
00170 int LLLexer::getNextChar() {
00171   char CurChar = *CurPtr++;
00172   switch (CurChar) {
00173   default: return (unsigned char)CurChar;
00174   case 0:
00175     // A nul character in the stream is either the end of the current buffer or
00176     // a random nul in the file.  Disambiguate that here.
00177     if (CurPtr-1 != CurBuf.end())
00178       return 0;  // Just whitespace.
00179 
00180     // Otherwise, return end of file.
00181     --CurPtr;  // Another call to lex will return EOF again.
00182     return EOF;
00183   }
00184 }
00185 
00186 
00187 lltok::Kind LLLexer::LexToken() {
00188   TokStart = CurPtr;
00189 
00190   int CurChar = getNextChar();
00191   switch (CurChar) {
00192   default:
00193     // Handle letters: [a-zA-Z_]
00194     if (isalpha(static_cast<unsigned char>(CurChar)) || CurChar == '_')
00195       return LexIdentifier();
00196 
00197     return lltok::Error;
00198   case EOF: return lltok::Eof;
00199   case 0:
00200   case ' ':
00201   case '\t':
00202   case '\n':
00203   case '\r':
00204     // Ignore whitespace.
00205     return LexToken();
00206   case '+': return LexPositive();
00207   case '@': return LexAt();
00208   case '$': return LexDollar();
00209   case '%': return LexPercent();
00210   case '"': return LexQuote();
00211   case '.':
00212     if (const char *Ptr = isLabelTail(CurPtr)) {
00213       CurPtr = Ptr;
00214       StrVal.assign(TokStart, CurPtr-1);
00215       return lltok::LabelStr;
00216     }
00217     if (CurPtr[0] == '.' && CurPtr[1] == '.') {
00218       CurPtr += 2;
00219       return lltok::dotdotdot;
00220     }
00221     return lltok::Error;
00222   case ';':
00223     SkipLineComment();
00224     return LexToken();
00225   case '!': return LexExclaim();
00226   case '#': return LexHash();
00227   case '0': case '1': case '2': case '3': case '4':
00228   case '5': case '6': case '7': case '8': case '9':
00229   case '-':
00230     return LexDigitOrNegative();
00231   case '=': return lltok::equal;
00232   case '[': return lltok::lsquare;
00233   case ']': return lltok::rsquare;
00234   case '{': return lltok::lbrace;
00235   case '}': return lltok::rbrace;
00236   case '<': return lltok::less;
00237   case '>': return lltok::greater;
00238   case '(': return lltok::lparen;
00239   case ')': return lltok::rparen;
00240   case ',': return lltok::comma;
00241   case '*': return lltok::star;
00242   case '\\': return lltok::backslash;
00243   }
00244 }
00245 
00246 void LLLexer::SkipLineComment() {
00247   while (1) {
00248     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
00249       return;
00250   }
00251 }
00252 
00253 /// LexAt - Lex all tokens that start with an @ character:
00254 ///   GlobalVar   @\"[^\"]*\"
00255 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
00256 ///   GlobalVarID @[0-9]+
00257 lltok::Kind LLLexer::LexAt() {
00258   // Handle AtStringConstant: @\"[^\"]*\"
00259   if (CurPtr[0] == '"') {
00260     ++CurPtr;
00261 
00262     while (1) {
00263       int CurChar = getNextChar();
00264 
00265       if (CurChar == EOF) {
00266         Error("end of file in global variable name");
00267         return lltok::Error;
00268       }
00269       if (CurChar == '"') {
00270         StrVal.assign(TokStart+2, CurPtr-1);
00271         UnEscapeLexed(StrVal);
00272         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
00273           Error("Null bytes are not allowed in names");
00274           return lltok::Error;
00275         }
00276         return lltok::GlobalVar;
00277       }
00278     }
00279   }
00280 
00281   // Handle GlobalVarName: @[-a-zA-Z$._][-a-zA-Z$._0-9]*
00282   if (ReadVarName())
00283     return lltok::GlobalVar;
00284 
00285   // Handle GlobalVarID: @[0-9]+
00286   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
00287     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
00288       /*empty*/;
00289 
00290     uint64_t Val = atoull(TokStart+1, CurPtr);
00291     if ((unsigned)Val != Val)
00292       Error("invalid value number (too large)!");
00293     UIntVal = unsigned(Val);
00294     return lltok::GlobalID;
00295   }
00296 
00297   return lltok::Error;
00298 }
00299 
00300 lltok::Kind LLLexer::LexDollar() {
00301   if (const char *Ptr = isLabelTail(TokStart)) {
00302     CurPtr = Ptr;
00303     StrVal.assign(TokStart, CurPtr - 1);
00304     return lltok::LabelStr;
00305   }
00306 
00307   // Handle DollarStringConstant: $\"[^\"]*\"
00308   if (CurPtr[0] == '"') {
00309     ++CurPtr;
00310 
00311     while (1) {
00312       int CurChar = getNextChar();
00313 
00314       if (CurChar == EOF) {
00315         Error("end of file in COMDAT variable name");
00316         return lltok::Error;
00317       }
00318       if (CurChar == '"') {
00319         StrVal.assign(TokStart + 2, CurPtr - 1);
00320         UnEscapeLexed(StrVal);
00321         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
00322           Error("Null bytes are not allowed in names");
00323           return lltok::Error;
00324         }
00325         return lltok::ComdatVar;
00326       }
00327     }
00328   }
00329 
00330   // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
00331   if (ReadVarName())
00332     return lltok::ComdatVar;
00333 
00334   return lltok::Error;
00335 }
00336 
00337 /// ReadString - Read a string until the closing quote.
00338 lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
00339   const char *Start = CurPtr;
00340   while (1) {
00341     int CurChar = getNextChar();
00342 
00343     if (CurChar == EOF) {
00344       Error("end of file in string constant");
00345       return lltok::Error;
00346     }
00347     if (CurChar == '"') {
00348       StrVal.assign(Start, CurPtr-1);
00349       UnEscapeLexed(StrVal);
00350       return kind;
00351     }
00352   }
00353 }
00354 
00355 /// ReadVarName - Read the rest of a token containing a variable name.
00356 bool LLLexer::ReadVarName() {
00357   const char *NameStart = CurPtr;
00358   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
00359       CurPtr[0] == '-' || CurPtr[0] == '$' ||
00360       CurPtr[0] == '.' || CurPtr[0] == '_') {
00361     ++CurPtr;
00362     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
00363            CurPtr[0] == '-' || CurPtr[0] == '$' ||
00364            CurPtr[0] == '.' || CurPtr[0] == '_')
00365       ++CurPtr;
00366 
00367     StrVal.assign(NameStart, CurPtr);
00368     return true;
00369   }
00370   return false;
00371 }
00372 
00373 /// LexPercent - Lex all tokens that start with a % character:
00374 ///   LocalVar   ::= %\"[^\"]*\"
00375 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
00376 ///   LocalVarID ::= %[0-9]+
00377 lltok::Kind LLLexer::LexPercent() {
00378   // Handle LocalVarName: %\"[^\"]*\"
00379   if (CurPtr[0] == '"') {
00380     ++CurPtr;
00381     return ReadString(lltok::LocalVar);
00382   }
00383 
00384   // Handle LocalVarName: %[-a-zA-Z$._][-a-zA-Z$._0-9]*
00385   if (ReadVarName())
00386     return lltok::LocalVar;
00387 
00388   // Handle LocalVarID: %[0-9]+
00389   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
00390     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
00391       /*empty*/;
00392 
00393     uint64_t Val = atoull(TokStart+1, CurPtr);
00394     if ((unsigned)Val != Val)
00395       Error("invalid value number (too large)!");
00396     UIntVal = unsigned(Val);
00397     return lltok::LocalVarID;
00398   }
00399 
00400   return lltok::Error;
00401 }
00402 
00403 /// LexQuote - Lex all tokens that start with a " character:
00404 ///   QuoteLabel        "[^"]+":
00405 ///   StringConstant    "[^"]*"
00406 lltok::Kind LLLexer::LexQuote() {
00407   lltok::Kind kind = ReadString(lltok::StringConstant);
00408   if (kind == lltok::Error || kind == lltok::Eof)
00409     return kind;
00410 
00411   if (CurPtr[0] == ':') {
00412     ++CurPtr;
00413     kind = lltok::LabelStr;
00414   }
00415 
00416   return kind;
00417 }
00418 
00419 /// LexExclaim:
00420 ///    !foo
00421 ///    !
00422 lltok::Kind LLLexer::LexExclaim() {
00423   // Lex a metadata name as a MetadataVar.
00424   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
00425       CurPtr[0] == '-' || CurPtr[0] == '$' ||
00426       CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
00427     ++CurPtr;
00428     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
00429            CurPtr[0] == '-' || CurPtr[0] == '$' ||
00430            CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
00431       ++CurPtr;
00432 
00433     StrVal.assign(TokStart+1, CurPtr);   // Skip !
00434     UnEscapeLexed(StrVal);
00435     return lltok::MetadataVar;
00436   }
00437   return lltok::exclaim;
00438 }
00439 
00440 /// LexHash - Lex all tokens that start with a # character:
00441 ///    AttrGrpID ::= #[0-9]+
00442 lltok::Kind LLLexer::LexHash() {
00443   // Handle AttrGrpID: #[0-9]+
00444   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
00445     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
00446       /*empty*/;
00447 
00448     uint64_t Val = atoull(TokStart+1, CurPtr);
00449     if ((unsigned)Val != Val)
00450       Error("invalid value number (too large)!");
00451     UIntVal = unsigned(Val);
00452     return lltok::AttrGrpID;
00453   }
00454 
00455   return lltok::Error;
00456 }
00457 
00458 /// LexIdentifier: Handle several related productions:
00459 ///    Label           [-a-zA-Z$._0-9]+:
00460 ///    IntegerType     i[0-9]+
00461 ///    Keyword         sdiv, float, ...
00462 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
00463 lltok::Kind LLLexer::LexIdentifier() {
00464   const char *StartChar = CurPtr;
00465   const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
00466   const char *KeywordEnd = nullptr;
00467 
00468   for (; isLabelChar(*CurPtr); ++CurPtr) {
00469     // If we decide this is an integer, remember the end of the sequence.
00470     if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
00471       IntEnd = CurPtr;
00472     if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
00473         *CurPtr != '_')
00474       KeywordEnd = CurPtr;
00475   }
00476 
00477   // If we stopped due to a colon, this really is a label.
00478   if (*CurPtr == ':') {
00479     StrVal.assign(StartChar-1, CurPtr++);
00480     return lltok::LabelStr;
00481   }
00482 
00483   // Otherwise, this wasn't a label.  If this was valid as an integer type,
00484   // return it.
00485   if (!IntEnd) IntEnd = CurPtr;
00486   if (IntEnd != StartChar) {
00487     CurPtr = IntEnd;
00488     uint64_t NumBits = atoull(StartChar, CurPtr);
00489     if (NumBits < IntegerType::MIN_INT_BITS ||
00490         NumBits > IntegerType::MAX_INT_BITS) {
00491       Error("bitwidth for integer type out of range!");
00492       return lltok::Error;
00493     }
00494     TyVal = IntegerType::get(Context, NumBits);
00495     return lltok::Type;
00496   }
00497 
00498   // Otherwise, this was a letter sequence.  See which keyword this is.
00499   if (!KeywordEnd) KeywordEnd = CurPtr;
00500   CurPtr = KeywordEnd;
00501   --StartChar;
00502   unsigned Len = CurPtr-StartChar;
00503 #define KEYWORD(STR)                                                    \
00504   do {                                                                  \
00505     if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR)))  \
00506       return lltok::kw_##STR;                                           \
00507   } while (0)
00508 
00509   KEYWORD(true);    KEYWORD(false);
00510   KEYWORD(declare); KEYWORD(define);
00511   KEYWORD(global);  KEYWORD(constant);
00512 
00513   KEYWORD(private);
00514   KEYWORD(internal);
00515   KEYWORD(available_externally);
00516   KEYWORD(linkonce);
00517   KEYWORD(linkonce_odr);
00518   KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
00519   KEYWORD(weak_odr);
00520   KEYWORD(appending);
00521   KEYWORD(dllimport);
00522   KEYWORD(dllexport);
00523   KEYWORD(common);
00524   KEYWORD(default);
00525   KEYWORD(hidden);
00526   KEYWORD(protected);
00527   KEYWORD(unnamed_addr);
00528   KEYWORD(externally_initialized);
00529   KEYWORD(extern_weak);
00530   KEYWORD(external);
00531   KEYWORD(thread_local);
00532   KEYWORD(localdynamic);
00533   KEYWORD(initialexec);
00534   KEYWORD(localexec);
00535   KEYWORD(zeroinitializer);
00536   KEYWORD(undef);
00537   KEYWORD(null);
00538   KEYWORD(to);
00539   KEYWORD(tail);
00540   KEYWORD(musttail);
00541   KEYWORD(target);
00542   KEYWORD(triple);
00543   KEYWORD(unwind);
00544   KEYWORD(deplibs);             // FIXME: Remove in 4.0.
00545   KEYWORD(datalayout);
00546   KEYWORD(volatile);
00547   KEYWORD(atomic);
00548   KEYWORD(unordered);
00549   KEYWORD(monotonic);
00550   KEYWORD(acquire);
00551   KEYWORD(release);
00552   KEYWORD(acq_rel);
00553   KEYWORD(seq_cst);
00554   KEYWORD(singlethread);
00555 
00556   KEYWORD(nnan);
00557   KEYWORD(ninf);
00558   KEYWORD(nsz);
00559   KEYWORD(arcp);
00560   KEYWORD(fast);
00561   KEYWORD(nuw);
00562   KEYWORD(nsw);
00563   KEYWORD(exact);
00564   KEYWORD(inbounds);
00565   KEYWORD(align);
00566   KEYWORD(addrspace);
00567   KEYWORD(section);
00568   KEYWORD(alias);
00569   KEYWORD(module);
00570   KEYWORD(asm);
00571   KEYWORD(sideeffect);
00572   KEYWORD(alignstack);
00573   KEYWORD(inteldialect);
00574   KEYWORD(gc);
00575   KEYWORD(prefix);
00576 
00577   KEYWORD(ccc);
00578   KEYWORD(fastcc);
00579   KEYWORD(coldcc);
00580   KEYWORD(x86_stdcallcc);
00581   KEYWORD(x86_fastcallcc);
00582   KEYWORD(x86_thiscallcc);
00583   KEYWORD(arm_apcscc);
00584   KEYWORD(arm_aapcscc);
00585   KEYWORD(arm_aapcs_vfpcc);
00586   KEYWORD(msp430_intrcc);
00587   KEYWORD(ptx_kernel);
00588   KEYWORD(ptx_device);
00589   KEYWORD(spir_kernel);
00590   KEYWORD(spir_func);
00591   KEYWORD(intel_ocl_bicc);
00592   KEYWORD(x86_64_sysvcc);
00593   KEYWORD(x86_64_win64cc);
00594   KEYWORD(webkit_jscc);
00595   KEYWORD(anyregcc);
00596   KEYWORD(preserve_mostcc);
00597   KEYWORD(preserve_allcc);
00598 
00599   KEYWORD(cc);
00600   KEYWORD(c);
00601 
00602   KEYWORD(attributes);
00603 
00604   KEYWORD(alwaysinline);
00605   KEYWORD(builtin);
00606   KEYWORD(byval);
00607   KEYWORD(inalloca);
00608   KEYWORD(cold);
00609   KEYWORD(dereferenceable);
00610   KEYWORD(inlinehint);
00611   KEYWORD(inreg);
00612   KEYWORD(jumptable);
00613   KEYWORD(minsize);
00614   KEYWORD(naked);
00615   KEYWORD(nest);
00616   KEYWORD(noalias);
00617   KEYWORD(nobuiltin);
00618   KEYWORD(nocapture);
00619   KEYWORD(noduplicate);
00620   KEYWORD(noimplicitfloat);
00621   KEYWORD(noinline);
00622   KEYWORD(nonlazybind);
00623   KEYWORD(nonnull);
00624   KEYWORD(noredzone);
00625   KEYWORD(noreturn);
00626   KEYWORD(nounwind);
00627   KEYWORD(optnone);
00628   KEYWORD(optsize);
00629   KEYWORD(readnone);
00630   KEYWORD(readonly);
00631   KEYWORD(returned);
00632   KEYWORD(returns_twice);
00633   KEYWORD(signext);
00634   KEYWORD(sret);
00635   KEYWORD(ssp);
00636   KEYWORD(sspreq);
00637   KEYWORD(sspstrong);
00638   KEYWORD(sanitize_address);
00639   KEYWORD(sanitize_thread);
00640   KEYWORD(sanitize_memory);
00641   KEYWORD(uwtable);
00642   KEYWORD(zeroext);
00643 
00644   KEYWORD(type);
00645   KEYWORD(opaque);
00646 
00647   KEYWORD(comdat);
00648 
00649   // Comdat types
00650   KEYWORD(any);
00651   KEYWORD(exactmatch);
00652   KEYWORD(largest);
00653   KEYWORD(noduplicates);
00654   KEYWORD(samesize);
00655 
00656   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
00657   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
00658   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
00659   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
00660 
00661   KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
00662   KEYWORD(umin);
00663 
00664   KEYWORD(x);
00665   KEYWORD(blockaddress);
00666 
00667   // Use-list order directives.
00668   KEYWORD(uselistorder);
00669   KEYWORD(uselistorder_bb);
00670 
00671   KEYWORD(personality);
00672   KEYWORD(cleanup);
00673   KEYWORD(catch);
00674   KEYWORD(filter);
00675 #undef KEYWORD
00676 
00677   // Keywords for types.
00678 #define TYPEKEYWORD(STR, LLVMTY) \
00679   if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
00680     TyVal = LLVMTY; return lltok::Type; }
00681   TYPEKEYWORD("void",      Type::getVoidTy(Context));
00682   TYPEKEYWORD("half",      Type::getHalfTy(Context));
00683   TYPEKEYWORD("float",     Type::getFloatTy(Context));
00684   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
00685   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
00686   TYPEKEYWORD("fp128",     Type::getFP128Ty(Context));
00687   TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
00688   TYPEKEYWORD("label",     Type::getLabelTy(Context));
00689   TYPEKEYWORD("metadata",  Type::getMetadataTy(Context));
00690   TYPEKEYWORD("x86_mmx",   Type::getX86_MMXTy(Context));
00691 #undef TYPEKEYWORD
00692 
00693   // Keywords for instructions.
00694 #define INSTKEYWORD(STR, Enum) \
00695   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) { \
00696     UIntVal = Instruction::Enum; return lltok::kw_##STR; }
00697 
00698   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
00699   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
00700   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
00701   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
00702   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
00703   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
00704   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
00705   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
00706 
00707   INSTKEYWORD(phi,         PHI);
00708   INSTKEYWORD(call,        Call);
00709   INSTKEYWORD(trunc,       Trunc);
00710   INSTKEYWORD(zext,        ZExt);
00711   INSTKEYWORD(sext,        SExt);
00712   INSTKEYWORD(fptrunc,     FPTrunc);
00713   INSTKEYWORD(fpext,       FPExt);
00714   INSTKEYWORD(uitofp,      UIToFP);
00715   INSTKEYWORD(sitofp,      SIToFP);
00716   INSTKEYWORD(fptoui,      FPToUI);
00717   INSTKEYWORD(fptosi,      FPToSI);
00718   INSTKEYWORD(inttoptr,    IntToPtr);
00719   INSTKEYWORD(ptrtoint,    PtrToInt);
00720   INSTKEYWORD(bitcast,     BitCast);
00721   INSTKEYWORD(addrspacecast, AddrSpaceCast);
00722   INSTKEYWORD(select,      Select);
00723   INSTKEYWORD(va_arg,      VAArg);
00724   INSTKEYWORD(ret,         Ret);
00725   INSTKEYWORD(br,          Br);
00726   INSTKEYWORD(switch,      Switch);
00727   INSTKEYWORD(indirectbr,  IndirectBr);
00728   INSTKEYWORD(invoke,      Invoke);
00729   INSTKEYWORD(resume,      Resume);
00730   INSTKEYWORD(unreachable, Unreachable);
00731 
00732   INSTKEYWORD(alloca,      Alloca);
00733   INSTKEYWORD(load,        Load);
00734   INSTKEYWORD(store,       Store);
00735   INSTKEYWORD(cmpxchg,     AtomicCmpXchg);
00736   INSTKEYWORD(atomicrmw,   AtomicRMW);
00737   INSTKEYWORD(fence,       Fence);
00738   INSTKEYWORD(getelementptr, GetElementPtr);
00739 
00740   INSTKEYWORD(extractelement, ExtractElement);
00741   INSTKEYWORD(insertelement,  InsertElement);
00742   INSTKEYWORD(shufflevector,  ShuffleVector);
00743   INSTKEYWORD(extractvalue,   ExtractValue);
00744   INSTKEYWORD(insertvalue,    InsertValue);
00745   INSTKEYWORD(landingpad,     LandingPad);
00746 #undef INSTKEYWORD
00747 
00748   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
00749   // the CFE to avoid forcing it to deal with 64-bit numbers.
00750   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
00751       TokStart[1] == '0' && TokStart[2] == 'x' &&
00752       isxdigit(static_cast<unsigned char>(TokStart[3]))) {
00753     int len = CurPtr-TokStart-3;
00754     uint32_t bits = len * 4;
00755     APInt Tmp(bits, StringRef(TokStart+3, len), 16);
00756     uint32_t activeBits = Tmp.getActiveBits();
00757     if (activeBits > 0 && activeBits < bits)
00758       Tmp = Tmp.trunc(activeBits);
00759     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
00760     return lltok::APSInt;
00761   }
00762 
00763   // If this is "cc1234", return this as just "cc".
00764   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
00765     CurPtr = TokStart+2;
00766     return lltok::kw_cc;
00767   }
00768 
00769   // Finally, if this isn't known, return an error.
00770   CurPtr = TokStart+1;
00771   return lltok::Error;
00772 }
00773 
00774 
00775 /// Lex0x: Handle productions that start with 0x, knowing that it matches and
00776 /// that this is not a label:
00777 ///    HexFPConstant     0x[0-9A-Fa-f]+
00778 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
00779 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
00780 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
00781 ///    HexHalfConstant   0xH[0-9A-Fa-f]+
00782 lltok::Kind LLLexer::Lex0x() {
00783   CurPtr = TokStart + 2;
00784 
00785   char Kind;
00786   if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H') {
00787     Kind = *CurPtr++;
00788   } else {
00789     Kind = 'J';
00790   }
00791 
00792   if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
00793     // Bad token, return it as an error.
00794     CurPtr = TokStart+1;
00795     return lltok::Error;
00796   }
00797 
00798   while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
00799     ++CurPtr;
00800 
00801   if (Kind == 'J') {
00802     // HexFPConstant - Floating point constant represented in IEEE format as a
00803     // hexadecimal number for when exponential notation is not precise enough.
00804     // Half, Float, and double only.
00805     APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
00806     return lltok::APFloat;
00807   }
00808 
00809   uint64_t Pair[2];
00810   switch (Kind) {
00811   default: llvm_unreachable("Unknown kind!");
00812   case 'K':
00813     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
00814     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
00815     APFloatVal = APFloat(APFloat::x87DoubleExtended, APInt(80, Pair));
00816     return lltok::APFloat;
00817   case 'L':
00818     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
00819     HexToIntPair(TokStart+3, CurPtr, Pair);
00820     APFloatVal = APFloat(APFloat::IEEEquad, APInt(128, Pair));
00821     return lltok::APFloat;
00822   case 'M':
00823     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
00824     HexToIntPair(TokStart+3, CurPtr, Pair);
00825     APFloatVal = APFloat(APFloat::PPCDoubleDouble, APInt(128, Pair));
00826     return lltok::APFloat;
00827   case 'H':
00828     APFloatVal = APFloat(APFloat::IEEEhalf,
00829                          APInt(16,HexIntToVal(TokStart+3, CurPtr)));
00830     return lltok::APFloat;
00831   }
00832 }
00833 
00834 /// LexIdentifier: Handle several related productions:
00835 ///    Label             [-a-zA-Z$._0-9]+:
00836 ///    NInteger          -[0-9]+
00837 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
00838 ///    PInteger          [0-9]+
00839 ///    HexFPConstant     0x[0-9A-Fa-f]+
00840 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
00841 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
00842 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
00843 lltok::Kind LLLexer::LexDigitOrNegative() {
00844   // If the letter after the negative is not a number, this is probably a label.
00845   if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
00846       !isdigit(static_cast<unsigned char>(CurPtr[0]))) {
00847     // Okay, this is not a number after the -, it's probably a label.
00848     if (const char *End = isLabelTail(CurPtr)) {
00849       StrVal.assign(TokStart, End-1);
00850       CurPtr = End;
00851       return lltok::LabelStr;
00852     }
00853 
00854     return lltok::Error;
00855   }
00856 
00857   // At this point, it is either a label, int or fp constant.
00858 
00859   // Skip digits, we have at least one.
00860   for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
00861     /*empty*/;
00862 
00863   // Check to see if this really is a label afterall, e.g. "-1:".
00864   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
00865     if (const char *End = isLabelTail(CurPtr)) {
00866       StrVal.assign(TokStart, End-1);
00867       CurPtr = End;
00868       return lltok::LabelStr;
00869     }
00870   }
00871 
00872   // If the next character is a '.', then it is a fp value, otherwise its
00873   // integer.
00874   if (CurPtr[0] != '.') {
00875     if (TokStart[0] == '0' && TokStart[1] == 'x')
00876       return Lex0x();
00877     unsigned Len = CurPtr-TokStart;
00878     uint32_t numBits = ((Len * 64) / 19) + 2;
00879     APInt Tmp(numBits, StringRef(TokStart, Len), 10);
00880     if (TokStart[0] == '-') {
00881       uint32_t minBits = Tmp.getMinSignedBits();
00882       if (minBits > 0 && minBits < numBits)
00883         Tmp = Tmp.trunc(minBits);
00884       APSIntVal = APSInt(Tmp, false);
00885     } else {
00886       uint32_t activeBits = Tmp.getActiveBits();
00887       if (activeBits > 0 && activeBits < numBits)
00888         Tmp = Tmp.trunc(activeBits);
00889       APSIntVal = APSInt(Tmp, true);
00890     }
00891     return lltok::APSInt;
00892   }
00893 
00894   ++CurPtr;
00895 
00896   // Skip over [0-9]*([eE][-+]?[0-9]+)?
00897   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
00898 
00899   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
00900     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
00901         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
00902           isdigit(static_cast<unsigned char>(CurPtr[2])))) {
00903       CurPtr += 2;
00904       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
00905     }
00906   }
00907 
00908   APFloatVal = APFloat(std::atof(TokStart));
00909   return lltok::APFloat;
00910 }
00911 
00912 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
00913 lltok::Kind LLLexer::LexPositive() {
00914   // If the letter after the negative is a number, this is probably not a
00915   // label.
00916   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
00917     return lltok::Error;
00918 
00919   // Skip digits.
00920   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
00921     /*empty*/;
00922 
00923   // At this point, we need a '.'.
00924   if (CurPtr[0] != '.') {
00925     CurPtr = TokStart+1;
00926     return lltok::Error;
00927   }
00928 
00929   ++CurPtr;
00930 
00931   // Skip over [0-9]*([eE][-+]?[0-9]+)?
00932   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
00933 
00934   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
00935     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
00936         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
00937         isdigit(static_cast<unsigned char>(CurPtr[2])))) {
00938       CurPtr += 2;
00939       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
00940     }
00941   }
00942 
00943   APFloatVal = APFloat(std::atof(TokStart));
00944   return lltok::APFloat;
00945 }