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 /// A wrapper struct around the 'MachineOperand' struct that includes a source
36 struct MachineOperandWithLocation {
37 MachineOperand Operand;
38 StringRef::iterator Begin;
39 StringRef::iterator End;
41 MachineOperandWithLocation(const MachineOperand &Operand,
42 StringRef::iterator Begin, StringRef::iterator End)
43 : Operand(Operand), Begin(Begin), End(End) {}
50 StringRef Source, CurrentSource;
52 const PerFunctionMIParsingState &PFS;
53 /// Maps from indices to unnamed global values and metadata nodes.
54 const SlotMapping &IRSlots;
55 /// Maps from instruction names to op codes.
56 StringMap<unsigned> Names2InstrOpCodes;
57 /// Maps from register names to registers.
58 StringMap<unsigned> Names2Regs;
59 /// Maps from register mask names to register masks.
60 StringMap<const uint32_t *> Names2RegMasks;
61 /// Maps from subregister names to subregister indices.
62 StringMap<unsigned> Names2SubRegIndices;
65 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
66 StringRef Source, const PerFunctionMIParsingState &PFS,
67 const SlotMapping &IRSlots);
71 /// Report an error at the current location with the given message.
73 /// This function always return true.
74 bool error(const Twine &Msg);
76 /// Report an error at the given location with the given message.
78 /// This function always return true.
79 bool error(StringRef::iterator Loc, const Twine &Msg);
81 bool parse(MachineInstr *&MI);
82 bool parseMBB(MachineBasicBlock *&MBB);
83 bool parseNamedRegister(unsigned &Reg);
85 bool parseRegister(unsigned &Reg);
86 bool parseRegisterFlag(unsigned &Flags);
87 bool parseSubRegisterIndex(unsigned &SubReg);
88 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
89 bool parseImmediateOperand(MachineOperand &Dest);
90 bool parseMBBReference(MachineBasicBlock *&MBB);
91 bool parseMBBOperand(MachineOperand &Dest);
92 bool parseStackObjectOperand(MachineOperand &Dest);
93 bool parseFixedStackObjectOperand(MachineOperand &Dest);
94 bool parseGlobalAddressOperand(MachineOperand &Dest);
95 bool parseJumpTableIndexOperand(MachineOperand &Dest);
96 bool parseMachineOperand(MachineOperand &Dest);
99 /// Convert the integer literal in the current token into an unsigned integer.
101 /// Return true if an error occurred.
102 bool getUnsigned(unsigned &Result);
104 void initNames2InstrOpCodes();
106 /// Try to convert an instruction name to an opcode. Return true if the
107 /// instruction name is invalid.
108 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
110 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
112 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
113 const MCInstrDesc &MCID);
115 void initNames2Regs();
117 /// Try to convert a register name to a register number. Return true if the
118 /// register name is invalid.
119 bool getRegisterByName(StringRef RegName, unsigned &Reg);
121 void initNames2RegMasks();
123 /// Check if the given identifier is a name of a register mask.
125 /// Return null if the identifier isn't a register mask.
126 const uint32_t *getRegMask(StringRef Identifier);
128 void initNames2SubRegIndices();
130 /// Check if the given identifier is a name of a subregister index.
132 /// Return 0 if the name isn't a subregister index class.
133 unsigned getSubRegIndex(StringRef Name);
136 } // end anonymous namespace
138 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
139 StringRef Source, const PerFunctionMIParsingState &PFS,
140 const SlotMapping &IRSlots)
141 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
142 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
144 void MIParser::lex() {
145 CurrentSource = lexMIToken(
146 CurrentSource, Token,
147 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
150 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
152 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
153 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
154 Error = SMDiagnostic(
156 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
157 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
161 bool MIParser::parse(MachineInstr *&MI) {
164 // Parse any register operands before '='
165 // TODO: Allow parsing of multiple operands before '='
166 MachineOperand MO = MachineOperand::CreateImm(0);
167 SmallVector<MachineOperandWithLocation, 8> Operands;
168 if (Token.isRegister() || Token.isRegisterFlag()) {
169 auto Loc = Token.location();
170 if (parseRegisterOperand(MO, /*IsDef=*/true))
172 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
173 if (Token.isNot(MIToken::equal))
174 return error("expected '='");
178 unsigned OpCode, Flags = 0;
179 if (Token.isError() || parseInstruction(OpCode, Flags))
182 // TODO: Parse the bundle instruction flags and memory operands.
184 // Parse the remaining machine operands.
185 while (Token.isNot(MIToken::Eof)) {
186 auto Loc = Token.location();
187 if (parseMachineOperand(MO))
189 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
190 if (Token.is(MIToken::Eof))
192 if (Token.isNot(MIToken::comma))
193 return error("expected ',' before the next machine operand");
197 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
198 if (!MCID.isVariadic()) {
199 // FIXME: Move the implicit operand verification to the machine verifier.
200 if (verifyImplicitOperands(Operands, MCID))
204 // TODO: Check for extraneous machine operands.
205 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
207 for (const auto &Operand : Operands)
208 MI->addOperand(MF, Operand.Operand);
212 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
214 if (Token.isNot(MIToken::MachineBasicBlock))
215 return error("expected a machine basic block reference");
216 if (parseMBBReference(MBB))
219 if (Token.isNot(MIToken::Eof))
221 "expected end of string after the machine basic block reference");
225 bool MIParser::parseNamedRegister(unsigned &Reg) {
227 if (Token.isNot(MIToken::NamedRegister))
228 return error("expected a named register");
229 if (parseRegister(Reg))
232 if (Token.isNot(MIToken::Eof))
233 return error("expected end of string after the register reference");
237 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
238 assert(MO.isImplicit());
239 return MO.isDef() ? "implicit-def" : "implicit";
242 static std::string getRegisterName(const TargetRegisterInfo *TRI,
244 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
245 return StringRef(TRI->getName(Reg)).lower();
248 bool MIParser::verifyImplicitOperands(
249 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
251 // We can't verify call instructions as they can contain arbitrary implicit
252 // register and register mask operands.
255 // Gather all the expected implicit operands.
256 SmallVector<MachineOperand, 4> ImplicitOperands;
257 if (MCID.ImplicitDefs)
258 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
259 ImplicitOperands.push_back(
260 MachineOperand::CreateReg(*ImpDefs, true, true));
261 if (MCID.ImplicitUses)
262 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
263 ImplicitOperands.push_back(
264 MachineOperand::CreateReg(*ImpUses, false, true));
266 const auto *TRI = MF.getSubtarget().getRegisterInfo();
267 assert(TRI && "Expected target register info");
268 size_t I = ImplicitOperands.size(), J = Operands.size();
273 const auto &ImplicitOperand = ImplicitOperands[I];
274 const auto &Operand = Operands[J].Operand;
275 if (ImplicitOperand.isIdenticalTo(Operand))
277 if (Operand.isReg() && Operand.isImplicit()) {
278 return error(Operands[J].Begin,
279 Twine("expected an implicit register operand '") +
280 printImplicitRegisterFlag(ImplicitOperand) + " %" +
281 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
284 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
285 // insead of reporting an error at this location:
288 // report the error at the following location:
291 return error(J < Operands.size() ? Operands[J].End : Token.location(),
292 Twine("missing implicit register operand '") +
293 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
294 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
299 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
300 if (Token.is(MIToken::kw_frame_setup)) {
301 Flags |= MachineInstr::FrameSetup;
304 if (Token.isNot(MIToken::Identifier))
305 return error("expected a machine instruction");
306 StringRef InstrName = Token.stringValue();
307 if (parseInstrName(InstrName, OpCode))
308 return error(Twine("unknown machine instruction name '") + InstrName + "'");
313 bool MIParser::parseRegister(unsigned &Reg) {
314 switch (Token.kind()) {
315 case MIToken::underscore:
318 case MIToken::NamedRegister: {
319 StringRef Name = Token.stringValue();
320 if (getRegisterByName(Name, Reg))
321 return error(Twine("unknown register name '") + Name + "'");
324 case MIToken::VirtualRegister: {
328 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
329 if (RegInfo == PFS.VirtualRegisterSlots.end())
330 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
332 Reg = RegInfo->second;
335 // TODO: Parse other register kinds.
337 llvm_unreachable("The current token should be a register");
342 bool MIParser::parseRegisterFlag(unsigned &Flags) {
343 switch (Token.kind()) {
344 case MIToken::kw_implicit:
345 Flags |= RegState::Implicit;
347 case MIToken::kw_implicit_define:
348 Flags |= RegState::ImplicitDefine;
350 case MIToken::kw_dead:
351 Flags |= RegState::Dead;
353 case MIToken::kw_killed:
354 Flags |= RegState::Kill;
356 case MIToken::kw_undef:
357 Flags |= RegState::Undef;
359 // TODO: report an error when we specify the same flag more than once.
360 // TODO: parse the other register flags.
362 llvm_unreachable("The current token should be a register flag");
368 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
369 assert(Token.is(MIToken::colon));
371 if (Token.isNot(MIToken::Identifier))
372 return error("expected a subregister index after ':'");
373 auto Name = Token.stringValue();
374 SubReg = getSubRegIndex(Name);
376 return error(Twine("use of unknown subregister index '") + Name + "'");
381 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
383 unsigned Flags = IsDef ? RegState::Define : 0;
384 while (Token.isRegisterFlag()) {
385 if (parseRegisterFlag(Flags))
388 if (!Token.isRegister())
389 return error("expected a register after register flags");
390 if (parseRegister(Reg))
394 if (Token.is(MIToken::colon)) {
395 if (parseSubRegisterIndex(SubReg))
398 Dest = MachineOperand::CreateReg(
399 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
400 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
401 /*isEarlyClobber=*/false, SubReg);
405 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
406 assert(Token.is(MIToken::IntegerLiteral));
407 const APSInt &Int = Token.integerValue();
408 if (Int.getMinSignedBits() > 64)
409 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
410 llvm_unreachable("Can't parse large integer literals yet!");
411 Dest = MachineOperand::CreateImm(Int.getExtValue());
416 bool MIParser::getUnsigned(unsigned &Result) {
417 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
418 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
419 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
421 return error("expected 32-bit integer (too large)");
426 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
427 assert(Token.is(MIToken::MachineBasicBlock));
429 if (getUnsigned(Number))
431 auto MBBInfo = PFS.MBBSlots.find(Number);
432 if (MBBInfo == PFS.MBBSlots.end())
433 return error(Twine("use of undefined machine basic block #") +
435 MBB = MBBInfo->second;
436 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
437 return error(Twine("the name of machine basic block #") + Twine(Number) +
438 " isn't '" + Token.stringValue() + "'");
442 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
443 MachineBasicBlock *MBB;
444 if (parseMBBReference(MBB))
446 Dest = MachineOperand::CreateMBB(MBB);
451 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
452 assert(Token.is(MIToken::StackObject));
456 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
457 if (ObjectInfo == PFS.StackObjectSlots.end())
458 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
461 if (const auto *Alloca =
462 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
463 Name = Alloca->getName();
464 if (!Token.stringValue().empty() && Token.stringValue() != Name)
465 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
466 "' isn't '" + Token.stringValue() + "'");
468 Dest = MachineOperand::CreateFI(ObjectInfo->second);
472 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
473 assert(Token.is(MIToken::FixedStackObject));
477 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
478 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
479 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
482 Dest = MachineOperand::CreateFI(ObjectInfo->second);
486 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
487 switch (Token.kind()) {
488 case MIToken::NamedGlobalValue: {
489 auto Name = Token.stringValue();
490 const Module *M = MF.getFunction()->getParent();
491 if (const auto *GV = M->getNamedValue(Name)) {
492 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
495 return error(Twine("use of undefined global value '@") + Name + "'");
497 case MIToken::GlobalValue: {
499 if (getUnsigned(GVIdx))
501 if (GVIdx >= IRSlots.GlobalValues.size())
502 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
504 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
509 llvm_unreachable("The current token should be a global value");
511 // TODO: Parse offset and target flags.
516 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
517 assert(Token.is(MIToken::JumpTableIndex));
521 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
522 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
523 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
525 // TODO: Parse target flags.
526 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
530 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
531 switch (Token.kind()) {
532 case MIToken::kw_implicit:
533 case MIToken::kw_implicit_define:
534 case MIToken::kw_dead:
535 case MIToken::kw_killed:
536 case MIToken::kw_undef:
537 case MIToken::underscore:
538 case MIToken::NamedRegister:
539 case MIToken::VirtualRegister:
540 return parseRegisterOperand(Dest);
541 case MIToken::IntegerLiteral:
542 return parseImmediateOperand(Dest);
543 case MIToken::MachineBasicBlock:
544 return parseMBBOperand(Dest);
545 case MIToken::StackObject:
546 return parseStackObjectOperand(Dest);
547 case MIToken::FixedStackObject:
548 return parseFixedStackObjectOperand(Dest);
549 case MIToken::GlobalValue:
550 case MIToken::NamedGlobalValue:
551 return parseGlobalAddressOperand(Dest);
552 case MIToken::JumpTableIndex:
553 return parseJumpTableIndexOperand(Dest);
556 case MIToken::Identifier:
557 if (const auto *RegMask = getRegMask(Token.stringValue())) {
558 Dest = MachineOperand::CreateRegMask(RegMask);
564 // TODO: parse the other machine operands.
565 return error("expected a machine operand");
570 void MIParser::initNames2InstrOpCodes() {
571 if (!Names2InstrOpCodes.empty())
573 const auto *TII = MF.getSubtarget().getInstrInfo();
574 assert(TII && "Expected target instruction info");
575 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
576 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
579 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
580 initNames2InstrOpCodes();
581 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
582 if (InstrInfo == Names2InstrOpCodes.end())
584 OpCode = InstrInfo->getValue();
588 void MIParser::initNames2Regs() {
589 if (!Names2Regs.empty())
591 // The '%noreg' register is the register 0.
592 Names2Regs.insert(std::make_pair("noreg", 0));
593 const auto *TRI = MF.getSubtarget().getRegisterInfo();
594 assert(TRI && "Expected target register info");
595 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
597 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
600 assert(WasInserted && "Expected registers to be unique case-insensitively");
604 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
606 auto RegInfo = Names2Regs.find(RegName);
607 if (RegInfo == Names2Regs.end())
609 Reg = RegInfo->getValue();
613 void MIParser::initNames2RegMasks() {
614 if (!Names2RegMasks.empty())
616 const auto *TRI = MF.getSubtarget().getRegisterInfo();
617 assert(TRI && "Expected target register info");
618 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
619 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
620 assert(RegMasks.size() == RegMaskNames.size());
621 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
622 Names2RegMasks.insert(
623 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
626 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
627 initNames2RegMasks();
628 auto RegMaskInfo = Names2RegMasks.find(Identifier);
629 if (RegMaskInfo == Names2RegMasks.end())
631 return RegMaskInfo->getValue();
634 void MIParser::initNames2SubRegIndices() {
635 if (!Names2SubRegIndices.empty())
637 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
638 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
639 Names2SubRegIndices.insert(
640 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
643 unsigned MIParser::getSubRegIndex(StringRef Name) {
644 initNames2SubRegIndices();
645 auto SubRegInfo = Names2SubRegIndices.find(Name);
646 if (SubRegInfo == Names2SubRegIndices.end())
648 return SubRegInfo->getValue();
651 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
652 MachineFunction &MF, StringRef Src,
653 const PerFunctionMIParsingState &PFS,
654 const SlotMapping &IRSlots, SMDiagnostic &Error) {
655 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
658 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
659 MachineFunction &MF, StringRef Src,
660 const PerFunctionMIParsingState &PFS,
661 const SlotMapping &IRSlots, SMDiagnostic &Error) {
662 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseMBB(MBB);
665 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
666 MachineFunction &MF, StringRef Src,
667 const PerFunctionMIParsingState &PFS,
668 const SlotMapping &IRSlots,
669 SMDiagnostic &Error) {
670 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseNamedRegister(Reg);