xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MIRParser/MIParser.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the parsing of machine instructions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MIRParser/MIParser.h"
14 #include "MILexer.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Analysis/MemoryLocation.h"
25 #include "llvm/AsmParser/Parser.h"
26 #include "llvm/AsmParser/SlotMapping.h"
27 #include "llvm/CodeGen/LowLevelType.h"
28 #include "llvm/CodeGen/MIRFormatter.h"
29 #include "llvm/CodeGen/MIRPrinter.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineMemOperand.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/RegisterBank.h"
39 #include "llvm/CodeGen/RegisterBankInfo.h"
40 #include "llvm/CodeGen/TargetInstrInfo.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/CodeGen/TargetSubtargetInfo.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSlotTracker.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/IR/ValueSymbolTable.h"
58 #include "llvm/MC/LaneBitmask.h"
59 #include "llvm/MC/MCContext.h"
60 #include "llvm/MC/MCDwarf.h"
61 #include "llvm/MC/MCInstrDesc.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/BranchProbability.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/SMLoc.h"
68 #include "llvm/Support/SourceMgr.h"
69 #include "llvm/Target/TargetIntrinsicInfo.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include <cassert>
72 #include <cctype>
73 #include <cstddef>
74 #include <cstdint>
75 #include <limits>
76 #include <string>
77 #include <utility>
78 
79 using namespace llvm;
80 
81 void PerTargetMIParsingState::setTarget(
82   const TargetSubtargetInfo &NewSubtarget) {
83 
84   // If the subtarget changed, over conservatively assume everything is invalid.
85   if (&Subtarget == &NewSubtarget)
86     return;
87 
88   Names2InstrOpCodes.clear();
89   Names2Regs.clear();
90   Names2RegMasks.clear();
91   Names2SubRegIndices.clear();
92   Names2TargetIndices.clear();
93   Names2DirectTargetFlags.clear();
94   Names2BitmaskTargetFlags.clear();
95   Names2MMOTargetFlags.clear();
96 
97   initNames2RegClasses();
98   initNames2RegBanks();
99 }
100 
101 void PerTargetMIParsingState::initNames2Regs() {
102   if (!Names2Regs.empty())
103     return;
104 
105   // The '%noreg' register is the register 0.
106   Names2Regs.insert(std::make_pair("noreg", 0));
107   const auto *TRI = Subtarget.getRegisterInfo();
108   assert(TRI && "Expected target register info");
109 
110   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
111     bool WasInserted =
112         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
113             .second;
114     (void)WasInserted;
115     assert(WasInserted && "Expected registers to be unique case-insensitively");
116   }
117 }
118 
119 bool PerTargetMIParsingState::getRegisterByName(StringRef RegName,
120                                                 Register &Reg) {
121   initNames2Regs();
122   auto RegInfo = Names2Regs.find(RegName);
123   if (RegInfo == Names2Regs.end())
124     return true;
125   Reg = RegInfo->getValue();
126   return false;
127 }
128 
129 void PerTargetMIParsingState::initNames2InstrOpCodes() {
130   if (!Names2InstrOpCodes.empty())
131     return;
132   const auto *TII = Subtarget.getInstrInfo();
133   assert(TII && "Expected target instruction info");
134   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
135     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
136 }
137 
138 bool PerTargetMIParsingState::parseInstrName(StringRef InstrName,
139                                              unsigned &OpCode) {
140   initNames2InstrOpCodes();
141   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
142   if (InstrInfo == Names2InstrOpCodes.end())
143     return true;
144   OpCode = InstrInfo->getValue();
145   return false;
146 }
147 
148 void PerTargetMIParsingState::initNames2RegMasks() {
149   if (!Names2RegMasks.empty())
150     return;
151   const auto *TRI = Subtarget.getRegisterInfo();
152   assert(TRI && "Expected target register info");
153   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
154   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
155   assert(RegMasks.size() == RegMaskNames.size());
156   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
157     Names2RegMasks.insert(
158         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
159 }
160 
161 const uint32_t *PerTargetMIParsingState::getRegMask(StringRef Identifier) {
162   initNames2RegMasks();
163   auto RegMaskInfo = Names2RegMasks.find(Identifier);
164   if (RegMaskInfo == Names2RegMasks.end())
165     return nullptr;
166   return RegMaskInfo->getValue();
167 }
168 
169 void PerTargetMIParsingState::initNames2SubRegIndices() {
170   if (!Names2SubRegIndices.empty())
171     return;
172   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
173   for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
174     Names2SubRegIndices.insert(
175         std::make_pair(TRI->getSubRegIndexName(I), I));
176 }
177 
178 unsigned PerTargetMIParsingState::getSubRegIndex(StringRef Name) {
179   initNames2SubRegIndices();
180   auto SubRegInfo = Names2SubRegIndices.find(Name);
181   if (SubRegInfo == Names2SubRegIndices.end())
182     return 0;
183   return SubRegInfo->getValue();
184 }
185 
186 void PerTargetMIParsingState::initNames2TargetIndices() {
187   if (!Names2TargetIndices.empty())
188     return;
189   const auto *TII = Subtarget.getInstrInfo();
190   assert(TII && "Expected target instruction info");
191   auto Indices = TII->getSerializableTargetIndices();
192   for (const auto &I : Indices)
193     Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
194 }
195 
196 bool PerTargetMIParsingState::getTargetIndex(StringRef Name, int &Index) {
197   initNames2TargetIndices();
198   auto IndexInfo = Names2TargetIndices.find(Name);
199   if (IndexInfo == Names2TargetIndices.end())
200     return true;
201   Index = IndexInfo->second;
202   return false;
203 }
204 
205 void PerTargetMIParsingState::initNames2DirectTargetFlags() {
206   if (!Names2DirectTargetFlags.empty())
207     return;
208 
209   const auto *TII = Subtarget.getInstrInfo();
210   assert(TII && "Expected target instruction info");
211   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
212   for (const auto &I : Flags)
213     Names2DirectTargetFlags.insert(
214         std::make_pair(StringRef(I.second), I.first));
215 }
216 
217 bool PerTargetMIParsingState::getDirectTargetFlag(StringRef Name,
218                                                   unsigned &Flag) {
219   initNames2DirectTargetFlags();
220   auto FlagInfo = Names2DirectTargetFlags.find(Name);
221   if (FlagInfo == Names2DirectTargetFlags.end())
222     return true;
223   Flag = FlagInfo->second;
224   return false;
225 }
226 
227 void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
228   if (!Names2BitmaskTargetFlags.empty())
229     return;
230 
231   const auto *TII = Subtarget.getInstrInfo();
232   assert(TII && "Expected target instruction info");
233   auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
234   for (const auto &I : Flags)
235     Names2BitmaskTargetFlags.insert(
236         std::make_pair(StringRef(I.second), I.first));
237 }
238 
239 bool PerTargetMIParsingState::getBitmaskTargetFlag(StringRef Name,
240                                                    unsigned &Flag) {
241   initNames2BitmaskTargetFlags();
242   auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
243   if (FlagInfo == Names2BitmaskTargetFlags.end())
244     return true;
245   Flag = FlagInfo->second;
246   return false;
247 }
248 
249 void PerTargetMIParsingState::initNames2MMOTargetFlags() {
250   if (!Names2MMOTargetFlags.empty())
251     return;
252 
253   const auto *TII = Subtarget.getInstrInfo();
254   assert(TII && "Expected target instruction info");
255   auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
256   for (const auto &I : Flags)
257     Names2MMOTargetFlags.insert(std::make_pair(StringRef(I.second), I.first));
258 }
259 
260 bool PerTargetMIParsingState::getMMOTargetFlag(StringRef Name,
261                                                MachineMemOperand::Flags &Flag) {
262   initNames2MMOTargetFlags();
263   auto FlagInfo = Names2MMOTargetFlags.find(Name);
264   if (FlagInfo == Names2MMOTargetFlags.end())
265     return true;
266   Flag = FlagInfo->second;
267   return false;
268 }
269 
270 void PerTargetMIParsingState::initNames2RegClasses() {
271   if (!Names2RegClasses.empty())
272     return;
273 
274   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
275   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
276     const auto *RC = TRI->getRegClass(I);
277     Names2RegClasses.insert(
278         std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
279   }
280 }
281 
282 void PerTargetMIParsingState::initNames2RegBanks() {
283   if (!Names2RegBanks.empty())
284     return;
285 
286   const RegisterBankInfo *RBI = Subtarget.getRegBankInfo();
287   // If the target does not support GlobalISel, we may not have a
288   // register bank info.
289   if (!RBI)
290     return;
291 
292   for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
293     const auto &RegBank = RBI->getRegBank(I);
294     Names2RegBanks.insert(
295         std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
296   }
297 }
298 
299 const TargetRegisterClass *
300 PerTargetMIParsingState::getRegClass(StringRef Name) {
301   auto RegClassInfo = Names2RegClasses.find(Name);
302   if (RegClassInfo == Names2RegClasses.end())
303     return nullptr;
304   return RegClassInfo->getValue();
305 }
306 
307 const RegisterBank *PerTargetMIParsingState::getRegBank(StringRef Name) {
308   auto RegBankInfo = Names2RegBanks.find(Name);
309   if (RegBankInfo == Names2RegBanks.end())
310     return nullptr;
311   return RegBankInfo->getValue();
312 }
313 
314 PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction &MF,
315     SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &T)
316   : MF(MF), SM(&SM), IRSlots(IRSlots), Target(T) {
317 }
318 
319 VRegInfo &PerFunctionMIParsingState::getVRegInfo(Register Num) {
320   auto I = VRegInfos.insert(std::make_pair(Num, nullptr));
321   if (I.second) {
322     MachineRegisterInfo &MRI = MF.getRegInfo();
323     VRegInfo *Info = new (Allocator) VRegInfo;
324     Info->VReg = MRI.createIncompleteVirtualRegister();
325     I.first->second = Info;
326   }
327   return *I.first->second;
328 }
329 
330 VRegInfo &PerFunctionMIParsingState::getVRegInfoNamed(StringRef RegName) {
331   assert(RegName != "" && "Expected named reg.");
332 
333   auto I = VRegInfosNamed.insert(std::make_pair(RegName.str(), nullptr));
334   if (I.second) {
335     VRegInfo *Info = new (Allocator) VRegInfo;
336     Info->VReg = MF.getRegInfo().createIncompleteVirtualRegister(RegName);
337     I.first->second = Info;
338   }
339   return *I.first->second;
340 }
341 
342 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
343                            DenseMap<unsigned, const Value *> &Slots2Values) {
344   int Slot = MST.getLocalSlot(V);
345   if (Slot == -1)
346     return;
347   Slots2Values.insert(std::make_pair(unsigned(Slot), V));
348 }
349 
350 /// Creates the mapping from slot numbers to function's unnamed IR values.
351 static void initSlots2Values(const Function &F,
352                              DenseMap<unsigned, const Value *> &Slots2Values) {
353   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
354   MST.incorporateFunction(F);
355   for (const auto &Arg : F.args())
356     mapValueToSlot(&Arg, MST, Slots2Values);
357   for (const auto &BB : F) {
358     mapValueToSlot(&BB, MST, Slots2Values);
359     for (const auto &I : BB)
360       mapValueToSlot(&I, MST, Slots2Values);
361   }
362 }
363 
364 const Value* PerFunctionMIParsingState::getIRValue(unsigned Slot) {
365   if (Slots2Values.empty())
366     initSlots2Values(MF.getFunction(), Slots2Values);
367   return Slots2Values.lookup(Slot);
368 }
369 
370 namespace {
371 
372 /// A wrapper struct around the 'MachineOperand' struct that includes a source
373 /// range and other attributes.
374 struct ParsedMachineOperand {
375   MachineOperand Operand;
376   StringRef::iterator Begin;
377   StringRef::iterator End;
378   std::optional<unsigned> TiedDefIdx;
379 
380   ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
381                        StringRef::iterator End,
382                        std::optional<unsigned> &TiedDefIdx)
383       : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
384     if (TiedDefIdx)
385       assert(Operand.isReg() && Operand.isUse() &&
386              "Only used register operands can be tied");
387   }
388 };
389 
390 class MIParser {
391   MachineFunction &MF;
392   SMDiagnostic &Error;
393   StringRef Source, CurrentSource;
394   SMRange SourceRange;
395   MIToken Token;
396   PerFunctionMIParsingState &PFS;
397   /// Maps from slot numbers to function's unnamed basic blocks.
398   DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
399 
400 public:
401   MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
402            StringRef Source);
403   MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
404            StringRef Source, SMRange SourceRange);
405 
406   /// \p SkipChar gives the number of characters to skip before looking
407   /// for the next token.
408   void lex(unsigned SkipChar = 0);
409 
410   /// Report an error at the current location with the given message.
411   ///
412   /// This function always return true.
413   bool error(const Twine &Msg);
414 
415   /// Report an error at the given location with the given message.
416   ///
417   /// This function always return true.
418   bool error(StringRef::iterator Loc, const Twine &Msg);
419 
420   bool
421   parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
422   bool parseBasicBlocks();
423   bool parse(MachineInstr *&MI);
424   bool parseStandaloneMBB(MachineBasicBlock *&MBB);
425   bool parseStandaloneNamedRegister(Register &Reg);
426   bool parseStandaloneVirtualRegister(VRegInfo *&Info);
427   bool parseStandaloneRegister(Register &Reg);
428   bool parseStandaloneStackObject(int &FI);
429   bool parseStandaloneMDNode(MDNode *&Node);
430   bool parseMachineMetadata();
431   bool parseMDTuple(MDNode *&MD, bool IsDistinct);
432   bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
433   bool parseMetadata(Metadata *&MD);
434 
435   bool
436   parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
437   bool parseBasicBlock(MachineBasicBlock &MBB,
438                        MachineBasicBlock *&AddFalthroughFrom);
439   bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
440   bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
441 
442   bool parseNamedRegister(Register &Reg);
443   bool parseVirtualRegister(VRegInfo *&Info);
444   bool parseNamedVirtualRegister(VRegInfo *&Info);
445   bool parseRegister(Register &Reg, VRegInfo *&VRegInfo);
446   bool parseRegisterFlag(unsigned &Flags);
447   bool parseRegisterClassOrBank(VRegInfo &RegInfo);
448   bool parseSubRegisterIndex(unsigned &SubReg);
449   bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
450   bool parseRegisterOperand(MachineOperand &Dest,
451                             std::optional<unsigned> &TiedDefIdx,
452                             bool IsDef = false);
453   bool parseImmediateOperand(MachineOperand &Dest);
454   bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
455                        const Constant *&C);
456   bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
457   bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
458   bool parseTypedImmediateOperand(MachineOperand &Dest);
459   bool parseFPImmediateOperand(MachineOperand &Dest);
460   bool parseMBBReference(MachineBasicBlock *&MBB);
461   bool parseMBBOperand(MachineOperand &Dest);
462   bool parseStackFrameIndex(int &FI);
463   bool parseStackObjectOperand(MachineOperand &Dest);
464   bool parseFixedStackFrameIndex(int &FI);
465   bool parseFixedStackObjectOperand(MachineOperand &Dest);
466   bool parseGlobalValue(GlobalValue *&GV);
467   bool parseGlobalAddressOperand(MachineOperand &Dest);
468   bool parseConstantPoolIndexOperand(MachineOperand &Dest);
469   bool parseSubRegisterIndexOperand(MachineOperand &Dest);
470   bool parseJumpTableIndexOperand(MachineOperand &Dest);
471   bool parseExternalSymbolOperand(MachineOperand &Dest);
472   bool parseMCSymbolOperand(MachineOperand &Dest);
473   [[nodiscard]] bool parseMDNode(MDNode *&Node);
474   bool parseDIExpression(MDNode *&Expr);
475   bool parseDILocation(MDNode *&Expr);
476   bool parseMetadataOperand(MachineOperand &Dest);
477   bool parseCFIOffset(int &Offset);
478   bool parseCFIRegister(Register &Reg);
479   bool parseCFIAddressSpace(unsigned &AddressSpace);
480   bool parseCFIEscapeValues(std::string& Values);
481   bool parseCFIOperand(MachineOperand &Dest);
482   bool parseIRBlock(BasicBlock *&BB, const Function &F);
483   bool parseBlockAddressOperand(MachineOperand &Dest);
484   bool parseIntrinsicOperand(MachineOperand &Dest);
485   bool parsePredicateOperand(MachineOperand &Dest);
486   bool parseShuffleMaskOperand(MachineOperand &Dest);
487   bool parseTargetIndexOperand(MachineOperand &Dest);
488   bool parseDbgInstrRefOperand(MachineOperand &Dest);
489   bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
490   bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
491   bool parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
492                            MachineOperand &Dest,
493                            std::optional<unsigned> &TiedDefIdx);
494   bool parseMachineOperandAndTargetFlags(const unsigned OpCode,
495                                          const unsigned OpIdx,
496                                          MachineOperand &Dest,
497                                          std::optional<unsigned> &TiedDefIdx);
498   bool parseOffset(int64_t &Offset);
499   bool parseIRBlockAddressTaken(BasicBlock *&BB);
500   bool parseAlignment(uint64_t &Alignment);
501   bool parseAddrspace(unsigned &Addrspace);
502   bool parseSectionID(std::optional<MBBSectionID> &SID);
503   bool parseBBID(std::optional<unsigned> &BBID);
504   bool parseOperandsOffset(MachineOperand &Op);
505   bool parseIRValue(const Value *&V);
506   bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
507   bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
508   bool parseMachinePointerInfo(MachinePointerInfo &Dest);
509   bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
510   bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
511   bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
512   bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
513   bool parseHeapAllocMarker(MDNode *&Node);
514   bool parsePCSections(MDNode *&Node);
515 
516   bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
517                               MachineOperand &Dest, const MIRFormatter &MF);
518 
519 private:
520   /// Convert the integer literal in the current token into an unsigned integer.
521   ///
522   /// Return true if an error occurred.
523   bool getUnsigned(unsigned &Result);
524 
525   /// Convert the integer literal in the current token into an uint64.
526   ///
527   /// Return true if an error occurred.
528   bool getUint64(uint64_t &Result);
529 
530   /// Convert the hexadecimal literal in the current token into an unsigned
531   ///  APInt with a minimum bitwidth required to represent the value.
532   ///
533   /// Return true if the literal does not represent an integer value.
534   bool getHexUint(APInt &Result);
535 
536   /// If the current token is of the given kind, consume it and return false.
537   /// Otherwise report an error and return true.
538   bool expectAndConsume(MIToken::TokenKind TokenKind);
539 
540   /// If the current token is of the given kind, consume it and return true.
541   /// Otherwise return false.
542   bool consumeIfPresent(MIToken::TokenKind TokenKind);
543 
544   bool parseInstruction(unsigned &OpCode, unsigned &Flags);
545 
546   bool assignRegisterTies(MachineInstr &MI,
547                           ArrayRef<ParsedMachineOperand> Operands);
548 
549   bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
550                               const MCInstrDesc &MCID);
551 
552   const BasicBlock *getIRBlock(unsigned Slot);
553   const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
554 
555   /// Get or create an MCSymbol for a given name.
556   MCSymbol *getOrCreateMCSymbol(StringRef Name);
557 
558   /// parseStringConstant
559   ///   ::= StringConstant
560   bool parseStringConstant(std::string &Result);
561 
562   /// Map the location in the MI string to the corresponding location specified
563   /// in `SourceRange`.
564   SMLoc mapSMLoc(StringRef::iterator Loc);
565 };
566 
567 } // end anonymous namespace
568 
569 MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
570                    StringRef Source)
571     : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
572 {}
573 
574 MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
575                    StringRef Source, SMRange SourceRange)
576     : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source),
577       SourceRange(SourceRange), PFS(PFS) {}
578 
579 void MIParser::lex(unsigned SkipChar) {
580   CurrentSource = lexMIToken(
581       CurrentSource.slice(SkipChar, StringRef::npos), Token,
582       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
583 }
584 
585 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
586 
587 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
588   const SourceMgr &SM = *PFS.SM;
589   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
590   const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
591   if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
592     // Create an ordinary diagnostic when the source manager's buffer is the
593     // source string.
594     Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
595     return true;
596   }
597   // Create a diagnostic for a YAML string literal.
598   Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
599                        Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
600                        Source, std::nullopt, std::nullopt);
601   return true;
602 }
603 
604 SMLoc MIParser::mapSMLoc(StringRef::iterator Loc) {
605   assert(SourceRange.isValid() && "Invalid source range");
606   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
607   return SMLoc::getFromPointer(SourceRange.Start.getPointer() +
608                                (Loc - Source.data()));
609 }
610 
611 typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
612     ErrorCallbackType;
613 
614 static const char *toString(MIToken::TokenKind TokenKind) {
615   switch (TokenKind) {
616   case MIToken::comma:
617     return "','";
618   case MIToken::equal:
619     return "'='";
620   case MIToken::colon:
621     return "':'";
622   case MIToken::lparen:
623     return "'('";
624   case MIToken::rparen:
625     return "')'";
626   default:
627     return "<unknown token>";
628   }
629 }
630 
631 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
632   if (Token.isNot(TokenKind))
633     return error(Twine("expected ") + toString(TokenKind));
634   lex();
635   return false;
636 }
637 
638 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
639   if (Token.isNot(TokenKind))
640     return false;
641   lex();
642   return true;
643 }
644 
645 // Parse Machine Basic Block Section ID.
646 bool MIParser::parseSectionID(std::optional<MBBSectionID> &SID) {
647   assert(Token.is(MIToken::kw_bbsections));
648   lex();
649   if (Token.is(MIToken::IntegerLiteral)) {
650     unsigned Value = 0;
651     if (getUnsigned(Value))
652       return error("Unknown Section ID");
653     SID = MBBSectionID{Value};
654   } else {
655     const StringRef &S = Token.stringValue();
656     if (S == "Exception")
657       SID = MBBSectionID::ExceptionSectionID;
658     else if (S == "Cold")
659       SID = MBBSectionID::ColdSectionID;
660     else
661       return error("Unknown Section ID");
662   }
663   lex();
664   return false;
665 }
666 
667 // Parse Machine Basic Block ID.
668 bool MIParser::parseBBID(std::optional<unsigned> &BBID) {
669   assert(Token.is(MIToken::kw_bb_id));
670   lex();
671   unsigned Value = 0;
672   if (getUnsigned(Value))
673     return error("Unknown BB ID");
674   BBID = Value;
675   lex();
676   return false;
677 }
678 
679 bool MIParser::parseBasicBlockDefinition(
680     DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
681   assert(Token.is(MIToken::MachineBasicBlockLabel));
682   unsigned ID = 0;
683   if (getUnsigned(ID))
684     return true;
685   auto Loc = Token.location();
686   auto Name = Token.stringValue();
687   lex();
688   bool MachineBlockAddressTaken = false;
689   BasicBlock *AddressTakenIRBlock = nullptr;
690   bool IsLandingPad = false;
691   bool IsInlineAsmBrIndirectTarget = false;
692   bool IsEHFuncletEntry = false;
693   std::optional<MBBSectionID> SectionID;
694   uint64_t Alignment = 0;
695   std::optional<unsigned> BBID;
696   BasicBlock *BB = nullptr;
697   if (consumeIfPresent(MIToken::lparen)) {
698     do {
699       // TODO: Report an error when multiple same attributes are specified.
700       switch (Token.kind()) {
701       case MIToken::kw_machine_block_address_taken:
702         MachineBlockAddressTaken = true;
703         lex();
704         break;
705       case MIToken::kw_ir_block_address_taken:
706         if (parseIRBlockAddressTaken(AddressTakenIRBlock))
707           return true;
708         break;
709       case MIToken::kw_landing_pad:
710         IsLandingPad = true;
711         lex();
712         break;
713       case MIToken::kw_inlineasm_br_indirect_target:
714         IsInlineAsmBrIndirectTarget = true;
715         lex();
716         break;
717       case MIToken::kw_ehfunclet_entry:
718         IsEHFuncletEntry = true;
719         lex();
720         break;
721       case MIToken::kw_align:
722         if (parseAlignment(Alignment))
723           return true;
724         break;
725       case MIToken::IRBlock:
726       case MIToken::NamedIRBlock:
727         // TODO: Report an error when both name and ir block are specified.
728         if (parseIRBlock(BB, MF.getFunction()))
729           return true;
730         lex();
731         break;
732       case MIToken::kw_bbsections:
733         if (parseSectionID(SectionID))
734           return true;
735         break;
736       case MIToken::kw_bb_id:
737         if (parseBBID(BBID))
738           return true;
739         break;
740       default:
741         break;
742       }
743     } while (consumeIfPresent(MIToken::comma));
744     if (expectAndConsume(MIToken::rparen))
745       return true;
746   }
747   if (expectAndConsume(MIToken::colon))
748     return true;
749 
750   if (!Name.empty()) {
751     BB = dyn_cast_or_null<BasicBlock>(
752         MF.getFunction().getValueSymbolTable()->lookup(Name));
753     if (!BB)
754       return error(Loc, Twine("basic block '") + Name +
755                             "' is not defined in the function '" +
756                             MF.getName() + "'");
757   }
758   auto *MBB = MF.CreateMachineBasicBlock(BB);
759   MF.insert(MF.end(), MBB);
760   bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
761   if (!WasInserted)
762     return error(Loc, Twine("redefinition of machine basic block with id #") +
763                           Twine(ID));
764   if (Alignment)
765     MBB->setAlignment(Align(Alignment));
766   if (MachineBlockAddressTaken)
767     MBB->setMachineBlockAddressTaken();
768   if (AddressTakenIRBlock)
769     MBB->setAddressTakenIRBlock(AddressTakenIRBlock);
770   MBB->setIsEHPad(IsLandingPad);
771   MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
772   MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
773   if (SectionID) {
774     MBB->setSectionID(*SectionID);
775     MF.setBBSectionsType(BasicBlockSection::List);
776   }
777   if (BBID.has_value()) {
778     // BBSectionsType is set to `List` if any basic blocks has `SectionID`.
779     // Here, we set it to `Labels` if it hasn't been set above.
780     if (!MF.hasBBSections())
781       MF.setBBSectionsType(BasicBlockSection::Labels);
782     MBB->setBBID(BBID.value());
783   }
784   return false;
785 }
786 
787 bool MIParser::parseBasicBlockDefinitions(
788     DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
789   lex();
790   // Skip until the first machine basic block.
791   while (Token.is(MIToken::Newline))
792     lex();
793   if (Token.isErrorOrEOF())
794     return Token.isError();
795   if (Token.isNot(MIToken::MachineBasicBlockLabel))
796     return error("expected a basic block definition before instructions");
797   unsigned BraceDepth = 0;
798   do {
799     if (parseBasicBlockDefinition(MBBSlots))
800       return true;
801     bool IsAfterNewline = false;
802     // Skip until the next machine basic block.
803     while (true) {
804       if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
805           Token.isErrorOrEOF())
806         break;
807       else if (Token.is(MIToken::MachineBasicBlockLabel))
808         return error("basic block definition should be located at the start of "
809                      "the line");
810       else if (consumeIfPresent(MIToken::Newline)) {
811         IsAfterNewline = true;
812         continue;
813       }
814       IsAfterNewline = false;
815       if (Token.is(MIToken::lbrace))
816         ++BraceDepth;
817       if (Token.is(MIToken::rbrace)) {
818         if (!BraceDepth)
819           return error("extraneous closing brace ('}')");
820         --BraceDepth;
821       }
822       lex();
823     }
824     // Verify that we closed all of the '{' at the end of a file or a block.
825     if (!Token.isError() && BraceDepth)
826       return error("expected '}'"); // FIXME: Report a note that shows '{'.
827   } while (!Token.isErrorOrEOF());
828   return Token.isError();
829 }
830 
831 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
832   assert(Token.is(MIToken::kw_liveins));
833   lex();
834   if (expectAndConsume(MIToken::colon))
835     return true;
836   if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
837     return false;
838   do {
839     if (Token.isNot(MIToken::NamedRegister))
840       return error("expected a named register");
841     Register Reg;
842     if (parseNamedRegister(Reg))
843       return true;
844     lex();
845     LaneBitmask Mask = LaneBitmask::getAll();
846     if (consumeIfPresent(MIToken::colon)) {
847       // Parse lane mask.
848       if (Token.isNot(MIToken::IntegerLiteral) &&
849           Token.isNot(MIToken::HexLiteral))
850         return error("expected a lane mask");
851       static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
852                     "Use correct get-function for lane mask");
853       LaneBitmask::Type V;
854       if (getUint64(V))
855         return error("invalid lane mask value");
856       Mask = LaneBitmask(V);
857       lex();
858     }
859     MBB.addLiveIn(Reg, Mask);
860   } while (consumeIfPresent(MIToken::comma));
861   return false;
862 }
863 
864 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
865   assert(Token.is(MIToken::kw_successors));
866   lex();
867   if (expectAndConsume(MIToken::colon))
868     return true;
869   if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
870     return false;
871   do {
872     if (Token.isNot(MIToken::MachineBasicBlock))
873       return error("expected a machine basic block reference");
874     MachineBasicBlock *SuccMBB = nullptr;
875     if (parseMBBReference(SuccMBB))
876       return true;
877     lex();
878     unsigned Weight = 0;
879     if (consumeIfPresent(MIToken::lparen)) {
880       if (Token.isNot(MIToken::IntegerLiteral) &&
881           Token.isNot(MIToken::HexLiteral))
882         return error("expected an integer literal after '('");
883       if (getUnsigned(Weight))
884         return true;
885       lex();
886       if (expectAndConsume(MIToken::rparen))
887         return true;
888     }
889     MBB.addSuccessor(SuccMBB, BranchProbability::getRaw(Weight));
890   } while (consumeIfPresent(MIToken::comma));
891   MBB.normalizeSuccProbs();
892   return false;
893 }
894 
895 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
896                                MachineBasicBlock *&AddFalthroughFrom) {
897   // Skip the definition.
898   assert(Token.is(MIToken::MachineBasicBlockLabel));
899   lex();
900   if (consumeIfPresent(MIToken::lparen)) {
901     while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
902       lex();
903     consumeIfPresent(MIToken::rparen);
904   }
905   consumeIfPresent(MIToken::colon);
906 
907   // Parse the liveins and successors.
908   // N.B: Multiple lists of successors and liveins are allowed and they're
909   // merged into one.
910   // Example:
911   //   liveins: $edi
912   //   liveins: $esi
913   //
914   // is equivalent to
915   //   liveins: $edi, $esi
916   bool ExplicitSuccessors = false;
917   while (true) {
918     if (Token.is(MIToken::kw_successors)) {
919       if (parseBasicBlockSuccessors(MBB))
920         return true;
921       ExplicitSuccessors = true;
922     } else if (Token.is(MIToken::kw_liveins)) {
923       if (parseBasicBlockLiveins(MBB))
924         return true;
925     } else if (consumeIfPresent(MIToken::Newline)) {
926       continue;
927     } else
928       break;
929     if (!Token.isNewlineOrEOF())
930       return error("expected line break at the end of a list");
931     lex();
932   }
933 
934   // Parse the instructions.
935   bool IsInBundle = false;
936   MachineInstr *PrevMI = nullptr;
937   while (!Token.is(MIToken::MachineBasicBlockLabel) &&
938          !Token.is(MIToken::Eof)) {
939     if (consumeIfPresent(MIToken::Newline))
940       continue;
941     if (consumeIfPresent(MIToken::rbrace)) {
942       // The first parsing pass should verify that all closing '}' have an
943       // opening '{'.
944       assert(IsInBundle);
945       IsInBundle = false;
946       continue;
947     }
948     MachineInstr *MI = nullptr;
949     if (parse(MI))
950       return true;
951     MBB.insert(MBB.end(), MI);
952     if (IsInBundle) {
953       PrevMI->setFlag(MachineInstr::BundledSucc);
954       MI->setFlag(MachineInstr::BundledPred);
955     }
956     PrevMI = MI;
957     if (Token.is(MIToken::lbrace)) {
958       if (IsInBundle)
959         return error("nested instruction bundles are not allowed");
960       lex();
961       // This instruction is the start of the bundle.
962       MI->setFlag(MachineInstr::BundledSucc);
963       IsInBundle = true;
964       if (!Token.is(MIToken::Newline))
965         // The next instruction can be on the same line.
966         continue;
967     }
968     assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
969     lex();
970   }
971 
972   // Construct successor list by searching for basic block machine operands.
973   if (!ExplicitSuccessors) {
974     SmallVector<MachineBasicBlock*,4> Successors;
975     bool IsFallthrough;
976     guessSuccessors(MBB, Successors, IsFallthrough);
977     for (MachineBasicBlock *Succ : Successors)
978       MBB.addSuccessor(Succ);
979 
980     if (IsFallthrough) {
981       AddFalthroughFrom = &MBB;
982     } else {
983       MBB.normalizeSuccProbs();
984     }
985   }
986 
987   return false;
988 }
989 
990 bool MIParser::parseBasicBlocks() {
991   lex();
992   // Skip until the first machine basic block.
993   while (Token.is(MIToken::Newline))
994     lex();
995   if (Token.isErrorOrEOF())
996     return Token.isError();
997   // The first parsing pass should have verified that this token is a MBB label
998   // in the 'parseBasicBlockDefinitions' method.
999   assert(Token.is(MIToken::MachineBasicBlockLabel));
1000   MachineBasicBlock *AddFalthroughFrom = nullptr;
1001   do {
1002     MachineBasicBlock *MBB = nullptr;
1003     if (parseMBBReference(MBB))
1004       return true;
1005     if (AddFalthroughFrom) {
1006       if (!AddFalthroughFrom->isSuccessor(MBB))
1007         AddFalthroughFrom->addSuccessor(MBB);
1008       AddFalthroughFrom->normalizeSuccProbs();
1009       AddFalthroughFrom = nullptr;
1010     }
1011     if (parseBasicBlock(*MBB, AddFalthroughFrom))
1012       return true;
1013     // The method 'parseBasicBlock' should parse the whole block until the next
1014     // block or the end of file.
1015     assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
1016   } while (Token.isNot(MIToken::Eof));
1017   return false;
1018 }
1019 
1020 bool MIParser::parse(MachineInstr *&MI) {
1021   // Parse any register operands before '='
1022   MachineOperand MO = MachineOperand::CreateImm(0);
1023   SmallVector<ParsedMachineOperand, 8> Operands;
1024   while (Token.isRegister() || Token.isRegisterFlag()) {
1025     auto Loc = Token.location();
1026     std::optional<unsigned> TiedDefIdx;
1027     if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
1028       return true;
1029     Operands.push_back(
1030         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1031     if (Token.isNot(MIToken::comma))
1032       break;
1033     lex();
1034   }
1035   if (!Operands.empty() && expectAndConsume(MIToken::equal))
1036     return true;
1037 
1038   unsigned OpCode, Flags = 0;
1039   if (Token.isError() || parseInstruction(OpCode, Flags))
1040     return true;
1041 
1042   // Parse the remaining machine operands.
1043   while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
1044          Token.isNot(MIToken::kw_post_instr_symbol) &&
1045          Token.isNot(MIToken::kw_heap_alloc_marker) &&
1046          Token.isNot(MIToken::kw_pcsections) &&
1047          Token.isNot(MIToken::kw_cfi_type) &&
1048          Token.isNot(MIToken::kw_debug_location) &&
1049          Token.isNot(MIToken::kw_debug_instr_number) &&
1050          Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
1051     auto Loc = Token.location();
1052     std::optional<unsigned> TiedDefIdx;
1053     if (parseMachineOperandAndTargetFlags(OpCode, Operands.size(), MO, TiedDefIdx))
1054       return true;
1055     Operands.push_back(
1056         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1057     if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
1058         Token.is(MIToken::lbrace))
1059       break;
1060     if (Token.isNot(MIToken::comma))
1061       return error("expected ',' before the next machine operand");
1062     lex();
1063   }
1064 
1065   MCSymbol *PreInstrSymbol = nullptr;
1066   if (Token.is(MIToken::kw_pre_instr_symbol))
1067     if (parsePreOrPostInstrSymbol(PreInstrSymbol))
1068       return true;
1069   MCSymbol *PostInstrSymbol = nullptr;
1070   if (Token.is(MIToken::kw_post_instr_symbol))
1071     if (parsePreOrPostInstrSymbol(PostInstrSymbol))
1072       return true;
1073   MDNode *HeapAllocMarker = nullptr;
1074   if (Token.is(MIToken::kw_heap_alloc_marker))
1075     if (parseHeapAllocMarker(HeapAllocMarker))
1076       return true;
1077   MDNode *PCSections = nullptr;
1078   if (Token.is(MIToken::kw_pcsections))
1079     if (parsePCSections(PCSections))
1080       return true;
1081 
1082   unsigned CFIType = 0;
1083   if (Token.is(MIToken::kw_cfi_type)) {
1084     lex();
1085     if (Token.isNot(MIToken::IntegerLiteral))
1086       return error("expected an integer literal after 'cfi-type'");
1087     // getUnsigned is sufficient for 32-bit integers.
1088     if (getUnsigned(CFIType))
1089       return true;
1090     lex();
1091     // Lex past trailing comma if present.
1092     if (Token.is(MIToken::comma))
1093       lex();
1094   }
1095 
1096   unsigned InstrNum = 0;
1097   if (Token.is(MIToken::kw_debug_instr_number)) {
1098     lex();
1099     if (Token.isNot(MIToken::IntegerLiteral))
1100       return error("expected an integer literal after 'debug-instr-number'");
1101     if (getUnsigned(InstrNum))
1102       return true;
1103     lex();
1104     // Lex past trailing comma if present.
1105     if (Token.is(MIToken::comma))
1106       lex();
1107   }
1108 
1109   DebugLoc DebugLocation;
1110   if (Token.is(MIToken::kw_debug_location)) {
1111     lex();
1112     MDNode *Node = nullptr;
1113     if (Token.is(MIToken::exclaim)) {
1114       if (parseMDNode(Node))
1115         return true;
1116     } else if (Token.is(MIToken::md_dilocation)) {
1117       if (parseDILocation(Node))
1118         return true;
1119     } else
1120       return error("expected a metadata node after 'debug-location'");
1121     if (!isa<DILocation>(Node))
1122       return error("referenced metadata is not a DILocation");
1123     DebugLocation = DebugLoc(Node);
1124   }
1125 
1126   // Parse the machine memory operands.
1127   SmallVector<MachineMemOperand *, 2> MemOperands;
1128   if (Token.is(MIToken::coloncolon)) {
1129     lex();
1130     while (!Token.isNewlineOrEOF()) {
1131       MachineMemOperand *MemOp = nullptr;
1132       if (parseMachineMemoryOperand(MemOp))
1133         return true;
1134       MemOperands.push_back(MemOp);
1135       if (Token.isNewlineOrEOF())
1136         break;
1137       if (Token.isNot(MIToken::comma))
1138         return error("expected ',' before the next machine memory operand");
1139       lex();
1140     }
1141   }
1142 
1143   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
1144   if (!MCID.isVariadic()) {
1145     // FIXME: Move the implicit operand verification to the machine verifier.
1146     if (verifyImplicitOperands(Operands, MCID))
1147       return true;
1148   }
1149 
1150   MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
1151   MI->setFlags(Flags);
1152 
1153   unsigned NumExplicitOps = 0;
1154   for (const auto &Operand : Operands) {
1155     bool IsImplicitOp = Operand.Operand.isReg() && Operand.Operand.isImplicit();
1156     if (!IsImplicitOp) {
1157       if (!MCID.isVariadic() && NumExplicitOps >= MCID.getNumOperands() &&
1158           !Operand.Operand.isValidExcessOperand())
1159         return error(Operand.Begin, "too many operands for instruction");
1160 
1161       ++NumExplicitOps;
1162     }
1163 
1164     MI->addOperand(MF, Operand.Operand);
1165   }
1166 
1167   if (assignRegisterTies(*MI, Operands))
1168     return true;
1169   if (PreInstrSymbol)
1170     MI->setPreInstrSymbol(MF, PreInstrSymbol);
1171   if (PostInstrSymbol)
1172     MI->setPostInstrSymbol(MF, PostInstrSymbol);
1173   if (HeapAllocMarker)
1174     MI->setHeapAllocMarker(MF, HeapAllocMarker);
1175   if (PCSections)
1176     MI->setPCSections(MF, PCSections);
1177   if (CFIType)
1178     MI->setCFIType(MF, CFIType);
1179   if (!MemOperands.empty())
1180     MI->setMemRefs(MF, MemOperands);
1181   if (InstrNum)
1182     MI->setDebugInstrNum(InstrNum);
1183   return false;
1184 }
1185 
1186 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
1187   lex();
1188   if (Token.isNot(MIToken::MachineBasicBlock))
1189     return error("expected a machine basic block reference");
1190   if (parseMBBReference(MBB))
1191     return true;
1192   lex();
1193   if (Token.isNot(MIToken::Eof))
1194     return error(
1195         "expected end of string after the machine basic block reference");
1196   return false;
1197 }
1198 
1199 bool MIParser::parseStandaloneNamedRegister(Register &Reg) {
1200   lex();
1201   if (Token.isNot(MIToken::NamedRegister))
1202     return error("expected a named register");
1203   if (parseNamedRegister(Reg))
1204     return true;
1205   lex();
1206   if (Token.isNot(MIToken::Eof))
1207     return error("expected end of string after the register reference");
1208   return false;
1209 }
1210 
1211 bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
1212   lex();
1213   if (Token.isNot(MIToken::VirtualRegister))
1214     return error("expected a virtual register");
1215   if (parseVirtualRegister(Info))
1216     return true;
1217   lex();
1218   if (Token.isNot(MIToken::Eof))
1219     return error("expected end of string after the register reference");
1220   return false;
1221 }
1222 
1223 bool MIParser::parseStandaloneRegister(Register &Reg) {
1224   lex();
1225   if (Token.isNot(MIToken::NamedRegister) &&
1226       Token.isNot(MIToken::VirtualRegister))
1227     return error("expected either a named or virtual register");
1228 
1229   VRegInfo *Info;
1230   if (parseRegister(Reg, Info))
1231     return true;
1232 
1233   lex();
1234   if (Token.isNot(MIToken::Eof))
1235     return error("expected end of string after the register reference");
1236   return false;
1237 }
1238 
1239 bool MIParser::parseStandaloneStackObject(int &FI) {
1240   lex();
1241   if (Token.isNot(MIToken::StackObject))
1242     return error("expected a stack object");
1243   if (parseStackFrameIndex(FI))
1244     return true;
1245   if (Token.isNot(MIToken::Eof))
1246     return error("expected end of string after the stack object reference");
1247   return false;
1248 }
1249 
1250 bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
1251   lex();
1252   if (Token.is(MIToken::exclaim)) {
1253     if (parseMDNode(Node))
1254       return true;
1255   } else if (Token.is(MIToken::md_diexpr)) {
1256     if (parseDIExpression(Node))
1257       return true;
1258   } else if (Token.is(MIToken::md_dilocation)) {
1259     if (parseDILocation(Node))
1260       return true;
1261   } else
1262     return error("expected a metadata node");
1263   if (Token.isNot(MIToken::Eof))
1264     return error("expected end of string after the metadata node");
1265   return false;
1266 }
1267 
1268 bool MIParser::parseMachineMetadata() {
1269   lex();
1270   if (Token.isNot(MIToken::exclaim))
1271     return error("expected a metadata node");
1272 
1273   lex();
1274   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1275     return error("expected metadata id after '!'");
1276   unsigned ID = 0;
1277   if (getUnsigned(ID))
1278     return true;
1279   lex();
1280   if (expectAndConsume(MIToken::equal))
1281     return true;
1282   bool IsDistinct = Token.is(MIToken::kw_distinct);
1283   if (IsDistinct)
1284     lex();
1285   if (Token.isNot(MIToken::exclaim))
1286     return error("expected a metadata node");
1287   lex();
1288 
1289   MDNode *MD;
1290   if (parseMDTuple(MD, IsDistinct))
1291     return true;
1292 
1293   auto FI = PFS.MachineForwardRefMDNodes.find(ID);
1294   if (FI != PFS.MachineForwardRefMDNodes.end()) {
1295     FI->second.first->replaceAllUsesWith(MD);
1296     PFS.MachineForwardRefMDNodes.erase(FI);
1297 
1298     assert(PFS.MachineMetadataNodes[ID] == MD && "Tracking VH didn't work");
1299   } else {
1300     if (PFS.MachineMetadataNodes.count(ID))
1301       return error("Metadata id is already used");
1302     PFS.MachineMetadataNodes[ID].reset(MD);
1303   }
1304 
1305   return false;
1306 }
1307 
1308 bool MIParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
1309   SmallVector<Metadata *, 16> Elts;
1310   if (parseMDNodeVector(Elts))
1311     return true;
1312   MD = (IsDistinct ? MDTuple::getDistinct
1313                    : MDTuple::get)(MF.getFunction().getContext(), Elts);
1314   return false;
1315 }
1316 
1317 bool MIParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
1318   if (Token.isNot(MIToken::lbrace))
1319     return error("expected '{' here");
1320   lex();
1321 
1322   if (Token.is(MIToken::rbrace)) {
1323     lex();
1324     return false;
1325   }
1326 
1327   do {
1328     Metadata *MD;
1329     if (parseMetadata(MD))
1330       return true;
1331 
1332     Elts.push_back(MD);
1333 
1334     if (Token.isNot(MIToken::comma))
1335       break;
1336     lex();
1337   } while (true);
1338 
1339   if (Token.isNot(MIToken::rbrace))
1340     return error("expected end of metadata node");
1341   lex();
1342 
1343   return false;
1344 }
1345 
1346 // ::= !42
1347 // ::= !"string"
1348 bool MIParser::parseMetadata(Metadata *&MD) {
1349   if (Token.isNot(MIToken::exclaim))
1350     return error("expected '!' here");
1351   lex();
1352 
1353   if (Token.is(MIToken::StringConstant)) {
1354     std::string Str;
1355     if (parseStringConstant(Str))
1356       return true;
1357     MD = MDString::get(MF.getFunction().getContext(), Str);
1358     return false;
1359   }
1360 
1361   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1362     return error("expected metadata id after '!'");
1363 
1364   SMLoc Loc = mapSMLoc(Token.location());
1365 
1366   unsigned ID = 0;
1367   if (getUnsigned(ID))
1368     return true;
1369   lex();
1370 
1371   auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
1372   if (NodeInfo != PFS.IRSlots.MetadataNodes.end()) {
1373     MD = NodeInfo->second.get();
1374     return false;
1375   }
1376   // Check machine metadata.
1377   NodeInfo = PFS.MachineMetadataNodes.find(ID);
1378   if (NodeInfo != PFS.MachineMetadataNodes.end()) {
1379     MD = NodeInfo->second.get();
1380     return false;
1381   }
1382   // Forward reference.
1383   auto &FwdRef = PFS.MachineForwardRefMDNodes[ID];
1384   FwdRef = std::make_pair(
1385       MDTuple::getTemporary(MF.getFunction().getContext(), std::nullopt), Loc);
1386   PFS.MachineMetadataNodes[ID].reset(FwdRef.first.get());
1387   MD = FwdRef.first.get();
1388 
1389   return false;
1390 }
1391 
1392 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
1393   assert(MO.isImplicit());
1394   return MO.isDef() ? "implicit-def" : "implicit";
1395 }
1396 
1397 static std::string getRegisterName(const TargetRegisterInfo *TRI,
1398                                    Register Reg) {
1399   assert(Reg.isPhysical() && "expected phys reg");
1400   return StringRef(TRI->getName(Reg)).lower();
1401 }
1402 
1403 /// Return true if the parsed machine operands contain a given machine operand.
1404 static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
1405                                 ArrayRef<ParsedMachineOperand> Operands) {
1406   for (const auto &I : Operands) {
1407     if (ImplicitOperand.isIdenticalTo(I.Operand))
1408       return true;
1409   }
1410   return false;
1411 }
1412 
1413 bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
1414                                       const MCInstrDesc &MCID) {
1415   if (MCID.isCall())
1416     // We can't verify call instructions as they can contain arbitrary implicit
1417     // register and register mask operands.
1418     return false;
1419 
1420   // Gather all the expected implicit operands.
1421   SmallVector<MachineOperand, 4> ImplicitOperands;
1422   for (MCPhysReg ImpDef : MCID.implicit_defs())
1423     ImplicitOperands.push_back(MachineOperand::CreateReg(ImpDef, true, true));
1424   for (MCPhysReg ImpUse : MCID.implicit_uses())
1425     ImplicitOperands.push_back(MachineOperand::CreateReg(ImpUse, false, true));
1426 
1427   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1428   assert(TRI && "Expected target register info");
1429   for (const auto &I : ImplicitOperands) {
1430     if (isImplicitOperandIn(I, Operands))
1431       continue;
1432     return error(Operands.empty() ? Token.location() : Operands.back().End,
1433                  Twine("missing implicit register operand '") +
1434                      printImplicitRegisterFlag(I) + " $" +
1435                      getRegisterName(TRI, I.getReg()) + "'");
1436   }
1437   return false;
1438 }
1439 
1440 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
1441   // Allow frame and fast math flags for OPCODE
1442   while (Token.is(MIToken::kw_frame_setup) ||
1443          Token.is(MIToken::kw_frame_destroy) ||
1444          Token.is(MIToken::kw_nnan) ||
1445          Token.is(MIToken::kw_ninf) ||
1446          Token.is(MIToken::kw_nsz) ||
1447          Token.is(MIToken::kw_arcp) ||
1448          Token.is(MIToken::kw_contract) ||
1449          Token.is(MIToken::kw_afn) ||
1450          Token.is(MIToken::kw_reassoc) ||
1451          Token.is(MIToken::kw_nuw) ||
1452          Token.is(MIToken::kw_nsw) ||
1453          Token.is(MIToken::kw_exact) ||
1454          Token.is(MIToken::kw_nofpexcept) ||
1455          Token.is(MIToken::kw_unpredictable)) {
1456     // Mine frame and fast math flags
1457     if (Token.is(MIToken::kw_frame_setup))
1458       Flags |= MachineInstr::FrameSetup;
1459     if (Token.is(MIToken::kw_frame_destroy))
1460       Flags |= MachineInstr::FrameDestroy;
1461     if (Token.is(MIToken::kw_nnan))
1462       Flags |= MachineInstr::FmNoNans;
1463     if (Token.is(MIToken::kw_ninf))
1464       Flags |= MachineInstr::FmNoInfs;
1465     if (Token.is(MIToken::kw_nsz))
1466       Flags |= MachineInstr::FmNsz;
1467     if (Token.is(MIToken::kw_arcp))
1468       Flags |= MachineInstr::FmArcp;
1469     if (Token.is(MIToken::kw_contract))
1470       Flags |= MachineInstr::FmContract;
1471     if (Token.is(MIToken::kw_afn))
1472       Flags |= MachineInstr::FmAfn;
1473     if (Token.is(MIToken::kw_reassoc))
1474       Flags |= MachineInstr::FmReassoc;
1475     if (Token.is(MIToken::kw_nuw))
1476       Flags |= MachineInstr::NoUWrap;
1477     if (Token.is(MIToken::kw_nsw))
1478       Flags |= MachineInstr::NoSWrap;
1479     if (Token.is(MIToken::kw_exact))
1480       Flags |= MachineInstr::IsExact;
1481     if (Token.is(MIToken::kw_nofpexcept))
1482       Flags |= MachineInstr::NoFPExcept;
1483     if (Token.is(MIToken::kw_unpredictable))
1484       Flags |= MachineInstr::Unpredictable;
1485 
1486     lex();
1487   }
1488   if (Token.isNot(MIToken::Identifier))
1489     return error("expected a machine instruction");
1490   StringRef InstrName = Token.stringValue();
1491   if (PFS.Target.parseInstrName(InstrName, OpCode))
1492     return error(Twine("unknown machine instruction name '") + InstrName + "'");
1493   lex();
1494   return false;
1495 }
1496 
1497 bool MIParser::parseNamedRegister(Register &Reg) {
1498   assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1499   StringRef Name = Token.stringValue();
1500   if (PFS.Target.getRegisterByName(Name, Reg))
1501     return error(Twine("unknown register name '") + Name + "'");
1502   return false;
1503 }
1504 
1505 bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1506   assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1507   StringRef Name = Token.stringValue();
1508   // TODO: Check that the VReg name is not the same as a physical register name.
1509   //       If it is, then print a warning (when warnings are implemented).
1510   Info = &PFS.getVRegInfoNamed(Name);
1511   return false;
1512 }
1513 
1514 bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1515   if (Token.is(MIToken::NamedVirtualRegister))
1516     return parseNamedVirtualRegister(Info);
1517   assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1518   unsigned ID;
1519   if (getUnsigned(ID))
1520     return true;
1521   Info = &PFS.getVRegInfo(ID);
1522   return false;
1523 }
1524 
1525 bool MIParser::parseRegister(Register &Reg, VRegInfo *&Info) {
1526   switch (Token.kind()) {
1527   case MIToken::underscore:
1528     Reg = 0;
1529     return false;
1530   case MIToken::NamedRegister:
1531     return parseNamedRegister(Reg);
1532   case MIToken::NamedVirtualRegister:
1533   case MIToken::VirtualRegister:
1534     if (parseVirtualRegister(Info))
1535       return true;
1536     Reg = Info->VReg;
1537     return false;
1538   // TODO: Parse other register kinds.
1539   default:
1540     llvm_unreachable("The current token should be a register");
1541   }
1542 }
1543 
1544 bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1545   if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1546     return error("expected '_', register class, or register bank name");
1547   StringRef::iterator Loc = Token.location();
1548   StringRef Name = Token.stringValue();
1549 
1550   // Was it a register class?
1551   const TargetRegisterClass *RC = PFS.Target.getRegClass(Name);
1552   if (RC) {
1553     lex();
1554 
1555     switch (RegInfo.Kind) {
1556     case VRegInfo::UNKNOWN:
1557     case VRegInfo::NORMAL:
1558       RegInfo.Kind = VRegInfo::NORMAL;
1559       if (RegInfo.Explicit && RegInfo.D.RC != RC) {
1560         const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1561         return error(Loc, Twine("conflicting register classes, previously: ") +
1562                      Twine(TRI.getRegClassName(RegInfo.D.RC)));
1563       }
1564       RegInfo.D.RC = RC;
1565       RegInfo.Explicit = true;
1566       return false;
1567 
1568     case VRegInfo::GENERIC:
1569     case VRegInfo::REGBANK:
1570       return error(Loc, "register class specification on generic register");
1571     }
1572     llvm_unreachable("Unexpected register kind");
1573   }
1574 
1575   // Should be a register bank or a generic register.
1576   const RegisterBank *RegBank = nullptr;
1577   if (Name != "_") {
1578     RegBank = PFS.Target.getRegBank(Name);
1579     if (!RegBank)
1580       return error(Loc, "expected '_', register class, or register bank name");
1581   }
1582 
1583   lex();
1584 
1585   switch (RegInfo.Kind) {
1586   case VRegInfo::UNKNOWN:
1587   case VRegInfo::GENERIC:
1588   case VRegInfo::REGBANK:
1589     RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1590     if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1591       return error(Loc, "conflicting generic register banks");
1592     RegInfo.D.RegBank = RegBank;
1593     RegInfo.Explicit = true;
1594     return false;
1595 
1596   case VRegInfo::NORMAL:
1597     return error(Loc, "register bank specification on normal register");
1598   }
1599   llvm_unreachable("Unexpected register kind");
1600 }
1601 
1602 bool MIParser::parseRegisterFlag(unsigned &Flags) {
1603   const unsigned OldFlags = Flags;
1604   switch (Token.kind()) {
1605   case MIToken::kw_implicit:
1606     Flags |= RegState::Implicit;
1607     break;
1608   case MIToken::kw_implicit_define:
1609     Flags |= RegState::ImplicitDefine;
1610     break;
1611   case MIToken::kw_def:
1612     Flags |= RegState::Define;
1613     break;
1614   case MIToken::kw_dead:
1615     Flags |= RegState::Dead;
1616     break;
1617   case MIToken::kw_killed:
1618     Flags |= RegState::Kill;
1619     break;
1620   case MIToken::kw_undef:
1621     Flags |= RegState::Undef;
1622     break;
1623   case MIToken::kw_internal:
1624     Flags |= RegState::InternalRead;
1625     break;
1626   case MIToken::kw_early_clobber:
1627     Flags |= RegState::EarlyClobber;
1628     break;
1629   case MIToken::kw_debug_use:
1630     Flags |= RegState::Debug;
1631     break;
1632   case MIToken::kw_renamable:
1633     Flags |= RegState::Renamable;
1634     break;
1635   default:
1636     llvm_unreachable("The current token should be a register flag");
1637   }
1638   if (OldFlags == Flags)
1639     // We know that the same flag is specified more than once when the flags
1640     // weren't modified.
1641     return error("duplicate '" + Token.stringValue() + "' register flag");
1642   lex();
1643   return false;
1644 }
1645 
1646 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1647   assert(Token.is(MIToken::dot));
1648   lex();
1649   if (Token.isNot(MIToken::Identifier))
1650     return error("expected a subregister index after '.'");
1651   auto Name = Token.stringValue();
1652   SubReg = PFS.Target.getSubRegIndex(Name);
1653   if (!SubReg)
1654     return error(Twine("use of unknown subregister index '") + Name + "'");
1655   lex();
1656   return false;
1657 }
1658 
1659 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1660   if (!consumeIfPresent(MIToken::kw_tied_def))
1661     return true;
1662   if (Token.isNot(MIToken::IntegerLiteral))
1663     return error("expected an integer literal after 'tied-def'");
1664   if (getUnsigned(TiedDefIdx))
1665     return true;
1666   lex();
1667   if (expectAndConsume(MIToken::rparen))
1668     return true;
1669   return false;
1670 }
1671 
1672 bool MIParser::assignRegisterTies(MachineInstr &MI,
1673                                   ArrayRef<ParsedMachineOperand> Operands) {
1674   SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1675   for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1676     if (!Operands[I].TiedDefIdx)
1677       continue;
1678     // The parser ensures that this operand is a register use, so we just have
1679     // to check the tied-def operand.
1680     unsigned DefIdx = *Operands[I].TiedDefIdx;
1681     if (DefIdx >= E)
1682       return error(Operands[I].Begin,
1683                    Twine("use of invalid tied-def operand index '" +
1684                          Twine(DefIdx) + "'; instruction has only ") +
1685                        Twine(E) + " operands");
1686     const auto &DefOperand = Operands[DefIdx].Operand;
1687     if (!DefOperand.isReg() || !DefOperand.isDef())
1688       // FIXME: add note with the def operand.
1689       return error(Operands[I].Begin,
1690                    Twine("use of invalid tied-def operand index '") +
1691                        Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1692                        " isn't a defined register");
1693     // Check that the tied-def operand wasn't tied elsewhere.
1694     for (const auto &TiedPair : TiedRegisterPairs) {
1695       if (TiedPair.first == DefIdx)
1696         return error(Operands[I].Begin,
1697                      Twine("the tied-def operand #") + Twine(DefIdx) +
1698                          " is already tied with another register operand");
1699     }
1700     TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1701   }
1702   // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1703   // indices must be less than tied max.
1704   for (const auto &TiedPair : TiedRegisterPairs)
1705     MI.tieOperands(TiedPair.first, TiedPair.second);
1706   return false;
1707 }
1708 
1709 bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1710                                     std::optional<unsigned> &TiedDefIdx,
1711                                     bool IsDef) {
1712   unsigned Flags = IsDef ? RegState::Define : 0;
1713   while (Token.isRegisterFlag()) {
1714     if (parseRegisterFlag(Flags))
1715       return true;
1716   }
1717   if (!Token.isRegister())
1718     return error("expected a register after register flags");
1719   Register Reg;
1720   VRegInfo *RegInfo;
1721   if (parseRegister(Reg, RegInfo))
1722     return true;
1723   lex();
1724   unsigned SubReg = 0;
1725   if (Token.is(MIToken::dot)) {
1726     if (parseSubRegisterIndex(SubReg))
1727       return true;
1728     if (!Reg.isVirtual())
1729       return error("subregister index expects a virtual register");
1730   }
1731   if (Token.is(MIToken::colon)) {
1732     if (!Reg.isVirtual())
1733       return error("register class specification expects a virtual register");
1734     lex();
1735     if (parseRegisterClassOrBank(*RegInfo))
1736         return true;
1737   }
1738   MachineRegisterInfo &MRI = MF.getRegInfo();
1739   if ((Flags & RegState::Define) == 0) {
1740     if (consumeIfPresent(MIToken::lparen)) {
1741       unsigned Idx;
1742       if (!parseRegisterTiedDefIndex(Idx))
1743         TiedDefIdx = Idx;
1744       else {
1745         // Try a redundant low-level type.
1746         LLT Ty;
1747         if (parseLowLevelType(Token.location(), Ty))
1748           return error("expected tied-def or low-level type after '('");
1749 
1750         if (expectAndConsume(MIToken::rparen))
1751           return true;
1752 
1753         if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1754           return error("inconsistent type for generic virtual register");
1755 
1756         MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1757         MRI.setType(Reg, Ty);
1758       }
1759     }
1760   } else if (consumeIfPresent(MIToken::lparen)) {
1761     // Virtual registers may have a tpe with GlobalISel.
1762     if (!Reg.isVirtual())
1763       return error("unexpected type on physical register");
1764 
1765     LLT Ty;
1766     if (parseLowLevelType(Token.location(), Ty))
1767       return true;
1768 
1769     if (expectAndConsume(MIToken::rparen))
1770       return true;
1771 
1772     if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1773       return error("inconsistent type for generic virtual register");
1774 
1775     MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1776     MRI.setType(Reg, Ty);
1777   } else if (Reg.isVirtual()) {
1778     // Generic virtual registers must have a type.
1779     // If we end up here this means the type hasn't been specified and
1780     // this is bad!
1781     if (RegInfo->Kind == VRegInfo::GENERIC ||
1782         RegInfo->Kind == VRegInfo::REGBANK)
1783       return error("generic virtual registers must have a type");
1784   }
1785 
1786   if (Flags & RegState::Define) {
1787     if (Flags & RegState::Kill)
1788       return error("cannot have a killed def operand");
1789   } else {
1790     if (Flags & RegState::Dead)
1791       return error("cannot have a dead use operand");
1792   }
1793 
1794   Dest = MachineOperand::CreateReg(
1795       Reg, Flags & RegState::Define, Flags & RegState::Implicit,
1796       Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
1797       Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
1798       Flags & RegState::InternalRead, Flags & RegState::Renamable);
1799 
1800   return false;
1801 }
1802 
1803 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1804   assert(Token.is(MIToken::IntegerLiteral));
1805   const APSInt &Int = Token.integerValue();
1806   if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1807     Dest = MachineOperand::CreateImm(*SImm);
1808   else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1809     Dest = MachineOperand::CreateImm(*UImm);
1810   else
1811     return error("integer literal is too large to be an immediate operand");
1812   lex();
1813   return false;
1814 }
1815 
1816 bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
1817                                       const unsigned OpIdx,
1818                                       MachineOperand &Dest,
1819                                       const MIRFormatter &MF) {
1820   assert(Token.is(MIToken::dot));
1821   auto Loc = Token.location(); // record start position
1822   size_t Len = 1;              // for "."
1823   lex();
1824 
1825   // Handle the case that mnemonic starts with number.
1826   if (Token.is(MIToken::IntegerLiteral)) {
1827     Len += Token.range().size();
1828     lex();
1829   }
1830 
1831   StringRef Src;
1832   if (Token.is(MIToken::comma))
1833     Src = StringRef(Loc, Len);
1834   else {
1835     assert(Token.is(MIToken::Identifier));
1836     Src = StringRef(Loc, Len + Token.stringValue().size());
1837   }
1838   int64_t Val;
1839   if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
1840                           [this](StringRef::iterator Loc, const Twine &Msg)
1841                               -> bool { return error(Loc, Msg); }))
1842     return true;
1843 
1844   Dest = MachineOperand::CreateImm(Val);
1845   if (!Token.is(MIToken::comma))
1846     lex();
1847   return false;
1848 }
1849 
1850 static bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1851                             PerFunctionMIParsingState &PFS, const Constant *&C,
1852                             ErrorCallbackType ErrCB) {
1853   auto Source = StringValue.str(); // The source has to be null terminated.
1854   SMDiagnostic Err;
1855   C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
1856                          &PFS.IRSlots);
1857   if (!C)
1858     return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
1859   return false;
1860 }
1861 
1862 bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1863                                const Constant *&C) {
1864   return ::parseIRConstant(
1865       Loc, StringValue, PFS, C,
1866       [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
1867         return error(Loc, Msg);
1868       });
1869 }
1870 
1871 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1872   if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1873     return true;
1874   lex();
1875   return false;
1876 }
1877 
1878 // See LLT implementation for bit size limits.
1879 static bool verifyScalarSize(uint64_t Size) {
1880   return Size != 0 && isUInt<16>(Size);
1881 }
1882 
1883 static bool verifyVectorElementCount(uint64_t NumElts) {
1884   return NumElts != 0 && isUInt<16>(NumElts);
1885 }
1886 
1887 static bool verifyAddrSpace(uint64_t AddrSpace) {
1888   return isUInt<24>(AddrSpace);
1889 }
1890 
1891 bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
1892   if (Token.range().front() == 's' || Token.range().front() == 'p') {
1893     StringRef SizeStr = Token.range().drop_front();
1894     if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1895       return error("expected integers after 's'/'p' type character");
1896   }
1897 
1898   if (Token.range().front() == 's') {
1899     auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
1900     if (!verifyScalarSize(ScalarSize))
1901       return error("invalid size for scalar type");
1902 
1903     Ty = LLT::scalar(ScalarSize);
1904     lex();
1905     return false;
1906   } else if (Token.range().front() == 'p') {
1907     const DataLayout &DL = MF.getDataLayout();
1908     uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
1909     if (!verifyAddrSpace(AS))
1910       return error("invalid address space number");
1911 
1912     Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1913     lex();
1914     return false;
1915   }
1916 
1917   // Now we're looking for a vector.
1918   if (Token.isNot(MIToken::less))
1919     return error(Loc,
1920                  "expected sN, pA, <M x sN>, or <M x pA> for GlobalISel type");
1921   lex();
1922 
1923   if (Token.isNot(MIToken::IntegerLiteral))
1924     return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1925   uint64_t NumElements = Token.integerValue().getZExtValue();
1926   if (!verifyVectorElementCount(NumElements))
1927     return error("invalid number of vector elements");
1928 
1929   lex();
1930 
1931   if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
1932     return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1933   lex();
1934 
1935   if (Token.range().front() != 's' && Token.range().front() != 'p')
1936     return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1937   StringRef SizeStr = Token.range().drop_front();
1938   if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1939     return error("expected integers after 's'/'p' type character");
1940 
1941   if (Token.range().front() == 's') {
1942     auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
1943     if (!verifyScalarSize(ScalarSize))
1944       return error("invalid size for scalar type");
1945     Ty = LLT::scalar(ScalarSize);
1946   } else if (Token.range().front() == 'p') {
1947     const DataLayout &DL = MF.getDataLayout();
1948     uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
1949     if (!verifyAddrSpace(AS))
1950       return error("invalid address space number");
1951 
1952     Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1953   } else
1954     return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1955   lex();
1956 
1957   if (Token.isNot(MIToken::greater))
1958     return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1959   lex();
1960 
1961   Ty = LLT::fixed_vector(NumElements, Ty);
1962   return false;
1963 }
1964 
1965 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
1966   assert(Token.is(MIToken::Identifier));
1967   StringRef TypeStr = Token.range();
1968   if (TypeStr.front() != 'i' && TypeStr.front() != 's' &&
1969       TypeStr.front() != 'p')
1970     return error(
1971         "a typed immediate operand should start with one of 'i', 's', or 'p'");
1972   StringRef SizeStr = Token.range().drop_front();
1973   if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1974     return error("expected integers after 'i'/'s'/'p' type character");
1975 
1976   auto Loc = Token.location();
1977   lex();
1978   if (Token.isNot(MIToken::IntegerLiteral)) {
1979     if (Token.isNot(MIToken::Identifier) ||
1980         !(Token.range() == "true" || Token.range() == "false"))
1981       return error("expected an integer literal");
1982   }
1983   const Constant *C = nullptr;
1984   if (parseIRConstant(Loc, C))
1985     return true;
1986   Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
1987   return false;
1988 }
1989 
1990 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
1991   auto Loc = Token.location();
1992   lex();
1993   if (Token.isNot(MIToken::FloatingPointLiteral) &&
1994       Token.isNot(MIToken::HexLiteral))
1995     return error("expected a floating point literal");
1996   const Constant *C = nullptr;
1997   if (parseIRConstant(Loc, C))
1998     return true;
1999   Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
2000   return false;
2001 }
2002 
2003 static bool getHexUint(const MIToken &Token, APInt &Result) {
2004   assert(Token.is(MIToken::HexLiteral));
2005   StringRef S = Token.range();
2006   assert(S[0] == '0' && tolower(S[1]) == 'x');
2007   // This could be a floating point literal with a special prefix.
2008   if (!isxdigit(S[2]))
2009     return true;
2010   StringRef V = S.substr(2);
2011   APInt A(V.size()*4, V, 16);
2012 
2013   // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2014   // sure it isn't the case before constructing result.
2015   unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2016   Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2017   return false;
2018 }
2019 
2020 static bool getUnsigned(const MIToken &Token, unsigned &Result,
2021                         ErrorCallbackType ErrCB) {
2022   if (Token.hasIntegerValue()) {
2023     const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2024     uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
2025     if (Val64 == Limit)
2026       return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2027     Result = Val64;
2028     return false;
2029   }
2030   if (Token.is(MIToken::HexLiteral)) {
2031     APInt A;
2032     if (getHexUint(Token, A))
2033       return true;
2034     if (A.getBitWidth() > 32)
2035       return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2036     Result = A.getZExtValue();
2037     return false;
2038   }
2039   return true;
2040 }
2041 
2042 bool MIParser::getUnsigned(unsigned &Result) {
2043   return ::getUnsigned(
2044       Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2045         return error(Loc, Msg);
2046       });
2047 }
2048 
2049 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2050   assert(Token.is(MIToken::MachineBasicBlock) ||
2051          Token.is(MIToken::MachineBasicBlockLabel));
2052   unsigned Number;
2053   if (getUnsigned(Number))
2054     return true;
2055   auto MBBInfo = PFS.MBBSlots.find(Number);
2056   if (MBBInfo == PFS.MBBSlots.end())
2057     return error(Twine("use of undefined machine basic block #") +
2058                  Twine(Number));
2059   MBB = MBBInfo->second;
2060   // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2061   // we drop the <irname> from the bb.<id>.<irname> format.
2062   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2063     return error(Twine("the name of machine basic block #") + Twine(Number) +
2064                  " isn't '" + Token.stringValue() + "'");
2065   return false;
2066 }
2067 
2068 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2069   MachineBasicBlock *MBB;
2070   if (parseMBBReference(MBB))
2071     return true;
2072   Dest = MachineOperand::CreateMBB(MBB);
2073   lex();
2074   return false;
2075 }
2076 
2077 bool MIParser::parseStackFrameIndex(int &FI) {
2078   assert(Token.is(MIToken::StackObject));
2079   unsigned ID;
2080   if (getUnsigned(ID))
2081     return true;
2082   auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2083   if (ObjectInfo == PFS.StackObjectSlots.end())
2084     return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2085                  "'");
2086   StringRef Name;
2087   if (const auto *Alloca =
2088           MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2089     Name = Alloca->getName();
2090   if (!Token.stringValue().empty() && Token.stringValue() != Name)
2091     return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2092                  "' isn't '" + Token.stringValue() + "'");
2093   lex();
2094   FI = ObjectInfo->second;
2095   return false;
2096 }
2097 
2098 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2099   int FI;
2100   if (parseStackFrameIndex(FI))
2101     return true;
2102   Dest = MachineOperand::CreateFI(FI);
2103   return false;
2104 }
2105 
2106 bool MIParser::parseFixedStackFrameIndex(int &FI) {
2107   assert(Token.is(MIToken::FixedStackObject));
2108   unsigned ID;
2109   if (getUnsigned(ID))
2110     return true;
2111   auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2112   if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2113     return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2114                  Twine(ID) + "'");
2115   lex();
2116   FI = ObjectInfo->second;
2117   return false;
2118 }
2119 
2120 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2121   int FI;
2122   if (parseFixedStackFrameIndex(FI))
2123     return true;
2124   Dest = MachineOperand::CreateFI(FI);
2125   return false;
2126 }
2127 
2128 static bool parseGlobalValue(const MIToken &Token,
2129                              PerFunctionMIParsingState &PFS, GlobalValue *&GV,
2130                              ErrorCallbackType ErrCB) {
2131   switch (Token.kind()) {
2132   case MIToken::NamedGlobalValue: {
2133     const Module *M = PFS.MF.getFunction().getParent();
2134     GV = M->getNamedValue(Token.stringValue());
2135     if (!GV)
2136       return ErrCB(Token.location(), Twine("use of undefined global value '") +
2137                                          Token.range() + "'");
2138     break;
2139   }
2140   case MIToken::GlobalValue: {
2141     unsigned GVIdx;
2142     if (getUnsigned(Token, GVIdx, ErrCB))
2143       return true;
2144     if (GVIdx >= PFS.IRSlots.GlobalValues.size())
2145       return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2146                                          Twine(GVIdx) + "'");
2147     GV = PFS.IRSlots.GlobalValues[GVIdx];
2148     break;
2149   }
2150   default:
2151     llvm_unreachable("The current token should be a global value");
2152   }
2153   return false;
2154 }
2155 
2156 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2157   return ::parseGlobalValue(
2158       Token, PFS, GV,
2159       [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2160         return error(Loc, Msg);
2161       });
2162 }
2163 
2164 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2165   GlobalValue *GV = nullptr;
2166   if (parseGlobalValue(GV))
2167     return true;
2168   lex();
2169   Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2170   if (parseOperandsOffset(Dest))
2171     return true;
2172   return false;
2173 }
2174 
2175 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2176   assert(Token.is(MIToken::ConstantPoolItem));
2177   unsigned ID;
2178   if (getUnsigned(ID))
2179     return true;
2180   auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2181   if (ConstantInfo == PFS.ConstantPoolSlots.end())
2182     return error("use of undefined constant '%const." + Twine(ID) + "'");
2183   lex();
2184   Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2185   if (parseOperandsOffset(Dest))
2186     return true;
2187   return false;
2188 }
2189 
2190 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2191   assert(Token.is(MIToken::JumpTableIndex));
2192   unsigned ID;
2193   if (getUnsigned(ID))
2194     return true;
2195   auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2196   if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2197     return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2198   lex();
2199   Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2200   return false;
2201 }
2202 
2203 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2204   assert(Token.is(MIToken::ExternalSymbol));
2205   const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2206   lex();
2207   Dest = MachineOperand::CreateES(Symbol);
2208   if (parseOperandsOffset(Dest))
2209     return true;
2210   return false;
2211 }
2212 
2213 bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2214   assert(Token.is(MIToken::MCSymbol));
2215   MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2216   lex();
2217   Dest = MachineOperand::CreateMCSymbol(Symbol);
2218   if (parseOperandsOffset(Dest))
2219     return true;
2220   return false;
2221 }
2222 
2223 bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2224   assert(Token.is(MIToken::SubRegisterIndex));
2225   StringRef Name = Token.stringValue();
2226   unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2227   if (SubRegIndex == 0)
2228     return error(Twine("unknown subregister index '") + Name + "'");
2229   lex();
2230   Dest = MachineOperand::CreateImm(SubRegIndex);
2231   return false;
2232 }
2233 
2234 bool MIParser::parseMDNode(MDNode *&Node) {
2235   assert(Token.is(MIToken::exclaim));
2236 
2237   auto Loc = Token.location();
2238   lex();
2239   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2240     return error("expected metadata id after '!'");
2241   unsigned ID;
2242   if (getUnsigned(ID))
2243     return true;
2244   auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2245   if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2246     NodeInfo = PFS.MachineMetadataNodes.find(ID);
2247     if (NodeInfo == PFS.MachineMetadataNodes.end())
2248       return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2249   }
2250   lex();
2251   Node = NodeInfo->second.get();
2252   return false;
2253 }
2254 
2255 bool MIParser::parseDIExpression(MDNode *&Expr) {
2256   assert(Token.is(MIToken::md_diexpr));
2257   lex();
2258 
2259   // FIXME: Share this parsing with the IL parser.
2260   SmallVector<uint64_t, 8> Elements;
2261 
2262   if (expectAndConsume(MIToken::lparen))
2263     return true;
2264 
2265   if (Token.isNot(MIToken::rparen)) {
2266     do {
2267       if (Token.is(MIToken::Identifier)) {
2268         if (unsigned Op = dwarf::getOperationEncoding(Token.stringValue())) {
2269           lex();
2270           Elements.push_back(Op);
2271           continue;
2272         }
2273         if (unsigned Enc = dwarf::getAttributeEncoding(Token.stringValue())) {
2274           lex();
2275           Elements.push_back(Enc);
2276           continue;
2277         }
2278         return error(Twine("invalid DWARF op '") + Token.stringValue() + "'");
2279       }
2280 
2281       if (Token.isNot(MIToken::IntegerLiteral) ||
2282           Token.integerValue().isSigned())
2283         return error("expected unsigned integer");
2284 
2285       auto &U = Token.integerValue();
2286       if (U.ugt(UINT64_MAX))
2287         return error("element too large, limit is " + Twine(UINT64_MAX));
2288       Elements.push_back(U.getZExtValue());
2289       lex();
2290 
2291     } while (consumeIfPresent(MIToken::comma));
2292   }
2293 
2294   if (expectAndConsume(MIToken::rparen))
2295     return true;
2296 
2297   Expr = DIExpression::get(MF.getFunction().getContext(), Elements);
2298   return false;
2299 }
2300 
2301 bool MIParser::parseDILocation(MDNode *&Loc) {
2302   assert(Token.is(MIToken::md_dilocation));
2303   lex();
2304 
2305   bool HaveLine = false;
2306   unsigned Line = 0;
2307   unsigned Column = 0;
2308   MDNode *Scope = nullptr;
2309   MDNode *InlinedAt = nullptr;
2310   bool ImplicitCode = false;
2311 
2312   if (expectAndConsume(MIToken::lparen))
2313     return true;
2314 
2315   if (Token.isNot(MIToken::rparen)) {
2316     do {
2317       if (Token.is(MIToken::Identifier)) {
2318         if (Token.stringValue() == "line") {
2319           lex();
2320           if (expectAndConsume(MIToken::colon))
2321             return true;
2322           if (Token.isNot(MIToken::IntegerLiteral) ||
2323               Token.integerValue().isSigned())
2324             return error("expected unsigned integer");
2325           Line = Token.integerValue().getZExtValue();
2326           HaveLine = true;
2327           lex();
2328           continue;
2329         }
2330         if (Token.stringValue() == "column") {
2331           lex();
2332           if (expectAndConsume(MIToken::colon))
2333             return true;
2334           if (Token.isNot(MIToken::IntegerLiteral) ||
2335               Token.integerValue().isSigned())
2336             return error("expected unsigned integer");
2337           Column = Token.integerValue().getZExtValue();
2338           lex();
2339           continue;
2340         }
2341         if (Token.stringValue() == "scope") {
2342           lex();
2343           if (expectAndConsume(MIToken::colon))
2344             return true;
2345           if (parseMDNode(Scope))
2346             return error("expected metadata node");
2347           if (!isa<DIScope>(Scope))
2348             return error("expected DIScope node");
2349           continue;
2350         }
2351         if (Token.stringValue() == "inlinedAt") {
2352           lex();
2353           if (expectAndConsume(MIToken::colon))
2354             return true;
2355           if (Token.is(MIToken::exclaim)) {
2356             if (parseMDNode(InlinedAt))
2357               return true;
2358           } else if (Token.is(MIToken::md_dilocation)) {
2359             if (parseDILocation(InlinedAt))
2360               return true;
2361           } else
2362             return error("expected metadata node");
2363           if (!isa<DILocation>(InlinedAt))
2364             return error("expected DILocation node");
2365           continue;
2366         }
2367         if (Token.stringValue() == "isImplicitCode") {
2368           lex();
2369           if (expectAndConsume(MIToken::colon))
2370             return true;
2371           if (!Token.is(MIToken::Identifier))
2372             return error("expected true/false");
2373           // As far as I can see, we don't have any existing need for parsing
2374           // true/false in MIR yet. Do it ad-hoc until there's something else
2375           // that needs it.
2376           if (Token.stringValue() == "true")
2377             ImplicitCode = true;
2378           else if (Token.stringValue() == "false")
2379             ImplicitCode = false;
2380           else
2381             return error("expected true/false");
2382           lex();
2383           continue;
2384         }
2385       }
2386       return error(Twine("invalid DILocation argument '") +
2387                    Token.stringValue() + "'");
2388     } while (consumeIfPresent(MIToken::comma));
2389   }
2390 
2391   if (expectAndConsume(MIToken::rparen))
2392     return true;
2393 
2394   if (!HaveLine)
2395     return error("DILocation requires line number");
2396   if (!Scope)
2397     return error("DILocation requires a scope");
2398 
2399   Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2400                         InlinedAt, ImplicitCode);
2401   return false;
2402 }
2403 
2404 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2405   MDNode *Node = nullptr;
2406   if (Token.is(MIToken::exclaim)) {
2407     if (parseMDNode(Node))
2408       return true;
2409   } else if (Token.is(MIToken::md_diexpr)) {
2410     if (parseDIExpression(Node))
2411       return true;
2412   }
2413   Dest = MachineOperand::CreateMetadata(Node);
2414   return false;
2415 }
2416 
2417 bool MIParser::parseCFIOffset(int &Offset) {
2418   if (Token.isNot(MIToken::IntegerLiteral))
2419     return error("expected a cfi offset");
2420   if (Token.integerValue().getSignificantBits() > 32)
2421     return error("expected a 32 bit integer (the cfi offset is too large)");
2422   Offset = (int)Token.integerValue().getExtValue();
2423   lex();
2424   return false;
2425 }
2426 
2427 bool MIParser::parseCFIRegister(Register &Reg) {
2428   if (Token.isNot(MIToken::NamedRegister))
2429     return error("expected a cfi register");
2430   Register LLVMReg;
2431   if (parseNamedRegister(LLVMReg))
2432     return true;
2433   const auto *TRI = MF.getSubtarget().getRegisterInfo();
2434   assert(TRI && "Expected target register info");
2435   int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2436   if (DwarfReg < 0)
2437     return error("invalid DWARF register");
2438   Reg = (unsigned)DwarfReg;
2439   lex();
2440   return false;
2441 }
2442 
2443 bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2444   if (Token.isNot(MIToken::IntegerLiteral))
2445     return error("expected a cfi address space literal");
2446   if (Token.integerValue().isSigned())
2447     return error("expected an unsigned integer (cfi address space)");
2448   AddressSpace = Token.integerValue().getZExtValue();
2449   lex();
2450   return false;
2451 }
2452 
2453 bool MIParser::parseCFIEscapeValues(std::string &Values) {
2454   do {
2455     if (Token.isNot(MIToken::HexLiteral))
2456       return error("expected a hexadecimal literal");
2457     unsigned Value;
2458     if (getUnsigned(Value))
2459       return true;
2460     if (Value > UINT8_MAX)
2461       return error("expected a 8-bit integer (too large)");
2462     Values.push_back(static_cast<uint8_t>(Value));
2463     lex();
2464   } while (consumeIfPresent(MIToken::comma));
2465   return false;
2466 }
2467 
2468 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2469   auto Kind = Token.kind();
2470   lex();
2471   int Offset;
2472   Register Reg;
2473   unsigned AddressSpace;
2474   unsigned CFIIndex;
2475   switch (Kind) {
2476   case MIToken::kw_cfi_same_value:
2477     if (parseCFIRegister(Reg))
2478       return true;
2479     CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2480     break;
2481   case MIToken::kw_cfi_offset:
2482     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2483         parseCFIOffset(Offset))
2484       return true;
2485     CFIIndex =
2486         MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2487     break;
2488   case MIToken::kw_cfi_rel_offset:
2489     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2490         parseCFIOffset(Offset))
2491       return true;
2492     CFIIndex = MF.addFrameInst(
2493         MCCFIInstruction::createRelOffset(nullptr, Reg, Offset));
2494     break;
2495   case MIToken::kw_cfi_def_cfa_register:
2496     if (parseCFIRegister(Reg))
2497       return true;
2498     CFIIndex =
2499         MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2500     break;
2501   case MIToken::kw_cfi_def_cfa_offset:
2502     if (parseCFIOffset(Offset))
2503       return true;
2504     CFIIndex =
2505         MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2506     break;
2507   case MIToken::kw_cfi_adjust_cfa_offset:
2508     if (parseCFIOffset(Offset))
2509       return true;
2510     CFIIndex = MF.addFrameInst(
2511         MCCFIInstruction::createAdjustCfaOffset(nullptr, Offset));
2512     break;
2513   case MIToken::kw_cfi_def_cfa:
2514     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2515         parseCFIOffset(Offset))
2516       return true;
2517     CFIIndex =
2518         MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2519     break;
2520   case MIToken::kw_cfi_llvm_def_aspace_cfa:
2521     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2522         parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2523         parseCFIAddressSpace(AddressSpace))
2524       return true;
2525     CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2526         nullptr, Reg, Offset, AddressSpace, SMLoc()));
2527     break;
2528   case MIToken::kw_cfi_remember_state:
2529     CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2530     break;
2531   case MIToken::kw_cfi_restore:
2532     if (parseCFIRegister(Reg))
2533       return true;
2534     CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2535     break;
2536   case MIToken::kw_cfi_restore_state:
2537     CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2538     break;
2539   case MIToken::kw_cfi_undefined:
2540     if (parseCFIRegister(Reg))
2541       return true;
2542     CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2543     break;
2544   case MIToken::kw_cfi_register: {
2545     Register Reg2;
2546     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2547         parseCFIRegister(Reg2))
2548       return true;
2549 
2550     CFIIndex =
2551         MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2552     break;
2553   }
2554   case MIToken::kw_cfi_window_save:
2555     CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2556     break;
2557   case MIToken::kw_cfi_aarch64_negate_ra_sign_state:
2558     CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2559     break;
2560   case MIToken::kw_cfi_escape: {
2561     std::string Values;
2562     if (parseCFIEscapeValues(Values))
2563       return true;
2564     CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2565     break;
2566   }
2567   default:
2568     // TODO: Parse the other CFI operands.
2569     llvm_unreachable("The current token should be a cfi operand");
2570   }
2571   Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2572   return false;
2573 }
2574 
2575 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2576   switch (Token.kind()) {
2577   case MIToken::NamedIRBlock: {
2578     BB = dyn_cast_or_null<BasicBlock>(
2579         F.getValueSymbolTable()->lookup(Token.stringValue()));
2580     if (!BB)
2581       return error(Twine("use of undefined IR block '") + Token.range() + "'");
2582     break;
2583   }
2584   case MIToken::IRBlock: {
2585     unsigned SlotNumber = 0;
2586     if (getUnsigned(SlotNumber))
2587       return true;
2588     BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2589     if (!BB)
2590       return error(Twine("use of undefined IR block '%ir-block.") +
2591                    Twine(SlotNumber) + "'");
2592     break;
2593   }
2594   default:
2595     llvm_unreachable("The current token should be an IR block reference");
2596   }
2597   return false;
2598 }
2599 
2600 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2601   assert(Token.is(MIToken::kw_blockaddress));
2602   lex();
2603   if (expectAndConsume(MIToken::lparen))
2604     return true;
2605   if (Token.isNot(MIToken::GlobalValue) &&
2606       Token.isNot(MIToken::NamedGlobalValue))
2607     return error("expected a global value");
2608   GlobalValue *GV = nullptr;
2609   if (parseGlobalValue(GV))
2610     return true;
2611   auto *F = dyn_cast<Function>(GV);
2612   if (!F)
2613     return error("expected an IR function reference");
2614   lex();
2615   if (expectAndConsume(MIToken::comma))
2616     return true;
2617   BasicBlock *BB = nullptr;
2618   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2619     return error("expected an IR block reference");
2620   if (parseIRBlock(BB, *F))
2621     return true;
2622   lex();
2623   if (expectAndConsume(MIToken::rparen))
2624     return true;
2625   Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2626   if (parseOperandsOffset(Dest))
2627     return true;
2628   return false;
2629 }
2630 
2631 bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2632   assert(Token.is(MIToken::kw_intrinsic));
2633   lex();
2634   if (expectAndConsume(MIToken::lparen))
2635     return error("expected syntax intrinsic(@llvm.whatever)");
2636 
2637   if (Token.isNot(MIToken::NamedGlobalValue))
2638     return error("expected syntax intrinsic(@llvm.whatever)");
2639 
2640   std::string Name = std::string(Token.stringValue());
2641   lex();
2642 
2643   if (expectAndConsume(MIToken::rparen))
2644     return error("expected ')' to terminate intrinsic name");
2645 
2646   // Find out what intrinsic we're dealing with, first try the global namespace
2647   // and then the target's private intrinsics if that fails.
2648   const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
2649   Intrinsic::ID ID = Function::lookupIntrinsicID(Name);
2650   if (ID == Intrinsic::not_intrinsic && TII)
2651     ID = static_cast<Intrinsic::ID>(TII->lookupName(Name));
2652 
2653   if (ID == Intrinsic::not_intrinsic)
2654     return error("unknown intrinsic name");
2655   Dest = MachineOperand::CreateIntrinsicID(ID);
2656 
2657   return false;
2658 }
2659 
2660 bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2661   assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2662   bool IsFloat = Token.is(MIToken::kw_floatpred);
2663   lex();
2664 
2665   if (expectAndConsume(MIToken::lparen))
2666     return error("expected syntax intpred(whatever) or floatpred(whatever");
2667 
2668   if (Token.isNot(MIToken::Identifier))
2669     return error("whatever");
2670 
2671   CmpInst::Predicate Pred;
2672   if (IsFloat) {
2673     Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2674                .Case("false", CmpInst::FCMP_FALSE)
2675                .Case("oeq", CmpInst::FCMP_OEQ)
2676                .Case("ogt", CmpInst::FCMP_OGT)
2677                .Case("oge", CmpInst::FCMP_OGE)
2678                .Case("olt", CmpInst::FCMP_OLT)
2679                .Case("ole", CmpInst::FCMP_OLE)
2680                .Case("one", CmpInst::FCMP_ONE)
2681                .Case("ord", CmpInst::FCMP_ORD)
2682                .Case("uno", CmpInst::FCMP_UNO)
2683                .Case("ueq", CmpInst::FCMP_UEQ)
2684                .Case("ugt", CmpInst::FCMP_UGT)
2685                .Case("uge", CmpInst::FCMP_UGE)
2686                .Case("ult", CmpInst::FCMP_ULT)
2687                .Case("ule", CmpInst::FCMP_ULE)
2688                .Case("une", CmpInst::FCMP_UNE)
2689                .Case("true", CmpInst::FCMP_TRUE)
2690                .Default(CmpInst::BAD_FCMP_PREDICATE);
2691     if (!CmpInst::isFPPredicate(Pred))
2692       return error("invalid floating-point predicate");
2693   } else {
2694     Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2695                .Case("eq", CmpInst::ICMP_EQ)
2696                .Case("ne", CmpInst::ICMP_NE)
2697                .Case("sgt", CmpInst::ICMP_SGT)
2698                .Case("sge", CmpInst::ICMP_SGE)
2699                .Case("slt", CmpInst::ICMP_SLT)
2700                .Case("sle", CmpInst::ICMP_SLE)
2701                .Case("ugt", CmpInst::ICMP_UGT)
2702                .Case("uge", CmpInst::ICMP_UGE)
2703                .Case("ult", CmpInst::ICMP_ULT)
2704                .Case("ule", CmpInst::ICMP_ULE)
2705                .Default(CmpInst::BAD_ICMP_PREDICATE);
2706     if (!CmpInst::isIntPredicate(Pred))
2707       return error("invalid integer predicate");
2708   }
2709 
2710   lex();
2711   Dest = MachineOperand::CreatePredicate(Pred);
2712   if (expectAndConsume(MIToken::rparen))
2713     return error("predicate should be terminated by ')'.");
2714 
2715   return false;
2716 }
2717 
2718 bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
2719   assert(Token.is(MIToken::kw_shufflemask));
2720 
2721   lex();
2722   if (expectAndConsume(MIToken::lparen))
2723     return error("expected syntax shufflemask(<integer or undef>, ...)");
2724 
2725   SmallVector<int, 32> ShufMask;
2726   do {
2727     if (Token.is(MIToken::kw_undef)) {
2728       ShufMask.push_back(-1);
2729     } else if (Token.is(MIToken::IntegerLiteral)) {
2730       const APSInt &Int = Token.integerValue();
2731       ShufMask.push_back(Int.getExtValue());
2732     } else
2733       return error("expected integer constant");
2734 
2735     lex();
2736   } while (consumeIfPresent(MIToken::comma));
2737 
2738   if (expectAndConsume(MIToken::rparen))
2739     return error("shufflemask should be terminated by ')'.");
2740 
2741   ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
2742   Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
2743   return false;
2744 }
2745 
2746 bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
2747   assert(Token.is(MIToken::kw_dbg_instr_ref));
2748 
2749   lex();
2750   if (expectAndConsume(MIToken::lparen))
2751     return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2752 
2753   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2754     return error("expected unsigned integer for instruction index");
2755   uint64_t InstrIdx = Token.integerValue().getZExtValue();
2756   assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
2757          "Instruction reference's instruction index is too large");
2758   lex();
2759 
2760   if (expectAndConsume(MIToken::comma))
2761     return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2762 
2763   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2764     return error("expected unsigned integer for operand index");
2765   uint64_t OpIdx = Token.integerValue().getZExtValue();
2766   assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
2767          "Instruction reference's operand index is too large");
2768   lex();
2769 
2770   if (expectAndConsume(MIToken::rparen))
2771     return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2772 
2773   Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
2774   return false;
2775 }
2776 
2777 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
2778   assert(Token.is(MIToken::kw_target_index));
2779   lex();
2780   if (expectAndConsume(MIToken::lparen))
2781     return true;
2782   if (Token.isNot(MIToken::Identifier))
2783     return error("expected the name of the target index");
2784   int Index = 0;
2785   if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
2786     return error("use of undefined target index '" + Token.stringValue() + "'");
2787   lex();
2788   if (expectAndConsume(MIToken::rparen))
2789     return true;
2790   Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
2791   if (parseOperandsOffset(Dest))
2792     return true;
2793   return false;
2794 }
2795 
2796 bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
2797   assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2798   lex();
2799   if (expectAndConsume(MIToken::lparen))
2800     return true;
2801 
2802   uint32_t *Mask = MF.allocateRegMask();
2803   do {
2804     if (Token.isNot(MIToken::rparen)) {
2805       if (Token.isNot(MIToken::NamedRegister))
2806         return error("expected a named register");
2807       Register Reg;
2808       if (parseNamedRegister(Reg))
2809         return true;
2810       lex();
2811       Mask[Reg / 32] |= 1U << (Reg % 32);
2812     }
2813 
2814     // TODO: Report an error if the same register is used more than once.
2815   } while (consumeIfPresent(MIToken::comma));
2816 
2817   if (expectAndConsume(MIToken::rparen))
2818     return true;
2819   Dest = MachineOperand::CreateRegMask(Mask);
2820   return false;
2821 }
2822 
2823 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
2824   assert(Token.is(MIToken::kw_liveout));
2825   uint32_t *Mask = MF.allocateRegMask();
2826   lex();
2827   if (expectAndConsume(MIToken::lparen))
2828     return true;
2829   while (true) {
2830     if (Token.isNot(MIToken::NamedRegister))
2831       return error("expected a named register");
2832     Register Reg;
2833     if (parseNamedRegister(Reg))
2834       return true;
2835     lex();
2836     Mask[Reg / 32] |= 1U << (Reg % 32);
2837     // TODO: Report an error if the same register is used more than once.
2838     if (Token.isNot(MIToken::comma))
2839       break;
2840     lex();
2841   }
2842   if (expectAndConsume(MIToken::rparen))
2843     return true;
2844   Dest = MachineOperand::CreateRegLiveOut(Mask);
2845   return false;
2846 }
2847 
2848 bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
2849                                    MachineOperand &Dest,
2850                                    std::optional<unsigned> &TiedDefIdx) {
2851   switch (Token.kind()) {
2852   case MIToken::kw_implicit:
2853   case MIToken::kw_implicit_define:
2854   case MIToken::kw_def:
2855   case MIToken::kw_dead:
2856   case MIToken::kw_killed:
2857   case MIToken::kw_undef:
2858   case MIToken::kw_internal:
2859   case MIToken::kw_early_clobber:
2860   case MIToken::kw_debug_use:
2861   case MIToken::kw_renamable:
2862   case MIToken::underscore:
2863   case MIToken::NamedRegister:
2864   case MIToken::VirtualRegister:
2865   case MIToken::NamedVirtualRegister:
2866     return parseRegisterOperand(Dest, TiedDefIdx);
2867   case MIToken::IntegerLiteral:
2868     return parseImmediateOperand(Dest);
2869   case MIToken::kw_half:
2870   case MIToken::kw_float:
2871   case MIToken::kw_double:
2872   case MIToken::kw_x86_fp80:
2873   case MIToken::kw_fp128:
2874   case MIToken::kw_ppc_fp128:
2875     return parseFPImmediateOperand(Dest);
2876   case MIToken::MachineBasicBlock:
2877     return parseMBBOperand(Dest);
2878   case MIToken::StackObject:
2879     return parseStackObjectOperand(Dest);
2880   case MIToken::FixedStackObject:
2881     return parseFixedStackObjectOperand(Dest);
2882   case MIToken::GlobalValue:
2883   case MIToken::NamedGlobalValue:
2884     return parseGlobalAddressOperand(Dest);
2885   case MIToken::ConstantPoolItem:
2886     return parseConstantPoolIndexOperand(Dest);
2887   case MIToken::JumpTableIndex:
2888     return parseJumpTableIndexOperand(Dest);
2889   case MIToken::ExternalSymbol:
2890     return parseExternalSymbolOperand(Dest);
2891   case MIToken::MCSymbol:
2892     return parseMCSymbolOperand(Dest);
2893   case MIToken::SubRegisterIndex:
2894     return parseSubRegisterIndexOperand(Dest);
2895   case MIToken::md_diexpr:
2896   case MIToken::exclaim:
2897     return parseMetadataOperand(Dest);
2898   case MIToken::kw_cfi_same_value:
2899   case MIToken::kw_cfi_offset:
2900   case MIToken::kw_cfi_rel_offset:
2901   case MIToken::kw_cfi_def_cfa_register:
2902   case MIToken::kw_cfi_def_cfa_offset:
2903   case MIToken::kw_cfi_adjust_cfa_offset:
2904   case MIToken::kw_cfi_escape:
2905   case MIToken::kw_cfi_def_cfa:
2906   case MIToken::kw_cfi_llvm_def_aspace_cfa:
2907   case MIToken::kw_cfi_register:
2908   case MIToken::kw_cfi_remember_state:
2909   case MIToken::kw_cfi_restore:
2910   case MIToken::kw_cfi_restore_state:
2911   case MIToken::kw_cfi_undefined:
2912   case MIToken::kw_cfi_window_save:
2913   case MIToken::kw_cfi_aarch64_negate_ra_sign_state:
2914     return parseCFIOperand(Dest);
2915   case MIToken::kw_blockaddress:
2916     return parseBlockAddressOperand(Dest);
2917   case MIToken::kw_intrinsic:
2918     return parseIntrinsicOperand(Dest);
2919   case MIToken::kw_target_index:
2920     return parseTargetIndexOperand(Dest);
2921   case MIToken::kw_liveout:
2922     return parseLiveoutRegisterMaskOperand(Dest);
2923   case MIToken::kw_floatpred:
2924   case MIToken::kw_intpred:
2925     return parsePredicateOperand(Dest);
2926   case MIToken::kw_shufflemask:
2927     return parseShuffleMaskOperand(Dest);
2928   case MIToken::kw_dbg_instr_ref:
2929     return parseDbgInstrRefOperand(Dest);
2930   case MIToken::Error:
2931     return true;
2932   case MIToken::Identifier:
2933     if (const auto *RegMask = PFS.Target.getRegMask(Token.stringValue())) {
2934       Dest = MachineOperand::CreateRegMask(RegMask);
2935       lex();
2936       break;
2937     } else if (Token.stringValue() == "CustomRegMask") {
2938       return parseCustomRegisterMaskOperand(Dest);
2939     } else
2940       return parseTypedImmediateOperand(Dest);
2941   case MIToken::dot: {
2942     const auto *TII = MF.getSubtarget().getInstrInfo();
2943     if (const auto *Formatter = TII->getMIRFormatter()) {
2944       return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
2945     }
2946     [[fallthrough]];
2947   }
2948   default:
2949     // FIXME: Parse the MCSymbol machine operand.
2950     return error("expected a machine operand");
2951   }
2952   return false;
2953 }
2954 
2955 bool MIParser::parseMachineOperandAndTargetFlags(
2956     const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
2957     std::optional<unsigned> &TiedDefIdx) {
2958   unsigned TF = 0;
2959   bool HasTargetFlags = false;
2960   if (Token.is(MIToken::kw_target_flags)) {
2961     HasTargetFlags = true;
2962     lex();
2963     if (expectAndConsume(MIToken::lparen))
2964       return true;
2965     if (Token.isNot(MIToken::Identifier))
2966       return error("expected the name of the target flag");
2967     if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
2968       if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
2969         return error("use of undefined target flag '" + Token.stringValue() +
2970                      "'");
2971     }
2972     lex();
2973     while (Token.is(MIToken::comma)) {
2974       lex();
2975       if (Token.isNot(MIToken::Identifier))
2976         return error("expected the name of the target flag");
2977       unsigned BitFlag = 0;
2978       if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
2979         return error("use of undefined target flag '" + Token.stringValue() +
2980                      "'");
2981       // TODO: Report an error when using a duplicate bit target flag.
2982       TF |= BitFlag;
2983       lex();
2984     }
2985     if (expectAndConsume(MIToken::rparen))
2986       return true;
2987   }
2988   auto Loc = Token.location();
2989   if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
2990     return true;
2991   if (!HasTargetFlags)
2992     return false;
2993   if (Dest.isReg())
2994     return error(Loc, "register operands can't have target flags");
2995   Dest.setTargetFlags(TF);
2996   return false;
2997 }
2998 
2999 bool MIParser::parseOffset(int64_t &Offset) {
3000   if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3001     return false;
3002   StringRef Sign = Token.range();
3003   bool IsNegative = Token.is(MIToken::minus);
3004   lex();
3005   if (Token.isNot(MIToken::IntegerLiteral))
3006     return error("expected an integer literal after '" + Sign + "'");
3007   if (Token.integerValue().getSignificantBits() > 64)
3008     return error("expected 64-bit integer (too large)");
3009   Offset = Token.integerValue().getExtValue();
3010   if (IsNegative)
3011     Offset = -Offset;
3012   lex();
3013   return false;
3014 }
3015 
3016 bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3017   assert(Token.is(MIToken::kw_ir_block_address_taken));
3018   lex();
3019   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3020     return error("expected basic block after 'ir_block_address_taken'");
3021 
3022   if (parseIRBlock(BB, MF.getFunction()))
3023     return true;
3024 
3025   lex();
3026   return false;
3027 }
3028 
3029 bool MIParser::parseAlignment(uint64_t &Alignment) {
3030   assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3031   lex();
3032   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3033     return error("expected an integer literal after 'align'");
3034   if (getUint64(Alignment))
3035     return true;
3036   lex();
3037 
3038   if (!isPowerOf2_64(Alignment))
3039     return error("expected a power-of-2 literal after 'align'");
3040 
3041   return false;
3042 }
3043 
3044 bool MIParser::parseAddrspace(unsigned &Addrspace) {
3045   assert(Token.is(MIToken::kw_addrspace));
3046   lex();
3047   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3048     return error("expected an integer literal after 'addrspace'");
3049   if (getUnsigned(Addrspace))
3050     return true;
3051   lex();
3052   return false;
3053 }
3054 
3055 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3056   int64_t Offset = 0;
3057   if (parseOffset(Offset))
3058     return true;
3059   Op.setOffset(Offset);
3060   return false;
3061 }
3062 
3063 static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3064                          const Value *&V, ErrorCallbackType ErrCB) {
3065   switch (Token.kind()) {
3066   case MIToken::NamedIRValue: {
3067     V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3068     break;
3069   }
3070   case MIToken::IRValue: {
3071     unsigned SlotNumber = 0;
3072     if (getUnsigned(Token, SlotNumber, ErrCB))
3073       return true;
3074     V = PFS.getIRValue(SlotNumber);
3075     break;
3076   }
3077   case MIToken::NamedGlobalValue:
3078   case MIToken::GlobalValue: {
3079     GlobalValue *GV = nullptr;
3080     if (parseGlobalValue(Token, PFS, GV, ErrCB))
3081       return true;
3082     V = GV;
3083     break;
3084   }
3085   case MIToken::QuotedIRValue: {
3086     const Constant *C = nullptr;
3087     if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3088       return true;
3089     V = C;
3090     break;
3091   }
3092   case MIToken::kw_unknown_address:
3093     V = nullptr;
3094     return false;
3095   default:
3096     llvm_unreachable("The current token should be an IR block reference");
3097   }
3098   if (!V)
3099     return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3100   return false;
3101 }
3102 
3103 bool MIParser::parseIRValue(const Value *&V) {
3104   return ::parseIRValue(
3105       Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3106         return error(Loc, Msg);
3107       });
3108 }
3109 
3110 bool MIParser::getUint64(uint64_t &Result) {
3111   if (Token.hasIntegerValue()) {
3112     if (Token.integerValue().getActiveBits() > 64)
3113       return error("expected 64-bit integer (too large)");
3114     Result = Token.integerValue().getZExtValue();
3115     return false;
3116   }
3117   if (Token.is(MIToken::HexLiteral)) {
3118     APInt A;
3119     if (getHexUint(A))
3120       return true;
3121     if (A.getBitWidth() > 64)
3122       return error("expected 64-bit integer (too large)");
3123     Result = A.getZExtValue();
3124     return false;
3125   }
3126   return true;
3127 }
3128 
3129 bool MIParser::getHexUint(APInt &Result) {
3130   return ::getHexUint(Token, Result);
3131 }
3132 
3133 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3134   const auto OldFlags = Flags;
3135   switch (Token.kind()) {
3136   case MIToken::kw_volatile:
3137     Flags |= MachineMemOperand::MOVolatile;
3138     break;
3139   case MIToken::kw_non_temporal:
3140     Flags |= MachineMemOperand::MONonTemporal;
3141     break;
3142   case MIToken::kw_dereferenceable:
3143     Flags |= MachineMemOperand::MODereferenceable;
3144     break;
3145   case MIToken::kw_invariant:
3146     Flags |= MachineMemOperand::MOInvariant;
3147     break;
3148   case MIToken::StringConstant: {
3149     MachineMemOperand::Flags TF;
3150     if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3151       return error("use of undefined target MMO flag '" + Token.stringValue() +
3152                    "'");
3153     Flags |= TF;
3154     break;
3155   }
3156   default:
3157     llvm_unreachable("The current token should be a memory operand flag");
3158   }
3159   if (OldFlags == Flags)
3160     // We know that the same flag is specified more than once when the flags
3161     // weren't modified.
3162     return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3163   lex();
3164   return false;
3165 }
3166 
3167 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3168   switch (Token.kind()) {
3169   case MIToken::kw_stack:
3170     PSV = MF.getPSVManager().getStack();
3171     break;
3172   case MIToken::kw_got:
3173     PSV = MF.getPSVManager().getGOT();
3174     break;
3175   case MIToken::kw_jump_table:
3176     PSV = MF.getPSVManager().getJumpTable();
3177     break;
3178   case MIToken::kw_constant_pool:
3179     PSV = MF.getPSVManager().getConstantPool();
3180     break;
3181   case MIToken::FixedStackObject: {
3182     int FI;
3183     if (parseFixedStackFrameIndex(FI))
3184       return true;
3185     PSV = MF.getPSVManager().getFixedStack(FI);
3186     // The token was already consumed, so use return here instead of break.
3187     return false;
3188   }
3189   case MIToken::StackObject: {
3190     int FI;
3191     if (parseStackFrameIndex(FI))
3192       return true;
3193     PSV = MF.getPSVManager().getFixedStack(FI);
3194     // The token was already consumed, so use return here instead of break.
3195     return false;
3196   }
3197   case MIToken::kw_call_entry:
3198     lex();
3199     switch (Token.kind()) {
3200     case MIToken::GlobalValue:
3201     case MIToken::NamedGlobalValue: {
3202       GlobalValue *GV = nullptr;
3203       if (parseGlobalValue(GV))
3204         return true;
3205       PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3206       break;
3207     }
3208     case MIToken::ExternalSymbol:
3209       PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3210           MF.createExternalSymbolName(Token.stringValue()));
3211       break;
3212     default:
3213       return error(
3214           "expected a global value or an external symbol after 'call-entry'");
3215     }
3216     break;
3217   case MIToken::kw_custom: {
3218     lex();
3219     const auto *TII = MF.getSubtarget().getInstrInfo();
3220     if (const auto *Formatter = TII->getMIRFormatter()) {
3221       if (Formatter->parseCustomPseudoSourceValue(
3222               Token.stringValue(), MF, PFS, PSV,
3223               [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3224                 return error(Loc, Msg);
3225               }))
3226         return true;
3227     } else
3228       return error("unable to parse target custom pseudo source value");
3229     break;
3230   }
3231   default:
3232     llvm_unreachable("The current token should be pseudo source value");
3233   }
3234   lex();
3235   return false;
3236 }
3237 
3238 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3239   if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3240       Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3241       Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3242       Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3243     const PseudoSourceValue *PSV = nullptr;
3244     if (parseMemoryPseudoSourceValue(PSV))
3245       return true;
3246     int64_t Offset = 0;
3247     if (parseOffset(Offset))
3248       return true;
3249     Dest = MachinePointerInfo(PSV, Offset);
3250     return false;
3251   }
3252   if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3253       Token.isNot(MIToken::GlobalValue) &&
3254       Token.isNot(MIToken::NamedGlobalValue) &&
3255       Token.isNot(MIToken::QuotedIRValue) &&
3256       Token.isNot(MIToken::kw_unknown_address))
3257     return error("expected an IR value reference");
3258   const Value *V = nullptr;
3259   if (parseIRValue(V))
3260     return true;
3261   if (V && !V->getType()->isPointerTy())
3262     return error("expected a pointer IR value");
3263   lex();
3264   int64_t Offset = 0;
3265   if (parseOffset(Offset))
3266     return true;
3267   Dest = MachinePointerInfo(V, Offset);
3268   return false;
3269 }
3270 
3271 bool MIParser::parseOptionalScope(LLVMContext &Context,
3272                                   SyncScope::ID &SSID) {
3273   SSID = SyncScope::System;
3274   if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3275     lex();
3276     if (expectAndConsume(MIToken::lparen))
3277       return error("expected '(' in syncscope");
3278 
3279     std::string SSN;
3280     if (parseStringConstant(SSN))
3281       return true;
3282 
3283     SSID = Context.getOrInsertSyncScopeID(SSN);
3284     if (expectAndConsume(MIToken::rparen))
3285       return error("expected ')' in syncscope");
3286   }
3287 
3288   return false;
3289 }
3290 
3291 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3292   Order = AtomicOrdering::NotAtomic;
3293   if (Token.isNot(MIToken::Identifier))
3294     return false;
3295 
3296   Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3297               .Case("unordered", AtomicOrdering::Unordered)
3298               .Case("monotonic", AtomicOrdering::Monotonic)
3299               .Case("acquire", AtomicOrdering::Acquire)
3300               .Case("release", AtomicOrdering::Release)
3301               .Case("acq_rel", AtomicOrdering::AcquireRelease)
3302               .Case("seq_cst", AtomicOrdering::SequentiallyConsistent)
3303               .Default(AtomicOrdering::NotAtomic);
3304 
3305   if (Order != AtomicOrdering::NotAtomic) {
3306     lex();
3307     return false;
3308   }
3309 
3310   return error("expected an atomic scope, ordering or a size specification");
3311 }
3312 
3313 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3314   if (expectAndConsume(MIToken::lparen))
3315     return true;
3316   MachineMemOperand::Flags Flags = MachineMemOperand::MONone;
3317   while (Token.isMemoryOperandFlag()) {
3318     if (parseMemoryOperandFlag(Flags))
3319       return true;
3320   }
3321   if (Token.isNot(MIToken::Identifier) ||
3322       (Token.stringValue() != "load" && Token.stringValue() != "store"))
3323     return error("expected 'load' or 'store' memory operation");
3324   if (Token.stringValue() == "load")
3325     Flags |= MachineMemOperand::MOLoad;
3326   else
3327     Flags |= MachineMemOperand::MOStore;
3328   lex();
3329 
3330   // Optional 'store' for operands that both load and store.
3331   if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3332     Flags |= MachineMemOperand::MOStore;
3333     lex();
3334   }
3335 
3336   // Optional synchronization scope.
3337   SyncScope::ID SSID;
3338   if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3339     return true;
3340 
3341   // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3342   AtomicOrdering Order, FailureOrder;
3343   if (parseOptionalAtomicOrdering(Order))
3344     return true;
3345 
3346   if (parseOptionalAtomicOrdering(FailureOrder))
3347     return true;
3348 
3349   LLT MemoryType;
3350   if (Token.isNot(MIToken::IntegerLiteral) &&
3351       Token.isNot(MIToken::kw_unknown_size) &&
3352       Token.isNot(MIToken::lparen))
3353     return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3354                  "memory operation");
3355 
3356   uint64_t Size = MemoryLocation::UnknownSize;
3357   if (Token.is(MIToken::IntegerLiteral)) {
3358     if (getUint64(Size))
3359       return true;
3360 
3361     // Convert from bytes to bits for storage.
3362     MemoryType = LLT::scalar(8 * Size);
3363     lex();
3364   } else if (Token.is(MIToken::kw_unknown_size)) {
3365     Size = MemoryLocation::UnknownSize;
3366     lex();
3367   } else {
3368     if (expectAndConsume(MIToken::lparen))
3369       return true;
3370     if (parseLowLevelType(Token.location(), MemoryType))
3371       return true;
3372     if (expectAndConsume(MIToken::rparen))
3373       return true;
3374 
3375     Size = MemoryType.getSizeInBytes();
3376   }
3377 
3378   MachinePointerInfo Ptr = MachinePointerInfo();
3379   if (Token.is(MIToken::Identifier)) {
3380     const char *Word =
3381         ((Flags & MachineMemOperand::MOLoad) &&
3382          (Flags & MachineMemOperand::MOStore))
3383             ? "on"
3384             : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3385     if (Token.stringValue() != Word)
3386       return error(Twine("expected '") + Word + "'");
3387     lex();
3388 
3389     if (parseMachinePointerInfo(Ptr))
3390       return true;
3391   }
3392   uint64_t BaseAlignment =
3393       (Size != MemoryLocation::UnknownSize ? PowerOf2Ceil(Size) : 1);
3394   AAMDNodes AAInfo;
3395   MDNode *Range = nullptr;
3396   while (consumeIfPresent(MIToken::comma)) {
3397     switch (Token.kind()) {
3398     case MIToken::kw_align: {
3399       // align is printed if it is different than size.
3400       uint64_t Alignment;
3401       if (parseAlignment(Alignment))
3402         return true;
3403       if (Ptr.Offset & (Alignment - 1)) {
3404         // MachineMemOperand::getAlign never returns a value greater than the
3405         // alignment of offset, so this just guards against hand-written MIR
3406         // that specifies a large "align" value when it should probably use
3407         // "basealign" instead.
3408         return error("specified alignment is more aligned than offset");
3409       }
3410       BaseAlignment = Alignment;
3411       break;
3412     }
3413     case MIToken::kw_basealign:
3414       // basealign is printed if it is different than align.
3415       if (parseAlignment(BaseAlignment))
3416         return true;
3417       break;
3418     case MIToken::kw_addrspace:
3419       if (parseAddrspace(Ptr.AddrSpace))
3420         return true;
3421       break;
3422     case MIToken::md_tbaa:
3423       lex();
3424       if (parseMDNode(AAInfo.TBAA))
3425         return true;
3426       break;
3427     case MIToken::md_alias_scope:
3428       lex();
3429       if (parseMDNode(AAInfo.Scope))
3430         return true;
3431       break;
3432     case MIToken::md_noalias:
3433       lex();
3434       if (parseMDNode(AAInfo.NoAlias))
3435         return true;
3436       break;
3437     case MIToken::md_range:
3438       lex();
3439       if (parseMDNode(Range))
3440         return true;
3441       break;
3442     // TODO: Report an error on duplicate metadata nodes.
3443     default:
3444       return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3445                    "'!noalias' or '!range'");
3446     }
3447   }
3448   if (expectAndConsume(MIToken::rparen))
3449     return true;
3450   Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3451                                  AAInfo, Range, SSID, Order, FailureOrder);
3452   return false;
3453 }
3454 
3455 bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3456   assert((Token.is(MIToken::kw_pre_instr_symbol) ||
3457           Token.is(MIToken::kw_post_instr_symbol)) &&
3458          "Invalid token for a pre- post-instruction symbol!");
3459   lex();
3460   if (Token.isNot(MIToken::MCSymbol))
3461     return error("expected a symbol after 'pre-instr-symbol'");
3462   Symbol = getOrCreateMCSymbol(Token.stringValue());
3463   lex();
3464   if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3465       Token.is(MIToken::lbrace))
3466     return false;
3467   if (Token.isNot(MIToken::comma))
3468     return error("expected ',' before the next machine operand");
3469   lex();
3470   return false;
3471 }
3472 
3473 bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3474   assert(Token.is(MIToken::kw_heap_alloc_marker) &&
3475          "Invalid token for a heap alloc marker!");
3476   lex();
3477   if (parseMDNode(Node))
3478     return true;
3479   if (!Node)
3480     return error("expected a MDNode after 'heap-alloc-marker'");
3481   if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3482       Token.is(MIToken::lbrace))
3483     return false;
3484   if (Token.isNot(MIToken::comma))
3485     return error("expected ',' before the next machine operand");
3486   lex();
3487   return false;
3488 }
3489 
3490 bool MIParser::parsePCSections(MDNode *&Node) {
3491   assert(Token.is(MIToken::kw_pcsections) &&
3492          "Invalid token for a PC sections!");
3493   lex();
3494   if (parseMDNode(Node))
3495     return true;
3496   if (!Node)
3497     return error("expected a MDNode after 'pcsections'");
3498   if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3499       Token.is(MIToken::lbrace))
3500     return false;
3501   if (Token.isNot(MIToken::comma))
3502     return error("expected ',' before the next machine operand");
3503   lex();
3504   return false;
3505 }
3506 
3507 static void initSlots2BasicBlocks(
3508     const Function &F,
3509     DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3510   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
3511   MST.incorporateFunction(F);
3512   for (const auto &BB : F) {
3513     if (BB.hasName())
3514       continue;
3515     int Slot = MST.getLocalSlot(&BB);
3516     if (Slot == -1)
3517       continue;
3518     Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3519   }
3520 }
3521 
3522 static const BasicBlock *getIRBlockFromSlot(
3523     unsigned Slot,
3524     const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3525   return Slots2BasicBlocks.lookup(Slot);
3526 }
3527 
3528 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3529   if (Slots2BasicBlocks.empty())
3530     initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3531   return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3532 }
3533 
3534 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3535   if (&F == &MF.getFunction())
3536     return getIRBlock(Slot);
3537   DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3538   initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3539   return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3540 }
3541 
3542 MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3543   // FIXME: Currently we can't recognize temporary or local symbols and call all
3544   // of the appropriate forms to create them. However, this handles basic cases
3545   // well as most of the special aspects are recognized by a prefix on their
3546   // name, and the input names should already be unique. For test cases, keeping
3547   // the symbol name out of the symbol table isn't terribly important.
3548   return MF.getContext().getOrCreateSymbol(Name);
3549 }
3550 
3551 bool MIParser::parseStringConstant(std::string &Result) {
3552   if (Token.isNot(MIToken::StringConstant))
3553     return error("expected string constant");
3554   Result = std::string(Token.stringValue());
3555   lex();
3556   return false;
3557 }
3558 
3559 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS,
3560                                              StringRef Src,
3561                                              SMDiagnostic &Error) {
3562   return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3563 }
3564 
3565 bool llvm::parseMachineInstructions(PerFunctionMIParsingState &PFS,
3566                                     StringRef Src, SMDiagnostic &Error) {
3567   return MIParser(PFS, Error, Src).parseBasicBlocks();
3568 }
3569 
3570 bool llvm::parseMBBReference(PerFunctionMIParsingState &PFS,
3571                              MachineBasicBlock *&MBB, StringRef Src,
3572                              SMDiagnostic &Error) {
3573   return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3574 }
3575 
3576 bool llvm::parseRegisterReference(PerFunctionMIParsingState &PFS,
3577                                   Register &Reg, StringRef Src,
3578                                   SMDiagnostic &Error) {
3579   return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3580 }
3581 
3582 bool llvm::parseNamedRegisterReference(PerFunctionMIParsingState &PFS,
3583                                        Register &Reg, StringRef Src,
3584                                        SMDiagnostic &Error) {
3585   return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3586 }
3587 
3588 bool llvm::parseVirtualRegisterReference(PerFunctionMIParsingState &PFS,
3589                                          VRegInfo *&Info, StringRef Src,
3590                                          SMDiagnostic &Error) {
3591   return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3592 }
3593 
3594 bool llvm::parseStackObjectReference(PerFunctionMIParsingState &PFS,
3595                                      int &FI, StringRef Src,
3596                                      SMDiagnostic &Error) {
3597   return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3598 }
3599 
3600 bool llvm::parseMDNode(PerFunctionMIParsingState &PFS,
3601                        MDNode *&Node, StringRef Src, SMDiagnostic &Error) {
3602   return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3603 }
3604 
3605 bool llvm::parseMachineMetadata(PerFunctionMIParsingState &PFS, StringRef Src,
3606                                 SMRange SrcRange, SMDiagnostic &Error) {
3607   return MIParser(PFS, Error, Src, SrcRange).parseMachineMetadata();
3608 }
3609 
3610 bool MIRFormatter::parseIRValue(StringRef Src, MachineFunction &MF,
3611                                 PerFunctionMIParsingState &PFS, const Value *&V,
3612                                 ErrorCallbackType ErrorCallback) {
3613   MIToken Token;
3614   Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3615     ErrorCallback(Loc, Msg);
3616   });
3617   V = nullptr;
3618 
3619   return ::parseIRValue(Token, PFS, V, ErrorCallback);
3620 }
3621