1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the parsing of machine instructions.
12 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/AsmParser/SlotMapping.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
34 struct StringValueUtility {
36 std::string UnescapedString;
38 StringValueUtility(const MIToken &Token) {
39 if (Token.isStringValueQuoted()) {
40 Token.unescapeQuotedStringValue(UnescapedString);
41 String = UnescapedString;
44 String = Token.stringValue();
47 operator StringRef() const { return String; }
50 /// A wrapper struct around the 'MachineOperand' struct that includes a source
52 struct MachineOperandWithLocation {
53 MachineOperand Operand;
54 StringRef::iterator Begin;
55 StringRef::iterator End;
57 MachineOperandWithLocation(const MachineOperand &Operand,
58 StringRef::iterator Begin, StringRef::iterator End)
59 : Operand(Operand), Begin(Begin), End(End) {}
66 StringRef Source, CurrentSource;
68 const PerFunctionMIParsingState &PFS;
69 /// Maps from indices to unnamed global values and metadata nodes.
70 const SlotMapping &IRSlots;
71 /// Maps from instruction names to op codes.
72 StringMap<unsigned> Names2InstrOpCodes;
73 /// Maps from register names to registers.
74 StringMap<unsigned> Names2Regs;
75 /// Maps from register mask names to register masks.
76 StringMap<const uint32_t *> Names2RegMasks;
77 /// Maps from subregister names to subregister indices.
78 StringMap<unsigned> Names2SubRegIndices;
81 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
82 StringRef Source, const PerFunctionMIParsingState &PFS,
83 const SlotMapping &IRSlots);
87 /// Report an error at the current location with the given message.
89 /// This function always return true.
90 bool error(const Twine &Msg);
92 /// Report an error at the given location with the given message.
94 /// This function always return true.
95 bool error(StringRef::iterator Loc, const Twine &Msg);
97 bool parse(MachineInstr *&MI);
98 bool parseMBB(MachineBasicBlock *&MBB);
99 bool parseNamedRegister(unsigned &Reg);
101 bool parseRegister(unsigned &Reg);
102 bool parseRegisterFlag(unsigned &Flags);
103 bool parseSubRegisterIndex(unsigned &SubReg);
104 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
105 bool parseImmediateOperand(MachineOperand &Dest);
106 bool parseMBBReference(MachineBasicBlock *&MBB);
107 bool parseMBBOperand(MachineOperand &Dest);
108 bool parseStackObjectOperand(MachineOperand &Dest);
109 bool parseFixedStackObjectOperand(MachineOperand &Dest);
110 bool parseGlobalAddressOperand(MachineOperand &Dest);
111 bool parseJumpTableIndexOperand(MachineOperand &Dest);
112 bool parseMachineOperand(MachineOperand &Dest);
115 /// Convert the integer literal in the current token into an unsigned integer.
117 /// Return true if an error occurred.
118 bool getUnsigned(unsigned &Result);
120 void initNames2InstrOpCodes();
122 /// Try to convert an instruction name to an opcode. Return true if the
123 /// instruction name is invalid.
124 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
126 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
128 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
129 const MCInstrDesc &MCID);
131 void initNames2Regs();
133 /// Try to convert a register name to a register number. Return true if the
134 /// register name is invalid.
135 bool getRegisterByName(StringRef RegName, unsigned &Reg);
137 void initNames2RegMasks();
139 /// Check if the given identifier is a name of a register mask.
141 /// Return null if the identifier isn't a register mask.
142 const uint32_t *getRegMask(StringRef Identifier);
144 void initNames2SubRegIndices();
146 /// Check if the given identifier is a name of a subregister index.
148 /// Return 0 if the name isn't a subregister index class.
149 unsigned getSubRegIndex(StringRef Name);
152 } // end anonymous namespace
154 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
155 StringRef Source, const PerFunctionMIParsingState &PFS,
156 const SlotMapping &IRSlots)
157 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
158 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
160 void MIParser::lex() {
161 CurrentSource = lexMIToken(
162 CurrentSource, Token,
163 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
166 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
168 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
169 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
170 Error = SMDiagnostic(
172 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
173 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
177 bool MIParser::parse(MachineInstr *&MI) {
180 // Parse any register operands before '='
181 // TODO: Allow parsing of multiple operands before '='
182 MachineOperand MO = MachineOperand::CreateImm(0);
183 SmallVector<MachineOperandWithLocation, 8> Operands;
184 if (Token.isRegister() || Token.isRegisterFlag()) {
185 auto Loc = Token.location();
186 if (parseRegisterOperand(MO, /*IsDef=*/true))
188 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
189 if (Token.isNot(MIToken::equal))
190 return error("expected '='");
194 unsigned OpCode, Flags = 0;
195 if (Token.isError() || parseInstruction(OpCode, Flags))
198 // TODO: Parse the bundle instruction flags and memory operands.
200 // Parse the remaining machine operands.
201 while (Token.isNot(MIToken::Eof)) {
202 auto Loc = Token.location();
203 if (parseMachineOperand(MO))
205 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
206 if (Token.is(MIToken::Eof))
208 if (Token.isNot(MIToken::comma))
209 return error("expected ',' before the next machine operand");
213 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
214 if (!MCID.isVariadic()) {
215 // FIXME: Move the implicit operand verification to the machine verifier.
216 if (verifyImplicitOperands(Operands, MCID))
220 // TODO: Check for extraneous machine operands.
221 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
223 for (const auto &Operand : Operands)
224 MI->addOperand(MF, Operand.Operand);
228 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
230 if (Token.isNot(MIToken::MachineBasicBlock))
231 return error("expected a machine basic block reference");
232 if (parseMBBReference(MBB))
235 if (Token.isNot(MIToken::Eof))
237 "expected end of string after the machine basic block reference");
241 bool MIParser::parseNamedRegister(unsigned &Reg) {
243 if (Token.isNot(MIToken::NamedRegister))
244 return error("expected a named register");
245 if (parseRegister(Reg))
248 if (Token.isNot(MIToken::Eof))
249 return error("expected end of string after the register reference");
253 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
254 assert(MO.isImplicit());
255 return MO.isDef() ? "implicit-def" : "implicit";
258 static std::string getRegisterName(const TargetRegisterInfo *TRI,
260 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
261 return StringRef(TRI->getName(Reg)).lower();
264 bool MIParser::verifyImplicitOperands(
265 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
267 // We can't verify call instructions as they can contain arbitrary implicit
268 // register and register mask operands.
271 // Gather all the expected implicit operands.
272 SmallVector<MachineOperand, 4> ImplicitOperands;
273 if (MCID.ImplicitDefs)
274 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
275 ImplicitOperands.push_back(
276 MachineOperand::CreateReg(*ImpDefs, true, true));
277 if (MCID.ImplicitUses)
278 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
279 ImplicitOperands.push_back(
280 MachineOperand::CreateReg(*ImpUses, false, true));
282 const auto *TRI = MF.getSubtarget().getRegisterInfo();
283 assert(TRI && "Expected target register info");
284 size_t I = ImplicitOperands.size(), J = Operands.size();
289 const auto &ImplicitOperand = ImplicitOperands[I];
290 const auto &Operand = Operands[J].Operand;
291 if (ImplicitOperand.isIdenticalTo(Operand))
293 if (Operand.isReg() && Operand.isImplicit()) {
294 return error(Operands[J].Begin,
295 Twine("expected an implicit register operand '") +
296 printImplicitRegisterFlag(ImplicitOperand) + " %" +
297 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
300 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
301 // insead of reporting an error at this location:
304 // report the error at the following location:
307 return error(J < Operands.size() ? Operands[J].End : Token.location(),
308 Twine("missing implicit register operand '") +
309 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
310 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
315 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
316 if (Token.is(MIToken::kw_frame_setup)) {
317 Flags |= MachineInstr::FrameSetup;
320 if (Token.isNot(MIToken::Identifier))
321 return error("expected a machine instruction");
322 StringRef InstrName = Token.stringValue();
323 if (parseInstrName(InstrName, OpCode))
324 return error(Twine("unknown machine instruction name '") + InstrName + "'");
329 bool MIParser::parseRegister(unsigned &Reg) {
330 switch (Token.kind()) {
331 case MIToken::underscore:
334 case MIToken::NamedRegister: {
335 StringRef Name = Token.stringValue();
336 if (getRegisterByName(Name, Reg))
337 return error(Twine("unknown register name '") + Name + "'");
340 case MIToken::VirtualRegister: {
344 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
345 if (RegInfo == PFS.VirtualRegisterSlots.end())
346 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
348 Reg = RegInfo->second;
351 // TODO: Parse other register kinds.
353 llvm_unreachable("The current token should be a register");
358 bool MIParser::parseRegisterFlag(unsigned &Flags) {
359 switch (Token.kind()) {
360 case MIToken::kw_implicit:
361 Flags |= RegState::Implicit;
363 case MIToken::kw_implicit_define:
364 Flags |= RegState::ImplicitDefine;
366 case MIToken::kw_dead:
367 Flags |= RegState::Dead;
369 case MIToken::kw_killed:
370 Flags |= RegState::Kill;
372 case MIToken::kw_undef:
373 Flags |= RegState::Undef;
375 // TODO: report an error when we specify the same flag more than once.
376 // TODO: parse the other register flags.
378 llvm_unreachable("The current token should be a register flag");
384 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
385 assert(Token.is(MIToken::colon));
387 if (Token.isNot(MIToken::Identifier))
388 return error("expected a subregister index after ':'");
389 auto Name = Token.stringValue();
390 SubReg = getSubRegIndex(Name);
392 return error(Twine("use of unknown subregister index '") + Name + "'");
397 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
399 unsigned Flags = IsDef ? RegState::Define : 0;
400 while (Token.isRegisterFlag()) {
401 if (parseRegisterFlag(Flags))
404 if (!Token.isRegister())
405 return error("expected a register after register flags");
406 if (parseRegister(Reg))
410 if (Token.is(MIToken::colon)) {
411 if (parseSubRegisterIndex(SubReg))
414 Dest = MachineOperand::CreateReg(
415 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
416 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
417 /*isEarlyClobber=*/false, SubReg);
421 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
422 assert(Token.is(MIToken::IntegerLiteral));
423 const APSInt &Int = Token.integerValue();
424 if (Int.getMinSignedBits() > 64)
425 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
426 llvm_unreachable("Can't parse large integer literals yet!");
427 Dest = MachineOperand::CreateImm(Int.getExtValue());
432 bool MIParser::getUnsigned(unsigned &Result) {
433 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
434 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
435 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
437 return error("expected 32-bit integer (too large)");
442 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
443 assert(Token.is(MIToken::MachineBasicBlock));
445 if (getUnsigned(Number))
447 auto MBBInfo = PFS.MBBSlots.find(Number);
448 if (MBBInfo == PFS.MBBSlots.end())
449 return error(Twine("use of undefined machine basic block #") +
451 MBB = MBBInfo->second;
452 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
453 return error(Twine("the name of machine basic block #") + Twine(Number) +
454 " isn't '" + Token.stringValue() + "'");
458 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
459 MachineBasicBlock *MBB;
460 if (parseMBBReference(MBB))
462 Dest = MachineOperand::CreateMBB(MBB);
467 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
468 assert(Token.is(MIToken::StackObject));
472 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
473 if (ObjectInfo == PFS.StackObjectSlots.end())
474 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
477 if (const auto *Alloca =
478 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
479 Name = Alloca->getName();
480 if (!Token.stringValue().empty() && Token.stringValue() != Name)
481 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
482 "' isn't '" + Token.stringValue() + "'");
484 Dest = MachineOperand::CreateFI(ObjectInfo->second);
488 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
489 assert(Token.is(MIToken::FixedStackObject));
493 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
494 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
495 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
498 Dest = MachineOperand::CreateFI(ObjectInfo->second);
502 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
503 switch (Token.kind()) {
504 case MIToken::NamedGlobalValue:
505 case MIToken::QuotedNamedGlobalValue: {
506 StringValueUtility Name(Token);
507 const Module *M = MF.getFunction()->getParent();
508 if (const auto *GV = M->getNamedValue(Name)) {
509 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
512 return error(Twine("use of undefined global value '@") +
513 Token.rawStringValue() + "'");
515 case MIToken::GlobalValue: {
517 if (getUnsigned(GVIdx))
519 if (GVIdx >= IRSlots.GlobalValues.size())
520 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
522 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
527 llvm_unreachable("The current token should be a global value");
529 // TODO: Parse offset and target flags.
534 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
535 assert(Token.is(MIToken::JumpTableIndex));
539 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
540 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
541 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
543 // TODO: Parse target flags.
544 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
548 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
549 switch (Token.kind()) {
550 case MIToken::kw_implicit:
551 case MIToken::kw_implicit_define:
552 case MIToken::kw_dead:
553 case MIToken::kw_killed:
554 case MIToken::kw_undef:
555 case MIToken::underscore:
556 case MIToken::NamedRegister:
557 case MIToken::VirtualRegister:
558 return parseRegisterOperand(Dest);
559 case MIToken::IntegerLiteral:
560 return parseImmediateOperand(Dest);
561 case MIToken::MachineBasicBlock:
562 return parseMBBOperand(Dest);
563 case MIToken::StackObject:
564 return parseStackObjectOperand(Dest);
565 case MIToken::FixedStackObject:
566 return parseFixedStackObjectOperand(Dest);
567 case MIToken::GlobalValue:
568 case MIToken::NamedGlobalValue:
569 case MIToken::QuotedNamedGlobalValue:
570 return parseGlobalAddressOperand(Dest);
571 case MIToken::JumpTableIndex:
572 return parseJumpTableIndexOperand(Dest);
575 case MIToken::Identifier:
576 if (const auto *RegMask = getRegMask(Token.stringValue())) {
577 Dest = MachineOperand::CreateRegMask(RegMask);
583 // TODO: parse the other machine operands.
584 return error("expected a machine operand");
589 void MIParser::initNames2InstrOpCodes() {
590 if (!Names2InstrOpCodes.empty())
592 const auto *TII = MF.getSubtarget().getInstrInfo();
593 assert(TII && "Expected target instruction info");
594 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
595 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
598 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
599 initNames2InstrOpCodes();
600 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
601 if (InstrInfo == Names2InstrOpCodes.end())
603 OpCode = InstrInfo->getValue();
607 void MIParser::initNames2Regs() {
608 if (!Names2Regs.empty())
610 // The '%noreg' register is the register 0.
611 Names2Regs.insert(std::make_pair("noreg", 0));
612 const auto *TRI = MF.getSubtarget().getRegisterInfo();
613 assert(TRI && "Expected target register info");
614 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
616 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
619 assert(WasInserted && "Expected registers to be unique case-insensitively");
623 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
625 auto RegInfo = Names2Regs.find(RegName);
626 if (RegInfo == Names2Regs.end())
628 Reg = RegInfo->getValue();
632 void MIParser::initNames2RegMasks() {
633 if (!Names2RegMasks.empty())
635 const auto *TRI = MF.getSubtarget().getRegisterInfo();
636 assert(TRI && "Expected target register info");
637 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
638 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
639 assert(RegMasks.size() == RegMaskNames.size());
640 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
641 Names2RegMasks.insert(
642 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
645 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
646 initNames2RegMasks();
647 auto RegMaskInfo = Names2RegMasks.find(Identifier);
648 if (RegMaskInfo == Names2RegMasks.end())
650 return RegMaskInfo->getValue();
653 void MIParser::initNames2SubRegIndices() {
654 if (!Names2SubRegIndices.empty())
656 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
657 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
658 Names2SubRegIndices.insert(
659 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
662 unsigned MIParser::getSubRegIndex(StringRef Name) {
663 initNames2SubRegIndices();
664 auto SubRegInfo = Names2SubRegIndices.find(Name);
665 if (SubRegInfo == Names2SubRegIndices.end())
667 return SubRegInfo->getValue();
670 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
671 MachineFunction &MF, StringRef Src,
672 const PerFunctionMIParsingState &PFS,
673 const SlotMapping &IRSlots, SMDiagnostic &Error) {
674 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
677 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
678 MachineFunction &MF, StringRef Src,
679 const PerFunctionMIParsingState &PFS,
680 const SlotMapping &IRSlots, SMDiagnostic &Error) {
681 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseMBB(MBB);
684 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
685 MachineFunction &MF, StringRef Src,
686 const PerFunctionMIParsingState &PFS,
687 const SlotMapping &IRSlots,
688 SMDiagnostic &Error) {
689 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseNamedRegister(Reg);