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/Parser.h"
18 #include "llvm/AsmParser/SlotMapping.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
40 /// A wrapper struct around the 'MachineOperand' struct that includes a source
42 struct MachineOperandWithLocation {
43 MachineOperand Operand;
44 StringRef::iterator Begin;
45 StringRef::iterator End;
47 MachineOperandWithLocation(const MachineOperand &Operand,
48 StringRef::iterator Begin, StringRef::iterator End)
49 : Operand(Operand), Begin(Begin), End(End) {}
56 StringRef Source, CurrentSource;
58 const PerFunctionMIParsingState &PFS;
59 /// Maps from indices to unnamed global values and metadata nodes.
60 const SlotMapping &IRSlots;
61 /// Maps from instruction names to op codes.
62 StringMap<unsigned> Names2InstrOpCodes;
63 /// Maps from register names to registers.
64 StringMap<unsigned> Names2Regs;
65 /// Maps from register mask names to register masks.
66 StringMap<const uint32_t *> Names2RegMasks;
67 /// Maps from subregister names to subregister indices.
68 StringMap<unsigned> Names2SubRegIndices;
69 /// Maps from slot numbers to function's unnamed basic blocks.
70 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
71 /// Maps from target index names to target indices.
72 StringMap<int> Names2TargetIndices;
75 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
76 StringRef Source, const PerFunctionMIParsingState &PFS,
77 const SlotMapping &IRSlots);
81 /// Report an error at the current location with the given message.
83 /// This function always return true.
84 bool error(const Twine &Msg);
86 /// Report an error at the given location with the given message.
88 /// This function always return true.
89 bool error(StringRef::iterator Loc, const Twine &Msg);
91 bool parse(MachineInstr *&MI);
92 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
93 bool parseStandaloneNamedRegister(unsigned &Reg);
94 bool parseStandaloneVirtualRegister(unsigned &Reg);
95 bool parseStandaloneIRBlockReference(const BasicBlock *&BB);
97 bool parseRegister(unsigned &Reg);
98 bool parseRegisterFlag(unsigned &Flags);
99 bool parseSubRegisterIndex(unsigned &SubReg);
100 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
101 bool parseImmediateOperand(MachineOperand &Dest);
102 bool parseFPImmediateOperand(MachineOperand &Dest);
103 bool parseMBBReference(MachineBasicBlock *&MBB);
104 bool parseMBBOperand(MachineOperand &Dest);
105 bool parseStackObjectOperand(MachineOperand &Dest);
106 bool parseFixedStackObjectOperand(MachineOperand &Dest);
107 bool parseGlobalValue(GlobalValue *&GV);
108 bool parseGlobalAddressOperand(MachineOperand &Dest);
109 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
110 bool parseJumpTableIndexOperand(MachineOperand &Dest);
111 bool parseExternalSymbolOperand(MachineOperand &Dest);
112 bool parseMDNode(MDNode *&Node);
113 bool parseMetadataOperand(MachineOperand &Dest);
114 bool parseCFIOffset(int &Offset);
115 bool parseCFIRegister(unsigned &Reg);
116 bool parseCFIOperand(MachineOperand &Dest);
117 bool parseIRBlock(BasicBlock *&BB, const Function &F);
118 bool parseBlockAddressOperand(MachineOperand &Dest);
119 bool parseTargetIndexOperand(MachineOperand &Dest);
120 bool parseMachineOperand(MachineOperand &Dest);
121 bool parseIRValue(Value *&V);
122 bool parseMemoryOperandFlag(unsigned &Flags);
123 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
126 /// Convert the integer literal in the current token into an unsigned integer.
128 /// Return true if an error occurred.
129 bool getUnsigned(unsigned &Result);
131 /// Convert the integer literal in the current token into an uint64.
133 /// Return true if an error occurred.
134 bool getUint64(uint64_t &Result);
136 /// If the current token is of the given kind, consume it and return false.
137 /// Otherwise report an error and return true.
138 bool expectAndConsume(MIToken::TokenKind TokenKind);
140 void initNames2InstrOpCodes();
142 /// Try to convert an instruction name to an opcode. Return true if the
143 /// instruction name is invalid.
144 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
146 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
148 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
149 const MCInstrDesc &MCID);
151 void initNames2Regs();
153 /// Try to convert a register name to a register number. Return true if the
154 /// register name is invalid.
155 bool getRegisterByName(StringRef RegName, unsigned &Reg);
157 void initNames2RegMasks();
159 /// Check if the given identifier is a name of a register mask.
161 /// Return null if the identifier isn't a register mask.
162 const uint32_t *getRegMask(StringRef Identifier);
164 void initNames2SubRegIndices();
166 /// Check if the given identifier is a name of a subregister index.
168 /// Return 0 if the name isn't a subregister index class.
169 unsigned getSubRegIndex(StringRef Name);
171 void initSlots2BasicBlocks();
173 const BasicBlock *getIRBlock(unsigned Slot);
175 void initNames2TargetIndices();
177 /// Try to convert a name of target index to the corresponding target index.
179 /// Return true if the name isn't a name of a target index.
180 bool getTargetIndex(StringRef Name, int &Index);
183 } // end anonymous namespace
185 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
186 StringRef Source, const PerFunctionMIParsingState &PFS,
187 const SlotMapping &IRSlots)
188 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
189 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
191 void MIParser::lex() {
192 CurrentSource = lexMIToken(
193 CurrentSource, Token,
194 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
197 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
199 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
200 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
201 Error = SMDiagnostic(
203 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
204 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
208 static const char *toString(MIToken::TokenKind TokenKind) {
214 case MIToken::lparen:
216 case MIToken::rparen:
219 return "<unknown token>";
223 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
224 if (Token.isNot(TokenKind))
225 return error(Twine("expected ") + toString(TokenKind));
230 bool MIParser::parse(MachineInstr *&MI) {
233 // Parse any register operands before '='
234 MachineOperand MO = MachineOperand::CreateImm(0);
235 SmallVector<MachineOperandWithLocation, 8> Operands;
236 while (Token.isRegister() || Token.isRegisterFlag()) {
237 auto Loc = Token.location();
238 if (parseRegisterOperand(MO, /*IsDef=*/true))
240 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
241 if (Token.isNot(MIToken::comma))
245 if (!Operands.empty() && expectAndConsume(MIToken::equal))
248 unsigned OpCode, Flags = 0;
249 if (Token.isError() || parseInstruction(OpCode, Flags))
252 // TODO: Parse the bundle instruction flags.
254 // Parse the remaining machine operands.
255 while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location) &&
256 Token.isNot(MIToken::coloncolon)) {
257 auto Loc = Token.location();
258 if (parseMachineOperand(MO))
260 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
261 if (Token.is(MIToken::Eof) || Token.is(MIToken::coloncolon))
263 if (Token.isNot(MIToken::comma))
264 return error("expected ',' before the next machine operand");
268 DebugLoc DebugLocation;
269 if (Token.is(MIToken::kw_debug_location)) {
271 if (Token.isNot(MIToken::exclaim))
272 return error("expected a metadata node after 'debug-location'");
273 MDNode *Node = nullptr;
274 if (parseMDNode(Node))
276 DebugLocation = DebugLoc(Node);
279 // Parse the machine memory operands.
280 SmallVector<MachineMemOperand *, 2> MemOperands;
281 if (Token.is(MIToken::coloncolon)) {
283 while (Token.isNot(MIToken::Eof)) {
284 MachineMemOperand *MemOp = nullptr;
285 if (parseMachineMemoryOperand(MemOp))
287 MemOperands.push_back(MemOp);
288 if (Token.is(MIToken::Eof))
290 if (Token.isNot(MIToken::comma))
291 return error("expected ',' before the next machine memory operand");
296 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
297 if (!MCID.isVariadic()) {
298 // FIXME: Move the implicit operand verification to the machine verifier.
299 if (verifyImplicitOperands(Operands, MCID))
303 // TODO: Check for extraneous machine operands.
304 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
306 for (const auto &Operand : Operands)
307 MI->addOperand(MF, Operand.Operand);
308 if (MemOperands.empty())
310 MachineInstr::mmo_iterator MemRefs =
311 MF.allocateMemRefsArray(MemOperands.size());
312 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
313 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
317 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
319 if (Token.isNot(MIToken::MachineBasicBlock))
320 return error("expected a machine basic block reference");
321 if (parseMBBReference(MBB))
324 if (Token.isNot(MIToken::Eof))
326 "expected end of string after the machine basic block reference");
330 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
332 if (Token.isNot(MIToken::NamedRegister))
333 return error("expected a named register");
334 if (parseRegister(Reg))
337 if (Token.isNot(MIToken::Eof))
338 return error("expected end of string after the register reference");
342 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
344 if (Token.isNot(MIToken::VirtualRegister))
345 return error("expected a virtual register");
346 if (parseRegister(Reg))
349 if (Token.isNot(MIToken::Eof))
350 return error("expected end of string after the register reference");
354 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
356 if (Token.isNot(MIToken::IRBlock))
357 return error("expected an IR block reference");
358 unsigned SlotNumber = 0;
359 if (getUnsigned(SlotNumber))
361 BB = getIRBlock(SlotNumber);
363 return error(Twine("use of undefined IR block '%ir-block.") +
364 Twine(SlotNumber) + "'");
366 if (Token.isNot(MIToken::Eof))
367 return error("expected end of string after the IR block reference");
371 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
372 assert(MO.isImplicit());
373 return MO.isDef() ? "implicit-def" : "implicit";
376 static std::string getRegisterName(const TargetRegisterInfo *TRI,
378 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
379 return StringRef(TRI->getName(Reg)).lower();
382 bool MIParser::verifyImplicitOperands(
383 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
385 // We can't verify call instructions as they can contain arbitrary implicit
386 // register and register mask operands.
389 // Gather all the expected implicit operands.
390 SmallVector<MachineOperand, 4> ImplicitOperands;
391 if (MCID.ImplicitDefs)
392 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
393 ImplicitOperands.push_back(
394 MachineOperand::CreateReg(*ImpDefs, true, true));
395 if (MCID.ImplicitUses)
396 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
397 ImplicitOperands.push_back(
398 MachineOperand::CreateReg(*ImpUses, false, true));
400 const auto *TRI = MF.getSubtarget().getRegisterInfo();
401 assert(TRI && "Expected target register info");
402 size_t I = ImplicitOperands.size(), J = Operands.size();
407 const auto &ImplicitOperand = ImplicitOperands[I];
408 const auto &Operand = Operands[J].Operand;
409 if (ImplicitOperand.isIdenticalTo(Operand))
411 if (Operand.isReg() && Operand.isImplicit()) {
412 return error(Operands[J].Begin,
413 Twine("expected an implicit register operand '") +
414 printImplicitRegisterFlag(ImplicitOperand) + " %" +
415 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
418 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
419 // insead of reporting an error at this location:
422 // report the error at the following location:
425 return error(J < Operands.size() ? Operands[J].End : Token.location(),
426 Twine("missing implicit register operand '") +
427 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
428 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
433 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
434 if (Token.is(MIToken::kw_frame_setup)) {
435 Flags |= MachineInstr::FrameSetup;
438 if (Token.isNot(MIToken::Identifier))
439 return error("expected a machine instruction");
440 StringRef InstrName = Token.stringValue();
441 if (parseInstrName(InstrName, OpCode))
442 return error(Twine("unknown machine instruction name '") + InstrName + "'");
447 bool MIParser::parseRegister(unsigned &Reg) {
448 switch (Token.kind()) {
449 case MIToken::underscore:
452 case MIToken::NamedRegister: {
453 StringRef Name = Token.stringValue();
454 if (getRegisterByName(Name, Reg))
455 return error(Twine("unknown register name '") + Name + "'");
458 case MIToken::VirtualRegister: {
462 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
463 if (RegInfo == PFS.VirtualRegisterSlots.end())
464 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
466 Reg = RegInfo->second;
469 // TODO: Parse other register kinds.
471 llvm_unreachable("The current token should be a register");
476 bool MIParser::parseRegisterFlag(unsigned &Flags) {
477 const unsigned OldFlags = Flags;
478 switch (Token.kind()) {
479 case MIToken::kw_implicit:
480 Flags |= RegState::Implicit;
482 case MIToken::kw_implicit_define:
483 Flags |= RegState::ImplicitDefine;
485 case MIToken::kw_dead:
486 Flags |= RegState::Dead;
488 case MIToken::kw_killed:
489 Flags |= RegState::Kill;
491 case MIToken::kw_undef:
492 Flags |= RegState::Undef;
494 case MIToken::kw_early_clobber:
495 Flags |= RegState::EarlyClobber;
497 case MIToken::kw_debug_use:
498 Flags |= RegState::Debug;
500 // TODO: parse the other register flags.
502 llvm_unreachable("The current token should be a register flag");
504 if (OldFlags == Flags)
505 // We know that the same flag is specified more than once when the flags
507 return error("duplicate '" + Token.stringValue() + "' register flag");
512 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
513 assert(Token.is(MIToken::colon));
515 if (Token.isNot(MIToken::Identifier))
516 return error("expected a subregister index after ':'");
517 auto Name = Token.stringValue();
518 SubReg = getSubRegIndex(Name);
520 return error(Twine("use of unknown subregister index '") + Name + "'");
525 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
527 unsigned Flags = IsDef ? RegState::Define : 0;
528 while (Token.isRegisterFlag()) {
529 if (parseRegisterFlag(Flags))
532 if (!Token.isRegister())
533 return error("expected a register after register flags");
534 if (parseRegister(Reg))
538 if (Token.is(MIToken::colon)) {
539 if (parseSubRegisterIndex(SubReg))
542 Dest = MachineOperand::CreateReg(
543 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
544 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
545 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
549 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
550 assert(Token.is(MIToken::IntegerLiteral));
551 const APSInt &Int = Token.integerValue();
552 if (Int.getMinSignedBits() > 64)
553 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
554 llvm_unreachable("Can't parse large integer literals yet!");
555 Dest = MachineOperand::CreateImm(Int.getExtValue());
560 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
561 auto Loc = Token.location();
563 if (Token.isNot(MIToken::FloatingPointLiteral))
564 return error("expected a floating point literal");
565 auto Source = StringRef(Loc, Token.stringValue().end() - Loc).str();
569 parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
571 return error(Loc + Err.getColumnNo(), Err.getMessage());
572 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
576 bool MIParser::getUnsigned(unsigned &Result) {
577 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
578 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
579 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
581 return error("expected 32-bit integer (too large)");
586 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
587 assert(Token.is(MIToken::MachineBasicBlock));
589 if (getUnsigned(Number))
591 auto MBBInfo = PFS.MBBSlots.find(Number);
592 if (MBBInfo == PFS.MBBSlots.end())
593 return error(Twine("use of undefined machine basic block #") +
595 MBB = MBBInfo->second;
596 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
597 return error(Twine("the name of machine basic block #") + Twine(Number) +
598 " isn't '" + Token.stringValue() + "'");
602 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
603 MachineBasicBlock *MBB;
604 if (parseMBBReference(MBB))
606 Dest = MachineOperand::CreateMBB(MBB);
611 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
612 assert(Token.is(MIToken::StackObject));
616 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
617 if (ObjectInfo == PFS.StackObjectSlots.end())
618 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
621 if (const auto *Alloca =
622 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
623 Name = Alloca->getName();
624 if (!Token.stringValue().empty() && Token.stringValue() != Name)
625 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
626 "' isn't '" + Token.stringValue() + "'");
628 Dest = MachineOperand::CreateFI(ObjectInfo->second);
632 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
633 assert(Token.is(MIToken::FixedStackObject));
637 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
638 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
639 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
642 Dest = MachineOperand::CreateFI(ObjectInfo->second);
646 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
647 switch (Token.kind()) {
648 case MIToken::NamedGlobalValue: {
649 const Module *M = MF.getFunction()->getParent();
650 GV = M->getNamedValue(Token.stringValue());
652 return error(Twine("use of undefined global value '@") +
653 Token.rawStringValue() + "'");
656 case MIToken::GlobalValue: {
658 if (getUnsigned(GVIdx))
660 if (GVIdx >= IRSlots.GlobalValues.size())
661 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
663 GV = IRSlots.GlobalValues[GVIdx];
667 llvm_unreachable("The current token should be a global value");
672 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
673 GlobalValue *GV = nullptr;
674 if (parseGlobalValue(GV))
676 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
677 // TODO: Parse offset and target flags.
682 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
683 assert(Token.is(MIToken::ConstantPoolItem));
687 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
688 if (ConstantInfo == PFS.ConstantPoolSlots.end())
689 return error("use of undefined constant '%const." + Twine(ID) + "'");
691 // TODO: Parse offset and target flags.
692 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
696 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
697 assert(Token.is(MIToken::JumpTableIndex));
701 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
702 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
703 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
705 // TODO: Parse target flags.
706 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
710 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
711 assert(Token.is(MIToken::ExternalSymbol));
712 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
714 // TODO: Parse the target flags.
715 Dest = MachineOperand::CreateES(Symbol);
719 bool MIParser::parseMDNode(MDNode *&Node) {
720 assert(Token.is(MIToken::exclaim));
721 auto Loc = Token.location();
723 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
724 return error("expected metadata id after '!'");
728 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
729 if (NodeInfo == IRSlots.MetadataNodes.end())
730 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
732 Node = NodeInfo->second.get();
736 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
737 MDNode *Node = nullptr;
738 if (parseMDNode(Node))
740 Dest = MachineOperand::CreateMetadata(Node);
744 bool MIParser::parseCFIOffset(int &Offset) {
745 if (Token.isNot(MIToken::IntegerLiteral))
746 return error("expected a cfi offset");
747 if (Token.integerValue().getMinSignedBits() > 32)
748 return error("expected a 32 bit integer (the cfi offset is too large)");
749 Offset = (int)Token.integerValue().getExtValue();
754 bool MIParser::parseCFIRegister(unsigned &Reg) {
755 if (Token.isNot(MIToken::NamedRegister))
756 return error("expected a cfi register");
758 if (parseRegister(LLVMReg))
760 const auto *TRI = MF.getSubtarget().getRegisterInfo();
761 assert(TRI && "Expected target register info");
762 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
764 return error("invalid DWARF register");
765 Reg = (unsigned)DwarfReg;
770 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
771 auto Kind = Token.kind();
773 auto &MMI = MF.getMMI();
778 case MIToken::kw_cfi_offset:
779 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
780 parseCFIOffset(Offset))
783 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
785 case MIToken::kw_cfi_def_cfa_register:
786 if (parseCFIRegister(Reg))
789 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
791 case MIToken::kw_cfi_def_cfa_offset:
792 if (parseCFIOffset(Offset))
794 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
795 CFIIndex = MMI.addFrameInst(
796 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
798 case MIToken::kw_cfi_def_cfa:
799 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
800 parseCFIOffset(Offset))
802 // NB: MCCFIInstruction::createDefCfa negates the offset.
804 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
807 // TODO: Parse the other CFI operands.
808 llvm_unreachable("The current token should be a cfi operand");
810 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
814 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
815 switch (Token.kind()) {
816 case MIToken::NamedIRBlock: {
817 BB = dyn_cast_or_null<BasicBlock>(
818 F.getValueSymbolTable().lookup(Token.stringValue()));
820 return error(Twine("use of undefined IR block '%ir-block.") +
821 Token.rawStringValue() + "'");
824 case MIToken::IRBlock: {
825 unsigned SlotNumber = 0;
826 if (getUnsigned(SlotNumber))
828 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber));
830 return error(Twine("use of undefined IR block '%ir-block.") +
831 Twine(SlotNumber) + "'");
835 llvm_unreachable("The current token should be an IR block reference");
840 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
841 assert(Token.is(MIToken::kw_blockaddress));
843 if (expectAndConsume(MIToken::lparen))
845 if (Token.isNot(MIToken::GlobalValue) &&
846 Token.isNot(MIToken::NamedGlobalValue))
847 return error("expected a global value");
848 GlobalValue *GV = nullptr;
849 if (parseGlobalValue(GV))
851 auto *F = dyn_cast<Function>(GV);
853 return error("expected an IR function reference");
855 if (expectAndConsume(MIToken::comma))
857 BasicBlock *BB = nullptr;
858 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
859 return error("expected an IR block reference");
860 if (parseIRBlock(BB, *F))
863 if (expectAndConsume(MIToken::rparen))
865 // TODO: parse offset and target flags.
866 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
870 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
871 assert(Token.is(MIToken::kw_target_index));
873 if (expectAndConsume(MIToken::lparen))
875 if (Token.isNot(MIToken::Identifier))
876 return error("expected the name of the target index");
878 if (getTargetIndex(Token.stringValue(), Index))
879 return error("use of undefined target index '" + Token.stringValue() + "'");
881 if (expectAndConsume(MIToken::rparen))
883 // TODO: Parse the offset and target flags.
884 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
888 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
889 switch (Token.kind()) {
890 case MIToken::kw_implicit:
891 case MIToken::kw_implicit_define:
892 case MIToken::kw_dead:
893 case MIToken::kw_killed:
894 case MIToken::kw_undef:
895 case MIToken::kw_early_clobber:
896 case MIToken::kw_debug_use:
897 case MIToken::underscore:
898 case MIToken::NamedRegister:
899 case MIToken::VirtualRegister:
900 return parseRegisterOperand(Dest);
901 case MIToken::IntegerLiteral:
902 return parseImmediateOperand(Dest);
903 case MIToken::kw_half:
904 case MIToken::kw_float:
905 case MIToken::kw_double:
906 case MIToken::kw_x86_fp80:
907 case MIToken::kw_fp128:
908 case MIToken::kw_ppc_fp128:
909 return parseFPImmediateOperand(Dest);
910 case MIToken::MachineBasicBlock:
911 return parseMBBOperand(Dest);
912 case MIToken::StackObject:
913 return parseStackObjectOperand(Dest);
914 case MIToken::FixedStackObject:
915 return parseFixedStackObjectOperand(Dest);
916 case MIToken::GlobalValue:
917 case MIToken::NamedGlobalValue:
918 return parseGlobalAddressOperand(Dest);
919 case MIToken::ConstantPoolItem:
920 return parseConstantPoolIndexOperand(Dest);
921 case MIToken::JumpTableIndex:
922 return parseJumpTableIndexOperand(Dest);
923 case MIToken::ExternalSymbol:
924 return parseExternalSymbolOperand(Dest);
925 case MIToken::exclaim:
926 return parseMetadataOperand(Dest);
927 case MIToken::kw_cfi_offset:
928 case MIToken::kw_cfi_def_cfa_register:
929 case MIToken::kw_cfi_def_cfa_offset:
930 case MIToken::kw_cfi_def_cfa:
931 return parseCFIOperand(Dest);
932 case MIToken::kw_blockaddress:
933 return parseBlockAddressOperand(Dest);
934 case MIToken::kw_target_index:
935 return parseTargetIndexOperand(Dest);
938 case MIToken::Identifier:
939 if (const auto *RegMask = getRegMask(Token.stringValue())) {
940 Dest = MachineOperand::CreateRegMask(RegMask);
946 // TODO: parse the other machine operands.
947 return error("expected a machine operand");
952 bool MIParser::parseIRValue(Value *&V) {
953 switch (Token.kind()) {
954 case MIToken::NamedIRValue: {
955 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
957 return error(Twine("use of undefined IR value '%ir.") +
958 Token.rawStringValue() + "'");
961 // TODO: Parse unnamed IR value references.
963 llvm_unreachable("The current token should be an IR block reference");
968 bool MIParser::getUint64(uint64_t &Result) {
969 assert(Token.hasIntegerValue());
970 if (Token.integerValue().getActiveBits() > 64)
971 return error("expected 64-bit integer (too large)");
972 Result = Token.integerValue().getZExtValue();
976 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
977 switch (Token.kind()) {
978 case MIToken::kw_volatile:
979 Flags |= MachineMemOperand::MOVolatile;
981 // TODO: report an error when we specify the same flag more than once.
982 // TODO: parse the other memory operand flags.
984 llvm_unreachable("The current token should be a memory operand flag");
990 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
991 if (expectAndConsume(MIToken::lparen))
994 while (Token.isMemoryOperandFlag()) {
995 if (parseMemoryOperandFlag(Flags))
998 if (Token.isNot(MIToken::Identifier) ||
999 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1000 return error("expected 'load' or 'store' memory operation");
1001 if (Token.stringValue() == "load")
1002 Flags |= MachineMemOperand::MOLoad;
1004 Flags |= MachineMemOperand::MOStore;
1007 if (Token.isNot(MIToken::IntegerLiteral))
1008 return error("expected the size integer literal after memory operation");
1010 if (getUint64(Size))
1014 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1015 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1016 return error(Twine("expected '") + Word + "'");
1019 // TODO: Parse pseudo source values.
1020 if (Token.isNot(MIToken::NamedIRValue))
1021 return error("expected an IR value reference");
1023 if (parseIRValue(V))
1025 if (!V->getType()->isPointerTy())
1026 return error("expected a pointer IR value");
1028 // TODO: Parse the base alignment.
1029 // TODO: Parse the attached metadata nodes.
1030 if (expectAndConsume(MIToken::rparen))
1033 Dest = MF.getMachineMemOperand(MachinePointerInfo(V), Flags, Size, Size);
1037 void MIParser::initNames2InstrOpCodes() {
1038 if (!Names2InstrOpCodes.empty())
1040 const auto *TII = MF.getSubtarget().getInstrInfo();
1041 assert(TII && "Expected target instruction info");
1042 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1043 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1046 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1047 initNames2InstrOpCodes();
1048 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1049 if (InstrInfo == Names2InstrOpCodes.end())
1051 OpCode = InstrInfo->getValue();
1055 void MIParser::initNames2Regs() {
1056 if (!Names2Regs.empty())
1058 // The '%noreg' register is the register 0.
1059 Names2Regs.insert(std::make_pair("noreg", 0));
1060 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1061 assert(TRI && "Expected target register info");
1062 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1064 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1067 assert(WasInserted && "Expected registers to be unique case-insensitively");
1071 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1073 auto RegInfo = Names2Regs.find(RegName);
1074 if (RegInfo == Names2Regs.end())
1076 Reg = RegInfo->getValue();
1080 void MIParser::initNames2RegMasks() {
1081 if (!Names2RegMasks.empty())
1083 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1084 assert(TRI && "Expected target register info");
1085 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1086 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1087 assert(RegMasks.size() == RegMaskNames.size());
1088 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1089 Names2RegMasks.insert(
1090 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1093 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1094 initNames2RegMasks();
1095 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1096 if (RegMaskInfo == Names2RegMasks.end())
1098 return RegMaskInfo->getValue();
1101 void MIParser::initNames2SubRegIndices() {
1102 if (!Names2SubRegIndices.empty())
1104 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1105 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1106 Names2SubRegIndices.insert(
1107 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1110 unsigned MIParser::getSubRegIndex(StringRef Name) {
1111 initNames2SubRegIndices();
1112 auto SubRegInfo = Names2SubRegIndices.find(Name);
1113 if (SubRegInfo == Names2SubRegIndices.end())
1115 return SubRegInfo->getValue();
1118 void MIParser::initSlots2BasicBlocks() {
1119 if (!Slots2BasicBlocks.empty())
1121 const auto &F = *MF.getFunction();
1122 ModuleSlotTracker MST(F.getParent());
1123 MST.incorporateFunction(F);
1124 for (auto &BB : F) {
1127 int Slot = MST.getLocalSlot(&BB);
1130 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1134 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1135 initSlots2BasicBlocks();
1136 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1137 if (BlockInfo == Slots2BasicBlocks.end())
1139 return BlockInfo->second;
1142 void MIParser::initNames2TargetIndices() {
1143 if (!Names2TargetIndices.empty())
1145 const auto *TII = MF.getSubtarget().getInstrInfo();
1146 assert(TII && "Expected target instruction info");
1147 auto Indices = TII->getSerializableTargetIndices();
1148 for (const auto &I : Indices)
1149 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1152 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1153 initNames2TargetIndices();
1154 auto IndexInfo = Names2TargetIndices.find(Name);
1155 if (IndexInfo == Names2TargetIndices.end())
1157 Index = IndexInfo->second;
1161 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1162 MachineFunction &MF, StringRef Src,
1163 const PerFunctionMIParsingState &PFS,
1164 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1165 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1168 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1169 MachineFunction &MF, StringRef Src,
1170 const PerFunctionMIParsingState &PFS,
1171 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1172 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1175 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1176 MachineFunction &MF, StringRef Src,
1177 const PerFunctionMIParsingState &PFS,
1178 const SlotMapping &IRSlots,
1179 SMDiagnostic &Error) {
1180 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1181 .parseStandaloneNamedRegister(Reg);
1184 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1185 MachineFunction &MF, StringRef Src,
1186 const PerFunctionMIParsingState &PFS,
1187 const SlotMapping &IRSlots,
1188 SMDiagnostic &Error) {
1189 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1190 .parseStandaloneVirtualRegister(Reg);
1193 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1194 MachineFunction &MF, StringRef Src,
1195 const PerFunctionMIParsingState &PFS,
1196 const SlotMapping &IRSlots,
1197 SMDiagnostic &Error) {
1198 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1199 .parseStandaloneIRBlockReference(BB);