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;
73 /// Maps from direct target flag names to the direct target flag values.
74 StringMap<unsigned> Names2DirectTargetFlags;
77 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
78 StringRef Source, const PerFunctionMIParsingState &PFS,
79 const SlotMapping &IRSlots);
83 /// Report an error at the current location with the given message.
85 /// This function always return true.
86 bool error(const Twine &Msg);
88 /// Report an error at the given location with the given message.
90 /// This function always return true.
91 bool error(StringRef::iterator Loc, const Twine &Msg);
94 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
95 bool parseBasicBlocks();
96 bool parse(MachineInstr *&MI);
97 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
98 bool parseStandaloneNamedRegister(unsigned &Reg);
99 bool parseStandaloneVirtualRegister(unsigned &Reg);
102 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
103 bool parseBasicBlock(MachineBasicBlock &MBB);
104 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
105 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
107 bool parseRegister(unsigned &Reg);
108 bool parseRegisterFlag(unsigned &Flags);
109 bool parseSubRegisterIndex(unsigned &SubReg);
110 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
111 bool parseImmediateOperand(MachineOperand &Dest);
112 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
113 bool parseTypedImmediateOperand(MachineOperand &Dest);
114 bool parseFPImmediateOperand(MachineOperand &Dest);
115 bool parseMBBReference(MachineBasicBlock *&MBB);
116 bool parseMBBOperand(MachineOperand &Dest);
117 bool parseStackObjectOperand(MachineOperand &Dest);
118 bool parseFixedStackFrameIndex(int &FI);
119 bool parseFixedStackObjectOperand(MachineOperand &Dest);
120 bool parseGlobalValue(GlobalValue *&GV);
121 bool parseGlobalAddressOperand(MachineOperand &Dest);
122 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
123 bool parseJumpTableIndexOperand(MachineOperand &Dest);
124 bool parseExternalSymbolOperand(MachineOperand &Dest);
125 bool parseMDNode(MDNode *&Node);
126 bool parseMetadataOperand(MachineOperand &Dest);
127 bool parseCFIOffset(int &Offset);
128 bool parseCFIRegister(unsigned &Reg);
129 bool parseCFIOperand(MachineOperand &Dest);
130 bool parseIRBlock(BasicBlock *&BB, const Function &F);
131 bool parseBlockAddressOperand(MachineOperand &Dest);
132 bool parseTargetIndexOperand(MachineOperand &Dest);
133 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
134 bool parseMachineOperand(MachineOperand &Dest);
135 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
136 bool parseOffset(int64_t &Offset);
137 bool parseAlignment(unsigned &Alignment);
138 bool parseOperandsOffset(MachineOperand &Op);
139 bool parseIRValue(Value *&V);
140 bool parseMemoryOperandFlag(unsigned &Flags);
141 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
142 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
143 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
146 /// Convert the integer literal in the current token into an unsigned integer.
148 /// Return true if an error occurred.
149 bool getUnsigned(unsigned &Result);
151 /// Convert the integer literal in the current token into an uint64.
153 /// Return true if an error occurred.
154 bool getUint64(uint64_t &Result);
156 /// If the current token is of the given kind, consume it and return false.
157 /// Otherwise report an error and return true.
158 bool expectAndConsume(MIToken::TokenKind TokenKind);
160 /// If the current token is of the given kind, consume it and return true.
161 /// Otherwise return false.
162 bool consumeIfPresent(MIToken::TokenKind TokenKind);
164 void initNames2InstrOpCodes();
166 /// Try to convert an instruction name to an opcode. Return true if the
167 /// instruction name is invalid.
168 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
170 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
172 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
173 const MCInstrDesc &MCID);
175 void initNames2Regs();
177 /// Try to convert a register name to a register number. Return true if the
178 /// register name is invalid.
179 bool getRegisterByName(StringRef RegName, unsigned &Reg);
181 void initNames2RegMasks();
183 /// Check if the given identifier is a name of a register mask.
185 /// Return null if the identifier isn't a register mask.
186 const uint32_t *getRegMask(StringRef Identifier);
188 void initNames2SubRegIndices();
190 /// Check if the given identifier is a name of a subregister index.
192 /// Return 0 if the name isn't a subregister index class.
193 unsigned getSubRegIndex(StringRef Name);
195 const BasicBlock *getIRBlock(unsigned Slot);
196 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
198 void initNames2TargetIndices();
200 /// Try to convert a name of target index to the corresponding target index.
202 /// Return true if the name isn't a name of a target index.
203 bool getTargetIndex(StringRef Name, int &Index);
205 void initNames2DirectTargetFlags();
207 /// Try to convert a name of a direct target flag to the corresponding
210 /// Return true if the name isn't a name of a direct flag.
211 bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
214 } // end anonymous namespace
216 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
217 StringRef Source, const PerFunctionMIParsingState &PFS,
218 const SlotMapping &IRSlots)
219 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
220 PFS(PFS), IRSlots(IRSlots) {}
222 void MIParser::lex() {
223 CurrentSource = lexMIToken(
224 CurrentSource, Token,
225 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
228 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
230 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
231 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
232 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
233 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
234 // Create an ordinary diagnostic when the source manager's buffer is the
236 Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
239 // Create a diagnostic for a YAML string literal.
240 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
241 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
246 static const char *toString(MIToken::TokenKind TokenKind) {
254 case MIToken::lparen:
256 case MIToken::rparen:
259 return "<unknown token>";
263 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
264 if (Token.isNot(TokenKind))
265 return error(Twine("expected ") + toString(TokenKind));
270 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
271 if (Token.isNot(TokenKind))
277 bool MIParser::parseBasicBlockDefinition(
278 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
279 assert(Token.is(MIToken::MachineBasicBlockLabel));
283 auto Loc = Token.location();
284 auto Name = Token.stringValue();
286 bool HasAddressTaken = false;
287 bool IsLandingPad = false;
288 unsigned Alignment = 0;
289 BasicBlock *BB = nullptr;
290 if (consumeIfPresent(MIToken::lparen)) {
292 // TODO: Report an error when multiple same attributes are specified.
293 switch (Token.kind()) {
294 case MIToken::kw_address_taken:
295 HasAddressTaken = true;
298 case MIToken::kw_landing_pad:
302 case MIToken::kw_align:
303 if (parseAlignment(Alignment))
306 case MIToken::IRBlock:
307 // TODO: Report an error when both name and ir block are specified.
308 if (parseIRBlock(BB, *MF.getFunction()))
315 } while (consumeIfPresent(MIToken::comma));
316 if (expectAndConsume(MIToken::rparen))
319 if (expectAndConsume(MIToken::colon))
323 BB = dyn_cast_or_null<BasicBlock>(
324 MF.getFunction()->getValueSymbolTable().lookup(Name));
326 return error(Loc, Twine("basic block '") + Name +
327 "' is not defined in the function '" +
330 auto *MBB = MF.CreateMachineBasicBlock(BB);
331 MF.insert(MF.end(), MBB);
332 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
334 return error(Loc, Twine("redefinition of machine basic block with id #") +
337 MBB->setAlignment(Alignment);
339 MBB->setHasAddressTaken();
340 MBB->setIsLandingPad(IsLandingPad);
344 bool MIParser::parseBasicBlockDefinitions(
345 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
347 // Skip until the first machine basic block.
348 while (Token.is(MIToken::Newline))
350 if (Token.isErrorOrEOF())
351 return Token.isError();
352 if (Token.isNot(MIToken::MachineBasicBlockLabel))
353 return error("expected a basic block definition before instructions");
354 unsigned BraceDepth = 0;
356 if (parseBasicBlockDefinition(MBBSlots))
358 bool IsAfterNewline = false;
359 // Skip until the next machine basic block.
361 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
362 Token.isErrorOrEOF())
364 else if (Token.is(MIToken::MachineBasicBlockLabel))
365 return error("basic block definition should be located at the start of "
367 else if (consumeIfPresent(MIToken::Newline)) {
368 IsAfterNewline = true;
371 IsAfterNewline = false;
372 if (Token.is(MIToken::lbrace))
374 if (Token.is(MIToken::rbrace)) {
376 return error("extraneous closing brace ('}')");
381 // Verify that we closed all of the '{' at the end of a file or a block.
382 if (!Token.isError() && BraceDepth)
383 return error("expected '}'"); // FIXME: Report a note that shows '{'.
384 } while (!Token.isErrorOrEOF());
385 return Token.isError();
388 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
389 assert(Token.is(MIToken::kw_liveins));
391 if (expectAndConsume(MIToken::colon))
393 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
396 if (Token.isNot(MIToken::NamedRegister))
397 return error("expected a named register");
399 if (parseRegister(Reg))
403 } while (consumeIfPresent(MIToken::comma));
407 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
408 assert(Token.is(MIToken::kw_successors));
410 if (expectAndConsume(MIToken::colon))
412 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
415 if (Token.isNot(MIToken::MachineBasicBlock))
416 return error("expected a machine basic block reference");
417 MachineBasicBlock *SuccMBB = nullptr;
418 if (parseMBBReference(SuccMBB))
422 if (consumeIfPresent(MIToken::lparen)) {
423 if (Token.isNot(MIToken::IntegerLiteral))
424 return error("expected an integer literal after '('");
425 if (getUnsigned(Weight))
428 if (expectAndConsume(MIToken::rparen))
431 MBB.addSuccessor(SuccMBB, Weight);
432 } while (consumeIfPresent(MIToken::comma));
436 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) {
437 // Skip the definition.
438 assert(Token.is(MIToken::MachineBasicBlockLabel));
440 if (consumeIfPresent(MIToken::lparen)) {
441 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
443 consumeIfPresent(MIToken::rparen);
445 consumeIfPresent(MIToken::colon);
447 // Parse the liveins and successors.
448 // N.B: Multiple lists of successors and liveins are allowed and they're
455 // liveins: %edi, %esi
457 if (Token.is(MIToken::kw_successors)) {
458 if (parseBasicBlockSuccessors(MBB))
460 } else if (Token.is(MIToken::kw_liveins)) {
461 if (parseBasicBlockLiveins(MBB))
463 } else if (consumeIfPresent(MIToken::Newline)) {
467 if (!Token.isNewlineOrEOF())
468 return error("expected line break at the end of a list");
472 // Parse the instructions.
473 bool IsInBundle = false;
474 MachineInstr *PrevMI = nullptr;
476 if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof))
478 else if (consumeIfPresent(MIToken::Newline))
480 if (consumeIfPresent(MIToken::rbrace)) {
481 // The first parsing pass should verify that all closing '}' have an
487 MachineInstr *MI = nullptr;
490 MBB.insert(MBB.end(), MI);
492 PrevMI->setFlag(MachineInstr::BundledSucc);
493 MI->setFlag(MachineInstr::BundledPred);
496 if (Token.is(MIToken::lbrace)) {
498 return error("nested instruction bundles are not allowed");
500 // This instruction is the start of the bundle.
501 MI->setFlag(MachineInstr::BundledSucc);
503 if (!Token.is(MIToken::Newline))
504 // The next instruction can be on the same line.
507 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
513 bool MIParser::parseBasicBlocks() {
515 // Skip until the first machine basic block.
516 while (Token.is(MIToken::Newline))
518 if (Token.isErrorOrEOF())
519 return Token.isError();
520 // The first parsing pass should have verified that this token is a MBB label
521 // in the 'parseBasicBlockDefinitions' method.
522 assert(Token.is(MIToken::MachineBasicBlockLabel));
524 MachineBasicBlock *MBB = nullptr;
525 if (parseMBBReference(MBB))
527 if (parseBasicBlock(*MBB))
529 // The method 'parseBasicBlock' should parse the whole block until the next
530 // block or the end of file.
531 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
532 } while (Token.isNot(MIToken::Eof));
536 bool MIParser::parse(MachineInstr *&MI) {
537 // Parse any register operands before '='
538 MachineOperand MO = MachineOperand::CreateImm(0);
539 SmallVector<MachineOperandWithLocation, 8> Operands;
540 while (Token.isRegister() || Token.isRegisterFlag()) {
541 auto Loc = Token.location();
542 if (parseRegisterOperand(MO, /*IsDef=*/true))
544 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
545 if (Token.isNot(MIToken::comma))
549 if (!Operands.empty() && expectAndConsume(MIToken::equal))
552 unsigned OpCode, Flags = 0;
553 if (Token.isError() || parseInstruction(OpCode, Flags))
556 // Parse the remaining machine operands.
557 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
558 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
559 auto Loc = Token.location();
560 if (parseMachineOperandAndTargetFlags(MO))
562 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
563 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
564 Token.is(MIToken::lbrace))
566 if (Token.isNot(MIToken::comma))
567 return error("expected ',' before the next machine operand");
571 DebugLoc DebugLocation;
572 if (Token.is(MIToken::kw_debug_location)) {
574 if (Token.isNot(MIToken::exclaim))
575 return error("expected a metadata node after 'debug-location'");
576 MDNode *Node = nullptr;
577 if (parseMDNode(Node))
579 DebugLocation = DebugLoc(Node);
582 // Parse the machine memory operands.
583 SmallVector<MachineMemOperand *, 2> MemOperands;
584 if (Token.is(MIToken::coloncolon)) {
586 while (!Token.isNewlineOrEOF()) {
587 MachineMemOperand *MemOp = nullptr;
588 if (parseMachineMemoryOperand(MemOp))
590 MemOperands.push_back(MemOp);
591 if (Token.isNewlineOrEOF())
593 if (Token.isNot(MIToken::comma))
594 return error("expected ',' before the next machine memory operand");
599 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
600 if (!MCID.isVariadic()) {
601 // FIXME: Move the implicit operand verification to the machine verifier.
602 if (verifyImplicitOperands(Operands, MCID))
606 // TODO: Check for extraneous machine operands.
607 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
609 for (const auto &Operand : Operands)
610 MI->addOperand(MF, Operand.Operand);
611 if (MemOperands.empty())
613 MachineInstr::mmo_iterator MemRefs =
614 MF.allocateMemRefsArray(MemOperands.size());
615 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
616 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
620 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
622 if (Token.isNot(MIToken::MachineBasicBlock))
623 return error("expected a machine basic block reference");
624 if (parseMBBReference(MBB))
627 if (Token.isNot(MIToken::Eof))
629 "expected end of string after the machine basic block reference");
633 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
635 if (Token.isNot(MIToken::NamedRegister))
636 return error("expected a named register");
637 if (parseRegister(Reg))
640 if (Token.isNot(MIToken::Eof))
641 return error("expected end of string after the register reference");
645 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
647 if (Token.isNot(MIToken::VirtualRegister))
648 return error("expected a virtual register");
649 if (parseRegister(Reg))
652 if (Token.isNot(MIToken::Eof))
653 return error("expected end of string after the register reference");
657 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
658 assert(MO.isImplicit());
659 return MO.isDef() ? "implicit-def" : "implicit";
662 static std::string getRegisterName(const TargetRegisterInfo *TRI,
664 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
665 return StringRef(TRI->getName(Reg)).lower();
668 bool MIParser::verifyImplicitOperands(
669 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
671 // We can't verify call instructions as they can contain arbitrary implicit
672 // register and register mask operands.
675 // Gather all the expected implicit operands.
676 SmallVector<MachineOperand, 4> ImplicitOperands;
677 if (MCID.ImplicitDefs)
678 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
679 ImplicitOperands.push_back(
680 MachineOperand::CreateReg(*ImpDefs, true, true));
681 if (MCID.ImplicitUses)
682 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
683 ImplicitOperands.push_back(
684 MachineOperand::CreateReg(*ImpUses, false, true));
686 const auto *TRI = MF.getSubtarget().getRegisterInfo();
687 assert(TRI && "Expected target register info");
688 size_t I = ImplicitOperands.size(), J = Operands.size();
693 const auto &ImplicitOperand = ImplicitOperands[I];
694 const auto &Operand = Operands[J].Operand;
695 if (ImplicitOperand.isIdenticalTo(Operand))
697 if (Operand.isReg() && Operand.isImplicit()) {
698 return error(Operands[J].Begin,
699 Twine("expected an implicit register operand '") +
700 printImplicitRegisterFlag(ImplicitOperand) + " %" +
701 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
704 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
705 // insead of reporting an error at this location:
708 // report the error at the following location:
711 return error(J < Operands.size() ? Operands[J].End : Token.location(),
712 Twine("missing implicit register operand '") +
713 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
714 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
719 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
720 if (Token.is(MIToken::kw_frame_setup)) {
721 Flags |= MachineInstr::FrameSetup;
724 if (Token.isNot(MIToken::Identifier))
725 return error("expected a machine instruction");
726 StringRef InstrName = Token.stringValue();
727 if (parseInstrName(InstrName, OpCode))
728 return error(Twine("unknown machine instruction name '") + InstrName + "'");
733 bool MIParser::parseRegister(unsigned &Reg) {
734 switch (Token.kind()) {
735 case MIToken::underscore:
738 case MIToken::NamedRegister: {
739 StringRef Name = Token.stringValue();
740 if (getRegisterByName(Name, Reg))
741 return error(Twine("unknown register name '") + Name + "'");
744 case MIToken::VirtualRegister: {
748 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
749 if (RegInfo == PFS.VirtualRegisterSlots.end())
750 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
752 Reg = RegInfo->second;
755 // TODO: Parse other register kinds.
757 llvm_unreachable("The current token should be a register");
762 bool MIParser::parseRegisterFlag(unsigned &Flags) {
763 const unsigned OldFlags = Flags;
764 switch (Token.kind()) {
765 case MIToken::kw_implicit:
766 Flags |= RegState::Implicit;
768 case MIToken::kw_implicit_define:
769 Flags |= RegState::ImplicitDefine;
771 case MIToken::kw_dead:
772 Flags |= RegState::Dead;
774 case MIToken::kw_killed:
775 Flags |= RegState::Kill;
777 case MIToken::kw_undef:
778 Flags |= RegState::Undef;
780 case MIToken::kw_internal:
781 Flags |= RegState::InternalRead;
783 case MIToken::kw_early_clobber:
784 Flags |= RegState::EarlyClobber;
786 case MIToken::kw_debug_use:
787 Flags |= RegState::Debug;
790 llvm_unreachable("The current token should be a register flag");
792 if (OldFlags == Flags)
793 // We know that the same flag is specified more than once when the flags
795 return error("duplicate '" + Token.stringValue() + "' register flag");
800 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
801 assert(Token.is(MIToken::colon));
803 if (Token.isNot(MIToken::Identifier))
804 return error("expected a subregister index after ':'");
805 auto Name = Token.stringValue();
806 SubReg = getSubRegIndex(Name);
808 return error(Twine("use of unknown subregister index '") + Name + "'");
813 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
815 unsigned Flags = IsDef ? RegState::Define : 0;
816 while (Token.isRegisterFlag()) {
817 if (parseRegisterFlag(Flags))
820 if (!Token.isRegister())
821 return error("expected a register after register flags");
822 if (parseRegister(Reg))
826 if (Token.is(MIToken::colon)) {
827 if (parseSubRegisterIndex(SubReg))
830 Dest = MachineOperand::CreateReg(
831 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
832 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
833 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
834 Flags & RegState::InternalRead);
838 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
839 assert(Token.is(MIToken::IntegerLiteral));
840 const APSInt &Int = Token.integerValue();
841 if (Int.getMinSignedBits() > 64)
842 return error("integer literal is too large to be an immediate operand");
843 Dest = MachineOperand::CreateImm(Int.getExtValue());
848 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
849 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
852 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
854 return error(Loc + Err.getColumnNo(), Err.getMessage());
858 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
859 assert(Token.is(MIToken::IntegerType));
860 auto Loc = Token.location();
862 if (Token.isNot(MIToken::IntegerLiteral))
863 return error("expected an integer literal");
864 const Constant *C = nullptr;
865 if (parseIRConstant(Loc, C))
867 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
871 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
872 auto Loc = Token.location();
874 if (Token.isNot(MIToken::FloatingPointLiteral))
875 return error("expected a floating point literal");
876 const Constant *C = nullptr;
877 if (parseIRConstant(Loc, C))
879 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
883 bool MIParser::getUnsigned(unsigned &Result) {
884 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
885 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
886 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
888 return error("expected 32-bit integer (too large)");
893 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
894 assert(Token.is(MIToken::MachineBasicBlock) ||
895 Token.is(MIToken::MachineBasicBlockLabel));
897 if (getUnsigned(Number))
899 auto MBBInfo = PFS.MBBSlots.find(Number);
900 if (MBBInfo == PFS.MBBSlots.end())
901 return error(Twine("use of undefined machine basic block #") +
903 MBB = MBBInfo->second;
904 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
905 return error(Twine("the name of machine basic block #") + Twine(Number) +
906 " isn't '" + Token.stringValue() + "'");
910 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
911 MachineBasicBlock *MBB;
912 if (parseMBBReference(MBB))
914 Dest = MachineOperand::CreateMBB(MBB);
919 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
920 assert(Token.is(MIToken::StackObject));
924 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
925 if (ObjectInfo == PFS.StackObjectSlots.end())
926 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
929 if (const auto *Alloca =
930 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
931 Name = Alloca->getName();
932 if (!Token.stringValue().empty() && Token.stringValue() != Name)
933 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
934 "' isn't '" + Token.stringValue() + "'");
936 Dest = MachineOperand::CreateFI(ObjectInfo->second);
940 bool MIParser::parseFixedStackFrameIndex(int &FI) {
941 assert(Token.is(MIToken::FixedStackObject));
945 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
946 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
947 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
950 FI = ObjectInfo->second;
954 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
956 if (parseFixedStackFrameIndex(FI))
958 Dest = MachineOperand::CreateFI(FI);
962 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
963 switch (Token.kind()) {
964 case MIToken::NamedGlobalValue: {
965 const Module *M = MF.getFunction()->getParent();
966 GV = M->getNamedValue(Token.stringValue());
968 return error(Twine("use of undefined global value '") + Token.range() +
972 case MIToken::GlobalValue: {
974 if (getUnsigned(GVIdx))
976 if (GVIdx >= IRSlots.GlobalValues.size())
977 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
979 GV = IRSlots.GlobalValues[GVIdx];
983 llvm_unreachable("The current token should be a global value");
988 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
989 GlobalValue *GV = nullptr;
990 if (parseGlobalValue(GV))
993 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
994 if (parseOperandsOffset(Dest))
999 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1000 assert(Token.is(MIToken::ConstantPoolItem));
1002 if (getUnsigned(ID))
1004 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1005 if (ConstantInfo == PFS.ConstantPoolSlots.end())
1006 return error("use of undefined constant '%const." + Twine(ID) + "'");
1008 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1009 if (parseOperandsOffset(Dest))
1014 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1015 assert(Token.is(MIToken::JumpTableIndex));
1017 if (getUnsigned(ID))
1019 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1020 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1021 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1023 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1027 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1028 assert(Token.is(MIToken::ExternalSymbol));
1029 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1031 Dest = MachineOperand::CreateES(Symbol);
1032 if (parseOperandsOffset(Dest))
1037 bool MIParser::parseMDNode(MDNode *&Node) {
1038 assert(Token.is(MIToken::exclaim));
1039 auto Loc = Token.location();
1041 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1042 return error("expected metadata id after '!'");
1044 if (getUnsigned(ID))
1046 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1047 if (NodeInfo == IRSlots.MetadataNodes.end())
1048 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1050 Node = NodeInfo->second.get();
1054 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1055 MDNode *Node = nullptr;
1056 if (parseMDNode(Node))
1058 Dest = MachineOperand::CreateMetadata(Node);
1062 bool MIParser::parseCFIOffset(int &Offset) {
1063 if (Token.isNot(MIToken::IntegerLiteral))
1064 return error("expected a cfi offset");
1065 if (Token.integerValue().getMinSignedBits() > 32)
1066 return error("expected a 32 bit integer (the cfi offset is too large)");
1067 Offset = (int)Token.integerValue().getExtValue();
1072 bool MIParser::parseCFIRegister(unsigned &Reg) {
1073 if (Token.isNot(MIToken::NamedRegister))
1074 return error("expected a cfi register");
1076 if (parseRegister(LLVMReg))
1078 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1079 assert(TRI && "Expected target register info");
1080 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1082 return error("invalid DWARF register");
1083 Reg = (unsigned)DwarfReg;
1088 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1089 auto Kind = Token.kind();
1091 auto &MMI = MF.getMMI();
1096 case MIToken::kw_cfi_same_value:
1097 if (parseCFIRegister(Reg))
1100 MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1102 case MIToken::kw_cfi_offset:
1103 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1104 parseCFIOffset(Offset))
1107 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1109 case MIToken::kw_cfi_def_cfa_register:
1110 if (parseCFIRegister(Reg))
1113 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1115 case MIToken::kw_cfi_def_cfa_offset:
1116 if (parseCFIOffset(Offset))
1118 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1119 CFIIndex = MMI.addFrameInst(
1120 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1122 case MIToken::kw_cfi_def_cfa:
1123 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1124 parseCFIOffset(Offset))
1126 // NB: MCCFIInstruction::createDefCfa negates the offset.
1128 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1131 // TODO: Parse the other CFI operands.
1132 llvm_unreachable("The current token should be a cfi operand");
1134 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1138 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1139 switch (Token.kind()) {
1140 case MIToken::NamedIRBlock: {
1141 BB = dyn_cast_or_null<BasicBlock>(
1142 F.getValueSymbolTable().lookup(Token.stringValue()));
1144 return error(Twine("use of undefined IR block '") + Token.range() + "'");
1147 case MIToken::IRBlock: {
1148 unsigned SlotNumber = 0;
1149 if (getUnsigned(SlotNumber))
1151 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1153 return error(Twine("use of undefined IR block '%ir-block.") +
1154 Twine(SlotNumber) + "'");
1158 llvm_unreachable("The current token should be an IR block reference");
1163 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1164 assert(Token.is(MIToken::kw_blockaddress));
1166 if (expectAndConsume(MIToken::lparen))
1168 if (Token.isNot(MIToken::GlobalValue) &&
1169 Token.isNot(MIToken::NamedGlobalValue))
1170 return error("expected a global value");
1171 GlobalValue *GV = nullptr;
1172 if (parseGlobalValue(GV))
1174 auto *F = dyn_cast<Function>(GV);
1176 return error("expected an IR function reference");
1178 if (expectAndConsume(MIToken::comma))
1180 BasicBlock *BB = nullptr;
1181 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1182 return error("expected an IR block reference");
1183 if (parseIRBlock(BB, *F))
1186 if (expectAndConsume(MIToken::rparen))
1188 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1189 if (parseOperandsOffset(Dest))
1194 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1195 assert(Token.is(MIToken::kw_target_index));
1197 if (expectAndConsume(MIToken::lparen))
1199 if (Token.isNot(MIToken::Identifier))
1200 return error("expected the name of the target index");
1202 if (getTargetIndex(Token.stringValue(), Index))
1203 return error("use of undefined target index '" + Token.stringValue() + "'");
1205 if (expectAndConsume(MIToken::rparen))
1207 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1208 if (parseOperandsOffset(Dest))
1213 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1214 assert(Token.is(MIToken::kw_liveout));
1215 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1216 assert(TRI && "Expected target register info");
1217 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1219 if (expectAndConsume(MIToken::lparen))
1222 if (Token.isNot(MIToken::NamedRegister))
1223 return error("expected a named register");
1225 if (parseRegister(Reg))
1228 Mask[Reg / 32] |= 1U << (Reg % 32);
1229 // TODO: Report an error if the same register is used more than once.
1230 if (Token.isNot(MIToken::comma))
1234 if (expectAndConsume(MIToken::rparen))
1236 Dest = MachineOperand::CreateRegLiveOut(Mask);
1240 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
1241 switch (Token.kind()) {
1242 case MIToken::kw_implicit:
1243 case MIToken::kw_implicit_define:
1244 case MIToken::kw_dead:
1245 case MIToken::kw_killed:
1246 case MIToken::kw_undef:
1247 case MIToken::kw_internal:
1248 case MIToken::kw_early_clobber:
1249 case MIToken::kw_debug_use:
1250 case MIToken::underscore:
1251 case MIToken::NamedRegister:
1252 case MIToken::VirtualRegister:
1253 return parseRegisterOperand(Dest);
1254 case MIToken::IntegerLiteral:
1255 return parseImmediateOperand(Dest);
1256 case MIToken::IntegerType:
1257 return parseTypedImmediateOperand(Dest);
1258 case MIToken::kw_half:
1259 case MIToken::kw_float:
1260 case MIToken::kw_double:
1261 case MIToken::kw_x86_fp80:
1262 case MIToken::kw_fp128:
1263 case MIToken::kw_ppc_fp128:
1264 return parseFPImmediateOperand(Dest);
1265 case MIToken::MachineBasicBlock:
1266 return parseMBBOperand(Dest);
1267 case MIToken::StackObject:
1268 return parseStackObjectOperand(Dest);
1269 case MIToken::FixedStackObject:
1270 return parseFixedStackObjectOperand(Dest);
1271 case MIToken::GlobalValue:
1272 case MIToken::NamedGlobalValue:
1273 return parseGlobalAddressOperand(Dest);
1274 case MIToken::ConstantPoolItem:
1275 return parseConstantPoolIndexOperand(Dest);
1276 case MIToken::JumpTableIndex:
1277 return parseJumpTableIndexOperand(Dest);
1278 case MIToken::ExternalSymbol:
1279 return parseExternalSymbolOperand(Dest);
1280 case MIToken::exclaim:
1281 return parseMetadataOperand(Dest);
1282 case MIToken::kw_cfi_same_value:
1283 case MIToken::kw_cfi_offset:
1284 case MIToken::kw_cfi_def_cfa_register:
1285 case MIToken::kw_cfi_def_cfa_offset:
1286 case MIToken::kw_cfi_def_cfa:
1287 return parseCFIOperand(Dest);
1288 case MIToken::kw_blockaddress:
1289 return parseBlockAddressOperand(Dest);
1290 case MIToken::kw_target_index:
1291 return parseTargetIndexOperand(Dest);
1292 case MIToken::kw_liveout:
1293 return parseLiveoutRegisterMaskOperand(Dest);
1294 case MIToken::Error:
1296 case MIToken::Identifier:
1297 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1298 Dest = MachineOperand::CreateRegMask(RegMask);
1304 // TODO: parse the other machine operands.
1305 return error("expected a machine operand");
1310 bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1312 bool HasTargetFlags = false;
1313 if (Token.is(MIToken::kw_target_flags)) {
1314 HasTargetFlags = true;
1316 if (expectAndConsume(MIToken::lparen))
1318 if (Token.isNot(MIToken::Identifier))
1319 return error("expected the name of the target flag");
1320 if (getDirectTargetFlag(Token.stringValue(), TF))
1321 return error("use of undefined target flag '" + Token.stringValue() +
1324 // TODO: Parse target's bit target flags.
1325 if (expectAndConsume(MIToken::rparen))
1328 auto Loc = Token.location();
1329 if (parseMachineOperand(Dest))
1331 if (!HasTargetFlags)
1334 return error(Loc, "register operands can't have target flags");
1335 Dest.setTargetFlags(TF);
1339 bool MIParser::parseOffset(int64_t &Offset) {
1340 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1342 StringRef Sign = Token.range();
1343 bool IsNegative = Token.is(MIToken::minus);
1345 if (Token.isNot(MIToken::IntegerLiteral))
1346 return error("expected an integer literal after '" + Sign + "'");
1347 if (Token.integerValue().getMinSignedBits() > 64)
1348 return error("expected 64-bit integer (too large)");
1349 Offset = Token.integerValue().getExtValue();
1356 bool MIParser::parseAlignment(unsigned &Alignment) {
1357 assert(Token.is(MIToken::kw_align));
1359 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1360 return error("expected an integer literal after 'align'");
1361 if (getUnsigned(Alignment))
1367 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1369 if (parseOffset(Offset))
1371 Op.setOffset(Offset);
1375 bool MIParser::parseIRValue(Value *&V) {
1376 switch (Token.kind()) {
1377 case MIToken::NamedIRValue: {
1378 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1380 V = MF.getFunction()->getParent()->getValueSymbolTable().lookup(
1381 Token.stringValue());
1383 return error(Twine("use of undefined IR value '") + Token.range() + "'");
1386 // TODO: Parse unnamed IR value references.
1388 llvm_unreachable("The current token should be an IR block reference");
1393 bool MIParser::getUint64(uint64_t &Result) {
1394 assert(Token.hasIntegerValue());
1395 if (Token.integerValue().getActiveBits() > 64)
1396 return error("expected 64-bit integer (too large)");
1397 Result = Token.integerValue().getZExtValue();
1401 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1402 const unsigned OldFlags = Flags;
1403 switch (Token.kind()) {
1404 case MIToken::kw_volatile:
1405 Flags |= MachineMemOperand::MOVolatile;
1407 case MIToken::kw_non_temporal:
1408 Flags |= MachineMemOperand::MONonTemporal;
1410 case MIToken::kw_invariant:
1411 Flags |= MachineMemOperand::MOInvariant;
1413 // TODO: parse the target specific memory operand flags.
1415 llvm_unreachable("The current token should be a memory operand flag");
1417 if (OldFlags == Flags)
1418 // We know that the same flag is specified more than once when the flags
1419 // weren't modified.
1420 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1425 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1426 switch (Token.kind()) {
1427 case MIToken::kw_stack:
1428 PSV = MF.getPSVManager().getStack();
1430 case MIToken::kw_got:
1431 PSV = MF.getPSVManager().getGOT();
1433 case MIToken::kw_jump_table:
1434 PSV = MF.getPSVManager().getJumpTable();
1436 case MIToken::kw_constant_pool:
1437 PSV = MF.getPSVManager().getConstantPool();
1439 case MIToken::FixedStackObject: {
1441 if (parseFixedStackFrameIndex(FI))
1443 PSV = MF.getPSVManager().getFixedStack(FI);
1444 // The token was already consumed, so use return here instead of break.
1447 case MIToken::GlobalValue:
1448 case MIToken::NamedGlobalValue: {
1449 GlobalValue *GV = nullptr;
1450 if (parseGlobalValue(GV))
1452 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
1455 case MIToken::ExternalSymbol:
1456 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
1457 MF.createExternalSymbolName(Token.stringValue()));
1460 llvm_unreachable("The current token should be pseudo source value");
1466 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
1467 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
1468 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1469 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::GlobalValue) ||
1470 Token.is(MIToken::NamedGlobalValue) ||
1471 Token.is(MIToken::ExternalSymbol)) {
1472 const PseudoSourceValue *PSV = nullptr;
1473 if (parseMemoryPseudoSourceValue(PSV))
1476 if (parseOffset(Offset))
1478 Dest = MachinePointerInfo(PSV, Offset);
1481 if (Token.isNot(MIToken::NamedIRValue))
1482 return error("expected an IR value reference");
1484 if (parseIRValue(V))
1486 if (!V->getType()->isPointerTy())
1487 return error("expected a pointer IR value");
1490 if (parseOffset(Offset))
1492 Dest = MachinePointerInfo(V, Offset);
1496 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1497 if (expectAndConsume(MIToken::lparen))
1500 while (Token.isMemoryOperandFlag()) {
1501 if (parseMemoryOperandFlag(Flags))
1504 if (Token.isNot(MIToken::Identifier) ||
1505 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1506 return error("expected 'load' or 'store' memory operation");
1507 if (Token.stringValue() == "load")
1508 Flags |= MachineMemOperand::MOLoad;
1510 Flags |= MachineMemOperand::MOStore;
1513 if (Token.isNot(MIToken::IntegerLiteral))
1514 return error("expected the size integer literal after memory operation");
1516 if (getUint64(Size))
1520 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1521 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1522 return error(Twine("expected '") + Word + "'");
1525 MachinePointerInfo Ptr = MachinePointerInfo();
1526 if (parseMachinePointerInfo(Ptr))
1528 unsigned BaseAlignment = Size;
1530 while (consumeIfPresent(MIToken::comma)) {
1531 switch (Token.kind()) {
1532 case MIToken::kw_align:
1533 if (parseAlignment(BaseAlignment))
1536 case MIToken::md_tbaa:
1538 if (parseMDNode(AAInfo.TBAA))
1541 case MIToken::md_alias_scope:
1543 if (parseMDNode(AAInfo.Scope))
1546 // TODO: Parse AA NoAlias metadata.
1547 // TODO: Parse the ranges metadata.
1548 // TODO: Report an error on duplicate metadata nodes.
1550 return error("expected 'align' or '!tbaa' or '!alias.scope'");
1553 if (expectAndConsume(MIToken::rparen))
1555 Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo);
1559 void MIParser::initNames2InstrOpCodes() {
1560 if (!Names2InstrOpCodes.empty())
1562 const auto *TII = MF.getSubtarget().getInstrInfo();
1563 assert(TII && "Expected target instruction info");
1564 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1565 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1568 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1569 initNames2InstrOpCodes();
1570 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1571 if (InstrInfo == Names2InstrOpCodes.end())
1573 OpCode = InstrInfo->getValue();
1577 void MIParser::initNames2Regs() {
1578 if (!Names2Regs.empty())
1580 // The '%noreg' register is the register 0.
1581 Names2Regs.insert(std::make_pair("noreg", 0));
1582 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1583 assert(TRI && "Expected target register info");
1584 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1586 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1589 assert(WasInserted && "Expected registers to be unique case-insensitively");
1593 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1595 auto RegInfo = Names2Regs.find(RegName);
1596 if (RegInfo == Names2Regs.end())
1598 Reg = RegInfo->getValue();
1602 void MIParser::initNames2RegMasks() {
1603 if (!Names2RegMasks.empty())
1605 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1606 assert(TRI && "Expected target register info");
1607 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1608 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1609 assert(RegMasks.size() == RegMaskNames.size());
1610 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1611 Names2RegMasks.insert(
1612 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1615 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1616 initNames2RegMasks();
1617 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1618 if (RegMaskInfo == Names2RegMasks.end())
1620 return RegMaskInfo->getValue();
1623 void MIParser::initNames2SubRegIndices() {
1624 if (!Names2SubRegIndices.empty())
1626 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1627 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1628 Names2SubRegIndices.insert(
1629 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1632 unsigned MIParser::getSubRegIndex(StringRef Name) {
1633 initNames2SubRegIndices();
1634 auto SubRegInfo = Names2SubRegIndices.find(Name);
1635 if (SubRegInfo == Names2SubRegIndices.end())
1637 return SubRegInfo->getValue();
1640 static void initSlots2BasicBlocks(
1642 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1643 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1644 MST.incorporateFunction(F);
1645 for (auto &BB : F) {
1648 int Slot = MST.getLocalSlot(&BB);
1651 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1655 static const BasicBlock *getIRBlockFromSlot(
1657 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1658 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1659 if (BlockInfo == Slots2BasicBlocks.end())
1661 return BlockInfo->second;
1664 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1665 if (Slots2BasicBlocks.empty())
1666 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1667 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1670 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1671 if (&F == MF.getFunction())
1672 return getIRBlock(Slot);
1673 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1674 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1675 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1678 void MIParser::initNames2TargetIndices() {
1679 if (!Names2TargetIndices.empty())
1681 const auto *TII = MF.getSubtarget().getInstrInfo();
1682 assert(TII && "Expected target instruction info");
1683 auto Indices = TII->getSerializableTargetIndices();
1684 for (const auto &I : Indices)
1685 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1688 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1689 initNames2TargetIndices();
1690 auto IndexInfo = Names2TargetIndices.find(Name);
1691 if (IndexInfo == Names2TargetIndices.end())
1693 Index = IndexInfo->second;
1697 void MIParser::initNames2DirectTargetFlags() {
1698 if (!Names2DirectTargetFlags.empty())
1700 const auto *TII = MF.getSubtarget().getInstrInfo();
1701 assert(TII && "Expected target instruction info");
1702 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1703 for (const auto &I : Flags)
1704 Names2DirectTargetFlags.insert(
1705 std::make_pair(StringRef(I.second), I.first));
1708 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1709 initNames2DirectTargetFlags();
1710 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1711 if (FlagInfo == Names2DirectTargetFlags.end())
1713 Flag = FlagInfo->second;
1717 bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1718 PerFunctionMIParsingState &PFS,
1719 const SlotMapping &IRSlots,
1720 SMDiagnostic &Error) {
1722 SM.AddNewSourceBuffer(
1723 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1725 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1726 .parseBasicBlockDefinitions(PFS.MBBSlots);
1729 bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1730 const PerFunctionMIParsingState &PFS,
1731 const SlotMapping &IRSlots,
1732 SMDiagnostic &Error) {
1734 SM.AddNewSourceBuffer(
1735 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1737 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
1740 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1741 MachineFunction &MF, StringRef Src,
1742 const PerFunctionMIParsingState &PFS,
1743 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1744 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1747 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1748 MachineFunction &MF, StringRef Src,
1749 const PerFunctionMIParsingState &PFS,
1750 const SlotMapping &IRSlots,
1751 SMDiagnostic &Error) {
1752 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1753 .parseStandaloneNamedRegister(Reg);
1756 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1757 MachineFunction &MF, StringRef Src,
1758 const PerFunctionMIParsingState &PFS,
1759 const SlotMapping &IRSlots,
1760 SMDiagnostic &Error) {
1761 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1762 .parseStandaloneVirtualRegister(Reg);