1 //===- MILexer.cpp - Machine instructions lexer implementation ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the lexing of machine instructions.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
30 using ErrorCallbackType =
31 function_ref<void(StringRef::iterator Loc, const Twine &)>;
33 /// This class provides a way to iterate and get characters from the source
36 const char *Ptr = nullptr;
37 const char *End = nullptr;
42 explicit Cursor(StringRef Str) {
44 End = Ptr + Str.size();
47 bool isEOF() const { return Ptr == End; }
49 char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
51 void advance(unsigned I = 1) { Ptr += I; }
53 StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
55 StringRef upto(Cursor C) const {
56 assert(C.Ptr >= Ptr && C.Ptr <= End);
57 return StringRef(Ptr, C.Ptr - Ptr);
60 StringRef::iterator location() const { return Ptr; }
62 operator bool() const { return Ptr != nullptr; }
65 } // end anonymous namespace
67 MIToken &MIToken::reset(TokenKind Kind, StringRef Range) {
73 MIToken &MIToken::setStringValue(StringRef StrVal) {
78 MIToken &MIToken::setOwnedStringValue(std::string StrVal) {
79 StringValueStorage = std::move(StrVal);
80 StringValue = StringValueStorage;
84 MIToken &MIToken::setIntegerValue(APSInt IntVal) {
85 this->IntVal = std::move(IntVal);
89 /// Skip the leading whitespace characters and return the updated cursor.
90 static Cursor skipWhitespace(Cursor C) {
91 while (isblank(C.peek()))
96 static bool isNewlineChar(char C) { return C == '\n' || C == '\r'; }
98 /// Skip a line comment and return the updated cursor.
99 static Cursor skipComment(Cursor C) {
102 while (!isNewlineChar(C.peek()) && !C.isEOF())
107 /// Return true if the given character satisfies the following regular
108 /// expression: [-a-zA-Z$._0-9]
109 static bool isIdentifierChar(char C) {
110 return isalpha(C) || isdigit(C) || C == '_' || C == '-' || C == '.' ||
114 /// Unescapes the given string value.
116 /// Expects the string value to be quoted.
117 static std::string unescapeQuotedString(StringRef Value) {
118 assert(Value.front() == '"' && Value.back() == '"');
119 Cursor C = Cursor(Value.substr(1, Value.size() - 2));
122 Str.reserve(C.remaining().size());
124 char Char = C.peek();
126 if (C.peek(1) == '\\') {
127 // Two '\' become one
132 if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
133 Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
144 /// Lex a string constant using the following regular expression: \"[^\"]*\"
145 static Cursor lexStringConstant(Cursor C, ErrorCallbackType ErrorCallback) {
146 assert(C.peek() == '"');
147 for (C.advance(); C.peek() != '"'; C.advance()) {
148 if (C.isEOF() || isNewlineChar(C.peek())) {
151 "end of machine instruction reached before the closing '\"'");
159 static Cursor lexName(Cursor C, MIToken &Token, MIToken::TokenKind Type,
160 unsigned PrefixLength, ErrorCallbackType ErrorCallback) {
162 C.advance(PrefixLength);
163 if (C.peek() == '"') {
164 if (Cursor R = lexStringConstant(C, ErrorCallback)) {
165 StringRef String = Range.upto(R);
166 Token.reset(Type, String)
167 .setOwnedStringValue(
168 unescapeQuotedString(String.drop_front(PrefixLength)));
171 Token.reset(MIToken::Error, Range.remaining());
174 while (isIdentifierChar(C.peek()))
176 Token.reset(Type, Range.upto(C))
177 .setStringValue(Range.upto(C).drop_front(PrefixLength));
181 static MIToken::TokenKind getIdentifierKind(StringRef Identifier) {
182 return StringSwitch<MIToken::TokenKind>(Identifier)
183 .Case("_", MIToken::underscore)
184 .Case("implicit", MIToken::kw_implicit)
185 .Case("implicit-def", MIToken::kw_implicit_define)
186 .Case("def", MIToken::kw_def)
187 .Case("dead", MIToken::kw_dead)
188 .Case("killed", MIToken::kw_killed)
189 .Case("undef", MIToken::kw_undef)
190 .Case("internal", MIToken::kw_internal)
191 .Case("early-clobber", MIToken::kw_early_clobber)
192 .Case("debug-use", MIToken::kw_debug_use)
193 .Case("renamable", MIToken::kw_renamable)
194 .Case("tied-def", MIToken::kw_tied_def)
195 .Case("frame-setup", MIToken::kw_frame_setup)
196 .Case("frame-destroy", MIToken::kw_frame_destroy)
197 .Case("nnan", MIToken::kw_nnan)
198 .Case("ninf", MIToken::kw_ninf)
199 .Case("nsz", MIToken::kw_nsz)
200 .Case("arcp", MIToken::kw_arcp)
201 .Case("contract", MIToken::kw_contract)
202 .Case("afn", MIToken::kw_afn)
203 .Case("reassoc", MIToken::kw_reassoc)
204 .Case("nuw" , MIToken::kw_nuw)
205 .Case("nsw" , MIToken::kw_nsw)
206 .Case("exact" , MIToken::kw_exact)
207 .Case("fpexcept", MIToken::kw_fpexcept)
208 .Case("debug-location", MIToken::kw_debug_location)
209 .Case("same_value", MIToken::kw_cfi_same_value)
210 .Case("offset", MIToken::kw_cfi_offset)
211 .Case("rel_offset", MIToken::kw_cfi_rel_offset)
212 .Case("def_cfa_register", MIToken::kw_cfi_def_cfa_register)
213 .Case("def_cfa_offset", MIToken::kw_cfi_def_cfa_offset)
214 .Case("adjust_cfa_offset", MIToken::kw_cfi_adjust_cfa_offset)
215 .Case("escape", MIToken::kw_cfi_escape)
216 .Case("def_cfa", MIToken::kw_cfi_def_cfa)
217 .Case("remember_state", MIToken::kw_cfi_remember_state)
218 .Case("restore", MIToken::kw_cfi_restore)
219 .Case("restore_state", MIToken::kw_cfi_restore_state)
220 .Case("undefined", MIToken::kw_cfi_undefined)
221 .Case("register", MIToken::kw_cfi_register)
222 .Case("window_save", MIToken::kw_cfi_window_save)
223 .Case("negate_ra_sign_state", MIToken::kw_cfi_aarch64_negate_ra_sign_state)
224 .Case("blockaddress", MIToken::kw_blockaddress)
225 .Case("intrinsic", MIToken::kw_intrinsic)
226 .Case("target-index", MIToken::kw_target_index)
227 .Case("half", MIToken::kw_half)
228 .Case("float", MIToken::kw_float)
229 .Case("double", MIToken::kw_double)
230 .Case("x86_fp80", MIToken::kw_x86_fp80)
231 .Case("fp128", MIToken::kw_fp128)
232 .Case("ppc_fp128", MIToken::kw_ppc_fp128)
233 .Case("target-flags", MIToken::kw_target_flags)
234 .Case("volatile", MIToken::kw_volatile)
235 .Case("non-temporal", MIToken::kw_non_temporal)
236 .Case("dereferenceable", MIToken::kw_dereferenceable)
237 .Case("invariant", MIToken::kw_invariant)
238 .Case("align", MIToken::kw_align)
239 .Case("addrspace", MIToken::kw_addrspace)
240 .Case("stack", MIToken::kw_stack)
241 .Case("got", MIToken::kw_got)
242 .Case("jump-table", MIToken::kw_jump_table)
243 .Case("constant-pool", MIToken::kw_constant_pool)
244 .Case("call-entry", MIToken::kw_call_entry)
245 .Case("liveout", MIToken::kw_liveout)
246 .Case("address-taken", MIToken::kw_address_taken)
247 .Case("landing-pad", MIToken::kw_landing_pad)
248 .Case("liveins", MIToken::kw_liveins)
249 .Case("successors", MIToken::kw_successors)
250 .Case("floatpred", MIToken::kw_floatpred)
251 .Case("intpred", MIToken::kw_intpred)
252 .Case("pre-instr-symbol", MIToken::kw_pre_instr_symbol)
253 .Case("post-instr-symbol", MIToken::kw_post_instr_symbol)
254 .Case("unknown-size", MIToken::kw_unknown_size)
255 .Default(MIToken::Identifier);
258 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
259 if (!isalpha(C.peek()) && C.peek() != '_')
262 while (isIdentifierChar(C.peek()))
264 auto Identifier = Range.upto(C);
265 Token.reset(getIdentifierKind(Identifier), Identifier)
266 .setStringValue(Identifier);
270 static Cursor maybeLexMachineBasicBlock(Cursor C, MIToken &Token,
271 ErrorCallbackType ErrorCallback) {
272 bool IsReference = C.remaining().startswith("%bb.");
273 if (!IsReference && !C.remaining().startswith("bb."))
276 unsigned PrefixLength = IsReference ? 4 : 3;
277 C.advance(PrefixLength); // Skip '%bb.' or 'bb.'
278 if (!isdigit(C.peek())) {
279 Token.reset(MIToken::Error, C.remaining());
280 ErrorCallback(C.location(), "expected a number after '%bb.'");
283 auto NumberRange = C;
284 while (isdigit(C.peek()))
286 StringRef Number = NumberRange.upto(C);
287 unsigned StringOffset = PrefixLength + Number.size(); // Drop '%bb.<id>'
288 // TODO: The format bb.<id>.<irname> is supported only when it's not a
289 // reference. Once we deprecate the format where the irname shows up, we
290 // should only lex forward if it is a reference.
291 if (C.peek() == '.') {
292 C.advance(); // Skip '.'
294 while (isIdentifierChar(C.peek()))
297 Token.reset(IsReference ? MIToken::MachineBasicBlock
298 : MIToken::MachineBasicBlockLabel,
300 .setIntegerValue(APSInt(Number))
301 .setStringValue(Range.upto(C).drop_front(StringOffset));
305 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
306 MIToken::TokenKind Kind) {
307 if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
310 C.advance(Rule.size());
311 auto NumberRange = C;
312 while (isdigit(C.peek()))
314 Token.reset(Kind, Range.upto(C)).setIntegerValue(APSInt(NumberRange.upto(C)));
318 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
319 MIToken::TokenKind Kind) {
320 if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
323 C.advance(Rule.size());
324 auto NumberRange = C;
325 while (isdigit(C.peek()))
327 StringRef Number = NumberRange.upto(C);
328 unsigned StringOffset = Rule.size() + Number.size();
329 if (C.peek() == '.') {
332 while (isIdentifierChar(C.peek()))
335 Token.reset(Kind, Range.upto(C))
336 .setIntegerValue(APSInt(Number))
337 .setStringValue(Range.upto(C).drop_front(StringOffset));
341 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
342 return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
345 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
346 return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
349 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
350 return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
353 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
354 return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
357 static Cursor maybeLexSubRegisterIndex(Cursor C, MIToken &Token,
358 ErrorCallbackType ErrorCallback) {
359 const StringRef Rule = "%subreg.";
360 if (!C.remaining().startswith(Rule))
362 return lexName(C, Token, MIToken::SubRegisterIndex, Rule.size(),
366 static Cursor maybeLexIRBlock(Cursor C, MIToken &Token,
367 ErrorCallbackType ErrorCallback) {
368 const StringRef Rule = "%ir-block.";
369 if (!C.remaining().startswith(Rule))
371 if (isdigit(C.peek(Rule.size())))
372 return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
373 return lexName(C, Token, MIToken::NamedIRBlock, Rule.size(), ErrorCallback);
376 static Cursor maybeLexIRValue(Cursor C, MIToken &Token,
377 ErrorCallbackType ErrorCallback) {
378 const StringRef Rule = "%ir.";
379 if (!C.remaining().startswith(Rule))
381 if (isdigit(C.peek(Rule.size())))
382 return maybeLexIndex(C, Token, Rule, MIToken::IRValue);
383 return lexName(C, Token, MIToken::NamedIRValue, Rule.size(), ErrorCallback);
386 static Cursor maybeLexStringConstant(Cursor C, MIToken &Token,
387 ErrorCallbackType ErrorCallback) {
390 return lexName(C, Token, MIToken::StringConstant, /*PrefixLength=*/0,
394 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
396 C.advance(); // Skip '%'
397 auto NumberRange = C;
398 while (isdigit(C.peek()))
400 Token.reset(MIToken::VirtualRegister, Range.upto(C))
401 .setIntegerValue(APSInt(NumberRange.upto(C)));
405 /// Returns true for a character allowed in a register name.
406 static bool isRegisterChar(char C) {
407 return isIdentifierChar(C) && C != '.';
410 static Cursor lexNamedVirtualRegister(Cursor C, MIToken &Token) {
412 C.advance(); // Skip '%'
413 while (isRegisterChar(C.peek()))
415 Token.reset(MIToken::NamedVirtualRegister, Range.upto(C))
416 .setStringValue(Range.upto(C).drop_front(1)); // Drop the '%'
420 static Cursor maybeLexRegister(Cursor C, MIToken &Token,
421 ErrorCallbackType ErrorCallback) {
422 if (C.peek() != '%' && C.peek() != '$')
425 if (C.peek() == '%') {
426 if (isdigit(C.peek(1)))
427 return lexVirtualRegister(C, Token);
429 if (isRegisterChar(C.peek(1)))
430 return lexNamedVirtualRegister(C, Token);
435 assert(C.peek() == '$');
437 C.advance(); // Skip '$'
438 while (isRegisterChar(C.peek()))
440 Token.reset(MIToken::NamedRegister, Range.upto(C))
441 .setStringValue(Range.upto(C).drop_front(1)); // Drop the '$'
445 static Cursor maybeLexGlobalValue(Cursor C, MIToken &Token,
446 ErrorCallbackType ErrorCallback) {
449 if (!isdigit(C.peek(1)))
450 return lexName(C, Token, MIToken::NamedGlobalValue, /*PrefixLength=*/1,
453 C.advance(1); // Skip the '@'
454 auto NumberRange = C;
455 while (isdigit(C.peek()))
457 Token.reset(MIToken::GlobalValue, Range.upto(C))
458 .setIntegerValue(APSInt(NumberRange.upto(C)));
462 static Cursor maybeLexExternalSymbol(Cursor C, MIToken &Token,
463 ErrorCallbackType ErrorCallback) {
466 return lexName(C, Token, MIToken::ExternalSymbol, /*PrefixLength=*/1,
470 static Cursor maybeLexMCSymbol(Cursor C, MIToken &Token,
471 ErrorCallbackType ErrorCallback) {
472 const StringRef Rule = "<mcsymbol ";
473 if (!C.remaining().startswith(Rule))
476 C.advance(Rule.size());
478 // Try a simple unquoted name.
479 if (C.peek() != '"') {
480 while (isIdentifierChar(C.peek()))
482 StringRef String = Start.upto(C).drop_front(Rule.size());
483 if (C.peek() != '>') {
484 ErrorCallback(C.location(),
485 "expected the '<mcsymbol ...' to be closed by a '>'");
486 Token.reset(MIToken::Error, Start.remaining());
491 Token.reset(MIToken::MCSymbol, Start.upto(C)).setStringValue(String);
495 // Otherwise lex out a quoted name.
496 Cursor R = lexStringConstant(C, ErrorCallback);
498 ErrorCallback(C.location(),
499 "unable to parse quoted string from opening quote");
500 Token.reset(MIToken::Error, Start.remaining());
503 StringRef String = Start.upto(R).drop_front(Rule.size());
504 if (R.peek() != '>') {
505 ErrorCallback(R.location(),
506 "expected the '<mcsymbol ...' to be closed by a '>'");
507 Token.reset(MIToken::Error, Start.remaining());
512 Token.reset(MIToken::MCSymbol, Start.upto(R))
513 .setOwnedStringValue(unescapeQuotedString(String));
517 static bool isValidHexFloatingPointPrefix(char C) {
518 return C == 'H' || C == 'K' || C == 'L' || C == 'M';
521 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
523 // Skip over [0-9]*([eE][-+]?[0-9]+)?
524 while (isdigit(C.peek()))
526 if ((C.peek() == 'e' || C.peek() == 'E') &&
527 (isdigit(C.peek(1)) ||
528 ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
530 while (isdigit(C.peek()))
533 Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
537 static Cursor maybeLexHexadecimalLiteral(Cursor C, MIToken &Token) {
538 if (C.peek() != '0' || (C.peek(1) != 'x' && C.peek(1) != 'X'))
542 unsigned PrefLen = 2;
543 if (isValidHexFloatingPointPrefix(C.peek())) {
547 while (isxdigit(C.peek()))
549 StringRef StrVal = Range.upto(C);
550 if (StrVal.size() <= PrefLen)
553 Token.reset(MIToken::HexLiteral, Range.upto(C));
554 else // It must be 3, which means that there was a floating-point prefix.
555 Token.reset(MIToken::FloatingPointLiteral, Range.upto(C));
559 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
560 if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
564 while (isdigit(C.peek()))
567 return lexFloatingPointLiteral(Range, C, Token);
568 StringRef StrVal = Range.upto(C);
569 Token.reset(MIToken::IntegerLiteral, StrVal).setIntegerValue(APSInt(StrVal));
573 static MIToken::TokenKind getMetadataKeywordKind(StringRef Identifier) {
574 return StringSwitch<MIToken::TokenKind>(Identifier)
575 .Case("!tbaa", MIToken::md_tbaa)
576 .Case("!alias.scope", MIToken::md_alias_scope)
577 .Case("!noalias", MIToken::md_noalias)
578 .Case("!range", MIToken::md_range)
579 .Case("!DIExpression", MIToken::md_diexpr)
580 .Case("!DILocation", MIToken::md_dilocation)
581 .Default(MIToken::Error);
584 static Cursor maybeLexExlaim(Cursor C, MIToken &Token,
585 ErrorCallbackType ErrorCallback) {
590 if (isdigit(C.peek()) || !isIdentifierChar(C.peek())) {
591 Token.reset(MIToken::exclaim, Range.upto(C));
594 while (isIdentifierChar(C.peek()))
596 StringRef StrVal = Range.upto(C);
597 Token.reset(getMetadataKeywordKind(StrVal), StrVal);
599 ErrorCallback(Token.location(),
600 "use of unknown metadata keyword '" + StrVal + "'");
604 static MIToken::TokenKind symbolToken(char C) {
607 return MIToken::comma;
611 return MIToken::equal;
613 return MIToken::colon;
615 return MIToken::lparen;
617 return MIToken::rparen;
619 return MIToken::lbrace;
621 return MIToken::rbrace;
623 return MIToken::plus;
625 return MIToken::minus;
627 return MIToken::less;
629 return MIToken::greater;
631 return MIToken::Error;
635 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
636 MIToken::TokenKind Kind;
638 if (C.peek() == ':' && C.peek(1) == ':') {
639 Kind = MIToken::coloncolon;
642 Kind = symbolToken(C.peek());
643 if (Kind == MIToken::Error)
647 Token.reset(Kind, Range.upto(C));
651 static Cursor maybeLexNewline(Cursor C, MIToken &Token) {
652 if (!isNewlineChar(C.peek()))
656 Token.reset(MIToken::Newline, Range.upto(C));
660 static Cursor maybeLexEscapedIRValue(Cursor C, MIToken &Token,
661 ErrorCallbackType ErrorCallback) {
667 while (C.peek() != '`') {
668 if (C.isEOF() || isNewlineChar(C.peek())) {
671 "end of machine instruction reached before the closing '`'");
672 Token.reset(MIToken::Error, Range.remaining());
677 StringRef Value = StrRange.upto(C);
679 Token.reset(MIToken::QuotedIRValue, Range.upto(C)).setStringValue(Value);
683 StringRef llvm::lexMIToken(StringRef Source, MIToken &Token,
684 ErrorCallbackType ErrorCallback) {
685 auto C = skipComment(skipWhitespace(Cursor(Source)));
687 Token.reset(MIToken::Eof, C.remaining());
688 return C.remaining();
691 if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
692 return R.remaining();
693 if (Cursor R = maybeLexIdentifier(C, Token))
694 return R.remaining();
695 if (Cursor R = maybeLexJumpTableIndex(C, Token))
696 return R.remaining();
697 if (Cursor R = maybeLexStackObject(C, Token))
698 return R.remaining();
699 if (Cursor R = maybeLexFixedStackObject(C, Token))
700 return R.remaining();
701 if (Cursor R = maybeLexConstantPoolItem(C, Token))
702 return R.remaining();
703 if (Cursor R = maybeLexSubRegisterIndex(C, Token, ErrorCallback))
704 return R.remaining();
705 if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
706 return R.remaining();
707 if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
708 return R.remaining();
709 if (Cursor R = maybeLexRegister(C, Token, ErrorCallback))
710 return R.remaining();
711 if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
712 return R.remaining();
713 if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
714 return R.remaining();
715 if (Cursor R = maybeLexMCSymbol(C, Token, ErrorCallback))
716 return R.remaining();
717 if (Cursor R = maybeLexHexadecimalLiteral(C, Token))
718 return R.remaining();
719 if (Cursor R = maybeLexNumericalLiteral(C, Token))
720 return R.remaining();
721 if (Cursor R = maybeLexExlaim(C, Token, ErrorCallback))
722 return R.remaining();
723 if (Cursor R = maybeLexSymbol(C, Token))
724 return R.remaining();
725 if (Cursor R = maybeLexNewline(C, Token))
726 return R.remaining();
727 if (Cursor R = maybeLexEscapedIRValue(C, Token, ErrorCallback))
728 return R.remaining();
729 if (Cursor R = maybeLexStringConstant(C, Token, ErrorCallback))
730 return R.remaining();
732 Token.reset(MIToken::Error, C.remaining());
733 ErrorCallback(C.location(),
734 Twine("unexpected character '") + Twine(C.peek()) + "'");
735 return C.remaining();