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/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Target/TargetSubtargetInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
32 /// A wrapper struct around the 'MachineOperand' struct that includes a source
34 struct MachineOperandWithLocation {
35 MachineOperand Operand;
36 StringRef::iterator Begin;
37 StringRef::iterator End;
39 MachineOperandWithLocation(const MachineOperand &Operand,
40 StringRef::iterator Begin, StringRef::iterator End)
41 : Operand(Operand), Begin(Begin), End(End) {}
48 StringRef Source, CurrentSource;
50 const PerFunctionMIParsingState &PFS;
51 /// Maps from indices to unnamed global values and metadata nodes.
52 const SlotMapping &IRSlots;
53 /// Maps from instruction names to op codes.
54 StringMap<unsigned> Names2InstrOpCodes;
55 /// Maps from register names to registers.
56 StringMap<unsigned> Names2Regs;
57 /// Maps from register mask names to register masks.
58 StringMap<const uint32_t *> Names2RegMasks;
59 /// Maps from subregister names to subregister indices.
60 StringMap<unsigned> Names2SubRegIndices;
63 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
64 StringRef Source, const PerFunctionMIParsingState &PFS,
65 const SlotMapping &IRSlots);
69 /// Report an error at the current location with the given message.
71 /// This function always return true.
72 bool error(const Twine &Msg);
74 /// Report an error at the given location with the given message.
76 /// This function always return true.
77 bool error(StringRef::iterator Loc, const Twine &Msg);
79 bool parse(MachineInstr *&MI);
80 bool parseMBB(MachineBasicBlock *&MBB);
81 bool parseNamedRegister(unsigned &Reg);
83 bool parseRegister(unsigned &Reg);
84 bool parseRegisterFlag(unsigned &Flags);
85 bool parseSubRegisterIndex(unsigned &SubReg);
86 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
87 bool parseImmediateOperand(MachineOperand &Dest);
88 bool parseMBBReference(MachineBasicBlock *&MBB);
89 bool parseMBBOperand(MachineOperand &Dest);
90 bool parseGlobalAddressOperand(MachineOperand &Dest);
91 bool parseJumpTableIndexOperand(MachineOperand &Dest);
92 bool parseMachineOperand(MachineOperand &Dest);
95 /// Convert the integer literal in the current token into an unsigned integer.
97 /// Return true if an error occurred.
98 bool getUnsigned(unsigned &Result);
100 void initNames2InstrOpCodes();
102 /// Try to convert an instruction name to an opcode. Return true if the
103 /// instruction name is invalid.
104 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
106 bool parseInstruction(unsigned &OpCode);
108 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
109 const MCInstrDesc &MCID);
111 void initNames2Regs();
113 /// Try to convert a register name to a register number. Return true if the
114 /// register name is invalid.
115 bool getRegisterByName(StringRef RegName, unsigned &Reg);
117 void initNames2RegMasks();
119 /// Check if the given identifier is a name of a register mask.
121 /// Return null if the identifier isn't a register mask.
122 const uint32_t *getRegMask(StringRef Identifier);
124 void initNames2SubRegIndices();
126 /// Check if the given identifier is a name of a subregister index.
128 /// Return 0 if the name isn't a subregister index class.
129 unsigned getSubRegIndex(StringRef Name);
132 } // end anonymous namespace
134 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
135 StringRef Source, const PerFunctionMIParsingState &PFS,
136 const SlotMapping &IRSlots)
137 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
138 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
140 void MIParser::lex() {
141 CurrentSource = lexMIToken(
142 CurrentSource, Token,
143 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
146 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
148 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
149 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
150 Error = SMDiagnostic(
152 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
153 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
157 bool MIParser::parse(MachineInstr *&MI) {
160 // Parse any register operands before '='
161 // TODO: Allow parsing of multiple operands before '='
162 MachineOperand MO = MachineOperand::CreateImm(0);
163 SmallVector<MachineOperandWithLocation, 8> Operands;
164 if (Token.isRegister() || Token.isRegisterFlag()) {
165 auto Loc = Token.location();
166 if (parseRegisterOperand(MO, /*IsDef=*/true))
168 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
169 if (Token.isNot(MIToken::equal))
170 return error("expected '='");
175 if (Token.isError() || parseInstruction(OpCode))
178 // TODO: Parse the instruction flags and memory operands.
180 // Parse the remaining machine operands.
181 while (Token.isNot(MIToken::Eof)) {
182 auto Loc = Token.location();
183 if (parseMachineOperand(MO))
185 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
186 if (Token.is(MIToken::Eof))
188 if (Token.isNot(MIToken::comma))
189 return error("expected ',' before the next machine operand");
193 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
194 if (!MCID.isVariadic()) {
195 // FIXME: Move the implicit operand verification to the machine verifier.
196 if (verifyImplicitOperands(Operands, MCID))
200 // TODO: Check for extraneous machine operands.
201 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
202 for (const auto &Operand : Operands)
203 MI->addOperand(MF, Operand.Operand);
207 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
209 if (Token.isNot(MIToken::MachineBasicBlock))
210 return error("expected a machine basic block reference");
211 if (parseMBBReference(MBB))
214 if (Token.isNot(MIToken::Eof))
216 "expected end of string after the machine basic block reference");
220 bool MIParser::parseNamedRegister(unsigned &Reg) {
222 if (Token.isNot(MIToken::NamedRegister))
223 return error("expected a named register");
224 if (parseRegister(Reg))
227 if (Token.isNot(MIToken::Eof))
228 return error("expected end of string after the register reference");
232 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
233 assert(MO.isImplicit());
234 return MO.isDef() ? "implicit-def" : "implicit";
237 static std::string getRegisterName(const TargetRegisterInfo *TRI,
239 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
240 return StringRef(TRI->getName(Reg)).lower();
243 bool MIParser::verifyImplicitOperands(
244 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
246 // We can't verify call instructions as they can contain arbitrary implicit
247 // register and register mask operands.
250 // Gather all the expected implicit operands.
251 SmallVector<MachineOperand, 4> ImplicitOperands;
252 if (MCID.ImplicitDefs)
253 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
254 ImplicitOperands.push_back(
255 MachineOperand::CreateReg(*ImpDefs, true, true));
256 if (MCID.ImplicitUses)
257 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
258 ImplicitOperands.push_back(
259 MachineOperand::CreateReg(*ImpUses, false, true));
261 const auto *TRI = MF.getSubtarget().getRegisterInfo();
262 assert(TRI && "Expected target register info");
263 size_t I = ImplicitOperands.size(), J = Operands.size();
268 const auto &ImplicitOperand = ImplicitOperands[I];
269 const auto &Operand = Operands[J].Operand;
270 if (ImplicitOperand.isIdenticalTo(Operand))
272 if (Operand.isReg() && Operand.isImplicit()) {
273 return error(Operands[J].Begin,
274 Twine("expected an implicit register operand '") +
275 printImplicitRegisterFlag(ImplicitOperand) + " %" +
276 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
279 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
280 // insead of reporting an error at this location:
283 // report the error at the following location:
286 return error(J < Operands.size() ? Operands[J].End : Token.location(),
287 Twine("missing implicit register operand '") +
288 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
289 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
294 bool MIParser::parseInstruction(unsigned &OpCode) {
295 if (Token.isNot(MIToken::Identifier))
296 return error("expected a machine instruction");
297 StringRef InstrName = Token.stringValue();
298 if (parseInstrName(InstrName, OpCode))
299 return error(Twine("unknown machine instruction name '") + InstrName + "'");
304 bool MIParser::parseRegister(unsigned &Reg) {
305 switch (Token.kind()) {
306 case MIToken::underscore:
309 case MIToken::NamedRegister: {
310 StringRef Name = Token.stringValue();
311 if (getRegisterByName(Name, Reg))
312 return error(Twine("unknown register name '") + Name + "'");
315 case MIToken::VirtualRegister: {
319 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
320 if (RegInfo == PFS.VirtualRegisterSlots.end())
321 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
323 Reg = RegInfo->second;
326 // TODO: Parse other register kinds.
328 llvm_unreachable("The current token should be a register");
333 bool MIParser::parseRegisterFlag(unsigned &Flags) {
334 switch (Token.kind()) {
335 case MIToken::kw_implicit:
336 Flags |= RegState::Implicit;
338 case MIToken::kw_implicit_define:
339 Flags |= RegState::ImplicitDefine;
341 case MIToken::kw_dead:
342 Flags |= RegState::Dead;
344 case MIToken::kw_killed:
345 Flags |= RegState::Kill;
347 case MIToken::kw_undef:
348 Flags |= RegState::Undef;
350 // TODO: report an error when we specify the same flag more than once.
351 // TODO: parse the other register flags.
353 llvm_unreachable("The current token should be a register flag");
359 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
360 assert(Token.is(MIToken::colon));
362 if (Token.isNot(MIToken::Identifier))
363 return error("expected a subregister index after ':'");
364 auto Name = Token.stringValue();
365 SubReg = getSubRegIndex(Name);
367 return error(Twine("use of unknown subregister index '") + Name + "'");
372 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
374 unsigned Flags = IsDef ? RegState::Define : 0;
375 while (Token.isRegisterFlag()) {
376 if (parseRegisterFlag(Flags))
379 if (!Token.isRegister())
380 return error("expected a register after register flags");
381 if (parseRegister(Reg))
385 if (Token.is(MIToken::colon)) {
386 if (parseSubRegisterIndex(SubReg))
389 Dest = MachineOperand::CreateReg(
390 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
391 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
392 /*isEarlyClobber=*/false, SubReg);
396 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
397 assert(Token.is(MIToken::IntegerLiteral));
398 const APSInt &Int = Token.integerValue();
399 if (Int.getMinSignedBits() > 64)
400 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
401 llvm_unreachable("Can't parse large integer literals yet!");
402 Dest = MachineOperand::CreateImm(Int.getExtValue());
407 bool MIParser::getUnsigned(unsigned &Result) {
408 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
409 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
410 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
412 return error("expected 32-bit integer (too large)");
417 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
418 assert(Token.is(MIToken::MachineBasicBlock));
420 if (getUnsigned(Number))
422 auto MBBInfo = PFS.MBBSlots.find(Number);
423 if (MBBInfo == PFS.MBBSlots.end())
424 return error(Twine("use of undefined machine basic block #") +
426 MBB = MBBInfo->second;
427 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
428 return error(Twine("the name of machine basic block #") + Twine(Number) +
429 " isn't '" + Token.stringValue() + "'");
433 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
434 MachineBasicBlock *MBB;
435 if (parseMBBReference(MBB))
437 Dest = MachineOperand::CreateMBB(MBB);
442 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
443 switch (Token.kind()) {
444 case MIToken::NamedGlobalValue: {
445 auto Name = Token.stringValue();
446 const Module *M = MF.getFunction()->getParent();
447 if (const auto *GV = M->getNamedValue(Name)) {
448 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
451 return error(Twine("use of undefined global value '@") + Name + "'");
453 case MIToken::GlobalValue: {
455 if (getUnsigned(GVIdx))
457 if (GVIdx >= IRSlots.GlobalValues.size())
458 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
460 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
465 llvm_unreachable("The current token should be a global value");
467 // TODO: Parse offset and target flags.
472 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
473 assert(Token.is(MIToken::JumpTableIndex));
477 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
478 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
479 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
481 // TODO: Parse target flags.
482 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
486 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
487 switch (Token.kind()) {
488 case MIToken::kw_implicit:
489 case MIToken::kw_implicit_define:
490 case MIToken::kw_dead:
491 case MIToken::kw_killed:
492 case MIToken::kw_undef:
493 case MIToken::underscore:
494 case MIToken::NamedRegister:
495 case MIToken::VirtualRegister:
496 return parseRegisterOperand(Dest);
497 case MIToken::IntegerLiteral:
498 return parseImmediateOperand(Dest);
499 case MIToken::MachineBasicBlock:
500 return parseMBBOperand(Dest);
501 case MIToken::GlobalValue:
502 case MIToken::NamedGlobalValue:
503 return parseGlobalAddressOperand(Dest);
504 case MIToken::JumpTableIndex:
505 return parseJumpTableIndexOperand(Dest);
508 case MIToken::Identifier:
509 if (const auto *RegMask = getRegMask(Token.stringValue())) {
510 Dest = MachineOperand::CreateRegMask(RegMask);
516 // TODO: parse the other machine operands.
517 return error("expected a machine operand");
522 void MIParser::initNames2InstrOpCodes() {
523 if (!Names2InstrOpCodes.empty())
525 const auto *TII = MF.getSubtarget().getInstrInfo();
526 assert(TII && "Expected target instruction info");
527 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
528 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
531 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
532 initNames2InstrOpCodes();
533 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
534 if (InstrInfo == Names2InstrOpCodes.end())
536 OpCode = InstrInfo->getValue();
540 void MIParser::initNames2Regs() {
541 if (!Names2Regs.empty())
543 // The '%noreg' register is the register 0.
544 Names2Regs.insert(std::make_pair("noreg", 0));
545 const auto *TRI = MF.getSubtarget().getRegisterInfo();
546 assert(TRI && "Expected target register info");
547 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
549 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
552 assert(WasInserted && "Expected registers to be unique case-insensitively");
556 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
558 auto RegInfo = Names2Regs.find(RegName);
559 if (RegInfo == Names2Regs.end())
561 Reg = RegInfo->getValue();
565 void MIParser::initNames2RegMasks() {
566 if (!Names2RegMasks.empty())
568 const auto *TRI = MF.getSubtarget().getRegisterInfo();
569 assert(TRI && "Expected target register info");
570 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
571 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
572 assert(RegMasks.size() == RegMaskNames.size());
573 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
574 Names2RegMasks.insert(
575 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
578 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
579 initNames2RegMasks();
580 auto RegMaskInfo = Names2RegMasks.find(Identifier);
581 if (RegMaskInfo == Names2RegMasks.end())
583 return RegMaskInfo->getValue();
586 void MIParser::initNames2SubRegIndices() {
587 if (!Names2SubRegIndices.empty())
589 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
590 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
591 Names2SubRegIndices.insert(
592 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
595 unsigned MIParser::getSubRegIndex(StringRef Name) {
596 initNames2SubRegIndices();
597 auto SubRegInfo = Names2SubRegIndices.find(Name);
598 if (SubRegInfo == Names2SubRegIndices.end())
600 return SubRegInfo->getValue();
603 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
604 MachineFunction &MF, StringRef Src,
605 const PerFunctionMIParsingState &PFS,
606 const SlotMapping &IRSlots, SMDiagnostic &Error) {
607 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
610 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
611 MachineFunction &MF, StringRef Src,
612 const PerFunctionMIParsingState &PFS,
613 const SlotMapping &IRSlots, SMDiagnostic &Error) {
614 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseMBB(MBB);
617 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
618 MachineFunction &MF, StringRef Src,
619 const PerFunctionMIParsingState &PFS,
620 const SlotMapping &IRSlots,
621 SMDiagnostic &Error) {
622 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseNamedRegister(Reg);