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/IR/Module.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
35 StringRef Source, CurrentSource;
37 /// Maps from basic block numbers to MBBs.
38 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
39 /// Maps from indices to unnamed global values and metadata nodes.
40 const SlotMapping &IRSlots;
41 /// Maps from instruction names to op codes.
42 StringMap<unsigned> Names2InstrOpCodes;
43 /// Maps from register names to registers.
44 StringMap<unsigned> Names2Regs;
45 /// Maps from register mask names to register masks.
46 StringMap<const uint32_t *> Names2RegMasks;
49 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
51 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
52 const SlotMapping &IRSlots);
56 /// Report an error at the current location with the given message.
58 /// This function always return true.
59 bool error(const Twine &Msg);
61 /// Report an error at the given location with the given message.
63 /// This function always return true.
64 bool error(StringRef::iterator Loc, const Twine &Msg);
66 bool parse(MachineInstr *&MI);
68 bool parseRegister(unsigned &Reg);
69 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
70 bool parseImmediateOperand(MachineOperand &Dest);
71 bool parseMBBOperand(MachineOperand &Dest);
72 bool parseGlobalAddressOperand(MachineOperand &Dest);
73 bool parseMachineOperand(MachineOperand &Dest);
76 /// Convert the integer literal in the current token into an unsigned integer.
78 /// Return true if an error occurred.
79 bool getUnsigned(unsigned &Result);
81 void initNames2InstrOpCodes();
83 /// Try to convert an instruction name to an opcode. Return true if the
84 /// instruction name is invalid.
85 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
87 bool parseInstruction(unsigned &OpCode);
89 void initNames2Regs();
91 /// Try to convert a register name to a register number. Return true if the
92 /// register name is invalid.
93 bool getRegisterByName(StringRef RegName, unsigned &Reg);
95 void initNames2RegMasks();
97 /// Check if the given identifier is a name of a register mask.
99 /// Return null if the identifier isn't a register mask.
100 const uint32_t *getRegMask(StringRef Identifier);
103 } // end anonymous namespace
105 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
107 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
108 const SlotMapping &IRSlots)
109 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
110 Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
113 void MIParser::lex() {
114 CurrentSource = lexMIToken(
115 CurrentSource, Token,
116 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
119 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
121 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
122 // TODO: Get the proper location in the MIR file, not just a location inside
124 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
125 Error = SMDiagnostic(
127 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
128 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
132 bool MIParser::parse(MachineInstr *&MI) {
135 // Parse any register operands before '='
136 // TODO: Allow parsing of multiple operands before '='
137 MachineOperand MO = MachineOperand::CreateImm(0);
138 SmallVector<MachineOperand, 8> Operands;
139 if (Token.isRegister()) {
140 if (parseRegisterOperand(MO, /*IsDef=*/true))
142 Operands.push_back(MO);
143 if (Token.isNot(MIToken::equal))
144 return error("expected '='");
149 if (Token.isError() || parseInstruction(OpCode))
152 // TODO: Parse the instruction flags and memory operands.
154 // Parse the remaining machine operands.
155 while (Token.isNot(MIToken::Eof)) {
156 if (parseMachineOperand(MO))
158 Operands.push_back(MO);
159 if (Token.is(MIToken::Eof))
161 if (Token.isNot(MIToken::comma))
162 return error("expected ',' before the next machine operand");
166 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
168 // Verify machine operands.
169 if (!MCID.isVariadic()) {
170 for (size_t I = 0, E = Operands.size(); I < E; ++I) {
171 if (I < MCID.getNumOperands())
173 // Mark this register as implicit to prevent an assertion when it's added
174 // to an instruction. This is a temporary workaround until the implicit
175 // register flag can be parsed.
176 if (Operands[I].isReg())
177 Operands[I].setImplicit();
181 // TODO: Determine the implicit behaviour when implicit register flags are
183 MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
184 for (const auto &Operand : Operands)
185 MI->addOperand(MF, Operand);
189 bool MIParser::parseInstruction(unsigned &OpCode) {
190 if (Token.isNot(MIToken::Identifier))
191 return error("expected a machine instruction");
192 StringRef InstrName = Token.stringValue();
193 if (parseInstrName(InstrName, OpCode))
194 return error(Twine("unknown machine instruction name '") + InstrName + "'");
199 bool MIParser::parseRegister(unsigned &Reg) {
200 switch (Token.kind()) {
201 case MIToken::underscore:
204 case MIToken::NamedRegister: {
205 StringRef Name = Token.stringValue();
206 if (getRegisterByName(Name, Reg))
207 return error(Twine("unknown register name '") + Name + "'");
210 // TODO: Parse other register kinds.
212 llvm_unreachable("The current token should be a register");
217 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
219 // TODO: Parse register flags.
220 if (parseRegister(Reg))
223 // TODO: Parse subregister.
224 Dest = MachineOperand::CreateReg(Reg, IsDef);
228 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
229 assert(Token.is(MIToken::IntegerLiteral));
230 const APSInt &Int = Token.integerValue();
231 if (Int.getMinSignedBits() > 64)
232 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
233 llvm_unreachable("Can't parse large integer literals yet!");
234 Dest = MachineOperand::CreateImm(Int.getExtValue());
239 bool MIParser::getUnsigned(unsigned &Result) {
240 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
241 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
242 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
244 return error("expected 32-bit integer (too large)");
249 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
250 assert(Token.is(MIToken::MachineBasicBlock));
252 if (getUnsigned(Number))
254 auto MBBInfo = MBBSlots.find(Number);
255 if (MBBInfo == MBBSlots.end())
256 return error(Twine("use of undefined machine basic block #") +
258 MachineBasicBlock *MBB = MBBInfo->second;
259 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
260 return error(Twine("the name of machine basic block #") + Twine(Number) +
261 " isn't '" + Token.stringValue() + "'");
262 Dest = MachineOperand::CreateMBB(MBB);
267 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
268 switch (Token.kind()) {
269 case MIToken::NamedGlobalValue: {
270 auto Name = Token.stringValue();
271 const Module *M = MF.getFunction()->getParent();
272 if (const auto *GV = M->getNamedValue(Name)) {
273 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
276 return error(Twine("use of undefined global value '@") + Name + "'");
278 case MIToken::GlobalValue: {
280 if (getUnsigned(GVIdx))
282 if (GVIdx >= IRSlots.GlobalValues.size())
283 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
285 Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
290 llvm_unreachable("The current token should be a global value");
292 // TODO: Parse offset and target flags.
297 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
298 switch (Token.kind()) {
299 case MIToken::underscore:
300 case MIToken::NamedRegister:
301 return parseRegisterOperand(Dest);
302 case MIToken::IntegerLiteral:
303 return parseImmediateOperand(Dest);
304 case MIToken::MachineBasicBlock:
305 return parseMBBOperand(Dest);
306 case MIToken::GlobalValue:
307 case MIToken::NamedGlobalValue:
308 return parseGlobalAddressOperand(Dest);
311 case MIToken::Identifier:
312 if (const auto *RegMask = getRegMask(Token.stringValue())) {
313 Dest = MachineOperand::CreateRegMask(RegMask);
319 // TODO: parse the other machine operands.
320 return error("expected a machine operand");
325 void MIParser::initNames2InstrOpCodes() {
326 if (!Names2InstrOpCodes.empty())
328 const auto *TII = MF.getSubtarget().getInstrInfo();
329 assert(TII && "Expected target instruction info");
330 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
331 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
334 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
335 initNames2InstrOpCodes();
336 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
337 if (InstrInfo == Names2InstrOpCodes.end())
339 OpCode = InstrInfo->getValue();
343 void MIParser::initNames2Regs() {
344 if (!Names2Regs.empty())
346 // The '%noreg' register is the register 0.
347 Names2Regs.insert(std::make_pair("noreg", 0));
348 const auto *TRI = MF.getSubtarget().getRegisterInfo();
349 assert(TRI && "Expected target register info");
350 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
352 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
355 assert(WasInserted && "Expected registers to be unique case-insensitively");
359 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
361 auto RegInfo = Names2Regs.find(RegName);
362 if (RegInfo == Names2Regs.end())
364 Reg = RegInfo->getValue();
368 void MIParser::initNames2RegMasks() {
369 if (!Names2RegMasks.empty())
371 const auto *TRI = MF.getSubtarget().getRegisterInfo();
372 assert(TRI && "Expected target register info");
373 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
374 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
375 assert(RegMasks.size() == RegMaskNames.size());
376 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
377 Names2RegMasks.insert(
378 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
381 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
382 initNames2RegMasks();
383 auto RegMaskInfo = Names2RegMasks.find(Identifier);
384 if (RegMaskInfo == Names2RegMasks.end())
386 return RegMaskInfo->getValue();
389 bool llvm::parseMachineInstr(
390 MachineInstr *&MI, SourceMgr &SM, MachineFunction &MF, StringRef Src,
391 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
392 const SlotMapping &IRSlots, SMDiagnostic &Error) {
393 return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse(MI);