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 parseMachineOperand(MachineOperand &Dest);
94 /// Convert the integer literal in the current token into an unsigned integer.
96 /// Return true if an error occurred.
97 bool getUnsigned(unsigned &Result);
99 void initNames2InstrOpCodes();
101 /// Try to convert an instruction name to an opcode. Return true if the
102 /// instruction name is invalid.
103 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
105 bool parseInstruction(unsigned &OpCode);
107 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
108 const MCInstrDesc &MCID);
110 void initNames2Regs();
112 /// Try to convert a register name to a register number. Return true if the
113 /// register name is invalid.
114 bool getRegisterByName(StringRef RegName, unsigned &Reg);
116 void initNames2RegMasks();
118 /// Check if the given identifier is a name of a register mask.
120 /// Return null if the identifier isn't a register mask.
121 const uint32_t *getRegMask(StringRef Identifier);
123 void initNames2SubRegIndices();
125 /// Check if the given identifier is a name of a subregister index.
127 /// Return 0 if the name isn't a subregister index class.
128 unsigned getSubRegIndex(StringRef Name);
131 } // end anonymous namespace
133 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
134 StringRef Source, const PerFunctionMIParsingState &PFS,
135 const SlotMapping &IRSlots)
136 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
137 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
139 void MIParser::lex() {
140 CurrentSource = lexMIToken(
141 CurrentSource, Token,
142 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
145 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
147 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
148 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
149 Error = SMDiagnostic(
151 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
152 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
156 bool MIParser::parse(MachineInstr *&MI) {
159 // Parse any register operands before '='
160 // TODO: Allow parsing of multiple operands before '='
161 MachineOperand MO = MachineOperand::CreateImm(0);
162 SmallVector<MachineOperandWithLocation, 8> Operands;
163 if (Token.isRegister() || Token.isRegisterFlag()) {
164 auto Loc = Token.location();
165 if (parseRegisterOperand(MO, /*IsDef=*/true))
167 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
168 if (Token.isNot(MIToken::equal))
169 return error("expected '='");
174 if (Token.isError() || parseInstruction(OpCode))
177 // TODO: Parse the instruction flags and memory operands.
179 // Parse the remaining machine operands.
180 while (Token.isNot(MIToken::Eof)) {
181 auto Loc = Token.location();
182 if (parseMachineOperand(MO))
184 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
185 if (Token.is(MIToken::Eof))
187 if (Token.isNot(MIToken::comma))
188 return error("expected ',' before the next machine operand");
192 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
193 if (!MCID.isVariadic()) {
194 // FIXME: Move the implicit operand verification to the machine verifier.
195 if (verifyImplicitOperands(Operands, MCID))
199 // TODO: Check for extraneous machine operands.
200 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
201 for (const auto &Operand : Operands)
202 MI->addOperand(MF, Operand.Operand);
206 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
208 if (Token.isNot(MIToken::MachineBasicBlock))
209 return error("expected a machine basic block reference");
210 if (parseMBBReference(MBB))
213 if (Token.isNot(MIToken::Eof))
215 "expected end of string after the machine basic block reference");
219 bool MIParser::parseNamedRegister(unsigned &Reg) {
221 if (Token.isNot(MIToken::NamedRegister))
222 return error("expected a named register");
223 if (parseRegister(Reg))
226 if (Token.isNot(MIToken::Eof))
227 return error("expected end of string after the register reference");
231 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
232 assert(MO.isImplicit());
233 return MO.isDef() ? "implicit-def" : "implicit";
236 static std::string getRegisterName(const TargetRegisterInfo *TRI,
238 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
239 return StringRef(TRI->getName(Reg)).lower();
242 bool MIParser::verifyImplicitOperands(
243 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
245 // We can't verify call instructions as they can contain arbitrary implicit
246 // register and register mask operands.
249 // Gather all the expected implicit operands.
250 SmallVector<MachineOperand, 4> ImplicitOperands;
251 if (MCID.ImplicitDefs)
252 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
253 ImplicitOperands.push_back(
254 MachineOperand::CreateReg(*ImpDefs, true, true));
255 if (MCID.ImplicitUses)
256 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
257 ImplicitOperands.push_back(
258 MachineOperand::CreateReg(*ImpUses, false, true));
260 const auto *TRI = MF.getSubtarget().getRegisterInfo();
261 assert(TRI && "Expected target register info");
262 size_t I = ImplicitOperands.size(), J = Operands.size();
267 const auto &ImplicitOperand = ImplicitOperands[I];
268 const auto &Operand = Operands[J].Operand;
269 if (ImplicitOperand.isIdenticalTo(Operand))
271 if (Operand.isReg() && Operand.isImplicit()) {
272 return error(Operands[J].Begin,
273 Twine("expected an implicit register operand '") +
274 printImplicitRegisterFlag(ImplicitOperand) + " %" +
275 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
278 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
279 // insead of reporting an error at this location:
282 // report the error at the following location:
285 return error(J < Operands.size() ? Operands[J].End : Token.location(),
286 Twine("missing implicit register operand '") +
287 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
288 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
293 bool MIParser::parseInstruction(unsigned &OpCode) {
294 if (Token.isNot(MIToken::Identifier))
295 return error("expected a machine instruction");
296 StringRef InstrName = Token.stringValue();
297 if (parseInstrName(InstrName, OpCode))
298 return error(Twine("unknown machine instruction name '") + InstrName + "'");
303 bool MIParser::parseRegister(unsigned &Reg) {
304 switch (Token.kind()) {
305 case MIToken::underscore:
308 case MIToken::NamedRegister: {
309 StringRef Name = Token.stringValue();
310 if (getRegisterByName(Name, Reg))
311 return error(Twine("unknown register name '") + Name + "'");
314 case MIToken::VirtualRegister: {
318 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
319 if (RegInfo == PFS.VirtualRegisterSlots.end())
320 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
322 Reg = RegInfo->second;
325 // TODO: Parse other register kinds.
327 llvm_unreachable("The current token should be a register");
332 bool MIParser::parseRegisterFlag(unsigned &Flags) {
333 switch (Token.kind()) {
334 case MIToken::kw_implicit:
335 Flags |= RegState::Implicit;
337 case MIToken::kw_implicit_define:
338 Flags |= RegState::ImplicitDefine;
340 case MIToken::kw_dead:
341 Flags |= RegState::Dead;
343 case MIToken::kw_killed:
344 Flags |= RegState::Kill;
346 case MIToken::kw_undef:
347 Flags |= RegState::Undef;
349 // TODO: report an error when we specify the same flag more than once.
350 // TODO: parse the other register flags.
352 llvm_unreachable("The current token should be a register flag");
358 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
359 assert(Token.is(MIToken::colon));
361 if (Token.isNot(MIToken::Identifier))
362 return error("expected a subregister index after ':'");
363 auto Name = Token.stringValue();
364 SubReg = getSubRegIndex(Name);
366 return error(Twine("use of unknown subregister index '") + Name + "'");
371 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
373 unsigned Flags = IsDef ? RegState::Define : 0;
374 while (Token.isRegisterFlag()) {
375 if (parseRegisterFlag(Flags))
378 if (!Token.isRegister())
379 return error("expected a register after register flags");
380 if (parseRegister(Reg))
384 if (Token.is(MIToken::colon)) {
385 if (parseSubRegisterIndex(SubReg))
388 Dest = MachineOperand::CreateReg(
389 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
390 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
391 /*isEarlyClobber=*/false, SubReg);
395 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
396 assert(Token.is(MIToken::IntegerLiteral));
397 const APSInt &Int = Token.integerValue();
398 if (Int.getMinSignedBits() > 64)
399 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
400 llvm_unreachable("Can't parse large integer literals yet!");
401 Dest = MachineOperand::CreateImm(Int.getExtValue());
406 bool MIParser::getUnsigned(unsigned &Result) {
407 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
408 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
409 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
411 return error("expected 32-bit integer (too large)");
416 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
417 assert(Token.is(MIToken::MachineBasicBlock));
419 if (getUnsigned(Number))
421 auto MBBInfo = PFS.MBBSlots.find(Number);
422 if (MBBInfo == PFS.MBBSlots.end())
423 return error(Twine("use of undefined machine basic block #") +
425 MBB = MBBInfo->second;
426 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
427 return error(Twine("the name of machine basic block #") + Twine(Number) +
428 " isn't '" + Token.stringValue() + "'");
432 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
433 MachineBasicBlock *MBB;
434 if (parseMBBReference(MBB))
436 Dest = MachineOperand::CreateMBB(MBB);
441 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
442 switch (Token.kind()) {
443 case MIToken::NamedGlobalValue: {
444 auto Name = Token.stringValue();
445 const Module *M = MF.getFunction()->getParent();
446 if (const auto *GV = M->getNamedValue(Name)) {
447 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
450 return error(Twine("use of undefined global value '@") + Name + "'");
452 case MIToken::GlobalValue: {
454 if (getUnsigned(GVIdx))
456 if (GVIdx >= IRSlots.GlobalValues.size())
457 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
459 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
464 llvm_unreachable("The current token should be a global value");
466 // TODO: Parse offset and target flags.
471 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
472 switch (Token.kind()) {
473 case MIToken::kw_implicit:
474 case MIToken::kw_implicit_define:
475 case MIToken::kw_dead:
476 case MIToken::kw_killed:
477 case MIToken::kw_undef:
478 case MIToken::underscore:
479 case MIToken::NamedRegister:
480 case MIToken::VirtualRegister:
481 return parseRegisterOperand(Dest);
482 case MIToken::IntegerLiteral:
483 return parseImmediateOperand(Dest);
484 case MIToken::MachineBasicBlock:
485 return parseMBBOperand(Dest);
486 case MIToken::GlobalValue:
487 case MIToken::NamedGlobalValue:
488 return parseGlobalAddressOperand(Dest);
491 case MIToken::Identifier:
492 if (const auto *RegMask = getRegMask(Token.stringValue())) {
493 Dest = MachineOperand::CreateRegMask(RegMask);
499 // TODO: parse the other machine operands.
500 return error("expected a machine operand");
505 void MIParser::initNames2InstrOpCodes() {
506 if (!Names2InstrOpCodes.empty())
508 const auto *TII = MF.getSubtarget().getInstrInfo();
509 assert(TII && "Expected target instruction info");
510 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
511 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
514 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
515 initNames2InstrOpCodes();
516 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
517 if (InstrInfo == Names2InstrOpCodes.end())
519 OpCode = InstrInfo->getValue();
523 void MIParser::initNames2Regs() {
524 if (!Names2Regs.empty())
526 // The '%noreg' register is the register 0.
527 Names2Regs.insert(std::make_pair("noreg", 0));
528 const auto *TRI = MF.getSubtarget().getRegisterInfo();
529 assert(TRI && "Expected target register info");
530 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
532 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
535 assert(WasInserted && "Expected registers to be unique case-insensitively");
539 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
541 auto RegInfo = Names2Regs.find(RegName);
542 if (RegInfo == Names2Regs.end())
544 Reg = RegInfo->getValue();
548 void MIParser::initNames2RegMasks() {
549 if (!Names2RegMasks.empty())
551 const auto *TRI = MF.getSubtarget().getRegisterInfo();
552 assert(TRI && "Expected target register info");
553 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
554 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
555 assert(RegMasks.size() == RegMaskNames.size());
556 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
557 Names2RegMasks.insert(
558 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
561 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
562 initNames2RegMasks();
563 auto RegMaskInfo = Names2RegMasks.find(Identifier);
564 if (RegMaskInfo == Names2RegMasks.end())
566 return RegMaskInfo->getValue();
569 void MIParser::initNames2SubRegIndices() {
570 if (!Names2SubRegIndices.empty())
572 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
573 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
574 Names2SubRegIndices.insert(
575 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
578 unsigned MIParser::getSubRegIndex(StringRef Name) {
579 initNames2SubRegIndices();
580 auto SubRegInfo = Names2SubRegIndices.find(Name);
581 if (SubRegInfo == Names2SubRegIndices.end())
583 return SubRegInfo->getValue();
586 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
587 MachineFunction &MF, StringRef Src,
588 const PerFunctionMIParsingState &PFS,
589 const SlotMapping &IRSlots, SMDiagnostic &Error) {
590 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
593 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
594 MachineFunction &MF, StringRef Src,
595 const PerFunctionMIParsingState &PFS,
596 const SlotMapping &IRSlots, SMDiagnostic &Error) {
597 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseMBB(MBB);
600 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
601 MachineFunction &MF, StringRef Src,
602 const PerFunctionMIParsingState &PFS,
603 const SlotMapping &IRSlots,
604 SMDiagnostic &Error) {
605 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseNamedRegister(Reg);