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 /// Maps from basic block numbers to MBBs.
51 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
52 /// Maps from indices to unnamed global values and metadata nodes.
53 const SlotMapping &IRSlots;
54 /// Maps from instruction names to op codes.
55 StringMap<unsigned> Names2InstrOpCodes;
56 /// Maps from register names to registers.
57 StringMap<unsigned> Names2Regs;
58 /// Maps from register mask names to register masks.
59 StringMap<const uint32_t *> Names2RegMasks;
62 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
64 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
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);
82 bool parseRegister(unsigned &Reg);
83 bool parseRegisterFlag(unsigned &Flags);
84 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
85 bool parseImmediateOperand(MachineOperand &Dest);
86 bool parseMBBReference(MachineBasicBlock *&MBB);
87 bool parseMBBOperand(MachineOperand &Dest);
88 bool parseGlobalAddressOperand(MachineOperand &Dest);
89 bool parseMachineOperand(MachineOperand &Dest);
92 /// Convert the integer literal in the current token into an unsigned integer.
94 /// Return true if an error occurred.
95 bool getUnsigned(unsigned &Result);
97 void initNames2InstrOpCodes();
99 /// Try to convert an instruction name to an opcode. Return true if the
100 /// instruction name is invalid.
101 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
103 bool parseInstruction(unsigned &OpCode);
105 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
106 const MCInstrDesc &MCID);
108 void initNames2Regs();
110 /// Try to convert a register name to a register number. Return true if the
111 /// register name is invalid.
112 bool getRegisterByName(StringRef RegName, unsigned &Reg);
114 void initNames2RegMasks();
116 /// Check if the given identifier is a name of a register mask.
118 /// Return null if the identifier isn't a register mask.
119 const uint32_t *getRegMask(StringRef Identifier);
122 } // end anonymous namespace
124 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
126 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
127 const SlotMapping &IRSlots)
128 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
129 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
132 void MIParser::lex() {
133 CurrentSource = lexMIToken(
134 CurrentSource, Token,
135 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
138 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
140 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
141 // TODO: Get the proper location in the MIR file, not just a location inside
143 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
144 Error = SMDiagnostic(
146 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
147 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
151 bool MIParser::parse(MachineInstr *&MI) {
154 // Parse any register operands before '='
155 // TODO: Allow parsing of multiple operands before '='
156 MachineOperand MO = MachineOperand::CreateImm(0);
157 SmallVector<MachineOperandWithLocation, 8> Operands;
158 if (Token.isRegister() || Token.isRegisterFlag()) {
159 auto Loc = Token.location();
160 if (parseRegisterOperand(MO, /*IsDef=*/true))
162 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
163 if (Token.isNot(MIToken::equal))
164 return error("expected '='");
169 if (Token.isError() || parseInstruction(OpCode))
172 // TODO: Parse the instruction flags and memory operands.
174 // Parse the remaining machine operands.
175 while (Token.isNot(MIToken::Eof)) {
176 auto Loc = Token.location();
177 if (parseMachineOperand(MO))
179 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
180 if (Token.is(MIToken::Eof))
182 if (Token.isNot(MIToken::comma))
183 return error("expected ',' before the next machine operand");
187 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
188 if (!MCID.isVariadic()) {
189 // FIXME: Move the implicit operand verification to the machine verifier.
190 if (verifyImplicitOperands(Operands, MCID))
194 // TODO: Check for extraneous machine operands.
195 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
196 for (const auto &Operand : Operands)
197 MI->addOperand(MF, Operand.Operand);
201 bool MIParser::parseMBB(MachineBasicBlock *&MBB) {
203 if (Token.isNot(MIToken::MachineBasicBlock))
204 return error("expected a machine basic block reference");
205 if (parseMBBReference(MBB))
208 if (Token.isNot(MIToken::Eof))
210 "expected end of string after the machine basic block reference");
214 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
215 assert(MO.isImplicit());
216 return MO.isDef() ? "implicit-def" : "implicit";
219 static std::string getRegisterName(const TargetRegisterInfo *TRI,
221 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
222 return StringRef(TRI->getName(Reg)).lower();
225 bool MIParser::verifyImplicitOperands(
226 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
228 // We can't verify call instructions as they can contain arbitrary implicit
229 // register and register mask operands.
232 // Gather all the expected implicit operands.
233 SmallVector<MachineOperand, 4> ImplicitOperands;
234 if (MCID.ImplicitDefs)
235 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
236 ImplicitOperands.push_back(
237 MachineOperand::CreateReg(*ImpDefs, true, true));
238 if (MCID.ImplicitUses)
239 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
240 ImplicitOperands.push_back(
241 MachineOperand::CreateReg(*ImpUses, false, true));
243 const auto *TRI = MF.getSubtarget().getRegisterInfo();
244 assert(TRI && "Expected target register info");
245 size_t I = ImplicitOperands.size(), J = Operands.size();
250 const auto &ImplicitOperand = ImplicitOperands[I];
251 const auto &Operand = Operands[J].Operand;
252 if (ImplicitOperand.isIdenticalTo(Operand))
254 if (Operand.isReg() && Operand.isImplicit()) {
255 return error(Operands[J].Begin,
256 Twine("expected an implicit register operand '") +
257 printImplicitRegisterFlag(ImplicitOperand) + " %" +
258 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
261 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
262 // insead of reporting an error at this location:
265 // report the error at the following location:
268 return error(J < Operands.size() ? Operands[J].End : Token.location(),
269 Twine("missing implicit register operand '") +
270 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
271 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
276 bool MIParser::parseInstruction(unsigned &OpCode) {
277 if (Token.isNot(MIToken::Identifier))
278 return error("expected a machine instruction");
279 StringRef InstrName = Token.stringValue();
280 if (parseInstrName(InstrName, OpCode))
281 return error(Twine("unknown machine instruction name '") + InstrName + "'");
286 bool MIParser::parseRegister(unsigned &Reg) {
287 switch (Token.kind()) {
288 case MIToken::underscore:
291 case MIToken::NamedRegister: {
292 StringRef Name = Token.stringValue();
293 if (getRegisterByName(Name, Reg))
294 return error(Twine("unknown register name '") + Name + "'");
297 // TODO: Parse other register kinds.
299 llvm_unreachable("The current token should be a register");
304 bool MIParser::parseRegisterFlag(unsigned &Flags) {
305 switch (Token.kind()) {
306 case MIToken::kw_implicit:
307 Flags |= RegState::Implicit;
309 case MIToken::kw_implicit_define:
310 Flags |= RegState::ImplicitDefine;
312 // TODO: report an error when we specify the same flag more than once.
313 // TODO: parse the other register flags.
315 llvm_unreachable("The current token should be a register flag");
321 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
323 unsigned Flags = IsDef ? RegState::Define : 0;
324 while (Token.isRegisterFlag()) {
325 if (parseRegisterFlag(Flags))
328 if (!Token.isRegister())
329 return error("expected a register after register flags");
330 if (parseRegister(Reg))
333 // TODO: Parse subregister.
334 Dest = MachineOperand::CreateReg(Reg, Flags & RegState::Define,
335 Flags & RegState::Implicit);
339 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
340 assert(Token.is(MIToken::IntegerLiteral));
341 const APSInt &Int = Token.integerValue();
342 if (Int.getMinSignedBits() > 64)
343 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
344 llvm_unreachable("Can't parse large integer literals yet!");
345 Dest = MachineOperand::CreateImm(Int.getExtValue());
350 bool MIParser::getUnsigned(unsigned &Result) {
351 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
352 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
353 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
355 return error("expected 32-bit integer (too large)");
360 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
361 assert(Token.is(MIToken::MachineBasicBlock));
363 if (getUnsigned(Number))
365 auto MBBInfo = MBBSlots.find(Number);
366 if (MBBInfo == MBBSlots.end())
367 return error(Twine("use of undefined machine basic block #") +
369 MBB = MBBInfo->second;
370 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
371 return error(Twine("the name of machine basic block #") + Twine(Number) +
372 " isn't '" + Token.stringValue() + "'");
376 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
377 MachineBasicBlock *MBB;
378 if (parseMBBReference(MBB))
380 Dest = MachineOperand::CreateMBB(MBB);
385 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
386 switch (Token.kind()) {
387 case MIToken::NamedGlobalValue: {
388 auto Name = Token.stringValue();
389 const Module *M = MF.getFunction()->getParent();
390 if (const auto *GV = M->getNamedValue(Name)) {
391 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
394 return error(Twine("use of undefined global value '@") + Name + "'");
396 case MIToken::GlobalValue: {
398 if (getUnsigned(GVIdx))
400 if (GVIdx >= IRSlots.GlobalValues.size())
401 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
403 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
408 llvm_unreachable("The current token should be a global value");
410 // TODO: Parse offset and target flags.
415 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
416 switch (Token.kind()) {
417 case MIToken::kw_implicit:
418 case MIToken::kw_implicit_define:
419 case MIToken::underscore:
420 case MIToken::NamedRegister:
421 return parseRegisterOperand(Dest);
422 case MIToken::IntegerLiteral:
423 return parseImmediateOperand(Dest);
424 case MIToken::MachineBasicBlock:
425 return parseMBBOperand(Dest);
426 case MIToken::GlobalValue:
427 case MIToken::NamedGlobalValue:
428 return parseGlobalAddressOperand(Dest);
431 case MIToken::Identifier:
432 if (const auto *RegMask = getRegMask(Token.stringValue())) {
433 Dest = MachineOperand::CreateRegMask(RegMask);
439 // TODO: parse the other machine operands.
440 return error("expected a machine operand");
445 void MIParser::initNames2InstrOpCodes() {
446 if (!Names2InstrOpCodes.empty())
448 const auto *TII = MF.getSubtarget().getInstrInfo();
449 assert(TII && "Expected target instruction info");
450 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
451 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
454 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
455 initNames2InstrOpCodes();
456 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
457 if (InstrInfo == Names2InstrOpCodes.end())
459 OpCode = InstrInfo->getValue();
463 void MIParser::initNames2Regs() {
464 if (!Names2Regs.empty())
466 // The '%noreg' register is the register 0.
467 Names2Regs.insert(std::make_pair("noreg", 0));
468 const auto *TRI = MF.getSubtarget().getRegisterInfo();
469 assert(TRI && "Expected target register info");
470 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
472 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
475 assert(WasInserted && "Expected registers to be unique case-insensitively");
479 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
481 auto RegInfo = Names2Regs.find(RegName);
482 if (RegInfo == Names2Regs.end())
484 Reg = RegInfo->getValue();
488 void MIParser::initNames2RegMasks() {
489 if (!Names2RegMasks.empty())
491 const auto *TRI = MF.getSubtarget().getRegisterInfo();
492 assert(TRI && "Expected target register info");
493 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
494 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
495 assert(RegMasks.size() == RegMaskNames.size());
496 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
497 Names2RegMasks.insert(
498 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
501 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
502 initNames2RegMasks();
503 auto RegMaskInfo = Names2RegMasks.find(Identifier);
504 if (RegMaskInfo == Names2RegMasks.end())
506 return RegMaskInfo->getValue();
509 bool llvm::parseMachineInstr(
510 MachineInstr *&MI, SourceMgr &SM, MachineFunction &MF, StringRef Src,
511 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
512 const SlotMapping &IRSlots, SMDiagnostic &Error) {
513 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse(MI);
516 bool llvm::parseMBBReference(
517 MachineBasicBlock *&MBB, SourceMgr &SM, MachineFunction &MF, StringRef Src,
518 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
519 const SlotMapping &IRSlots, SMDiagnostic &Error) {
520 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parseMBB(MBB);