MIR Serialization: Initial serialization of the machine memory operands.
[oota-llvm.git] / lib / CodeGen / MIRParser / MILexer.cpp
1 //===- MILexer.cpp - Machine instructions lexer implementation ----------===//
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 // This file implements the lexing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MILexer.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include <cctype>
19
20 using namespace llvm;
21
22 namespace {
23
24 /// This class provides a way to iterate and get characters from the source
25 /// string.
26 class Cursor {
27   const char *Ptr;
28   const char *End;
29
30 public:
31   Cursor(NoneType) : Ptr(nullptr), End(nullptr) {}
32
33   explicit Cursor(StringRef Str) {
34     Ptr = Str.data();
35     End = Ptr + Str.size();
36   }
37
38   bool isEOF() const { return Ptr == End; }
39
40   char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
41
42   void advance(unsigned I = 1) { Ptr += I; }
43
44   StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
45
46   StringRef upto(Cursor C) const {
47     assert(C.Ptr >= Ptr && C.Ptr <= End);
48     return StringRef(Ptr, C.Ptr - Ptr);
49   }
50
51   StringRef::iterator location() const { return Ptr; }
52
53   operator bool() const { return Ptr != nullptr; }
54 };
55
56 } // end anonymous namespace
57
58 /// Skip the leading whitespace characters and return the updated cursor.
59 static Cursor skipWhitespace(Cursor C) {
60   while (isspace(C.peek()))
61     C.advance();
62   return C;
63 }
64
65 /// Return true if the given character satisfies the following regular
66 /// expression: [-a-zA-Z$._0-9]
67 static bool isIdentifierChar(char C) {
68   return isalpha(C) || isdigit(C) || C == '_' || C == '-' || C == '.' ||
69          C == '$';
70 }
71
72 void MIToken::unescapeQuotedStringValue(std::string &Str) const {
73   assert(isStringValueQuoted() && "String value isn't quoted");
74   StringRef Value = Range.drop_front(StringOffset);
75   assert(Value.front() == '"' && Value.back() == '"');
76   Cursor C = Cursor(Value.substr(1, Value.size() - 2));
77
78   Str.clear();
79   Str.reserve(C.remaining().size());
80   while (!C.isEOF()) {
81     char Char = C.peek();
82     if (Char == '\\') {
83       if (C.peek(1) == '\\') {
84         // Two '\' become one
85         Str += '\\';
86         C.advance(2);
87         continue;
88       }
89       if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
90         Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
91         C.advance(3);
92         continue;
93       }
94     }
95     Str += Char;
96     C.advance();
97   }
98 }
99
100 /// Lex a string constant using the following regular expression: \"[^\"]*\"
101 static Cursor lexStringConstant(
102     Cursor C,
103     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
104   assert(C.peek() == '"');
105   for (C.advance(); C.peek() != '"'; C.advance()) {
106     if (C.isEOF()) {
107       ErrorCallback(
108           C.location(),
109           "end of machine instruction reached before the closing '\"'");
110       return None;
111     }
112   }
113   C.advance();
114   return C;
115 }
116
117 static Cursor lexName(
118     Cursor C, MIToken &Token, MIToken::TokenKind Type,
119     MIToken::TokenKind QuotedType, unsigned PrefixLength,
120     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
121   auto Range = C;
122   C.advance(PrefixLength);
123   if (C.peek() == '"') {
124     if (Cursor R = lexStringConstant(C, ErrorCallback)) {
125       Token = MIToken(QuotedType, Range.upto(R), PrefixLength);
126       return R;
127     }
128     Token = MIToken(MIToken::Error, Range.remaining());
129     return Range;
130   }
131   while (isIdentifierChar(C.peek()))
132     C.advance();
133   Token = MIToken(Type, Range.upto(C), PrefixLength);
134   return C;
135 }
136
137 static MIToken::TokenKind getIdentifierKind(StringRef Identifier) {
138   return StringSwitch<MIToken::TokenKind>(Identifier)
139       .Case("_", MIToken::underscore)
140       .Case("implicit", MIToken::kw_implicit)
141       .Case("implicit-def", MIToken::kw_implicit_define)
142       .Case("dead", MIToken::kw_dead)
143       .Case("killed", MIToken::kw_killed)
144       .Case("undef", MIToken::kw_undef)
145       .Case("frame-setup", MIToken::kw_frame_setup)
146       .Case("debug-location", MIToken::kw_debug_location)
147       .Case(".cfi_offset", MIToken::kw_cfi_offset)
148       .Case(".cfi_def_cfa_register", MIToken::kw_cfi_def_cfa_register)
149       .Case(".cfi_def_cfa_offset", MIToken::kw_cfi_def_cfa_offset)
150       .Case(".cfi_def_cfa", MIToken::kw_cfi_def_cfa)
151       .Case("blockaddress", MIToken::kw_blockaddress)
152       .Case("target-index", MIToken::kw_target_index)
153       .Case("half", MIToken::kw_half)
154       .Case("float", MIToken::kw_float)
155       .Case("double", MIToken::kw_double)
156       .Case("x86_fp80", MIToken::kw_x86_fp80)
157       .Case("fp128", MIToken::kw_fp128)
158       .Case("ppc_fp128", MIToken::kw_ppc_fp128)
159       .Default(MIToken::Identifier);
160 }
161
162 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
163   if (!isalpha(C.peek()) && C.peek() != '_' && C.peek() != '.')
164     return None;
165   auto Range = C;
166   while (isIdentifierChar(C.peek()))
167     C.advance();
168   auto Identifier = Range.upto(C);
169   Token = MIToken(getIdentifierKind(Identifier), Identifier);
170   return C;
171 }
172
173 static Cursor maybeLexMachineBasicBlock(
174     Cursor C, MIToken &Token,
175     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
176   if (!C.remaining().startswith("%bb."))
177     return None;
178   auto Range = C;
179   C.advance(4); // Skip '%bb.'
180   if (!isdigit(C.peek())) {
181     Token = MIToken(MIToken::Error, C.remaining());
182     ErrorCallback(C.location(), "expected a number after '%bb.'");
183     return C;
184   }
185   auto NumberRange = C;
186   while (isdigit(C.peek()))
187     C.advance();
188   StringRef Number = NumberRange.upto(C);
189   unsigned StringOffset = 4 + Number.size(); // Drop '%bb.<id>'
190   if (C.peek() == '.') {
191     C.advance(); // Skip '.'
192     ++StringOffset;
193     while (isIdentifierChar(C.peek()))
194       C.advance();
195   }
196   Token = MIToken(MIToken::MachineBasicBlock, Range.upto(C), APSInt(Number),
197                   StringOffset);
198   return C;
199 }
200
201 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
202                             MIToken::TokenKind Kind) {
203   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
204     return None;
205   auto Range = C;
206   C.advance(Rule.size());
207   auto NumberRange = C;
208   while (isdigit(C.peek()))
209     C.advance();
210   Token = MIToken(Kind, Range.upto(C), APSInt(NumberRange.upto(C)));
211   return C;
212 }
213
214 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
215                                    MIToken::TokenKind Kind) {
216   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
217     return None;
218   auto Range = C;
219   C.advance(Rule.size());
220   auto NumberRange = C;
221   while (isdigit(C.peek()))
222     C.advance();
223   StringRef Number = NumberRange.upto(C);
224   unsigned StringOffset = Rule.size() + Number.size();
225   if (C.peek() == '.') {
226     C.advance();
227     ++StringOffset;
228     while (isIdentifierChar(C.peek()))
229       C.advance();
230   }
231   Token = MIToken(Kind, Range.upto(C), APSInt(Number), StringOffset);
232   return C;
233 }
234
235 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
236   return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
237 }
238
239 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
240   return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
241 }
242
243 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
244   return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
245 }
246
247 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
248   return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
249 }
250
251 static Cursor maybeLexIRBlock(
252     Cursor C, MIToken &Token,
253     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
254   const StringRef Rule = "%ir-block.";
255   if (!C.remaining().startswith(Rule))
256     return None;
257   if (isdigit(C.peek(Rule.size())))
258     return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
259   return lexName(C, Token, MIToken::NamedIRBlock, MIToken::QuotedNamedIRBlock,
260                  Rule.size(), ErrorCallback);
261 }
262
263 static Cursor maybeLexIRValue(
264     Cursor C, MIToken &Token,
265     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
266   const StringRef Rule = "%ir.";
267   if (!C.remaining().startswith(Rule))
268     return None;
269   return lexName(C, Token, MIToken::NamedIRValue, MIToken::QuotedNamedIRValue,
270                  Rule.size(), ErrorCallback);
271 }
272
273 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
274   auto Range = C;
275   C.advance(); // Skip '%'
276   auto NumberRange = C;
277   while (isdigit(C.peek()))
278     C.advance();
279   Token = MIToken(MIToken::VirtualRegister, Range.upto(C),
280                   APSInt(NumberRange.upto(C)));
281   return C;
282 }
283
284 static Cursor maybeLexRegister(Cursor C, MIToken &Token) {
285   if (C.peek() != '%')
286     return None;
287   if (isdigit(C.peek(1)))
288     return lexVirtualRegister(C, Token);
289   auto Range = C;
290   C.advance(); // Skip '%'
291   while (isIdentifierChar(C.peek()))
292     C.advance();
293   Token = MIToken(MIToken::NamedRegister, Range.upto(C),
294                   /*StringOffset=*/1); // Drop the '%'
295   return C;
296 }
297
298 static Cursor maybeLexGlobalValue(
299     Cursor C, MIToken &Token,
300     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
301   if (C.peek() != '@')
302     return None;
303   if (!isdigit(C.peek(1)))
304     return lexName(C, Token, MIToken::NamedGlobalValue,
305                    MIToken::QuotedNamedGlobalValue, /*PrefixLength=*/1,
306                    ErrorCallback);
307   auto Range = C;
308   C.advance(1); // Skip the '@'
309   auto NumberRange = C;
310   while (isdigit(C.peek()))
311     C.advance();
312   Token =
313       MIToken(MIToken::GlobalValue, Range.upto(C), APSInt(NumberRange.upto(C)));
314   return C;
315 }
316
317 static Cursor maybeLexExternalSymbol(
318     Cursor C, MIToken &Token,
319     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
320   if (C.peek() != '$')
321     return None;
322   return lexName(C, Token, MIToken::ExternalSymbol,
323                  MIToken::QuotedExternalSymbol,
324                  /*PrefixLength=*/1, ErrorCallback);
325 }
326
327 static bool isValidHexFloatingPointPrefix(char C) {
328   return C == 'H' || C == 'K' || C == 'L' || C == 'M';
329 }
330
331 static Cursor maybeLexHexFloatingPointLiteral(Cursor C, MIToken &Token) {
332   if (C.peek() != '0' || C.peek(1) != 'x')
333     return None;
334   Cursor Range = C;
335   C.advance(2); // Skip '0x'
336   if (isValidHexFloatingPointPrefix(C.peek()))
337     C.advance();
338   while (isxdigit(C.peek()))
339     C.advance();
340   Token = MIToken(MIToken::FloatingPointLiteral, Range.upto(C));
341   return C;
342 }
343
344 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
345   C.advance();
346   // Skip over [0-9]*([eE][-+]?[0-9]+)?
347   while (isdigit(C.peek()))
348     C.advance();
349   if ((C.peek() == 'e' || C.peek() == 'E') &&
350       (isdigit(C.peek(1)) ||
351        ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
352     C.advance(2);
353     while (isdigit(C.peek()))
354       C.advance();
355   }
356   Token = MIToken(MIToken::FloatingPointLiteral, Range.upto(C));
357   return C;
358 }
359
360 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
361   if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
362     return None;
363   auto Range = C;
364   C.advance();
365   while (isdigit(C.peek()))
366     C.advance();
367   if (C.peek() == '.')
368     return lexFloatingPointLiteral(Range, C, Token);
369   StringRef StrVal = Range.upto(C);
370   Token = MIToken(MIToken::IntegerLiteral, StrVal, APSInt(StrVal));
371   return C;
372 }
373
374 static MIToken::TokenKind symbolToken(char C) {
375   switch (C) {
376   case ',':
377     return MIToken::comma;
378   case '=':
379     return MIToken::equal;
380   case ':':
381     return MIToken::colon;
382   case '!':
383     return MIToken::exclaim;
384   case '(':
385     return MIToken::lparen;
386   case ')':
387     return MIToken::rparen;
388   default:
389     return MIToken::Error;
390   }
391 }
392
393 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
394   MIToken::TokenKind Kind;
395   unsigned Length = 1;
396   if (C.peek() == ':' && C.peek(1) == ':') {
397     Kind = MIToken::coloncolon;
398     Length = 2;
399   } else
400     Kind = symbolToken(C.peek());
401   if (Kind == MIToken::Error)
402     return None;
403   auto Range = C;
404   C.advance(Length);
405   Token = MIToken(Kind, Range.upto(C));
406   return C;
407 }
408
409 StringRef llvm::lexMIToken(
410     StringRef Source, MIToken &Token,
411     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
412   auto C = skipWhitespace(Cursor(Source));
413   if (C.isEOF()) {
414     Token = MIToken(MIToken::Eof, C.remaining());
415     return C.remaining();
416   }
417
418   if (Cursor R = maybeLexIdentifier(C, Token))
419     return R.remaining();
420   if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
421     return R.remaining();
422   if (Cursor R = maybeLexJumpTableIndex(C, Token))
423     return R.remaining();
424   if (Cursor R = maybeLexStackObject(C, Token))
425     return R.remaining();
426   if (Cursor R = maybeLexFixedStackObject(C, Token))
427     return R.remaining();
428   if (Cursor R = maybeLexConstantPoolItem(C, Token))
429     return R.remaining();
430   if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
431     return R.remaining();
432   if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
433     return R.remaining();
434   if (Cursor R = maybeLexRegister(C, Token))
435     return R.remaining();
436   if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
437     return R.remaining();
438   if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
439     return R.remaining();
440   if (Cursor R = maybeLexHexFloatingPointLiteral(C, Token))
441     return R.remaining();
442   if (Cursor R = maybeLexNumericalLiteral(C, Token))
443     return R.remaining();
444   if (Cursor R = maybeLexSymbol(C, Token))
445     return R.remaining();
446
447   Token = MIToken(MIToken::Error, C.remaining());
448   ErrorCallback(C.location(),
449                 Twine("unexpected character '") + Twine(C.peek()) + "'");
450   return C.remaining();
451 }