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