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);
100 bool parseStandaloneStackObject(int &FI);
103 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
104 bool parseBasicBlock(MachineBasicBlock &MBB);
105 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
106 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
108 bool parseRegister(unsigned &Reg);
109 bool parseRegisterFlag(unsigned &Flags);
110 bool parseSubRegisterIndex(unsigned &SubReg);
111 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
112 bool parseImmediateOperand(MachineOperand &Dest);
113 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
114 bool parseTypedImmediateOperand(MachineOperand &Dest);
115 bool parseFPImmediateOperand(MachineOperand &Dest);
116 bool parseMBBReference(MachineBasicBlock *&MBB);
117 bool parseMBBOperand(MachineOperand &Dest);
118 bool parseStackFrameIndex(int &FI);
119 bool parseStackObjectOperand(MachineOperand &Dest);
120 bool parseFixedStackFrameIndex(int &FI);
121 bool parseFixedStackObjectOperand(MachineOperand &Dest);
122 bool parseGlobalValue(GlobalValue *&GV);
123 bool parseGlobalAddressOperand(MachineOperand &Dest);
124 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
125 bool parseJumpTableIndexOperand(MachineOperand &Dest);
126 bool parseExternalSymbolOperand(MachineOperand &Dest);
127 bool parseMDNode(MDNode *&Node);
128 bool parseMetadataOperand(MachineOperand &Dest);
129 bool parseCFIOffset(int &Offset);
130 bool parseCFIRegister(unsigned &Reg);
131 bool parseCFIOperand(MachineOperand &Dest);
132 bool parseIRBlock(BasicBlock *&BB, const Function &F);
133 bool parseBlockAddressOperand(MachineOperand &Dest);
134 bool parseTargetIndexOperand(MachineOperand &Dest);
135 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
136 bool parseMachineOperand(MachineOperand &Dest);
137 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
138 bool parseOffset(int64_t &Offset);
139 bool parseAlignment(unsigned &Alignment);
140 bool parseOperandsOffset(MachineOperand &Op);
141 bool parseIRValue(Value *&V);
142 bool parseMemoryOperandFlag(unsigned &Flags);
143 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
144 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
145 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
148 /// Convert the integer literal in the current token into an unsigned integer.
150 /// Return true if an error occurred.
151 bool getUnsigned(unsigned &Result);
153 /// Convert the integer literal in the current token into an uint64.
155 /// Return true if an error occurred.
156 bool getUint64(uint64_t &Result);
158 /// If the current token is of the given kind, consume it and return false.
159 /// Otherwise report an error and return true.
160 bool expectAndConsume(MIToken::TokenKind TokenKind);
162 /// If the current token is of the given kind, consume it and return true.
163 /// Otherwise return false.
164 bool consumeIfPresent(MIToken::TokenKind TokenKind);
166 void initNames2InstrOpCodes();
168 /// Try to convert an instruction name to an opcode. Return true if the
169 /// instruction name is invalid.
170 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
172 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
174 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
175 const MCInstrDesc &MCID);
177 void initNames2Regs();
179 /// Try to convert a register name to a register number. Return true if the
180 /// register name is invalid.
181 bool getRegisterByName(StringRef RegName, unsigned &Reg);
183 void initNames2RegMasks();
185 /// Check if the given identifier is a name of a register mask.
187 /// Return null if the identifier isn't a register mask.
188 const uint32_t *getRegMask(StringRef Identifier);
190 void initNames2SubRegIndices();
192 /// Check if the given identifier is a name of a subregister index.
194 /// Return 0 if the name isn't a subregister index class.
195 unsigned getSubRegIndex(StringRef Name);
197 const BasicBlock *getIRBlock(unsigned Slot);
198 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
200 void initNames2TargetIndices();
202 /// Try to convert a name of target index to the corresponding target index.
204 /// Return true if the name isn't a name of a target index.
205 bool getTargetIndex(StringRef Name, int &Index);
207 void initNames2DirectTargetFlags();
209 /// Try to convert a name of a direct target flag to the corresponding
212 /// Return true if the name isn't a name of a direct flag.
213 bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
216 } // end anonymous namespace
218 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
219 StringRef Source, const PerFunctionMIParsingState &PFS,
220 const SlotMapping &IRSlots)
221 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
222 PFS(PFS), IRSlots(IRSlots) {}
224 void MIParser::lex() {
225 CurrentSource = lexMIToken(
226 CurrentSource, Token,
227 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
230 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
232 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
233 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
234 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
235 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
236 // Create an ordinary diagnostic when the source manager's buffer is the
238 Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
241 // Create a diagnostic for a YAML string literal.
242 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
243 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
248 static const char *toString(MIToken::TokenKind TokenKind) {
256 case MIToken::lparen:
258 case MIToken::rparen:
261 return "<unknown token>";
265 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
266 if (Token.isNot(TokenKind))
267 return error(Twine("expected ") + toString(TokenKind));
272 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
273 if (Token.isNot(TokenKind))
279 bool MIParser::parseBasicBlockDefinition(
280 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
281 assert(Token.is(MIToken::MachineBasicBlockLabel));
285 auto Loc = Token.location();
286 auto Name = Token.stringValue();
288 bool HasAddressTaken = false;
289 bool IsLandingPad = false;
290 unsigned Alignment = 0;
291 BasicBlock *BB = nullptr;
292 if (consumeIfPresent(MIToken::lparen)) {
294 // TODO: Report an error when multiple same attributes are specified.
295 switch (Token.kind()) {
296 case MIToken::kw_address_taken:
297 HasAddressTaken = true;
300 case MIToken::kw_landing_pad:
304 case MIToken::kw_align:
305 if (parseAlignment(Alignment))
308 case MIToken::IRBlock:
309 // TODO: Report an error when both name and ir block are specified.
310 if (parseIRBlock(BB, *MF.getFunction()))
317 } while (consumeIfPresent(MIToken::comma));
318 if (expectAndConsume(MIToken::rparen))
321 if (expectAndConsume(MIToken::colon))
325 BB = dyn_cast_or_null<BasicBlock>(
326 MF.getFunction()->getValueSymbolTable().lookup(Name));
328 return error(Loc, Twine("basic block '") + Name +
329 "' is not defined in the function '" +
332 auto *MBB = MF.CreateMachineBasicBlock(BB);
333 MF.insert(MF.end(), MBB);
334 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
336 return error(Loc, Twine("redefinition of machine basic block with id #") +
339 MBB->setAlignment(Alignment);
341 MBB->setHasAddressTaken();
342 MBB->setIsLandingPad(IsLandingPad);
346 bool MIParser::parseBasicBlockDefinitions(
347 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
349 // Skip until the first machine basic block.
350 while (Token.is(MIToken::Newline))
352 if (Token.isErrorOrEOF())
353 return Token.isError();
354 if (Token.isNot(MIToken::MachineBasicBlockLabel))
355 return error("expected a basic block definition before instructions");
356 unsigned BraceDepth = 0;
358 if (parseBasicBlockDefinition(MBBSlots))
360 bool IsAfterNewline = false;
361 // Skip until the next machine basic block.
363 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
364 Token.isErrorOrEOF())
366 else if (Token.is(MIToken::MachineBasicBlockLabel))
367 return error("basic block definition should be located at the start of "
369 else if (consumeIfPresent(MIToken::Newline)) {
370 IsAfterNewline = true;
373 IsAfterNewline = false;
374 if (Token.is(MIToken::lbrace))
376 if (Token.is(MIToken::rbrace)) {
378 return error("extraneous closing brace ('}')");
383 // Verify that we closed all of the '{' at the end of a file or a block.
384 if (!Token.isError() && BraceDepth)
385 return error("expected '}'"); // FIXME: Report a note that shows '{'.
386 } while (!Token.isErrorOrEOF());
387 return Token.isError();
390 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
391 assert(Token.is(MIToken::kw_liveins));
393 if (expectAndConsume(MIToken::colon))
395 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
398 if (Token.isNot(MIToken::NamedRegister))
399 return error("expected a named register");
401 if (parseRegister(Reg))
405 } while (consumeIfPresent(MIToken::comma));
409 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
410 assert(Token.is(MIToken::kw_successors));
412 if (expectAndConsume(MIToken::colon))
414 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
417 if (Token.isNot(MIToken::MachineBasicBlock))
418 return error("expected a machine basic block reference");
419 MachineBasicBlock *SuccMBB = nullptr;
420 if (parseMBBReference(SuccMBB))
424 if (consumeIfPresent(MIToken::lparen)) {
425 if (Token.isNot(MIToken::IntegerLiteral))
426 return error("expected an integer literal after '('");
427 if (getUnsigned(Weight))
430 if (expectAndConsume(MIToken::rparen))
433 MBB.addSuccessor(SuccMBB, Weight);
434 } while (consumeIfPresent(MIToken::comma));
438 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) {
439 // Skip the definition.
440 assert(Token.is(MIToken::MachineBasicBlockLabel));
442 if (consumeIfPresent(MIToken::lparen)) {
443 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
445 consumeIfPresent(MIToken::rparen);
447 consumeIfPresent(MIToken::colon);
449 // Parse the liveins and successors.
450 // N.B: Multiple lists of successors and liveins are allowed and they're
457 // liveins: %edi, %esi
459 if (Token.is(MIToken::kw_successors)) {
460 if (parseBasicBlockSuccessors(MBB))
462 } else if (Token.is(MIToken::kw_liveins)) {
463 if (parseBasicBlockLiveins(MBB))
465 } else if (consumeIfPresent(MIToken::Newline)) {
469 if (!Token.isNewlineOrEOF())
470 return error("expected line break at the end of a list");
474 // Parse the instructions.
475 bool IsInBundle = false;
476 MachineInstr *PrevMI = nullptr;
478 if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof))
480 else if (consumeIfPresent(MIToken::Newline))
482 if (consumeIfPresent(MIToken::rbrace)) {
483 // The first parsing pass should verify that all closing '}' have an
489 MachineInstr *MI = nullptr;
492 MBB.insert(MBB.end(), MI);
494 PrevMI->setFlag(MachineInstr::BundledSucc);
495 MI->setFlag(MachineInstr::BundledPred);
498 if (Token.is(MIToken::lbrace)) {
500 return error("nested instruction bundles are not allowed");
502 // This instruction is the start of the bundle.
503 MI->setFlag(MachineInstr::BundledSucc);
505 if (!Token.is(MIToken::Newline))
506 // The next instruction can be on the same line.
509 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
515 bool MIParser::parseBasicBlocks() {
517 // Skip until the first machine basic block.
518 while (Token.is(MIToken::Newline))
520 if (Token.isErrorOrEOF())
521 return Token.isError();
522 // The first parsing pass should have verified that this token is a MBB label
523 // in the 'parseBasicBlockDefinitions' method.
524 assert(Token.is(MIToken::MachineBasicBlockLabel));
526 MachineBasicBlock *MBB = nullptr;
527 if (parseMBBReference(MBB))
529 if (parseBasicBlock(*MBB))
531 // The method 'parseBasicBlock' should parse the whole block until the next
532 // block or the end of file.
533 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
534 } while (Token.isNot(MIToken::Eof));
538 bool MIParser::parse(MachineInstr *&MI) {
539 // Parse any register operands before '='
540 MachineOperand MO = MachineOperand::CreateImm(0);
541 SmallVector<MachineOperandWithLocation, 8> Operands;
542 while (Token.isRegister() || Token.isRegisterFlag()) {
543 auto Loc = Token.location();
544 if (parseRegisterOperand(MO, /*IsDef=*/true))
546 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
547 if (Token.isNot(MIToken::comma))
551 if (!Operands.empty() && expectAndConsume(MIToken::equal))
554 unsigned OpCode, Flags = 0;
555 if (Token.isError() || parseInstruction(OpCode, Flags))
558 // Parse the remaining machine operands.
559 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
560 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
561 auto Loc = Token.location();
562 if (parseMachineOperandAndTargetFlags(MO))
564 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
565 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
566 Token.is(MIToken::lbrace))
568 if (Token.isNot(MIToken::comma))
569 return error("expected ',' before the next machine operand");
573 DebugLoc DebugLocation;
574 if (Token.is(MIToken::kw_debug_location)) {
576 if (Token.isNot(MIToken::exclaim))
577 return error("expected a metadata node after 'debug-location'");
578 MDNode *Node = nullptr;
579 if (parseMDNode(Node))
581 DebugLocation = DebugLoc(Node);
584 // Parse the machine memory operands.
585 SmallVector<MachineMemOperand *, 2> MemOperands;
586 if (Token.is(MIToken::coloncolon)) {
588 while (!Token.isNewlineOrEOF()) {
589 MachineMemOperand *MemOp = nullptr;
590 if (parseMachineMemoryOperand(MemOp))
592 MemOperands.push_back(MemOp);
593 if (Token.isNewlineOrEOF())
595 if (Token.isNot(MIToken::comma))
596 return error("expected ',' before the next machine memory operand");
601 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
602 if (!MCID.isVariadic()) {
603 // FIXME: Move the implicit operand verification to the machine verifier.
604 if (verifyImplicitOperands(Operands, MCID))
608 // TODO: Check for extraneous machine operands.
609 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
611 for (const auto &Operand : Operands)
612 MI->addOperand(MF, Operand.Operand);
613 if (MemOperands.empty())
615 MachineInstr::mmo_iterator MemRefs =
616 MF.allocateMemRefsArray(MemOperands.size());
617 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
618 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
622 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
624 if (Token.isNot(MIToken::MachineBasicBlock))
625 return error("expected a machine basic block reference");
626 if (parseMBBReference(MBB))
629 if (Token.isNot(MIToken::Eof))
631 "expected end of string after the machine basic block reference");
635 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
637 if (Token.isNot(MIToken::NamedRegister))
638 return error("expected a named register");
639 if (parseRegister(Reg))
642 if (Token.isNot(MIToken::Eof))
643 return error("expected end of string after the register reference");
647 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
649 if (Token.isNot(MIToken::VirtualRegister))
650 return error("expected a virtual register");
651 if (parseRegister(Reg))
654 if (Token.isNot(MIToken::Eof))
655 return error("expected end of string after the register reference");
659 bool MIParser::parseStandaloneStackObject(int &FI) {
661 if (Token.isNot(MIToken::StackObject))
662 return error("expected a stack object");
663 if (parseStackFrameIndex(FI))
665 if (Token.isNot(MIToken::Eof))
666 return error("expected end of string after the stack object reference");
670 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
671 assert(MO.isImplicit());
672 return MO.isDef() ? "implicit-def" : "implicit";
675 static std::string getRegisterName(const TargetRegisterInfo *TRI,
677 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
678 return StringRef(TRI->getName(Reg)).lower();
681 bool MIParser::verifyImplicitOperands(
682 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
684 // We can't verify call instructions as they can contain arbitrary implicit
685 // register and register mask operands.
688 // Gather all the expected implicit operands.
689 SmallVector<MachineOperand, 4> ImplicitOperands;
690 if (MCID.ImplicitDefs)
691 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
692 ImplicitOperands.push_back(
693 MachineOperand::CreateReg(*ImpDefs, true, true));
694 if (MCID.ImplicitUses)
695 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
696 ImplicitOperands.push_back(
697 MachineOperand::CreateReg(*ImpUses, false, true));
699 const auto *TRI = MF.getSubtarget().getRegisterInfo();
700 assert(TRI && "Expected target register info");
701 size_t I = ImplicitOperands.size(), J = Operands.size();
706 const auto &ImplicitOperand = ImplicitOperands[I];
707 const auto &Operand = Operands[J].Operand;
708 if (ImplicitOperand.isIdenticalTo(Operand))
710 if (Operand.isReg() && Operand.isImplicit()) {
711 // Check if this implicit register is a subregister of an explicit
713 bool IsImplicitSubRegister = false;
714 for (size_t K = 0, E = Operands.size(); K < E; ++K) {
715 const auto &Op = Operands[K].Operand;
716 if (Op.isReg() && !Op.isImplicit() &&
717 TRI->isSubRegister(Op.getReg(), Operand.getReg())) {
718 IsImplicitSubRegister = true;
722 if (IsImplicitSubRegister)
724 return error(Operands[J].Begin,
725 Twine("expected an implicit register operand '") +
726 printImplicitRegisterFlag(ImplicitOperand) + " %" +
727 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
730 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
731 // insead of reporting an error at this location:
734 // report the error at the following location:
737 return error(J < Operands.size() ? Operands[J].End : Token.location(),
738 Twine("missing implicit register operand '") +
739 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
740 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
745 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
746 if (Token.is(MIToken::kw_frame_setup)) {
747 Flags |= MachineInstr::FrameSetup;
750 if (Token.isNot(MIToken::Identifier))
751 return error("expected a machine instruction");
752 StringRef InstrName = Token.stringValue();
753 if (parseInstrName(InstrName, OpCode))
754 return error(Twine("unknown machine instruction name '") + InstrName + "'");
759 bool MIParser::parseRegister(unsigned &Reg) {
760 switch (Token.kind()) {
761 case MIToken::underscore:
764 case MIToken::NamedRegister: {
765 StringRef Name = Token.stringValue();
766 if (getRegisterByName(Name, Reg))
767 return error(Twine("unknown register name '") + Name + "'");
770 case MIToken::VirtualRegister: {
774 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
775 if (RegInfo == PFS.VirtualRegisterSlots.end())
776 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
778 Reg = RegInfo->second;
781 // TODO: Parse other register kinds.
783 llvm_unreachable("The current token should be a register");
788 bool MIParser::parseRegisterFlag(unsigned &Flags) {
789 const unsigned OldFlags = Flags;
790 switch (Token.kind()) {
791 case MIToken::kw_implicit:
792 Flags |= RegState::Implicit;
794 case MIToken::kw_implicit_define:
795 Flags |= RegState::ImplicitDefine;
797 case MIToken::kw_dead:
798 Flags |= RegState::Dead;
800 case MIToken::kw_killed:
801 Flags |= RegState::Kill;
803 case MIToken::kw_undef:
804 Flags |= RegState::Undef;
806 case MIToken::kw_internal:
807 Flags |= RegState::InternalRead;
809 case MIToken::kw_early_clobber:
810 Flags |= RegState::EarlyClobber;
812 case MIToken::kw_debug_use:
813 Flags |= RegState::Debug;
816 llvm_unreachable("The current token should be a register flag");
818 if (OldFlags == Flags)
819 // We know that the same flag is specified more than once when the flags
821 return error("duplicate '" + Token.stringValue() + "' register flag");
826 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
827 assert(Token.is(MIToken::colon));
829 if (Token.isNot(MIToken::Identifier))
830 return error("expected a subregister index after ':'");
831 auto Name = Token.stringValue();
832 SubReg = getSubRegIndex(Name);
834 return error(Twine("use of unknown subregister index '") + Name + "'");
839 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
841 unsigned Flags = IsDef ? RegState::Define : 0;
842 while (Token.isRegisterFlag()) {
843 if (parseRegisterFlag(Flags))
846 if (!Token.isRegister())
847 return error("expected a register after register flags");
848 if (parseRegister(Reg))
852 if (Token.is(MIToken::colon)) {
853 if (parseSubRegisterIndex(SubReg))
856 Dest = MachineOperand::CreateReg(
857 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
858 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
859 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
860 Flags & RegState::InternalRead);
864 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
865 assert(Token.is(MIToken::IntegerLiteral));
866 const APSInt &Int = Token.integerValue();
867 if (Int.getMinSignedBits() > 64)
868 return error("integer literal is too large to be an immediate operand");
869 Dest = MachineOperand::CreateImm(Int.getExtValue());
874 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
875 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
878 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
880 return error(Loc + Err.getColumnNo(), Err.getMessage());
884 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
885 assert(Token.is(MIToken::IntegerType));
886 auto Loc = Token.location();
888 if (Token.isNot(MIToken::IntegerLiteral))
889 return error("expected an integer literal");
890 const Constant *C = nullptr;
891 if (parseIRConstant(Loc, C))
893 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
897 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
898 auto Loc = Token.location();
900 if (Token.isNot(MIToken::FloatingPointLiteral))
901 return error("expected a floating point literal");
902 const Constant *C = nullptr;
903 if (parseIRConstant(Loc, C))
905 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
909 bool MIParser::getUnsigned(unsigned &Result) {
910 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
911 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
912 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
914 return error("expected 32-bit integer (too large)");
919 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
920 assert(Token.is(MIToken::MachineBasicBlock) ||
921 Token.is(MIToken::MachineBasicBlockLabel));
923 if (getUnsigned(Number))
925 auto MBBInfo = PFS.MBBSlots.find(Number);
926 if (MBBInfo == PFS.MBBSlots.end())
927 return error(Twine("use of undefined machine basic block #") +
929 MBB = MBBInfo->second;
930 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
931 return error(Twine("the name of machine basic block #") + Twine(Number) +
932 " isn't '" + Token.stringValue() + "'");
936 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
937 MachineBasicBlock *MBB;
938 if (parseMBBReference(MBB))
940 Dest = MachineOperand::CreateMBB(MBB);
945 bool MIParser::parseStackFrameIndex(int &FI) {
946 assert(Token.is(MIToken::StackObject));
950 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
951 if (ObjectInfo == PFS.StackObjectSlots.end())
952 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
955 if (const auto *Alloca =
956 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
957 Name = Alloca->getName();
958 if (!Token.stringValue().empty() && Token.stringValue() != Name)
959 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
960 "' isn't '" + Token.stringValue() + "'");
962 FI = ObjectInfo->second;
966 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
968 if (parseStackFrameIndex(FI))
970 Dest = MachineOperand::CreateFI(FI);
974 bool MIParser::parseFixedStackFrameIndex(int &FI) {
975 assert(Token.is(MIToken::FixedStackObject));
979 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
980 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
981 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
984 FI = ObjectInfo->second;
988 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
990 if (parseFixedStackFrameIndex(FI))
992 Dest = MachineOperand::CreateFI(FI);
996 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
997 switch (Token.kind()) {
998 case MIToken::NamedGlobalValue: {
999 const Module *M = MF.getFunction()->getParent();
1000 GV = M->getNamedValue(Token.stringValue());
1002 return error(Twine("use of undefined global value '") + Token.range() +
1006 case MIToken::GlobalValue: {
1008 if (getUnsigned(GVIdx))
1010 if (GVIdx >= IRSlots.GlobalValues.size())
1011 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
1013 GV = IRSlots.GlobalValues[GVIdx];
1017 llvm_unreachable("The current token should be a global value");
1022 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
1023 GlobalValue *GV = nullptr;
1024 if (parseGlobalValue(GV))
1027 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
1028 if (parseOperandsOffset(Dest))
1033 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1034 assert(Token.is(MIToken::ConstantPoolItem));
1036 if (getUnsigned(ID))
1038 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1039 if (ConstantInfo == PFS.ConstantPoolSlots.end())
1040 return error("use of undefined constant '%const." + Twine(ID) + "'");
1042 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1043 if (parseOperandsOffset(Dest))
1048 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1049 assert(Token.is(MIToken::JumpTableIndex));
1051 if (getUnsigned(ID))
1053 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1054 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1055 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1057 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1061 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1062 assert(Token.is(MIToken::ExternalSymbol));
1063 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1065 Dest = MachineOperand::CreateES(Symbol);
1066 if (parseOperandsOffset(Dest))
1071 bool MIParser::parseMDNode(MDNode *&Node) {
1072 assert(Token.is(MIToken::exclaim));
1073 auto Loc = Token.location();
1075 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1076 return error("expected metadata id after '!'");
1078 if (getUnsigned(ID))
1080 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1081 if (NodeInfo == IRSlots.MetadataNodes.end())
1082 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1084 Node = NodeInfo->second.get();
1088 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1089 MDNode *Node = nullptr;
1090 if (parseMDNode(Node))
1092 Dest = MachineOperand::CreateMetadata(Node);
1096 bool MIParser::parseCFIOffset(int &Offset) {
1097 if (Token.isNot(MIToken::IntegerLiteral))
1098 return error("expected a cfi offset");
1099 if (Token.integerValue().getMinSignedBits() > 32)
1100 return error("expected a 32 bit integer (the cfi offset is too large)");
1101 Offset = (int)Token.integerValue().getExtValue();
1106 bool MIParser::parseCFIRegister(unsigned &Reg) {
1107 if (Token.isNot(MIToken::NamedRegister))
1108 return error("expected a cfi register");
1110 if (parseRegister(LLVMReg))
1112 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1113 assert(TRI && "Expected target register info");
1114 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1116 return error("invalid DWARF register");
1117 Reg = (unsigned)DwarfReg;
1122 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1123 auto Kind = Token.kind();
1125 auto &MMI = MF.getMMI();
1130 case MIToken::kw_cfi_same_value:
1131 if (parseCFIRegister(Reg))
1134 MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1136 case MIToken::kw_cfi_offset:
1137 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1138 parseCFIOffset(Offset))
1141 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1143 case MIToken::kw_cfi_def_cfa_register:
1144 if (parseCFIRegister(Reg))
1147 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1149 case MIToken::kw_cfi_def_cfa_offset:
1150 if (parseCFIOffset(Offset))
1152 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1153 CFIIndex = MMI.addFrameInst(
1154 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1156 case MIToken::kw_cfi_def_cfa:
1157 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1158 parseCFIOffset(Offset))
1160 // NB: MCCFIInstruction::createDefCfa negates the offset.
1162 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1165 // TODO: Parse the other CFI operands.
1166 llvm_unreachable("The current token should be a cfi operand");
1168 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1172 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1173 switch (Token.kind()) {
1174 case MIToken::NamedIRBlock: {
1175 BB = dyn_cast_or_null<BasicBlock>(
1176 F.getValueSymbolTable().lookup(Token.stringValue()));
1178 return error(Twine("use of undefined IR block '") + Token.range() + "'");
1181 case MIToken::IRBlock: {
1182 unsigned SlotNumber = 0;
1183 if (getUnsigned(SlotNumber))
1185 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1187 return error(Twine("use of undefined IR block '%ir-block.") +
1188 Twine(SlotNumber) + "'");
1192 llvm_unreachable("The current token should be an IR block reference");
1197 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1198 assert(Token.is(MIToken::kw_blockaddress));
1200 if (expectAndConsume(MIToken::lparen))
1202 if (Token.isNot(MIToken::GlobalValue) &&
1203 Token.isNot(MIToken::NamedGlobalValue))
1204 return error("expected a global value");
1205 GlobalValue *GV = nullptr;
1206 if (parseGlobalValue(GV))
1208 auto *F = dyn_cast<Function>(GV);
1210 return error("expected an IR function reference");
1212 if (expectAndConsume(MIToken::comma))
1214 BasicBlock *BB = nullptr;
1215 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1216 return error("expected an IR block reference");
1217 if (parseIRBlock(BB, *F))
1220 if (expectAndConsume(MIToken::rparen))
1222 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1223 if (parseOperandsOffset(Dest))
1228 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1229 assert(Token.is(MIToken::kw_target_index));
1231 if (expectAndConsume(MIToken::lparen))
1233 if (Token.isNot(MIToken::Identifier))
1234 return error("expected the name of the target index");
1236 if (getTargetIndex(Token.stringValue(), Index))
1237 return error("use of undefined target index '" + Token.stringValue() + "'");
1239 if (expectAndConsume(MIToken::rparen))
1241 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1242 if (parseOperandsOffset(Dest))
1247 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1248 assert(Token.is(MIToken::kw_liveout));
1249 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1250 assert(TRI && "Expected target register info");
1251 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1253 if (expectAndConsume(MIToken::lparen))
1256 if (Token.isNot(MIToken::NamedRegister))
1257 return error("expected a named register");
1259 if (parseRegister(Reg))
1262 Mask[Reg / 32] |= 1U << (Reg % 32);
1263 // TODO: Report an error if the same register is used more than once.
1264 if (Token.isNot(MIToken::comma))
1268 if (expectAndConsume(MIToken::rparen))
1270 Dest = MachineOperand::CreateRegLiveOut(Mask);
1274 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
1275 switch (Token.kind()) {
1276 case MIToken::kw_implicit:
1277 case MIToken::kw_implicit_define:
1278 case MIToken::kw_dead:
1279 case MIToken::kw_killed:
1280 case MIToken::kw_undef:
1281 case MIToken::kw_internal:
1282 case MIToken::kw_early_clobber:
1283 case MIToken::kw_debug_use:
1284 case MIToken::underscore:
1285 case MIToken::NamedRegister:
1286 case MIToken::VirtualRegister:
1287 return parseRegisterOperand(Dest);
1288 case MIToken::IntegerLiteral:
1289 return parseImmediateOperand(Dest);
1290 case MIToken::IntegerType:
1291 return parseTypedImmediateOperand(Dest);
1292 case MIToken::kw_half:
1293 case MIToken::kw_float:
1294 case MIToken::kw_double:
1295 case MIToken::kw_x86_fp80:
1296 case MIToken::kw_fp128:
1297 case MIToken::kw_ppc_fp128:
1298 return parseFPImmediateOperand(Dest);
1299 case MIToken::MachineBasicBlock:
1300 return parseMBBOperand(Dest);
1301 case MIToken::StackObject:
1302 return parseStackObjectOperand(Dest);
1303 case MIToken::FixedStackObject:
1304 return parseFixedStackObjectOperand(Dest);
1305 case MIToken::GlobalValue:
1306 case MIToken::NamedGlobalValue:
1307 return parseGlobalAddressOperand(Dest);
1308 case MIToken::ConstantPoolItem:
1309 return parseConstantPoolIndexOperand(Dest);
1310 case MIToken::JumpTableIndex:
1311 return parseJumpTableIndexOperand(Dest);
1312 case MIToken::ExternalSymbol:
1313 return parseExternalSymbolOperand(Dest);
1314 case MIToken::exclaim:
1315 return parseMetadataOperand(Dest);
1316 case MIToken::kw_cfi_same_value:
1317 case MIToken::kw_cfi_offset:
1318 case MIToken::kw_cfi_def_cfa_register:
1319 case MIToken::kw_cfi_def_cfa_offset:
1320 case MIToken::kw_cfi_def_cfa:
1321 return parseCFIOperand(Dest);
1322 case MIToken::kw_blockaddress:
1323 return parseBlockAddressOperand(Dest);
1324 case MIToken::kw_target_index:
1325 return parseTargetIndexOperand(Dest);
1326 case MIToken::kw_liveout:
1327 return parseLiveoutRegisterMaskOperand(Dest);
1328 case MIToken::Error:
1330 case MIToken::Identifier:
1331 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1332 Dest = MachineOperand::CreateRegMask(RegMask);
1338 // TODO: parse the other machine operands.
1339 return error("expected a machine operand");
1344 bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1346 bool HasTargetFlags = false;
1347 if (Token.is(MIToken::kw_target_flags)) {
1348 HasTargetFlags = true;
1350 if (expectAndConsume(MIToken::lparen))
1352 if (Token.isNot(MIToken::Identifier))
1353 return error("expected the name of the target flag");
1354 if (getDirectTargetFlag(Token.stringValue(), TF))
1355 return error("use of undefined target flag '" + Token.stringValue() +
1358 // TODO: Parse target's bit target flags.
1359 if (expectAndConsume(MIToken::rparen))
1362 auto Loc = Token.location();
1363 if (parseMachineOperand(Dest))
1365 if (!HasTargetFlags)
1368 return error(Loc, "register operands can't have target flags");
1369 Dest.setTargetFlags(TF);
1373 bool MIParser::parseOffset(int64_t &Offset) {
1374 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1376 StringRef Sign = Token.range();
1377 bool IsNegative = Token.is(MIToken::minus);
1379 if (Token.isNot(MIToken::IntegerLiteral))
1380 return error("expected an integer literal after '" + Sign + "'");
1381 if (Token.integerValue().getMinSignedBits() > 64)
1382 return error("expected 64-bit integer (too large)");
1383 Offset = Token.integerValue().getExtValue();
1390 bool MIParser::parseAlignment(unsigned &Alignment) {
1391 assert(Token.is(MIToken::kw_align));
1393 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1394 return error("expected an integer literal after 'align'");
1395 if (getUnsigned(Alignment))
1401 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1403 if (parseOffset(Offset))
1405 Op.setOffset(Offset);
1409 bool MIParser::parseIRValue(Value *&V) {
1410 switch (Token.kind()) {
1411 case MIToken::NamedIRValue: {
1412 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1414 V = MF.getFunction()->getParent()->getValueSymbolTable().lookup(
1415 Token.stringValue());
1417 return error(Twine("use of undefined IR value '") + Token.range() + "'");
1420 // TODO: Parse unnamed IR value references.
1422 llvm_unreachable("The current token should be an IR block reference");
1427 bool MIParser::getUint64(uint64_t &Result) {
1428 assert(Token.hasIntegerValue());
1429 if (Token.integerValue().getActiveBits() > 64)
1430 return error("expected 64-bit integer (too large)");
1431 Result = Token.integerValue().getZExtValue();
1435 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1436 const unsigned OldFlags = Flags;
1437 switch (Token.kind()) {
1438 case MIToken::kw_volatile:
1439 Flags |= MachineMemOperand::MOVolatile;
1441 case MIToken::kw_non_temporal:
1442 Flags |= MachineMemOperand::MONonTemporal;
1444 case MIToken::kw_invariant:
1445 Flags |= MachineMemOperand::MOInvariant;
1447 // TODO: parse the target specific memory operand flags.
1449 llvm_unreachable("The current token should be a memory operand flag");
1451 if (OldFlags == Flags)
1452 // We know that the same flag is specified more than once when the flags
1453 // weren't modified.
1454 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1459 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1460 switch (Token.kind()) {
1461 case MIToken::kw_stack:
1462 PSV = MF.getPSVManager().getStack();
1464 case MIToken::kw_got:
1465 PSV = MF.getPSVManager().getGOT();
1467 case MIToken::kw_jump_table:
1468 PSV = MF.getPSVManager().getJumpTable();
1470 case MIToken::kw_constant_pool:
1471 PSV = MF.getPSVManager().getConstantPool();
1473 case MIToken::FixedStackObject: {
1475 if (parseFixedStackFrameIndex(FI))
1477 PSV = MF.getPSVManager().getFixedStack(FI);
1478 // The token was already consumed, so use return here instead of break.
1481 case MIToken::GlobalValue:
1482 case MIToken::NamedGlobalValue: {
1483 GlobalValue *GV = nullptr;
1484 if (parseGlobalValue(GV))
1486 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
1489 case MIToken::ExternalSymbol:
1490 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
1491 MF.createExternalSymbolName(Token.stringValue()));
1494 llvm_unreachable("The current token should be pseudo source value");
1500 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
1501 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
1502 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1503 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::GlobalValue) ||
1504 Token.is(MIToken::NamedGlobalValue) ||
1505 Token.is(MIToken::ExternalSymbol)) {
1506 const PseudoSourceValue *PSV = nullptr;
1507 if (parseMemoryPseudoSourceValue(PSV))
1510 if (parseOffset(Offset))
1512 Dest = MachinePointerInfo(PSV, Offset);
1515 if (Token.isNot(MIToken::NamedIRValue))
1516 return error("expected an IR value reference");
1518 if (parseIRValue(V))
1520 if (!V->getType()->isPointerTy())
1521 return error("expected a pointer IR value");
1524 if (parseOffset(Offset))
1526 Dest = MachinePointerInfo(V, Offset);
1530 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1531 if (expectAndConsume(MIToken::lparen))
1534 while (Token.isMemoryOperandFlag()) {
1535 if (parseMemoryOperandFlag(Flags))
1538 if (Token.isNot(MIToken::Identifier) ||
1539 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1540 return error("expected 'load' or 'store' memory operation");
1541 if (Token.stringValue() == "load")
1542 Flags |= MachineMemOperand::MOLoad;
1544 Flags |= MachineMemOperand::MOStore;
1547 if (Token.isNot(MIToken::IntegerLiteral))
1548 return error("expected the size integer literal after memory operation");
1550 if (getUint64(Size))
1554 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1555 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1556 return error(Twine("expected '") + Word + "'");
1559 MachinePointerInfo Ptr = MachinePointerInfo();
1560 if (parseMachinePointerInfo(Ptr))
1562 unsigned BaseAlignment = Size;
1564 MDNode *Range = nullptr;
1565 while (consumeIfPresent(MIToken::comma)) {
1566 switch (Token.kind()) {
1567 case MIToken::kw_align:
1568 if (parseAlignment(BaseAlignment))
1571 case MIToken::md_tbaa:
1573 if (parseMDNode(AAInfo.TBAA))
1576 case MIToken::md_alias_scope:
1578 if (parseMDNode(AAInfo.Scope))
1581 case MIToken::md_noalias:
1583 if (parseMDNode(AAInfo.NoAlias))
1586 case MIToken::md_range:
1588 if (parseMDNode(Range))
1591 // TODO: Report an error on duplicate metadata nodes.
1593 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
1594 "'!noalias' or '!range'");
1597 if (expectAndConsume(MIToken::rparen))
1600 MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range);
1604 void MIParser::initNames2InstrOpCodes() {
1605 if (!Names2InstrOpCodes.empty())
1607 const auto *TII = MF.getSubtarget().getInstrInfo();
1608 assert(TII && "Expected target instruction info");
1609 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1610 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1613 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1614 initNames2InstrOpCodes();
1615 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1616 if (InstrInfo == Names2InstrOpCodes.end())
1618 OpCode = InstrInfo->getValue();
1622 void MIParser::initNames2Regs() {
1623 if (!Names2Regs.empty())
1625 // The '%noreg' register is the register 0.
1626 Names2Regs.insert(std::make_pair("noreg", 0));
1627 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1628 assert(TRI && "Expected target register info");
1629 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1631 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1634 assert(WasInserted && "Expected registers to be unique case-insensitively");
1638 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1640 auto RegInfo = Names2Regs.find(RegName);
1641 if (RegInfo == Names2Regs.end())
1643 Reg = RegInfo->getValue();
1647 void MIParser::initNames2RegMasks() {
1648 if (!Names2RegMasks.empty())
1650 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1651 assert(TRI && "Expected target register info");
1652 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1653 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1654 assert(RegMasks.size() == RegMaskNames.size());
1655 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1656 Names2RegMasks.insert(
1657 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1660 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1661 initNames2RegMasks();
1662 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1663 if (RegMaskInfo == Names2RegMasks.end())
1665 return RegMaskInfo->getValue();
1668 void MIParser::initNames2SubRegIndices() {
1669 if (!Names2SubRegIndices.empty())
1671 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1672 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1673 Names2SubRegIndices.insert(
1674 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1677 unsigned MIParser::getSubRegIndex(StringRef Name) {
1678 initNames2SubRegIndices();
1679 auto SubRegInfo = Names2SubRegIndices.find(Name);
1680 if (SubRegInfo == Names2SubRegIndices.end())
1682 return SubRegInfo->getValue();
1685 static void initSlots2BasicBlocks(
1687 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1688 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1689 MST.incorporateFunction(F);
1690 for (auto &BB : F) {
1693 int Slot = MST.getLocalSlot(&BB);
1696 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1700 static const BasicBlock *getIRBlockFromSlot(
1702 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1703 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1704 if (BlockInfo == Slots2BasicBlocks.end())
1706 return BlockInfo->second;
1709 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1710 if (Slots2BasicBlocks.empty())
1711 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1712 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1715 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1716 if (&F == MF.getFunction())
1717 return getIRBlock(Slot);
1718 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1719 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1720 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1723 void MIParser::initNames2TargetIndices() {
1724 if (!Names2TargetIndices.empty())
1726 const auto *TII = MF.getSubtarget().getInstrInfo();
1727 assert(TII && "Expected target instruction info");
1728 auto Indices = TII->getSerializableTargetIndices();
1729 for (const auto &I : Indices)
1730 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1733 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1734 initNames2TargetIndices();
1735 auto IndexInfo = Names2TargetIndices.find(Name);
1736 if (IndexInfo == Names2TargetIndices.end())
1738 Index = IndexInfo->second;
1742 void MIParser::initNames2DirectTargetFlags() {
1743 if (!Names2DirectTargetFlags.empty())
1745 const auto *TII = MF.getSubtarget().getInstrInfo();
1746 assert(TII && "Expected target instruction info");
1747 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1748 for (const auto &I : Flags)
1749 Names2DirectTargetFlags.insert(
1750 std::make_pair(StringRef(I.second), I.first));
1753 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1754 initNames2DirectTargetFlags();
1755 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1756 if (FlagInfo == Names2DirectTargetFlags.end())
1758 Flag = FlagInfo->second;
1762 bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1763 PerFunctionMIParsingState &PFS,
1764 const SlotMapping &IRSlots,
1765 SMDiagnostic &Error) {
1767 SM.AddNewSourceBuffer(
1768 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1770 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1771 .parseBasicBlockDefinitions(PFS.MBBSlots);
1774 bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1775 const PerFunctionMIParsingState &PFS,
1776 const SlotMapping &IRSlots,
1777 SMDiagnostic &Error) {
1779 SM.AddNewSourceBuffer(
1780 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1782 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
1785 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1786 MachineFunction &MF, StringRef Src,
1787 const PerFunctionMIParsingState &PFS,
1788 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1789 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1792 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1793 MachineFunction &MF, StringRef Src,
1794 const PerFunctionMIParsingState &PFS,
1795 const SlotMapping &IRSlots,
1796 SMDiagnostic &Error) {
1797 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1798 .parseStandaloneNamedRegister(Reg);
1801 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1802 MachineFunction &MF, StringRef Src,
1803 const PerFunctionMIParsingState &PFS,
1804 const SlotMapping &IRSlots,
1805 SMDiagnostic &Error) {
1806 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1807 .parseStandaloneVirtualRegister(Reg);
1810 bool llvm::parseStackObjectReference(int &FI, SourceMgr &SM,
1811 MachineFunction &MF, StringRef Src,
1812 const PerFunctionMIParsingState &PFS,
1813 const SlotMapping &IRSlots,
1814 SMDiagnostic &Error) {
1815 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1816 .parseStandaloneStackObject(FI);