1 //===- MILexer.cpp - Machine instructions lexer implementation ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the lexing of machine instructions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MILexer.h"
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include <algorithm>
19 #include <cassert>
20 #include <cctype>
21 #include <string>
22 
23 using namespace llvm;
24 
25 namespace {
26 
27 using ErrorCallbackType =
28     function_ref<void(StringRef::iterator Loc, const Twine &)>;
29 
30 /// This class provides a way to iterate and get characters from the source
31 /// string.
32 class Cursor {
33   const char *Ptr = nullptr;
34   const char *End = nullptr;
35 
36 public:
37   Cursor(NoneType) {}
38 
39   explicit Cursor(StringRef Str) {
40     Ptr = Str.data();
41     End = Ptr + Str.size();
42   }
43 
44   bool isEOF() const { return Ptr == End; }
45 
46   char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
47 
48   void advance(unsigned I = 1) { Ptr += I; }
49 
50   StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
51 
52   StringRef upto(Cursor C) const {
53     assert(C.Ptr >= Ptr && C.Ptr <= End);
54     return StringRef(Ptr, C.Ptr - Ptr);
55   }
56 
57   StringRef::iterator location() const { return Ptr; }
58 
59   operator bool() const { return Ptr != nullptr; }
60 };
61 
62 } // end anonymous namespace
63 
64 MIToken &MIToken::reset(TokenKind Kind, StringRef Range) {
65   this->Kind = Kind;
66   this->Range = Range;
67   return *this;
68 }
69 
70 MIToken &MIToken::setStringValue(StringRef StrVal) {
71   StringValue = StrVal;
72   return *this;
73 }
74 
75 MIToken &MIToken::setOwnedStringValue(std::string StrVal) {
76   StringValueStorage = std::move(StrVal);
77   StringValue = StringValueStorage;
78   return *this;
79 }
80 
81 MIToken &MIToken::setIntegerValue(APSInt IntVal) {
82   this->IntVal = std::move(IntVal);
83   return *this;
84 }
85 
86 /// Skip the leading whitespace characters and return the updated cursor.
87 static Cursor skipWhitespace(Cursor C) {
88   while (isblank(C.peek()))
89     C.advance();
90   return C;
91 }
92 
93 static bool isNewlineChar(char C) { return C == '\n' || C == '\r'; }
94 
95 /// Skip a line comment and return the updated cursor.
96 static Cursor skipComment(Cursor C) {
97   if (C.peek() != ';')
98     return C;
99   while (!isNewlineChar(C.peek()) && !C.isEOF())
100     C.advance();
101   return C;
102 }
103 
104 /// Machine operands can have comments, enclosed between /* and */.
105 /// This eats up all tokens, including /* and */.
106 static Cursor skipMachineOperandComment(Cursor C) {
107   if (C.peek() != '/' || C.peek(1) != '*')
108     return C;
109 
110   while (C.peek() != '*' || C.peek(1) != '/')
111     C.advance();
112 
113   C.advance();
114   C.advance();
115   return C;
116 }
117 
118 /// Return true if the given character satisfies the following regular
119 /// expression: [-a-zA-Z$._0-9]
120 static bool isIdentifierChar(char C) {
121   return isalpha(C) || isdigit(C) || C == '_' || C == '-' || C == '.' ||
122          C == '$';
123 }
124 
125 /// Unescapes the given string value.
126 ///
127 /// Expects the string value to be quoted.
128 static std::string unescapeQuotedString(StringRef Value) {
129   assert(Value.front() == '"' && Value.back() == '"');
130   Cursor C = Cursor(Value.substr(1, Value.size() - 2));
131 
132   std::string Str;
133   Str.reserve(C.remaining().size());
134   while (!C.isEOF()) {
135     char Char = C.peek();
136     if (Char == '\\') {
137       if (C.peek(1) == '\\') {
138         // Two '\' become one
139         Str += '\\';
140         C.advance(2);
141         continue;
142       }
143       if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
144         Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
145         C.advance(3);
146         continue;
147       }
148     }
149     Str += Char;
150     C.advance();
151   }
152   return Str;
153 }
154 
155 /// Lex a string constant using the following regular expression: \"[^\"]*\"
156 static Cursor lexStringConstant(Cursor C, ErrorCallbackType ErrorCallback) {
157   assert(C.peek() == '"');
158   for (C.advance(); C.peek() != '"'; C.advance()) {
159     if (C.isEOF() || isNewlineChar(C.peek())) {
160       ErrorCallback(
161           C.location(),
162           "end of machine instruction reached before the closing '\"'");
163       return None;
164     }
165   }
166   C.advance();
167   return C;
168 }
169 
170 static Cursor lexName(Cursor C, MIToken &Token, MIToken::TokenKind Type,
171                       unsigned PrefixLength, ErrorCallbackType ErrorCallback) {
172   auto Range = C;
173   C.advance(PrefixLength);
174   if (C.peek() == '"') {
175     if (Cursor R = lexStringConstant(C, ErrorCallback)) {
176       StringRef String = Range.upto(R);
177       Token.reset(Type, String)
178           .setOwnedStringValue(
179               unescapeQuotedString(String.drop_front(PrefixLength)));
180       return R;
181     }
182     Token.reset(MIToken::Error, Range.remaining());
183     return Range;
184   }
185   while (isIdentifierChar(C.peek()))
186     C.advance();
187   Token.reset(Type, Range.upto(C))
188       .setStringValue(Range.upto(C).drop_front(PrefixLength));
189   return C;
190 }
191 
192 static MIToken::TokenKind getIdentifierKind(StringRef Identifier) {
193   return StringSwitch<MIToken::TokenKind>(Identifier)
194       .Case("_", MIToken::underscore)
195       .Case("implicit", MIToken::kw_implicit)
196       .Case("implicit-def", MIToken::kw_implicit_define)
197       .Case("def", MIToken::kw_def)
198       .Case("dead", MIToken::kw_dead)
199       .Case("killed", MIToken::kw_killed)
200       .Case("undef", MIToken::kw_undef)
201       .Case("internal", MIToken::kw_internal)
202       .Case("early-clobber", MIToken::kw_early_clobber)
203       .Case("debug-use", MIToken::kw_debug_use)
204       .Case("renamable", MIToken::kw_renamable)
205       .Case("tied-def", MIToken::kw_tied_def)
206       .Case("frame-setup", MIToken::kw_frame_setup)
207       .Case("frame-destroy", MIToken::kw_frame_destroy)
208       .Case("nnan", MIToken::kw_nnan)
209       .Case("ninf", MIToken::kw_ninf)
210       .Case("nsz", MIToken::kw_nsz)
211       .Case("arcp", MIToken::kw_arcp)
212       .Case("contract", MIToken::kw_contract)
213       .Case("afn", MIToken::kw_afn)
214       .Case("reassoc", MIToken::kw_reassoc)
215       .Case("nuw", MIToken::kw_nuw)
216       .Case("nsw", MIToken::kw_nsw)
217       .Case("exact", MIToken::kw_exact)
218       .Case("nofpexcept", MIToken::kw_nofpexcept)
219       .Case("debug-location", MIToken::kw_debug_location)
220       .Case("debug-instr-number", MIToken::kw_debug_instr_number)
221       .Case("same_value", MIToken::kw_cfi_same_value)
222       .Case("offset", MIToken::kw_cfi_offset)
223       .Case("rel_offset", MIToken::kw_cfi_rel_offset)
224       .Case("def_cfa_register", MIToken::kw_cfi_def_cfa_register)
225       .Case("def_cfa_offset", MIToken::kw_cfi_def_cfa_offset)
226       .Case("adjust_cfa_offset", MIToken::kw_cfi_adjust_cfa_offset)
227       .Case("escape", MIToken::kw_cfi_escape)
228       .Case("def_cfa", MIToken::kw_cfi_def_cfa)
229       .Case("llvm_def_aspace_cfa", MIToken::kw_cfi_llvm_def_aspace_cfa)
230       .Case("remember_state", MIToken::kw_cfi_remember_state)
231       .Case("restore", MIToken::kw_cfi_restore)
232       .Case("restore_state", MIToken::kw_cfi_restore_state)
233       .Case("undefined", MIToken::kw_cfi_undefined)
234       .Case("register", MIToken::kw_cfi_register)
235       .Case("window_save", MIToken::kw_cfi_window_save)
236       .Case("negate_ra_sign_state",
237             MIToken::kw_cfi_aarch64_negate_ra_sign_state)
238       .Case("blockaddress", MIToken::kw_blockaddress)
239       .Case("intrinsic", MIToken::kw_intrinsic)
240       .Case("target-index", MIToken::kw_target_index)
241       .Case("half", MIToken::kw_half)
242       .Case("float", MIToken::kw_float)
243       .Case("double", MIToken::kw_double)
244       .Case("x86_fp80", MIToken::kw_x86_fp80)
245       .Case("fp128", MIToken::kw_fp128)
246       .Case("ppc_fp128", MIToken::kw_ppc_fp128)
247       .Case("target-flags", MIToken::kw_target_flags)
248       .Case("volatile", MIToken::kw_volatile)
249       .Case("non-temporal", MIToken::kw_non_temporal)
250       .Case("dereferenceable", MIToken::kw_dereferenceable)
251       .Case("invariant", MIToken::kw_invariant)
252       .Case("align", MIToken::kw_align)
253       .Case("basealign", MIToken::kw_align)
254       .Case("addrspace", MIToken::kw_addrspace)
255       .Case("stack", MIToken::kw_stack)
256       .Case("got", MIToken::kw_got)
257       .Case("jump-table", MIToken::kw_jump_table)
258       .Case("constant-pool", MIToken::kw_constant_pool)
259       .Case("call-entry", MIToken::kw_call_entry)
260       .Case("custom", MIToken::kw_custom)
261       .Case("liveout", MIToken::kw_liveout)
262       .Case("address-taken", MIToken::kw_address_taken)
263       .Case("landing-pad", MIToken::kw_landing_pad)
264       .Case("ehfunclet-entry", MIToken::kw_ehfunclet_entry)
265       .Case("liveins", MIToken::kw_liveins)
266       .Case("successors", MIToken::kw_successors)
267       .Case("floatpred", MIToken::kw_floatpred)
268       .Case("intpred", MIToken::kw_intpred)
269       .Case("shufflemask", MIToken::kw_shufflemask)
270       .Case("pre-instr-symbol", MIToken::kw_pre_instr_symbol)
271       .Case("post-instr-symbol", MIToken::kw_post_instr_symbol)
272       .Case("heap-alloc-marker", MIToken::kw_heap_alloc_marker)
273       .Case("bbsections", MIToken::kw_bbsections)
274       .Case("unknown-size", MIToken::kw_unknown_size)
275       .Case("unknown-address", MIToken::kw_unknown_address)
276       .Default(MIToken::Identifier);
277 }
278 
279 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
280   if (!isalpha(C.peek()) && C.peek() != '_')
281     return None;
282   auto Range = C;
283   while (isIdentifierChar(C.peek()))
284     C.advance();
285   auto Identifier = Range.upto(C);
286   Token.reset(getIdentifierKind(Identifier), Identifier)
287       .setStringValue(Identifier);
288   return C;
289 }
290 
291 static Cursor maybeLexMachineBasicBlock(Cursor C, MIToken &Token,
292                                         ErrorCallbackType ErrorCallback) {
293   bool IsReference = C.remaining().startswith("%bb.");
294   if (!IsReference && !C.remaining().startswith("bb."))
295     return None;
296   auto Range = C;
297   unsigned PrefixLength = IsReference ? 4 : 3;
298   C.advance(PrefixLength); // Skip '%bb.' or 'bb.'
299   if (!isdigit(C.peek())) {
300     Token.reset(MIToken::Error, C.remaining());
301     ErrorCallback(C.location(), "expected a number after '%bb.'");
302     return C;
303   }
304   auto NumberRange = C;
305   while (isdigit(C.peek()))
306     C.advance();
307   StringRef Number = NumberRange.upto(C);
308   unsigned StringOffset = PrefixLength + Number.size(); // Drop '%bb.<id>'
309   // TODO: The format bb.<id>.<irname> is supported only when it's not a
310   // reference. Once we deprecate the format where the irname shows up, we
311   // should only lex forward if it is a reference.
312   if (C.peek() == '.') {
313     C.advance(); // Skip '.'
314     ++StringOffset;
315     while (isIdentifierChar(C.peek()))
316       C.advance();
317   }
318   Token.reset(IsReference ? MIToken::MachineBasicBlock
319                           : MIToken::MachineBasicBlockLabel,
320               Range.upto(C))
321       .setIntegerValue(APSInt(Number))
322       .setStringValue(Range.upto(C).drop_front(StringOffset));
323   return C;
324 }
325 
326 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
327                             MIToken::TokenKind Kind) {
328   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
329     return None;
330   auto Range = C;
331   C.advance(Rule.size());
332   auto NumberRange = C;
333   while (isdigit(C.peek()))
334     C.advance();
335   Token.reset(Kind, Range.upto(C)).setIntegerValue(APSInt(NumberRange.upto(C)));
336   return C;
337 }
338 
339 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
340                                    MIToken::TokenKind Kind) {
341   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
342     return None;
343   auto Range = C;
344   C.advance(Rule.size());
345   auto NumberRange = C;
346   while (isdigit(C.peek()))
347     C.advance();
348   StringRef Number = NumberRange.upto(C);
349   unsigned StringOffset = Rule.size() + Number.size();
350   if (C.peek() == '.') {
351     C.advance();
352     ++StringOffset;
353     while (isIdentifierChar(C.peek()))
354       C.advance();
355   }
356   Token.reset(Kind, Range.upto(C))
357       .setIntegerValue(APSInt(Number))
358       .setStringValue(Range.upto(C).drop_front(StringOffset));
359   return C;
360 }
361 
362 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
363   return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
364 }
365 
366 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
367   return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
368 }
369 
370 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
371   return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
372 }
373 
374 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
375   return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
376 }
377 
378 static Cursor maybeLexSubRegisterIndex(Cursor C, MIToken &Token,
379                                        ErrorCallbackType ErrorCallback) {
380   const StringRef Rule = "%subreg.";
381   if (!C.remaining().startswith(Rule))
382     return None;
383   return lexName(C, Token, MIToken::SubRegisterIndex, Rule.size(),
384                  ErrorCallback);
385 }
386 
387 static Cursor maybeLexIRBlock(Cursor C, MIToken &Token,
388                               ErrorCallbackType ErrorCallback) {
389   const StringRef Rule = "%ir-block.";
390   if (!C.remaining().startswith(Rule))
391     return None;
392   if (isdigit(C.peek(Rule.size())))
393     return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
394   return lexName(C, Token, MIToken::NamedIRBlock, Rule.size(), ErrorCallback);
395 }
396 
397 static Cursor maybeLexIRValue(Cursor C, MIToken &Token,
398                               ErrorCallbackType ErrorCallback) {
399   const StringRef Rule = "%ir.";
400   if (!C.remaining().startswith(Rule))
401     return None;
402   if (isdigit(C.peek(Rule.size())))
403     return maybeLexIndex(C, Token, Rule, MIToken::IRValue);
404   return lexName(C, Token, MIToken::NamedIRValue, Rule.size(), ErrorCallback);
405 }
406 
407 static Cursor maybeLexStringConstant(Cursor C, MIToken &Token,
408                                      ErrorCallbackType ErrorCallback) {
409   if (C.peek() != '"')
410     return None;
411   return lexName(C, Token, MIToken::StringConstant, /*PrefixLength=*/0,
412                  ErrorCallback);
413 }
414 
415 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
416   auto Range = C;
417   C.advance(); // Skip '%'
418   auto NumberRange = C;
419   while (isdigit(C.peek()))
420     C.advance();
421   Token.reset(MIToken::VirtualRegister, Range.upto(C))
422       .setIntegerValue(APSInt(NumberRange.upto(C)));
423   return C;
424 }
425 
426 /// Returns true for a character allowed in a register name.
427 static bool isRegisterChar(char C) {
428   return isIdentifierChar(C) && C != '.';
429 }
430 
431 static Cursor lexNamedVirtualRegister(Cursor C, MIToken &Token) {
432   Cursor Range = C;
433   C.advance(); // Skip '%'
434   while (isRegisterChar(C.peek()))
435     C.advance();
436   Token.reset(MIToken::NamedVirtualRegister, Range.upto(C))
437       .setStringValue(Range.upto(C).drop_front(1)); // Drop the '%'
438   return C;
439 }
440 
441 static Cursor maybeLexRegister(Cursor C, MIToken &Token,
442                                ErrorCallbackType ErrorCallback) {
443   if (C.peek() != '%' && C.peek() != '$')
444     return None;
445 
446   if (C.peek() == '%') {
447     if (isdigit(C.peek(1)))
448       return lexVirtualRegister(C, Token);
449 
450     if (isRegisterChar(C.peek(1)))
451       return lexNamedVirtualRegister(C, Token);
452 
453     return None;
454   }
455 
456   assert(C.peek() == '$');
457   auto Range = C;
458   C.advance(); // Skip '$'
459   while (isRegisterChar(C.peek()))
460     C.advance();
461   Token.reset(MIToken::NamedRegister, Range.upto(C))
462       .setStringValue(Range.upto(C).drop_front(1)); // Drop the '$'
463   return C;
464 }
465 
466 static Cursor maybeLexGlobalValue(Cursor C, MIToken &Token,
467                                   ErrorCallbackType ErrorCallback) {
468   if (C.peek() != '@')
469     return None;
470   if (!isdigit(C.peek(1)))
471     return lexName(C, Token, MIToken::NamedGlobalValue, /*PrefixLength=*/1,
472                    ErrorCallback);
473   auto Range = C;
474   C.advance(1); // Skip the '@'
475   auto NumberRange = C;
476   while (isdigit(C.peek()))
477     C.advance();
478   Token.reset(MIToken::GlobalValue, Range.upto(C))
479       .setIntegerValue(APSInt(NumberRange.upto(C)));
480   return C;
481 }
482 
483 static Cursor maybeLexExternalSymbol(Cursor C, MIToken &Token,
484                                      ErrorCallbackType ErrorCallback) {
485   if (C.peek() != '&')
486     return None;
487   return lexName(C, Token, MIToken::ExternalSymbol, /*PrefixLength=*/1,
488                  ErrorCallback);
489 }
490 
491 static Cursor maybeLexMCSymbol(Cursor C, MIToken &Token,
492                                ErrorCallbackType ErrorCallback) {
493   const StringRef Rule = "<mcsymbol ";
494   if (!C.remaining().startswith(Rule))
495     return None;
496   auto Start = C;
497   C.advance(Rule.size());
498 
499   // Try a simple unquoted name.
500   if (C.peek() != '"') {
501     while (isIdentifierChar(C.peek()))
502       C.advance();
503     StringRef String = Start.upto(C).drop_front(Rule.size());
504     if (C.peek() != '>') {
505       ErrorCallback(C.location(),
506                     "expected the '<mcsymbol ...' to be closed by a '>'");
507       Token.reset(MIToken::Error, Start.remaining());
508       return Start;
509     }
510     C.advance();
511 
512     Token.reset(MIToken::MCSymbol, Start.upto(C)).setStringValue(String);
513     return C;
514   }
515 
516   // Otherwise lex out a quoted name.
517   Cursor R = lexStringConstant(C, ErrorCallback);
518   if (!R) {
519     ErrorCallback(C.location(),
520                   "unable to parse quoted string from opening quote");
521     Token.reset(MIToken::Error, Start.remaining());
522     return Start;
523   }
524   StringRef String = Start.upto(R).drop_front(Rule.size());
525   if (R.peek() != '>') {
526     ErrorCallback(R.location(),
527                   "expected the '<mcsymbol ...' to be closed by a '>'");
528     Token.reset(MIToken::Error, Start.remaining());
529     return Start;
530   }
531   R.advance();
532 
533   Token.reset(MIToken::MCSymbol, Start.upto(R))
534       .setOwnedStringValue(unescapeQuotedString(String));
535   return R;
536 }
537 
538 static bool isValidHexFloatingPointPrefix(char C) {
539   return C == 'H' || C == 'K' || C == 'L' || C == 'M' || C == 'R';
540 }
541 
542 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
543   C.advance();
544   // Skip over [0-9]*([eE][-+]?[0-9]+)?
545   while (isdigit(C.peek()))
546     C.advance();
547   if ((C.peek() == 'e' || C.peek() == 'E') &&
548       (isdigit(C.peek(1)) ||
549        ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
550     C.advance(2);
551     while (isdigit(C.peek()))
552       C.advance();
553   }
554   Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
555   return C;
556 }
557 
558 static Cursor maybeLexHexadecimalLiteral(Cursor C, MIToken &Token) {
559   if (C.peek() != '0' || (C.peek(1) != 'x' && C.peek(1) != 'X'))
560     return None;
561   Cursor Range = C;
562   C.advance(2);
563   unsigned PrefLen = 2;
564   if (isValidHexFloatingPointPrefix(C.peek())) {
565     C.advance();
566     PrefLen++;
567   }
568   while (isxdigit(C.peek()))
569     C.advance();
570   StringRef StrVal = Range.upto(C);
571   if (StrVal.size() <= PrefLen)
572     return None;
573   if (PrefLen == 2)
574     Token.reset(MIToken::HexLiteral, Range.upto(C));
575   else // It must be 3, which means that there was a floating-point prefix.
576     Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
577   return C;
578 }
579 
580 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
581   if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
582     return None;
583   auto Range = C;
584   C.advance();
585   while (isdigit(C.peek()))
586     C.advance();
587   if (C.peek() == '.')
588     return lexFloatingPointLiteral(Range, C, Token);
589   StringRef StrVal = Range.upto(C);
590   Token.reset(MIToken::IntegerLiteral, StrVal).setIntegerValue(APSInt(StrVal));
591   return C;
592 }
593 
594 static MIToken::TokenKind getMetadataKeywordKind(StringRef Identifier) {
595   return StringSwitch<MIToken::TokenKind>(Identifier)
596       .Case("!tbaa", MIToken::md_tbaa)
597       .Case("!alias.scope", MIToken::md_alias_scope)
598       .Case("!noalias", MIToken::md_noalias)
599       .Case("!range", MIToken::md_range)
600       .Case("!DIExpression", MIToken::md_diexpr)
601       .Case("!DILocation", MIToken::md_dilocation)
602       .Default(MIToken::Error);
603 }
604 
605 static Cursor maybeLexExclaim(Cursor C, MIToken &Token,
606                               ErrorCallbackType ErrorCallback) {
607   if (C.peek() != '!')
608     return None;
609   auto Range = C;
610   C.advance(1);
611   if (isdigit(C.peek()) || !isIdentifierChar(C.peek())) {
612     Token.reset(MIToken::exclaim, Range.upto(C));
613     return C;
614   }
615   while (isIdentifierChar(C.peek()))
616     C.advance();
617   StringRef StrVal = Range.upto(C);
618   Token.reset(getMetadataKeywordKind(StrVal), StrVal);
619   if (Token.isError())
620     ErrorCallback(Token.location(),
621                   "use of unknown metadata keyword '" + StrVal + "'");
622   return C;
623 }
624 
625 static MIToken::TokenKind symbolToken(char C) {
626   switch (C) {
627   case ',':
628     return MIToken::comma;
629   case '.':
630     return MIToken::dot;
631   case '=':
632     return MIToken::equal;
633   case ':':
634     return MIToken::colon;
635   case '(':
636     return MIToken::lparen;
637   case ')':
638     return MIToken::rparen;
639   case '{':
640     return MIToken::lbrace;
641   case '}':
642     return MIToken::rbrace;
643   case '+':
644     return MIToken::plus;
645   case '-':
646     return MIToken::minus;
647   case '<':
648     return MIToken::less;
649   case '>':
650     return MIToken::greater;
651   default:
652     return MIToken::Error;
653   }
654 }
655 
656 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
657   MIToken::TokenKind Kind;
658   unsigned Length = 1;
659   if (C.peek() == ':' && C.peek(1) == ':') {
660     Kind = MIToken::coloncolon;
661     Length = 2;
662   } else
663     Kind = symbolToken(C.peek());
664   if (Kind == MIToken::Error)
665     return None;
666   auto Range = C;
667   C.advance(Length);
668   Token.reset(Kind, Range.upto(C));
669   return C;
670 }
671 
672 static Cursor maybeLexNewline(Cursor C, MIToken &Token) {
673   if (!isNewlineChar(C.peek()))
674     return None;
675   auto Range = C;
676   C.advance();
677   Token.reset(MIToken::Newline, Range.upto(C));
678   return C;
679 }
680 
681 static Cursor maybeLexEscapedIRValue(Cursor C, MIToken &Token,
682                                      ErrorCallbackType ErrorCallback) {
683   if (C.peek() != '`')
684     return None;
685   auto Range = C;
686   C.advance();
687   auto StrRange = C;
688   while (C.peek() != '`') {
689     if (C.isEOF() || isNewlineChar(C.peek())) {
690       ErrorCallback(
691           C.location(),
692           "end of machine instruction reached before the closing '`'");
693       Token.reset(MIToken::Error, Range.remaining());
694       return C;
695     }
696     C.advance();
697   }
698   StringRef Value = StrRange.upto(C);
699   C.advance();
700   Token.reset(MIToken::QuotedIRValue, Range.upto(C)).setStringValue(Value);
701   return C;
702 }
703 
704 StringRef llvm::lexMIToken(StringRef Source, MIToken &Token,
705                            ErrorCallbackType ErrorCallback) {
706   auto C = skipComment(skipWhitespace(Cursor(Source)));
707   if (C.isEOF()) {
708     Token.reset(MIToken::Eof, C.remaining());
709     return C.remaining();
710   }
711 
712   C = skipMachineOperandComment(C);
713 
714   if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
715     return R.remaining();
716   if (Cursor R = maybeLexIdentifier(C, Token))
717     return R.remaining();
718   if (Cursor R = maybeLexJumpTableIndex(C, Token))
719     return R.remaining();
720   if (Cursor R = maybeLexStackObject(C, Token))
721     return R.remaining();
722   if (Cursor R = maybeLexFixedStackObject(C, Token))
723     return R.remaining();
724   if (Cursor R = maybeLexConstantPoolItem(C, Token))
725     return R.remaining();
726   if (Cursor R = maybeLexSubRegisterIndex(C, Token, ErrorCallback))
727     return R.remaining();
728   if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
729     return R.remaining();
730   if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
731     return R.remaining();
732   if (Cursor R = maybeLexRegister(C, Token, ErrorCallback))
733     return R.remaining();
734   if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
735     return R.remaining();
736   if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
737     return R.remaining();
738   if (Cursor R = maybeLexMCSymbol(C, Token, ErrorCallback))
739     return R.remaining();
740   if (Cursor R = maybeLexHexadecimalLiteral(C, Token))
741     return R.remaining();
742   if (Cursor R = maybeLexNumericalLiteral(C, Token))
743     return R.remaining();
744   if (Cursor R = maybeLexExclaim(C, Token, ErrorCallback))
745     return R.remaining();
746   if (Cursor R = maybeLexSymbol(C, Token))
747     return R.remaining();
748   if (Cursor R = maybeLexNewline(C, Token))
749     return R.remaining();
750   if (Cursor R = maybeLexEscapedIRValue(C, Token, ErrorCallback))
751     return R.remaining();
752   if (Cursor R = maybeLexStringConstant(C, Token, ErrorCallback))
753     return R.remaining();
754 
755   Token.reset(MIToken::Error, C.remaining());
756   ErrorCallback(C.location(),
757                 Twine("unexpected character '") + Twine(C.peek()) + "'");
758   return C.remaining();
759 }
760