AsmParser: Don't crash if a null byte is inside a quoted string
[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   case '\\': return lltok::backslash;
245   }
246 }
247
248 void LLLexer::SkipLineComment() {
249   while (1) {
250     if (CurPtr[0] == '\n' || CurPtr[0] == '\r' || getNextChar() == EOF)
251       return;
252   }
253 }
254
255 /// LexAt - Lex all tokens that start with an @ character:
256 ///   GlobalVar   @\"[^\"]*\"
257 ///   GlobalVar   @[-a-zA-Z$._][-a-zA-Z$._0-9]*
258 ///   GlobalVarID @[0-9]+
259 lltok::Kind LLLexer::LexAt() {
260   return LexVar(lltok::GlobalVar, lltok::GlobalID);
261 }
262
263 lltok::Kind LLLexer::LexDollar() {
264   if (const char *Ptr = isLabelTail(TokStart)) {
265     CurPtr = Ptr;
266     StrVal.assign(TokStart, CurPtr - 1);
267     return lltok::LabelStr;
268   }
269
270   // Handle DollarStringConstant: $\"[^\"]*\"
271   if (CurPtr[0] == '"') {
272     ++CurPtr;
273
274     while (1) {
275       int CurChar = getNextChar();
276
277       if (CurChar == EOF) {
278         Error("end of file in COMDAT variable name");
279         return lltok::Error;
280       }
281       if (CurChar == '"') {
282         StrVal.assign(TokStart + 2, CurPtr - 1);
283         UnEscapeLexed(StrVal);
284         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
285           Error("Null bytes are not allowed in names");
286           return lltok::Error;
287         }
288         return lltok::ComdatVar;
289       }
290     }
291   }
292
293   // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
294   if (ReadVarName())
295     return lltok::ComdatVar;
296
297   return lltok::Error;
298 }
299
300 /// ReadString - Read a string until the closing quote.
301 lltok::Kind LLLexer::ReadString(lltok::Kind kind) {
302   const char *Start = CurPtr;
303   while (1) {
304     int CurChar = getNextChar();
305
306     if (CurChar == EOF) {
307       Error("end of file in string constant");
308       return lltok::Error;
309     }
310     if (CurChar == '"') {
311       StrVal.assign(Start, CurPtr-1);
312       UnEscapeLexed(StrVal);
313       return kind;
314     }
315   }
316 }
317
318 /// ReadVarName - Read the rest of a token containing a variable name.
319 bool LLLexer::ReadVarName() {
320   const char *NameStart = CurPtr;
321   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
322       CurPtr[0] == '-' || CurPtr[0] == '$' ||
323       CurPtr[0] == '.' || CurPtr[0] == '_') {
324     ++CurPtr;
325     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
326            CurPtr[0] == '-' || CurPtr[0] == '$' ||
327            CurPtr[0] == '.' || CurPtr[0] == '_')
328       ++CurPtr;
329
330     StrVal.assign(NameStart, CurPtr);
331     return true;
332   }
333   return false;
334 }
335
336 lltok::Kind LLLexer::LexVar(lltok::Kind Var, lltok::Kind VarID) {
337   // Handle StringConstant: \"[^\"]*\"
338   if (CurPtr[0] == '"') {
339     ++CurPtr;
340
341     while (1) {
342       int CurChar = getNextChar();
343
344       if (CurChar == EOF) {
345         Error("end of file in global variable name");
346         return lltok::Error;
347       }
348       if (CurChar == '"') {
349         StrVal.assign(TokStart+2, CurPtr-1);
350         UnEscapeLexed(StrVal);
351         if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
352           Error("Null bytes are not allowed in names");
353           return lltok::Error;
354         }
355         return Var;
356       }
357     }
358   }
359
360   // Handle VarName: [-a-zA-Z$._][-a-zA-Z$._0-9]*
361   if (ReadVarName())
362     return Var;
363
364   // Handle VarID: [0-9]+
365   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
366     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
367       /*empty*/;
368
369     uint64_t Val = atoull(TokStart+1, CurPtr);
370     if ((unsigned)Val != Val)
371       Error("invalid value number (too large)!");
372     UIntVal = unsigned(Val);
373     return VarID;
374   }
375   return lltok::Error;
376 }
377
378 /// LexPercent - Lex all tokens that start with a % character:
379 ///   LocalVar   ::= %\"[^\"]*\"
380 ///   LocalVar   ::= %[-a-zA-Z$._][-a-zA-Z$._0-9]*
381 ///   LocalVarID ::= %[0-9]+
382 lltok::Kind LLLexer::LexPercent() {
383   return LexVar(lltok::LocalVar, lltok::LocalVarID);
384 }
385
386 /// LexQuote - Lex all tokens that start with a " character:
387 ///   QuoteLabel        "[^"]+":
388 ///   StringConstant    "[^"]*"
389 lltok::Kind LLLexer::LexQuote() {
390   lltok::Kind kind = ReadString(lltok::StringConstant);
391   if (kind == lltok::Error || kind == lltok::Eof)
392     return kind;
393
394   if (CurPtr[0] == ':') {
395     ++CurPtr;
396     kind = lltok::LabelStr;
397   }
398
399   return kind;
400 }
401
402 /// LexExclaim:
403 ///    !foo
404 ///    !
405 lltok::Kind LLLexer::LexExclaim() {
406   // Lex a metadata name as a MetadataVar.
407   if (isalpha(static_cast<unsigned char>(CurPtr[0])) ||
408       CurPtr[0] == '-' || CurPtr[0] == '$' ||
409       CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\') {
410     ++CurPtr;
411     while (isalnum(static_cast<unsigned char>(CurPtr[0])) ||
412            CurPtr[0] == '-' || CurPtr[0] == '$' ||
413            CurPtr[0] == '.' || CurPtr[0] == '_' || CurPtr[0] == '\\')
414       ++CurPtr;
415
416     StrVal.assign(TokStart+1, CurPtr);   // Skip !
417     UnEscapeLexed(StrVal);
418     return lltok::MetadataVar;
419   }
420   return lltok::exclaim;
421 }
422
423 /// LexHash - Lex all tokens that start with a # character:
424 ///    AttrGrpID ::= #[0-9]+
425 lltok::Kind LLLexer::LexHash() {
426   // Handle AttrGrpID: #[0-9]+
427   if (isdigit(static_cast<unsigned char>(CurPtr[0]))) {
428     for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
429       /*empty*/;
430
431     uint64_t Val = atoull(TokStart+1, CurPtr);
432     if ((unsigned)Val != Val)
433       Error("invalid value number (too large)!");
434     UIntVal = unsigned(Val);
435     return lltok::AttrGrpID;
436   }
437
438   return lltok::Error;
439 }
440
441 /// LexIdentifier: Handle several related productions:
442 ///    Label           [-a-zA-Z$._0-9]+:
443 ///    IntegerType     i[0-9]+
444 ///    Keyword         sdiv, float, ...
445 ///    HexIntConstant  [us]0x[0-9A-Fa-f]+
446 lltok::Kind LLLexer::LexIdentifier() {
447   const char *StartChar = CurPtr;
448   const char *IntEnd = CurPtr[-1] == 'i' ? nullptr : StartChar;
449   const char *KeywordEnd = nullptr;
450
451   for (; isLabelChar(*CurPtr); ++CurPtr) {
452     // If we decide this is an integer, remember the end of the sequence.
453     if (!IntEnd && !isdigit(static_cast<unsigned char>(*CurPtr)))
454       IntEnd = CurPtr;
455     if (!KeywordEnd && !isalnum(static_cast<unsigned char>(*CurPtr)) &&
456         *CurPtr != '_')
457       KeywordEnd = CurPtr;
458   }
459
460   // If we stopped due to a colon, this really is a label.
461   if (*CurPtr == ':') {
462     StrVal.assign(StartChar-1, CurPtr++);
463     return lltok::LabelStr;
464   }
465
466   // Otherwise, this wasn't a label.  If this was valid as an integer type,
467   // return it.
468   if (!IntEnd) IntEnd = CurPtr;
469   if (IntEnd != StartChar) {
470     CurPtr = IntEnd;
471     uint64_t NumBits = atoull(StartChar, CurPtr);
472     if (NumBits < IntegerType::MIN_INT_BITS ||
473         NumBits > IntegerType::MAX_INT_BITS) {
474       Error("bitwidth for integer type out of range!");
475       return lltok::Error;
476     }
477     TyVal = IntegerType::get(Context, NumBits);
478     return lltok::Type;
479   }
480
481   // Otherwise, this was a letter sequence.  See which keyword this is.
482   if (!KeywordEnd) KeywordEnd = CurPtr;
483   CurPtr = KeywordEnd;
484   --StartChar;
485   unsigned Len = CurPtr-StartChar;
486 #define KEYWORD(STR)                                                    \
487   do {                                                                  \
488     if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR)))  \
489       return lltok::kw_##STR;                                           \
490   } while (0)
491
492   KEYWORD(true);    KEYWORD(false);
493   KEYWORD(declare); KEYWORD(define);
494   KEYWORD(global);  KEYWORD(constant);
495
496   KEYWORD(private);
497   KEYWORD(internal);
498   KEYWORD(available_externally);
499   KEYWORD(linkonce);
500   KEYWORD(linkonce_odr);
501   KEYWORD(weak); // Use as a linkage, and a modifier for "cmpxchg".
502   KEYWORD(weak_odr);
503   KEYWORD(appending);
504   KEYWORD(dllimport);
505   KEYWORD(dllexport);
506   KEYWORD(common);
507   KEYWORD(default);
508   KEYWORD(hidden);
509   KEYWORD(protected);
510   KEYWORD(unnamed_addr);
511   KEYWORD(externally_initialized);
512   KEYWORD(extern_weak);
513   KEYWORD(external);
514   KEYWORD(thread_local);
515   KEYWORD(localdynamic);
516   KEYWORD(initialexec);
517   KEYWORD(localexec);
518   KEYWORD(zeroinitializer);
519   KEYWORD(undef);
520   KEYWORD(null);
521   KEYWORD(to);
522   KEYWORD(tail);
523   KEYWORD(musttail);
524   KEYWORD(target);
525   KEYWORD(triple);
526   KEYWORD(unwind);
527   KEYWORD(deplibs);             // FIXME: Remove in 4.0.
528   KEYWORD(datalayout);
529   KEYWORD(volatile);
530   KEYWORD(atomic);
531   KEYWORD(unordered);
532   KEYWORD(monotonic);
533   KEYWORD(acquire);
534   KEYWORD(release);
535   KEYWORD(acq_rel);
536   KEYWORD(seq_cst);
537   KEYWORD(singlethread);
538
539   KEYWORD(nnan);
540   KEYWORD(ninf);
541   KEYWORD(nsz);
542   KEYWORD(arcp);
543   KEYWORD(fast);
544   KEYWORD(nuw);
545   KEYWORD(nsw);
546   KEYWORD(exact);
547   KEYWORD(inbounds);
548   KEYWORD(align);
549   KEYWORD(addrspace);
550   KEYWORD(section);
551   KEYWORD(alias);
552   KEYWORD(module);
553   KEYWORD(asm);
554   KEYWORD(sideeffect);
555   KEYWORD(alignstack);
556   KEYWORD(inteldialect);
557   KEYWORD(gc);
558   KEYWORD(prefix);
559   KEYWORD(prologue);
560
561   KEYWORD(ccc);
562   KEYWORD(fastcc);
563   KEYWORD(coldcc);
564   KEYWORD(x86_stdcallcc);
565   KEYWORD(x86_fastcallcc);
566   KEYWORD(x86_thiscallcc);
567   KEYWORD(x86_vectorcallcc);
568   KEYWORD(arm_apcscc);
569   KEYWORD(arm_aapcscc);
570   KEYWORD(arm_aapcs_vfpcc);
571   KEYWORD(msp430_intrcc);
572   KEYWORD(ptx_kernel);
573   KEYWORD(ptx_device);
574   KEYWORD(spir_kernel);
575   KEYWORD(spir_func);
576   KEYWORD(intel_ocl_bicc);
577   KEYWORD(x86_64_sysvcc);
578   KEYWORD(x86_64_win64cc);
579   KEYWORD(webkit_jscc);
580   KEYWORD(anyregcc);
581   KEYWORD(preserve_mostcc);
582   KEYWORD(preserve_allcc);
583   KEYWORD(ghccc);
584
585   KEYWORD(cc);
586   KEYWORD(c);
587
588   KEYWORD(attributes);
589
590   KEYWORD(alwaysinline);
591   KEYWORD(builtin);
592   KEYWORD(byval);
593   KEYWORD(inalloca);
594   KEYWORD(cold);
595   KEYWORD(dereferenceable);
596   KEYWORD(inlinehint);
597   KEYWORD(inreg);
598   KEYWORD(jumptable);
599   KEYWORD(minsize);
600   KEYWORD(naked);
601   KEYWORD(nest);
602   KEYWORD(noalias);
603   KEYWORD(nobuiltin);
604   KEYWORD(nocapture);
605   KEYWORD(noduplicate);
606   KEYWORD(noimplicitfloat);
607   KEYWORD(noinline);
608   KEYWORD(nonlazybind);
609   KEYWORD(nonnull);
610   KEYWORD(noredzone);
611   KEYWORD(noreturn);
612   KEYWORD(nounwind);
613   KEYWORD(optnone);
614   KEYWORD(optsize);
615   KEYWORD(readnone);
616   KEYWORD(readonly);
617   KEYWORD(returned);
618   KEYWORD(returns_twice);
619   KEYWORD(signext);
620   KEYWORD(sret);
621   KEYWORD(ssp);
622   KEYWORD(sspreq);
623   KEYWORD(sspstrong);
624   KEYWORD(sanitize_address);
625   KEYWORD(sanitize_thread);
626   KEYWORD(sanitize_memory);
627   KEYWORD(uwtable);
628   KEYWORD(zeroext);
629
630   KEYWORD(type);
631   KEYWORD(opaque);
632
633   KEYWORD(comdat);
634
635   // Comdat types
636   KEYWORD(any);
637   KEYWORD(exactmatch);
638   KEYWORD(largest);
639   KEYWORD(noduplicates);
640   KEYWORD(samesize);
641
642   KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
643   KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
644   KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
645   KEYWORD(oge); KEYWORD(ord); KEYWORD(uno); KEYWORD(ueq); KEYWORD(une);
646
647   KEYWORD(xchg); KEYWORD(nand); KEYWORD(max); KEYWORD(min); KEYWORD(umax);
648   KEYWORD(umin);
649
650   KEYWORD(x);
651   KEYWORD(blockaddress);
652
653   // Use-list order directives.
654   KEYWORD(uselistorder);
655   KEYWORD(uselistorder_bb);
656
657   KEYWORD(personality);
658   KEYWORD(cleanup);
659   KEYWORD(catch);
660   KEYWORD(filter);
661 #undef KEYWORD
662
663   // Keywords for types.
664 #define TYPEKEYWORD(STR, LLVMTY) \
665   if (Len == strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
666     TyVal = LLVMTY; return lltok::Type; }
667   TYPEKEYWORD("void",      Type::getVoidTy(Context));
668   TYPEKEYWORD("half",      Type::getHalfTy(Context));
669   TYPEKEYWORD("float",     Type::getFloatTy(Context));
670   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
671   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
672   TYPEKEYWORD("fp128",     Type::getFP128Ty(Context));
673   TYPEKEYWORD("ppc_fp128", Type::getPPC_FP128Ty(Context));
674   TYPEKEYWORD("label",     Type::getLabelTy(Context));
675   TYPEKEYWORD("metadata",  Type::getMetadataTy(Context));
676   TYPEKEYWORD("x86_mmx",   Type::getX86_MMXTy(Context));
677 #undef TYPEKEYWORD
678
679   // Keywords for instructions.
680 #define INSTKEYWORD(STR, Enum) \
681   if (Len == strlen(#STR) && !memcmp(StartChar, #STR, strlen(#STR))) { \
682     UIntVal = Instruction::Enum; return lltok::kw_##STR; }
683
684   INSTKEYWORD(add,   Add);  INSTKEYWORD(fadd,   FAdd);
685   INSTKEYWORD(sub,   Sub);  INSTKEYWORD(fsub,   FSub);
686   INSTKEYWORD(mul,   Mul);  INSTKEYWORD(fmul,   FMul);
687   INSTKEYWORD(udiv,  UDiv); INSTKEYWORD(sdiv,  SDiv); INSTKEYWORD(fdiv,  FDiv);
688   INSTKEYWORD(urem,  URem); INSTKEYWORD(srem,  SRem); INSTKEYWORD(frem,  FRem);
689   INSTKEYWORD(shl,   Shl);  INSTKEYWORD(lshr,  LShr); INSTKEYWORD(ashr,  AShr);
690   INSTKEYWORD(and,   And);  INSTKEYWORD(or,    Or);   INSTKEYWORD(xor,   Xor);
691   INSTKEYWORD(icmp,  ICmp); INSTKEYWORD(fcmp,  FCmp);
692
693   INSTKEYWORD(phi,         PHI);
694   INSTKEYWORD(call,        Call);
695   INSTKEYWORD(trunc,       Trunc);
696   INSTKEYWORD(zext,        ZExt);
697   INSTKEYWORD(sext,        SExt);
698   INSTKEYWORD(fptrunc,     FPTrunc);
699   INSTKEYWORD(fpext,       FPExt);
700   INSTKEYWORD(uitofp,      UIToFP);
701   INSTKEYWORD(sitofp,      SIToFP);
702   INSTKEYWORD(fptoui,      FPToUI);
703   INSTKEYWORD(fptosi,      FPToSI);
704   INSTKEYWORD(inttoptr,    IntToPtr);
705   INSTKEYWORD(ptrtoint,    PtrToInt);
706   INSTKEYWORD(bitcast,     BitCast);
707   INSTKEYWORD(addrspacecast, AddrSpaceCast);
708   INSTKEYWORD(select,      Select);
709   INSTKEYWORD(va_arg,      VAArg);
710   INSTKEYWORD(ret,         Ret);
711   INSTKEYWORD(br,          Br);
712   INSTKEYWORD(switch,      Switch);
713   INSTKEYWORD(indirectbr,  IndirectBr);
714   INSTKEYWORD(invoke,      Invoke);
715   INSTKEYWORD(resume,      Resume);
716   INSTKEYWORD(unreachable, Unreachable);
717
718   INSTKEYWORD(alloca,      Alloca);
719   INSTKEYWORD(load,        Load);
720   INSTKEYWORD(store,       Store);
721   INSTKEYWORD(cmpxchg,     AtomicCmpXchg);
722   INSTKEYWORD(atomicrmw,   AtomicRMW);
723   INSTKEYWORD(fence,       Fence);
724   INSTKEYWORD(getelementptr, GetElementPtr);
725
726   INSTKEYWORD(extractelement, ExtractElement);
727   INSTKEYWORD(insertelement,  InsertElement);
728   INSTKEYWORD(shufflevector,  ShuffleVector);
729   INSTKEYWORD(extractvalue,   ExtractValue);
730   INSTKEYWORD(insertvalue,    InsertValue);
731   INSTKEYWORD(landingpad,     LandingPad);
732 #undef INSTKEYWORD
733
734   // Check for [us]0x[0-9A-Fa-f]+ which are Hexadecimal constant generated by
735   // the CFE to avoid forcing it to deal with 64-bit numbers.
736   if ((TokStart[0] == 'u' || TokStart[0] == 's') &&
737       TokStart[1] == '0' && TokStart[2] == 'x' &&
738       isxdigit(static_cast<unsigned char>(TokStart[3]))) {
739     int len = CurPtr-TokStart-3;
740     uint32_t bits = len * 4;
741     StringRef HexStr(TokStart + 3, len);
742     if (!std::all_of(HexStr.begin(), HexStr.end(), isxdigit)) {
743       // Bad token, return it as an error.
744       CurPtr = TokStart+3;
745       return lltok::Error;
746     }
747     APInt Tmp(bits, HexStr, 16);
748     uint32_t activeBits = Tmp.getActiveBits();
749     if (activeBits > 0 && activeBits < bits)
750       Tmp = Tmp.trunc(activeBits);
751     APSIntVal = APSInt(Tmp, TokStart[0] == 'u');
752     return lltok::APSInt;
753   }
754
755   // If this is "cc1234", return this as just "cc".
756   if (TokStart[0] == 'c' && TokStart[1] == 'c') {
757     CurPtr = TokStart+2;
758     return lltok::kw_cc;
759   }
760
761   // Finally, if this isn't known, return an error.
762   CurPtr = TokStart+1;
763   return lltok::Error;
764 }
765
766
767 /// Lex0x: Handle productions that start with 0x, knowing that it matches and
768 /// that this is not a label:
769 ///    HexFPConstant     0x[0-9A-Fa-f]+
770 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
771 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
772 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
773 ///    HexHalfConstant   0xH[0-9A-Fa-f]+
774 lltok::Kind LLLexer::Lex0x() {
775   CurPtr = TokStart + 2;
776
777   char Kind;
778   if ((CurPtr[0] >= 'K' && CurPtr[0] <= 'M') || CurPtr[0] == 'H') {
779     Kind = *CurPtr++;
780   } else {
781     Kind = 'J';
782   }
783
784   if (!isxdigit(static_cast<unsigned char>(CurPtr[0]))) {
785     // Bad token, return it as an error.
786     CurPtr = TokStart+1;
787     return lltok::Error;
788   }
789
790   while (isxdigit(static_cast<unsigned char>(CurPtr[0])))
791     ++CurPtr;
792
793   if (Kind == 'J') {
794     // HexFPConstant - Floating point constant represented in IEEE format as a
795     // hexadecimal number for when exponential notation is not precise enough.
796     // Half, Float, and double only.
797     APFloatVal = APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
798     return lltok::APFloat;
799   }
800
801   uint64_t Pair[2];
802   switch (Kind) {
803   default: llvm_unreachable("Unknown kind!");
804   case 'K':
805     // F80HexFPConstant - x87 long double in hexadecimal format (10 bytes)
806     FP80HexToIntPair(TokStart+3, CurPtr, Pair);
807     APFloatVal = APFloat(APFloat::x87DoubleExtended, APInt(80, Pair));
808     return lltok::APFloat;
809   case 'L':
810     // F128HexFPConstant - IEEE 128-bit in hexadecimal format (16 bytes)
811     HexToIntPair(TokStart+3, CurPtr, Pair);
812     APFloatVal = APFloat(APFloat::IEEEquad, APInt(128, Pair));
813     return lltok::APFloat;
814   case 'M':
815     // PPC128HexFPConstant - PowerPC 128-bit in hexadecimal format (16 bytes)
816     HexToIntPair(TokStart+3, CurPtr, Pair);
817     APFloatVal = APFloat(APFloat::PPCDoubleDouble, APInt(128, Pair));
818     return lltok::APFloat;
819   case 'H':
820     APFloatVal = APFloat(APFloat::IEEEhalf,
821                          APInt(16,HexIntToVal(TokStart+3, CurPtr)));
822     return lltok::APFloat;
823   }
824 }
825
826 /// LexIdentifier: Handle several related productions:
827 ///    Label             [-a-zA-Z$._0-9]+:
828 ///    NInteger          -[0-9]+
829 ///    FPConstant        [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
830 ///    PInteger          [0-9]+
831 ///    HexFPConstant     0x[0-9A-Fa-f]+
832 ///    HexFP80Constant   0xK[0-9A-Fa-f]+
833 ///    HexFP128Constant  0xL[0-9A-Fa-f]+
834 ///    HexPPC128Constant 0xM[0-9A-Fa-f]+
835 lltok::Kind LLLexer::LexDigitOrNegative() {
836   // If the letter after the negative is not a number, this is probably a label.
837   if (!isdigit(static_cast<unsigned char>(TokStart[0])) &&
838       !isdigit(static_cast<unsigned char>(CurPtr[0]))) {
839     // Okay, this is not a number after the -, it's probably a label.
840     if (const char *End = isLabelTail(CurPtr)) {
841       StrVal.assign(TokStart, End-1);
842       CurPtr = End;
843       return lltok::LabelStr;
844     }
845
846     return lltok::Error;
847   }
848
849   // At this point, it is either a label, int or fp constant.
850
851   // Skip digits, we have at least one.
852   for (; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
853     /*empty*/;
854
855   // Check to see if this really is a label afterall, e.g. "-1:".
856   if (isLabelChar(CurPtr[0]) || CurPtr[0] == ':') {
857     if (const char *End = isLabelTail(CurPtr)) {
858       StrVal.assign(TokStart, End-1);
859       CurPtr = End;
860       return lltok::LabelStr;
861     }
862   }
863
864   // If the next character is a '.', then it is a fp value, otherwise its
865   // integer.
866   if (CurPtr[0] != '.') {
867     if (TokStart[0] == '0' && TokStart[1] == 'x')
868       return Lex0x();
869     unsigned Len = CurPtr-TokStart;
870     uint32_t numBits = ((Len * 64) / 19) + 2;
871     APInt Tmp(numBits, StringRef(TokStart, Len), 10);
872     if (TokStart[0] == '-') {
873       uint32_t minBits = Tmp.getMinSignedBits();
874       if (minBits > 0 && minBits < numBits)
875         Tmp = Tmp.trunc(minBits);
876       APSIntVal = APSInt(Tmp, false);
877     } else {
878       uint32_t activeBits = Tmp.getActiveBits();
879       if (activeBits > 0 && activeBits < numBits)
880         Tmp = Tmp.trunc(activeBits);
881       APSIntVal = APSInt(Tmp, true);
882     }
883     return lltok::APSInt;
884   }
885
886   ++CurPtr;
887
888   // Skip over [0-9]*([eE][-+]?[0-9]+)?
889   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
890
891   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
892     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
893         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
894           isdigit(static_cast<unsigned char>(CurPtr[2])))) {
895       CurPtr += 2;
896       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
897     }
898   }
899
900   APFloatVal = APFloat(std::atof(TokStart));
901   return lltok::APFloat;
902 }
903
904 ///    FPConstant  [-+]?[0-9]+[.][0-9]*([eE][-+]?[0-9]+)?
905 lltok::Kind LLLexer::LexPositive() {
906   // If the letter after the negative is a number, this is probably not a
907   // label.
908   if (!isdigit(static_cast<unsigned char>(CurPtr[0])))
909     return lltok::Error;
910
911   // Skip digits.
912   for (++CurPtr; isdigit(static_cast<unsigned char>(CurPtr[0])); ++CurPtr)
913     /*empty*/;
914
915   // At this point, we need a '.'.
916   if (CurPtr[0] != '.') {
917     CurPtr = TokStart+1;
918     return lltok::Error;
919   }
920
921   ++CurPtr;
922
923   // Skip over [0-9]*([eE][-+]?[0-9]+)?
924   while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
925
926   if (CurPtr[0] == 'e' || CurPtr[0] == 'E') {
927     if (isdigit(static_cast<unsigned char>(CurPtr[1])) ||
928         ((CurPtr[1] == '-' || CurPtr[1] == '+') &&
929         isdigit(static_cast<unsigned char>(CurPtr[2])))) {
930       CurPtr += 2;
931       while (isdigit(static_cast<unsigned char>(CurPtr[0]))) ++CurPtr;
932     }
933   }
934
935   APFloatVal = APFloat(std::atof(TokStart));
936   return lltok::APFloat;
937 }