1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the parsing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MILexer.h"
15 #include "MIParser.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/AsmParser/Parser.h"
28 #include "llvm/AsmParser/SlotMapping.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/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/InstrTypes.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/ModuleSlotTracker.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/IR/ValueSymbolTable.h"
53 #include "llvm/MC/LaneBitmask.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCInstrDesc.h"
56 #include "llvm/MC/MCRegisterInfo.h"
57 #include "llvm/Support/AtomicOrdering.h"
58 #include "llvm/Support/BranchProbability.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/LowLevelTypeImpl.h"
62 #include "llvm/Support/MemoryBuffer.h"
63 #include "llvm/Support/SMLoc.h"
64 #include "llvm/Support/SourceMgr.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include "llvm/Target/TargetInstrInfo.h"
67 #include "llvm/Target/TargetIntrinsicInfo.h"
68 #include "llvm/Target/TargetMachine.h"
69 #include "llvm/Target/TargetRegisterInfo.h"
70 #include "llvm/Target/TargetSubtargetInfo.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cctype>
74 #include <cstddef>
75 #include <cstdint>
76 #include <limits>
77 #include <string>
78 #include <utility>
79 
80 using namespace llvm;
81 
82 PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction &MF,
83     SourceMgr &SM, const SlotMapping &IRSlots,
84     const Name2RegClassMap &Names2RegClasses,
85     const Name2RegBankMap &Names2RegBanks)
86   : MF(MF), SM(&SM), IRSlots(IRSlots), Names2RegClasses(Names2RegClasses),
87     Names2RegBanks(Names2RegBanks) {
88 }
89 
90 VRegInfo &PerFunctionMIParsingState::getVRegInfo(unsigned Num) {
91   auto I = VRegInfos.insert(std::make_pair(Num, nullptr));
92   if (I.second) {
93     MachineRegisterInfo &MRI = MF.getRegInfo();
94     VRegInfo *Info = new (Allocator) VRegInfo;
95     Info->VReg = MRI.createIncompleteVirtualRegister();
96     I.first->second = Info;
97   }
98   return *I.first->second;
99 }
100 
101 namespace {
102 
103 /// A wrapper struct around the 'MachineOperand' struct that includes a source
104 /// range and other attributes.
105 struct ParsedMachineOperand {
106   MachineOperand Operand;
107   StringRef::iterator Begin;
108   StringRef::iterator End;
109   Optional<unsigned> TiedDefIdx;
110 
111   ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
112                        StringRef::iterator End, Optional<unsigned> &TiedDefIdx)
113       : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
114     if (TiedDefIdx)
115       assert(Operand.isReg() && Operand.isUse() &&
116              "Only used register operands can be tied");
117   }
118 };
119 
120 class MIParser {
121   MachineFunction &MF;
122   SMDiagnostic &Error;
123   StringRef Source, CurrentSource;
124   MIToken Token;
125   PerFunctionMIParsingState &PFS;
126   /// Maps from instruction names to op codes.
127   StringMap<unsigned> Names2InstrOpCodes;
128   /// Maps from register names to registers.
129   StringMap<unsigned> Names2Regs;
130   /// Maps from register mask names to register masks.
131   StringMap<const uint32_t *> Names2RegMasks;
132   /// Maps from subregister names to subregister indices.
133   StringMap<unsigned> Names2SubRegIndices;
134   /// Maps from slot numbers to function's unnamed basic blocks.
135   DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
136   /// Maps from slot numbers to function's unnamed values.
137   DenseMap<unsigned, const Value *> Slots2Values;
138   /// Maps from target index names to target indices.
139   StringMap<int> Names2TargetIndices;
140   /// Maps from direct target flag names to the direct target flag values.
141   StringMap<unsigned> Names2DirectTargetFlags;
142   /// Maps from direct target flag names to the bitmask target flag values.
143   StringMap<unsigned> Names2BitmaskTargetFlags;
144 
145 public:
146   MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
147            StringRef Source);
148 
149   /// \p SkipChar gives the number of characters to skip before looking
150   /// for the next token.
151   void lex(unsigned SkipChar = 0);
152 
153   /// Report an error at the current location with the given message.
154   ///
155   /// This function always return true.
156   bool error(const Twine &Msg);
157 
158   /// Report an error at the given location with the given message.
159   ///
160   /// This function always return true.
161   bool error(StringRef::iterator Loc, const Twine &Msg);
162 
163   bool
164   parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
165   bool parseBasicBlocks();
166   bool parse(MachineInstr *&MI);
167   bool parseStandaloneMBB(MachineBasicBlock *&MBB);
168   bool parseStandaloneNamedRegister(unsigned &Reg);
169   bool parseStandaloneVirtualRegister(VRegInfo *&Info);
170   bool parseStandaloneRegister(unsigned &Reg);
171   bool parseStandaloneStackObject(int &FI);
172   bool parseStandaloneMDNode(MDNode *&Node);
173 
174   bool
175   parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
176   bool parseBasicBlock(MachineBasicBlock &MBB,
177                        MachineBasicBlock *&AddFalthroughFrom);
178   bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
179   bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
180 
181   bool parseNamedRegister(unsigned &Reg);
182   bool parseVirtualRegister(VRegInfo *&Info);
183   bool parseRegister(unsigned &Reg, VRegInfo *&VRegInfo);
184   bool parseRegisterFlag(unsigned &Flags);
185   bool parseRegisterClassOrBank(VRegInfo &RegInfo);
186   bool parseSubRegisterIndex(unsigned &SubReg);
187   bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
188   bool parseRegisterOperand(MachineOperand &Dest,
189                             Optional<unsigned> &TiedDefIdx, bool IsDef = false);
190   bool parseImmediateOperand(MachineOperand &Dest);
191   bool parseIRConstant(StringRef::iterator Loc, StringRef Source,
192                        const Constant *&C);
193   bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
194   bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
195   bool parseTypedImmediateOperand(MachineOperand &Dest);
196   bool parseFPImmediateOperand(MachineOperand &Dest);
197   bool parseMBBReference(MachineBasicBlock *&MBB);
198   bool parseMBBOperand(MachineOperand &Dest);
199   bool parseStackFrameIndex(int &FI);
200   bool parseStackObjectOperand(MachineOperand &Dest);
201   bool parseFixedStackFrameIndex(int &FI);
202   bool parseFixedStackObjectOperand(MachineOperand &Dest);
203   bool parseGlobalValue(GlobalValue *&GV);
204   bool parseGlobalAddressOperand(MachineOperand &Dest);
205   bool parseConstantPoolIndexOperand(MachineOperand &Dest);
206   bool parseSubRegisterIndexOperand(MachineOperand &Dest);
207   bool parseJumpTableIndexOperand(MachineOperand &Dest);
208   bool parseExternalSymbolOperand(MachineOperand &Dest);
209   bool parseMDNode(MDNode *&Node);
210   bool parseMetadataOperand(MachineOperand &Dest);
211   bool parseCFIOffset(int &Offset);
212   bool parseCFIRegister(unsigned &Reg);
213   bool parseCFIOperand(MachineOperand &Dest);
214   bool parseIRBlock(BasicBlock *&BB, const Function &F);
215   bool parseBlockAddressOperand(MachineOperand &Dest);
216   bool parseIntrinsicOperand(MachineOperand &Dest);
217   bool parsePredicateOperand(MachineOperand &Dest);
218   bool parseTargetIndexOperand(MachineOperand &Dest);
219   bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
220   bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
221   bool parseMachineOperand(MachineOperand &Dest,
222                            Optional<unsigned> &TiedDefIdx);
223   bool parseMachineOperandAndTargetFlags(MachineOperand &Dest,
224                                          Optional<unsigned> &TiedDefIdx);
225   bool parseOffset(int64_t &Offset);
226   bool parseAlignment(unsigned &Alignment);
227   bool parseOperandsOffset(MachineOperand &Op);
228   bool parseIRValue(const Value *&V);
229   bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
230   bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
231   bool parseMachinePointerInfo(MachinePointerInfo &Dest);
232   bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
233   bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
234 
235 private:
236   /// Convert the integer literal in the current token into an unsigned integer.
237   ///
238   /// Return true if an error occurred.
239   bool getUnsigned(unsigned &Result);
240 
241   /// Convert the integer literal in the current token into an uint64.
242   ///
243   /// Return true if an error occurred.
244   bool getUint64(uint64_t &Result);
245 
246   /// Convert the hexadecimal literal in the current token into an unsigned
247   ///  APInt with a minimum bitwidth required to represent the value.
248   ///
249   /// Return true if the literal does not represent an integer value.
250   bool getHexUint(APInt &Result);
251 
252   /// If the current token is of the given kind, consume it and return false.
253   /// Otherwise report an error and return true.
254   bool expectAndConsume(MIToken::TokenKind TokenKind);
255 
256   /// If the current token is of the given kind, consume it and return true.
257   /// Otherwise return false.
258   bool consumeIfPresent(MIToken::TokenKind TokenKind);
259 
260   void initNames2InstrOpCodes();
261 
262   /// Try to convert an instruction name to an opcode. Return true if the
263   /// instruction name is invalid.
264   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
265 
266   bool parseInstruction(unsigned &OpCode, unsigned &Flags);
267 
268   bool assignRegisterTies(MachineInstr &MI,
269                           ArrayRef<ParsedMachineOperand> Operands);
270 
271   bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
272                               const MCInstrDesc &MCID);
273 
274   void initNames2Regs();
275 
276   /// Try to convert a register name to a register number. Return true if the
277   /// register name is invalid.
278   bool getRegisterByName(StringRef RegName, unsigned &Reg);
279 
280   void initNames2RegMasks();
281 
282   /// Check if the given identifier is a name of a register mask.
283   ///
284   /// Return null if the identifier isn't a register mask.
285   const uint32_t *getRegMask(StringRef Identifier);
286 
287   void initNames2SubRegIndices();
288 
289   /// Check if the given identifier is a name of a subregister index.
290   ///
291   /// Return 0 if the name isn't a subregister index class.
292   unsigned getSubRegIndex(StringRef Name);
293 
294   const BasicBlock *getIRBlock(unsigned Slot);
295   const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
296 
297   const Value *getIRValue(unsigned Slot);
298 
299   void initNames2TargetIndices();
300 
301   /// Try to convert a name of target index to the corresponding target index.
302   ///
303   /// Return true if the name isn't a name of a target index.
304   bool getTargetIndex(StringRef Name, int &Index);
305 
306   void initNames2DirectTargetFlags();
307 
308   /// Try to convert a name of a direct target flag to the corresponding
309   /// target flag.
310   ///
311   /// Return true if the name isn't a name of a direct flag.
312   bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
313 
314   void initNames2BitmaskTargetFlags();
315 
316   /// Try to convert a name of a bitmask target flag to the corresponding
317   /// target flag.
318   ///
319   /// Return true if the name isn't a name of a bitmask target flag.
320   bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag);
321 };
322 
323 } // end anonymous namespace
324 
325 MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
326                    StringRef Source)
327     : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
328 {}
329 
330 void MIParser::lex(unsigned SkipChar) {
331   CurrentSource = lexMIToken(
332       CurrentSource.data() + SkipChar, Token,
333       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
334 }
335 
336 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
337 
338 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
339   const SourceMgr &SM = *PFS.SM;
340   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
341   const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
342   if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
343     // Create an ordinary diagnostic when the source manager's buffer is the
344     // source string.
345     Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
346     return true;
347   }
348   // Create a diagnostic for a YAML string literal.
349   Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
350                        Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
351                        Source, None, None);
352   return true;
353 }
354 
355 static const char *toString(MIToken::TokenKind TokenKind) {
356   switch (TokenKind) {
357   case MIToken::comma:
358     return "','";
359   case MIToken::equal:
360     return "'='";
361   case MIToken::colon:
362     return "':'";
363   case MIToken::lparen:
364     return "'('";
365   case MIToken::rparen:
366     return "')'";
367   default:
368     return "<unknown token>";
369   }
370 }
371 
372 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
373   if (Token.isNot(TokenKind))
374     return error(Twine("expected ") + toString(TokenKind));
375   lex();
376   return false;
377 }
378 
379 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
380   if (Token.isNot(TokenKind))
381     return false;
382   lex();
383   return true;
384 }
385 
386 bool MIParser::parseBasicBlockDefinition(
387     DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
388   assert(Token.is(MIToken::MachineBasicBlockLabel));
389   unsigned ID = 0;
390   if (getUnsigned(ID))
391     return true;
392   auto Loc = Token.location();
393   auto Name = Token.stringValue();
394   lex();
395   bool HasAddressTaken = false;
396   bool IsLandingPad = false;
397   unsigned Alignment = 0;
398   BasicBlock *BB = nullptr;
399   if (consumeIfPresent(MIToken::lparen)) {
400     do {
401       // TODO: Report an error when multiple same attributes are specified.
402       switch (Token.kind()) {
403       case MIToken::kw_address_taken:
404         HasAddressTaken = true;
405         lex();
406         break;
407       case MIToken::kw_landing_pad:
408         IsLandingPad = true;
409         lex();
410         break;
411       case MIToken::kw_align:
412         if (parseAlignment(Alignment))
413           return true;
414         break;
415       case MIToken::IRBlock:
416         // TODO: Report an error when both name and ir block are specified.
417         if (parseIRBlock(BB, *MF.getFunction()))
418           return true;
419         lex();
420         break;
421       default:
422         break;
423       }
424     } while (consumeIfPresent(MIToken::comma));
425     if (expectAndConsume(MIToken::rparen))
426       return true;
427   }
428   if (expectAndConsume(MIToken::colon))
429     return true;
430 
431   if (!Name.empty()) {
432     BB = dyn_cast_or_null<BasicBlock>(
433         MF.getFunction()->getValueSymbolTable()->lookup(Name));
434     if (!BB)
435       return error(Loc, Twine("basic block '") + Name +
436                             "' is not defined in the function '" +
437                             MF.getName() + "'");
438   }
439   auto *MBB = MF.CreateMachineBasicBlock(BB);
440   MF.insert(MF.end(), MBB);
441   bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
442   if (!WasInserted)
443     return error(Loc, Twine("redefinition of machine basic block with id #") +
444                           Twine(ID));
445   if (Alignment)
446     MBB->setAlignment(Alignment);
447   if (HasAddressTaken)
448     MBB->setHasAddressTaken();
449   MBB->setIsEHPad(IsLandingPad);
450   return false;
451 }
452 
453 bool MIParser::parseBasicBlockDefinitions(
454     DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
455   lex();
456   // Skip until the first machine basic block.
457   while (Token.is(MIToken::Newline))
458     lex();
459   if (Token.isErrorOrEOF())
460     return Token.isError();
461   if (Token.isNot(MIToken::MachineBasicBlockLabel))
462     return error("expected a basic block definition before instructions");
463   unsigned BraceDepth = 0;
464   do {
465     if (parseBasicBlockDefinition(MBBSlots))
466       return true;
467     bool IsAfterNewline = false;
468     // Skip until the next machine basic block.
469     while (true) {
470       if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
471           Token.isErrorOrEOF())
472         break;
473       else if (Token.is(MIToken::MachineBasicBlockLabel))
474         return error("basic block definition should be located at the start of "
475                      "the line");
476       else if (consumeIfPresent(MIToken::Newline)) {
477         IsAfterNewline = true;
478         continue;
479       }
480       IsAfterNewline = false;
481       if (Token.is(MIToken::lbrace))
482         ++BraceDepth;
483       if (Token.is(MIToken::rbrace)) {
484         if (!BraceDepth)
485           return error("extraneous closing brace ('}')");
486         --BraceDepth;
487       }
488       lex();
489     }
490     // Verify that we closed all of the '{' at the end of a file or a block.
491     if (!Token.isError() && BraceDepth)
492       return error("expected '}'"); // FIXME: Report a note that shows '{'.
493   } while (!Token.isErrorOrEOF());
494   return Token.isError();
495 }
496 
497 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
498   assert(Token.is(MIToken::kw_liveins));
499   lex();
500   if (expectAndConsume(MIToken::colon))
501     return true;
502   if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
503     return false;
504   do {
505     if (Token.isNot(MIToken::NamedRegister))
506       return error("expected a named register");
507     unsigned Reg = 0;
508     if (parseNamedRegister(Reg))
509       return true;
510     lex();
511     LaneBitmask Mask = LaneBitmask::getAll();
512     if (consumeIfPresent(MIToken::colon)) {
513       // Parse lane mask.
514       if (Token.isNot(MIToken::IntegerLiteral) &&
515           Token.isNot(MIToken::HexLiteral))
516         return error("expected a lane mask");
517       static_assert(sizeof(LaneBitmask::Type) == sizeof(unsigned),
518                     "Use correct get-function for lane mask");
519       LaneBitmask::Type V;
520       if (getUnsigned(V))
521         return error("invalid lane mask value");
522       Mask = LaneBitmask(V);
523       lex();
524     }
525     MBB.addLiveIn(Reg, Mask);
526   } while (consumeIfPresent(MIToken::comma));
527   return false;
528 }
529 
530 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
531   assert(Token.is(MIToken::kw_successors));
532   lex();
533   if (expectAndConsume(MIToken::colon))
534     return true;
535   if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
536     return false;
537   do {
538     if (Token.isNot(MIToken::MachineBasicBlock))
539       return error("expected a machine basic block reference");
540     MachineBasicBlock *SuccMBB = nullptr;
541     if (parseMBBReference(SuccMBB))
542       return true;
543     lex();
544     unsigned Weight = 0;
545     if (consumeIfPresent(MIToken::lparen)) {
546       if (Token.isNot(MIToken::IntegerLiteral) &&
547           Token.isNot(MIToken::HexLiteral))
548         return error("expected an integer literal after '('");
549       if (getUnsigned(Weight))
550         return true;
551       lex();
552       if (expectAndConsume(MIToken::rparen))
553         return true;
554     }
555     MBB.addSuccessor(SuccMBB, BranchProbability::getRaw(Weight));
556   } while (consumeIfPresent(MIToken::comma));
557   MBB.normalizeSuccProbs();
558   return false;
559 }
560 
561 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
562                                MachineBasicBlock *&AddFalthroughFrom) {
563   // Skip the definition.
564   assert(Token.is(MIToken::MachineBasicBlockLabel));
565   lex();
566   if (consumeIfPresent(MIToken::lparen)) {
567     while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
568       lex();
569     consumeIfPresent(MIToken::rparen);
570   }
571   consumeIfPresent(MIToken::colon);
572 
573   // Parse the liveins and successors.
574   // N.B: Multiple lists of successors and liveins are allowed and they're
575   // merged into one.
576   // Example:
577   //   liveins: %edi
578   //   liveins: %esi
579   //
580   // is equivalent to
581   //   liveins: %edi, %esi
582   bool ExplicitSuccesors = false;
583   while (true) {
584     if (Token.is(MIToken::kw_successors)) {
585       if (parseBasicBlockSuccessors(MBB))
586         return true;
587       ExplicitSuccesors = true;
588     } else if (Token.is(MIToken::kw_liveins)) {
589       if (parseBasicBlockLiveins(MBB))
590         return true;
591     } else if (consumeIfPresent(MIToken::Newline)) {
592       continue;
593     } else
594       break;
595     if (!Token.isNewlineOrEOF())
596       return error("expected line break at the end of a list");
597     lex();
598   }
599 
600   // Parse the instructions.
601   bool IsInBundle = false;
602   MachineInstr *PrevMI = nullptr;
603   while (!Token.is(MIToken::MachineBasicBlockLabel) &&
604          !Token.is(MIToken::Eof)) {
605     if (consumeIfPresent(MIToken::Newline))
606       continue;
607     if (consumeIfPresent(MIToken::rbrace)) {
608       // The first parsing pass should verify that all closing '}' have an
609       // opening '{'.
610       assert(IsInBundle);
611       IsInBundle = false;
612       continue;
613     }
614     MachineInstr *MI = nullptr;
615     if (parse(MI))
616       return true;
617     MBB.insert(MBB.end(), MI);
618     if (IsInBundle) {
619       PrevMI->setFlag(MachineInstr::BundledSucc);
620       MI->setFlag(MachineInstr::BundledPred);
621     }
622     PrevMI = MI;
623     if (Token.is(MIToken::lbrace)) {
624       if (IsInBundle)
625         return error("nested instruction bundles are not allowed");
626       lex();
627       // This instruction is the start of the bundle.
628       MI->setFlag(MachineInstr::BundledSucc);
629       IsInBundle = true;
630       if (!Token.is(MIToken::Newline))
631         // The next instruction can be on the same line.
632         continue;
633     }
634     assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
635     lex();
636   }
637 
638   // Construct successor list by searching for basic block machine operands.
639   if (!ExplicitSuccesors) {
640     SmallVector<MachineBasicBlock*,4> Successors;
641     bool IsFallthrough;
642     guessSuccessors(MBB, Successors, IsFallthrough);
643     for (MachineBasicBlock *Succ : Successors)
644       MBB.addSuccessor(Succ);
645 
646     if (IsFallthrough) {
647       AddFalthroughFrom = &MBB;
648     } else {
649       MBB.normalizeSuccProbs();
650     }
651   }
652 
653   return false;
654 }
655 
656 bool MIParser::parseBasicBlocks() {
657   lex();
658   // Skip until the first machine basic block.
659   while (Token.is(MIToken::Newline))
660     lex();
661   if (Token.isErrorOrEOF())
662     return Token.isError();
663   // The first parsing pass should have verified that this token is a MBB label
664   // in the 'parseBasicBlockDefinitions' method.
665   assert(Token.is(MIToken::MachineBasicBlockLabel));
666   MachineBasicBlock *AddFalthroughFrom = nullptr;
667   do {
668     MachineBasicBlock *MBB = nullptr;
669     if (parseMBBReference(MBB))
670       return true;
671     if (AddFalthroughFrom) {
672       if (!AddFalthroughFrom->isSuccessor(MBB))
673         AddFalthroughFrom->addSuccessor(MBB);
674       AddFalthroughFrom->normalizeSuccProbs();
675       AddFalthroughFrom = nullptr;
676     }
677     if (parseBasicBlock(*MBB, AddFalthroughFrom))
678       return true;
679     // The method 'parseBasicBlock' should parse the whole block until the next
680     // block or the end of file.
681     assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
682   } while (Token.isNot(MIToken::Eof));
683   return false;
684 }
685 
686 bool MIParser::parse(MachineInstr *&MI) {
687   // Parse any register operands before '='
688   MachineOperand MO = MachineOperand::CreateImm(0);
689   SmallVector<ParsedMachineOperand, 8> Operands;
690   while (Token.isRegister() || Token.isRegisterFlag()) {
691     auto Loc = Token.location();
692     Optional<unsigned> TiedDefIdx;
693     if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
694       return true;
695     Operands.push_back(
696         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
697     if (Token.isNot(MIToken::comma))
698       break;
699     lex();
700   }
701   if (!Operands.empty() && expectAndConsume(MIToken::equal))
702     return true;
703 
704   unsigned OpCode, Flags = 0;
705   if (Token.isError() || parseInstruction(OpCode, Flags))
706     return true;
707 
708   // Parse the remaining machine operands.
709   while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
710          Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
711     auto Loc = Token.location();
712     Optional<unsigned> TiedDefIdx;
713     if (parseMachineOperandAndTargetFlags(MO, TiedDefIdx))
714       return true;
715     Operands.push_back(
716         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
717     if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
718         Token.is(MIToken::lbrace))
719       break;
720     if (Token.isNot(MIToken::comma))
721       return error("expected ',' before the next machine operand");
722     lex();
723   }
724 
725   DebugLoc DebugLocation;
726   if (Token.is(MIToken::kw_debug_location)) {
727     lex();
728     if (Token.isNot(MIToken::exclaim))
729       return error("expected a metadata node after 'debug-location'");
730     MDNode *Node = nullptr;
731     if (parseMDNode(Node))
732       return true;
733     DebugLocation = DebugLoc(Node);
734   }
735 
736   // Parse the machine memory operands.
737   SmallVector<MachineMemOperand *, 2> MemOperands;
738   if (Token.is(MIToken::coloncolon)) {
739     lex();
740     while (!Token.isNewlineOrEOF()) {
741       MachineMemOperand *MemOp = nullptr;
742       if (parseMachineMemoryOperand(MemOp))
743         return true;
744       MemOperands.push_back(MemOp);
745       if (Token.isNewlineOrEOF())
746         break;
747       if (Token.isNot(MIToken::comma))
748         return error("expected ',' before the next machine memory operand");
749       lex();
750     }
751   }
752 
753   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
754   if (!MCID.isVariadic()) {
755     // FIXME: Move the implicit operand verification to the machine verifier.
756     if (verifyImplicitOperands(Operands, MCID))
757       return true;
758   }
759 
760   // TODO: Check for extraneous machine operands.
761   MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
762   MI->setFlags(Flags);
763   for (const auto &Operand : Operands)
764     MI->addOperand(MF, Operand.Operand);
765   if (assignRegisterTies(*MI, Operands))
766     return true;
767   if (MemOperands.empty())
768     return false;
769   MachineInstr::mmo_iterator MemRefs =
770       MF.allocateMemRefsArray(MemOperands.size());
771   std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
772   MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
773   return false;
774 }
775 
776 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
777   lex();
778   if (Token.isNot(MIToken::MachineBasicBlock))
779     return error("expected a machine basic block reference");
780   if (parseMBBReference(MBB))
781     return true;
782   lex();
783   if (Token.isNot(MIToken::Eof))
784     return error(
785         "expected end of string after the machine basic block reference");
786   return false;
787 }
788 
789 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
790   lex();
791   if (Token.isNot(MIToken::NamedRegister))
792     return error("expected a named register");
793   if (parseNamedRegister(Reg))
794     return true;
795   lex();
796   if (Token.isNot(MIToken::Eof))
797     return error("expected end of string after the register reference");
798   return false;
799 }
800 
801 bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
802   lex();
803   if (Token.isNot(MIToken::VirtualRegister))
804     return error("expected a virtual register");
805   if (parseVirtualRegister(Info))
806     return true;
807   lex();
808   if (Token.isNot(MIToken::Eof))
809     return error("expected end of string after the register reference");
810   return false;
811 }
812 
813 bool MIParser::parseStandaloneRegister(unsigned &Reg) {
814   lex();
815   if (Token.isNot(MIToken::NamedRegister) &&
816       Token.isNot(MIToken::VirtualRegister))
817     return error("expected either a named or virtual register");
818 
819   VRegInfo *Info;
820   if (parseRegister(Reg, Info))
821     return true;
822 
823   lex();
824   if (Token.isNot(MIToken::Eof))
825     return error("expected end of string after the register reference");
826   return false;
827 }
828 
829 bool MIParser::parseStandaloneStackObject(int &FI) {
830   lex();
831   if (Token.isNot(MIToken::StackObject))
832     return error("expected a stack object");
833   if (parseStackFrameIndex(FI))
834     return true;
835   if (Token.isNot(MIToken::Eof))
836     return error("expected end of string after the stack object reference");
837   return false;
838 }
839 
840 bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
841   lex();
842   if (Token.isNot(MIToken::exclaim))
843     return error("expected a metadata node");
844   if (parseMDNode(Node))
845     return true;
846   if (Token.isNot(MIToken::Eof))
847     return error("expected end of string after the metadata node");
848   return false;
849 }
850 
851 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
852   assert(MO.isImplicit());
853   return MO.isDef() ? "implicit-def" : "implicit";
854 }
855 
856 static std::string getRegisterName(const TargetRegisterInfo *TRI,
857                                    unsigned Reg) {
858   assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
859   return StringRef(TRI->getName(Reg)).lower();
860 }
861 
862 /// Return true if the parsed machine operands contain a given machine operand.
863 static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
864                                 ArrayRef<ParsedMachineOperand> Operands) {
865   for (const auto &I : Operands) {
866     if (ImplicitOperand.isIdenticalTo(I.Operand))
867       return true;
868   }
869   return false;
870 }
871 
872 bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
873                                       const MCInstrDesc &MCID) {
874   if (MCID.isCall())
875     // We can't verify call instructions as they can contain arbitrary implicit
876     // register and register mask operands.
877     return false;
878 
879   // Gather all the expected implicit operands.
880   SmallVector<MachineOperand, 4> ImplicitOperands;
881   if (MCID.ImplicitDefs)
882     for (const MCPhysReg *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
883       ImplicitOperands.push_back(
884           MachineOperand::CreateReg(*ImpDefs, true, true));
885   if (MCID.ImplicitUses)
886     for (const MCPhysReg *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
887       ImplicitOperands.push_back(
888           MachineOperand::CreateReg(*ImpUses, false, true));
889 
890   const auto *TRI = MF.getSubtarget().getRegisterInfo();
891   assert(TRI && "Expected target register info");
892   for (const auto &I : ImplicitOperands) {
893     if (isImplicitOperandIn(I, Operands))
894       continue;
895     return error(Operands.empty() ? Token.location() : Operands.back().End,
896                  Twine("missing implicit register operand '") +
897                      printImplicitRegisterFlag(I) + " %" +
898                      getRegisterName(TRI, I.getReg()) + "'");
899   }
900   return false;
901 }
902 
903 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
904   if (Token.is(MIToken::kw_frame_setup)) {
905     Flags |= MachineInstr::FrameSetup;
906     lex();
907   }
908   if (Token.isNot(MIToken::Identifier))
909     return error("expected a machine instruction");
910   StringRef InstrName = Token.stringValue();
911   if (parseInstrName(InstrName, OpCode))
912     return error(Twine("unknown machine instruction name '") + InstrName + "'");
913   lex();
914   return false;
915 }
916 
917 bool MIParser::parseNamedRegister(unsigned &Reg) {
918   assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
919   StringRef Name = Token.stringValue();
920   if (getRegisterByName(Name, Reg))
921     return error(Twine("unknown register name '") + Name + "'");
922   return false;
923 }
924 
925 bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
926   assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
927   unsigned ID;
928   if (getUnsigned(ID))
929     return true;
930   Info = &PFS.getVRegInfo(ID);
931   return false;
932 }
933 
934 bool MIParser::parseRegister(unsigned &Reg, VRegInfo *&Info) {
935   switch (Token.kind()) {
936   case MIToken::underscore:
937     Reg = 0;
938     return false;
939   case MIToken::NamedRegister:
940     return parseNamedRegister(Reg);
941   case MIToken::VirtualRegister:
942     if (parseVirtualRegister(Info))
943       return true;
944     Reg = Info->VReg;
945     return false;
946   // TODO: Parse other register kinds.
947   default:
948     llvm_unreachable("The current token should be a register");
949   }
950 }
951 
952 bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
953   if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
954     return error("expected '_', register class, or register bank name");
955   StringRef::iterator Loc = Token.location();
956   StringRef Name = Token.stringValue();
957 
958   // Was it a register class?
959   auto RCNameI = PFS.Names2RegClasses.find(Name);
960   if (RCNameI != PFS.Names2RegClasses.end()) {
961     lex();
962     const TargetRegisterClass &RC = *RCNameI->getValue();
963 
964     switch (RegInfo.Kind) {
965     case VRegInfo::UNKNOWN:
966     case VRegInfo::NORMAL:
967       RegInfo.Kind = VRegInfo::NORMAL;
968       if (RegInfo.Explicit && RegInfo.D.RC != &RC) {
969         const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
970         return error(Loc, Twine("conflicting register classes, previously: ") +
971                      Twine(TRI.getRegClassName(RegInfo.D.RC)));
972       }
973       RegInfo.D.RC = &RC;
974       RegInfo.Explicit = true;
975       return false;
976 
977     case VRegInfo::GENERIC:
978     case VRegInfo::REGBANK:
979       return error(Loc, "register class specification on generic register");
980     }
981     llvm_unreachable("Unexpected register kind");
982   }
983 
984   // Should be a register bank or a generic register.
985   const RegisterBank *RegBank = nullptr;
986   if (Name != "_") {
987     auto RBNameI = PFS.Names2RegBanks.find(Name);
988     if (RBNameI == PFS.Names2RegBanks.end())
989       return error(Loc, "expected '_', register class, or register bank name");
990     RegBank = RBNameI->getValue();
991   }
992 
993   lex();
994 
995   switch (RegInfo.Kind) {
996   case VRegInfo::UNKNOWN:
997   case VRegInfo::GENERIC:
998   case VRegInfo::REGBANK:
999     RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1000     if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1001       return error(Loc, "conflicting generic register banks");
1002     RegInfo.D.RegBank = RegBank;
1003     RegInfo.Explicit = true;
1004     return false;
1005 
1006   case VRegInfo::NORMAL:
1007     return error(Loc, "register bank specification on normal register");
1008   }
1009   llvm_unreachable("Unexpected register kind");
1010 }
1011 
1012 bool MIParser::parseRegisterFlag(unsigned &Flags) {
1013   const unsigned OldFlags = Flags;
1014   switch (Token.kind()) {
1015   case MIToken::kw_implicit:
1016     Flags |= RegState::Implicit;
1017     break;
1018   case MIToken::kw_implicit_define:
1019     Flags |= RegState::ImplicitDefine;
1020     break;
1021   case MIToken::kw_def:
1022     Flags |= RegState::Define;
1023     break;
1024   case MIToken::kw_dead:
1025     Flags |= RegState::Dead;
1026     break;
1027   case MIToken::kw_killed:
1028     Flags |= RegState::Kill;
1029     break;
1030   case MIToken::kw_undef:
1031     Flags |= RegState::Undef;
1032     break;
1033   case MIToken::kw_internal:
1034     Flags |= RegState::InternalRead;
1035     break;
1036   case MIToken::kw_early_clobber:
1037     Flags |= RegState::EarlyClobber;
1038     break;
1039   case MIToken::kw_debug_use:
1040     Flags |= RegState::Debug;
1041     break;
1042   default:
1043     llvm_unreachable("The current token should be a register flag");
1044   }
1045   if (OldFlags == Flags)
1046     // We know that the same flag is specified more than once when the flags
1047     // weren't modified.
1048     return error("duplicate '" + Token.stringValue() + "' register flag");
1049   lex();
1050   return false;
1051 }
1052 
1053 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1054   assert(Token.is(MIToken::dot));
1055   lex();
1056   if (Token.isNot(MIToken::Identifier))
1057     return error("expected a subregister index after '.'");
1058   auto Name = Token.stringValue();
1059   SubReg = getSubRegIndex(Name);
1060   if (!SubReg)
1061     return error(Twine("use of unknown subregister index '") + Name + "'");
1062   lex();
1063   return false;
1064 }
1065 
1066 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1067   if (!consumeIfPresent(MIToken::kw_tied_def))
1068     return true;
1069   if (Token.isNot(MIToken::IntegerLiteral))
1070     return error("expected an integer literal after 'tied-def'");
1071   if (getUnsigned(TiedDefIdx))
1072     return true;
1073   lex();
1074   if (expectAndConsume(MIToken::rparen))
1075     return true;
1076   return false;
1077 }
1078 
1079 bool MIParser::assignRegisterTies(MachineInstr &MI,
1080                                   ArrayRef<ParsedMachineOperand> Operands) {
1081   SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1082   for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1083     if (!Operands[I].TiedDefIdx)
1084       continue;
1085     // The parser ensures that this operand is a register use, so we just have
1086     // to check the tied-def operand.
1087     unsigned DefIdx = Operands[I].TiedDefIdx.getValue();
1088     if (DefIdx >= E)
1089       return error(Operands[I].Begin,
1090                    Twine("use of invalid tied-def operand index '" +
1091                          Twine(DefIdx) + "'; instruction has only ") +
1092                        Twine(E) + " operands");
1093     const auto &DefOperand = Operands[DefIdx].Operand;
1094     if (!DefOperand.isReg() || !DefOperand.isDef())
1095       // FIXME: add note with the def operand.
1096       return error(Operands[I].Begin,
1097                    Twine("use of invalid tied-def operand index '") +
1098                        Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1099                        " isn't a defined register");
1100     // Check that the tied-def operand wasn't tied elsewhere.
1101     for (const auto &TiedPair : TiedRegisterPairs) {
1102       if (TiedPair.first == DefIdx)
1103         return error(Operands[I].Begin,
1104                      Twine("the tied-def operand #") + Twine(DefIdx) +
1105                          " is already tied with another register operand");
1106     }
1107     TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1108   }
1109   // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1110   // indices must be less than tied max.
1111   for (const auto &TiedPair : TiedRegisterPairs)
1112     MI.tieOperands(TiedPair.first, TiedPair.second);
1113   return false;
1114 }
1115 
1116 bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1117                                     Optional<unsigned> &TiedDefIdx,
1118                                     bool IsDef) {
1119   unsigned Flags = IsDef ? RegState::Define : 0;
1120   while (Token.isRegisterFlag()) {
1121     if (parseRegisterFlag(Flags))
1122       return true;
1123   }
1124   if (!Token.isRegister())
1125     return error("expected a register after register flags");
1126   unsigned Reg;
1127   VRegInfo *RegInfo;
1128   if (parseRegister(Reg, RegInfo))
1129     return true;
1130   lex();
1131   unsigned SubReg = 0;
1132   if (Token.is(MIToken::dot)) {
1133     if (parseSubRegisterIndex(SubReg))
1134       return true;
1135     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1136       return error("subregister index expects a virtual register");
1137   }
1138   if (Token.is(MIToken::colon)) {
1139     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1140       return error("register class specification expects a virtual register");
1141     lex();
1142     if (parseRegisterClassOrBank(*RegInfo))
1143         return true;
1144   }
1145   MachineRegisterInfo &MRI = MF.getRegInfo();
1146   if ((Flags & RegState::Define) == 0) {
1147     if (consumeIfPresent(MIToken::lparen)) {
1148       unsigned Idx;
1149       if (!parseRegisterTiedDefIndex(Idx))
1150         TiedDefIdx = Idx;
1151       else {
1152         // Try a redundant low-level type.
1153         LLT Ty;
1154         if (parseLowLevelType(Token.location(), Ty))
1155           return error("expected tied-def or low-level type after '('");
1156 
1157         if (expectAndConsume(MIToken::rparen))
1158           return true;
1159 
1160         if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1161           return error("inconsistent type for generic virtual register");
1162 
1163         MRI.setType(Reg, Ty);
1164       }
1165     }
1166   } else if (consumeIfPresent(MIToken::lparen)) {
1167     // Virtual registers may have a tpe with GlobalISel.
1168     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1169       return error("unexpected type on physical register");
1170 
1171     LLT Ty;
1172     if (parseLowLevelType(Token.location(), Ty))
1173       return true;
1174 
1175     if (expectAndConsume(MIToken::rparen))
1176       return true;
1177 
1178     if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1179       return error("inconsistent type for generic virtual register");
1180 
1181     MRI.setType(Reg, Ty);
1182   } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1183     // Generic virtual registers must have a type.
1184     // If we end up here this means the type hasn't been specified and
1185     // this is bad!
1186     if (RegInfo->Kind == VRegInfo::GENERIC ||
1187         RegInfo->Kind == VRegInfo::REGBANK)
1188       return error("generic virtual registers must have a type");
1189   }
1190   Dest = MachineOperand::CreateReg(
1191       Reg, Flags & RegState::Define, Flags & RegState::Implicit,
1192       Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
1193       Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
1194       Flags & RegState::InternalRead);
1195   return false;
1196 }
1197 
1198 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1199   assert(Token.is(MIToken::IntegerLiteral));
1200   const APSInt &Int = Token.integerValue();
1201   if (Int.getMinSignedBits() > 64)
1202     return error("integer literal is too large to be an immediate operand");
1203   Dest = MachineOperand::CreateImm(Int.getExtValue());
1204   lex();
1205   return false;
1206 }
1207 
1208 bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1209                                const Constant *&C) {
1210   auto Source = StringValue.str(); // The source has to be null terminated.
1211   SMDiagnostic Err;
1212   C = parseConstantValue(Source, Err, *MF.getFunction()->getParent(),
1213                          &PFS.IRSlots);
1214   if (!C)
1215     return error(Loc + Err.getColumnNo(), Err.getMessage());
1216   return false;
1217 }
1218 
1219 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1220   if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1221     return true;
1222   lex();
1223   return false;
1224 }
1225 
1226 bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
1227   if (Token.is(MIToken::ScalarType)) {
1228     Ty = LLT::scalar(APSInt(Token.range().drop_front()).getZExtValue());
1229     lex();
1230     return false;
1231   } else if (Token.is(MIToken::PointerType)) {
1232     const DataLayout &DL = MF.getFunction()->getParent()->getDataLayout();
1233     unsigned AS = APSInt(Token.range().drop_front()).getZExtValue();
1234     Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1235     lex();
1236     return false;
1237   }
1238 
1239   // Now we're looking for a vector.
1240   if (Token.isNot(MIToken::less))
1241     return error(Loc,
1242                  "expected unsized, pN, sN or <N x sM> for GlobalISel type");
1243 
1244   lex();
1245 
1246   if (Token.isNot(MIToken::IntegerLiteral))
1247     return error(Loc, "expected <N x sM> for vctor type");
1248   uint64_t NumElements = Token.integerValue().getZExtValue();
1249   lex();
1250 
1251   if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
1252     return error(Loc, "expected '<N x sM>' for vector type");
1253   lex();
1254 
1255   if (Token.isNot(MIToken::ScalarType))
1256     return error(Loc, "expected '<N x sM>' for vector type");
1257   uint64_t ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
1258   lex();
1259 
1260   if (Token.isNot(MIToken::greater))
1261     return error(Loc, "expected '<N x sM>' for vector type");
1262   lex();
1263 
1264   Ty = LLT::vector(NumElements, ScalarSize);
1265   return false;
1266 }
1267 
1268 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
1269   assert(Token.is(MIToken::IntegerType));
1270   auto Loc = Token.location();
1271   lex();
1272   if (Token.isNot(MIToken::IntegerLiteral))
1273     return error("expected an integer literal");
1274   const Constant *C = nullptr;
1275   if (parseIRConstant(Loc, C))
1276     return true;
1277   Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
1278   return false;
1279 }
1280 
1281 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
1282   auto Loc = Token.location();
1283   lex();
1284   if (Token.isNot(MIToken::FloatingPointLiteral) &&
1285       Token.isNot(MIToken::HexLiteral))
1286     return error("expected a floating point literal");
1287   const Constant *C = nullptr;
1288   if (parseIRConstant(Loc, C))
1289     return true;
1290   Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
1291   return false;
1292 }
1293 
1294 bool MIParser::getUnsigned(unsigned &Result) {
1295   if (Token.hasIntegerValue()) {
1296     const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
1297     uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
1298     if (Val64 == Limit)
1299       return error("expected 32-bit integer (too large)");
1300     Result = Val64;
1301     return false;
1302   }
1303   if (Token.is(MIToken::HexLiteral)) {
1304     APInt A;
1305     if (getHexUint(A))
1306       return true;
1307     if (A.getBitWidth() > 32)
1308       return error("expected 32-bit integer (too large)");
1309     Result = A.getZExtValue();
1310     return false;
1311   }
1312   return true;
1313 }
1314 
1315 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
1316   assert(Token.is(MIToken::MachineBasicBlock) ||
1317          Token.is(MIToken::MachineBasicBlockLabel));
1318   unsigned Number;
1319   if (getUnsigned(Number))
1320     return true;
1321   auto MBBInfo = PFS.MBBSlots.find(Number);
1322   if (MBBInfo == PFS.MBBSlots.end())
1323     return error(Twine("use of undefined machine basic block #") +
1324                  Twine(Number));
1325   MBB = MBBInfo->second;
1326   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
1327     return error(Twine("the name of machine basic block #") + Twine(Number) +
1328                  " isn't '" + Token.stringValue() + "'");
1329   return false;
1330 }
1331 
1332 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
1333   MachineBasicBlock *MBB;
1334   if (parseMBBReference(MBB))
1335     return true;
1336   Dest = MachineOperand::CreateMBB(MBB);
1337   lex();
1338   return false;
1339 }
1340 
1341 bool MIParser::parseStackFrameIndex(int &FI) {
1342   assert(Token.is(MIToken::StackObject));
1343   unsigned ID;
1344   if (getUnsigned(ID))
1345     return true;
1346   auto ObjectInfo = PFS.StackObjectSlots.find(ID);
1347   if (ObjectInfo == PFS.StackObjectSlots.end())
1348     return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
1349                  "'");
1350   StringRef Name;
1351   if (const auto *Alloca =
1352           MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
1353     Name = Alloca->getName();
1354   if (!Token.stringValue().empty() && Token.stringValue() != Name)
1355     return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
1356                  "' isn't '" + Token.stringValue() + "'");
1357   lex();
1358   FI = ObjectInfo->second;
1359   return false;
1360 }
1361 
1362 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
1363   int FI;
1364   if (parseStackFrameIndex(FI))
1365     return true;
1366   Dest = MachineOperand::CreateFI(FI);
1367   return false;
1368 }
1369 
1370 bool MIParser::parseFixedStackFrameIndex(int &FI) {
1371   assert(Token.is(MIToken::FixedStackObject));
1372   unsigned ID;
1373   if (getUnsigned(ID))
1374     return true;
1375   auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
1376   if (ObjectInfo == PFS.FixedStackObjectSlots.end())
1377     return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
1378                  Twine(ID) + "'");
1379   lex();
1380   FI = ObjectInfo->second;
1381   return false;
1382 }
1383 
1384 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
1385   int FI;
1386   if (parseFixedStackFrameIndex(FI))
1387     return true;
1388   Dest = MachineOperand::CreateFI(FI);
1389   return false;
1390 }
1391 
1392 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
1393   switch (Token.kind()) {
1394   case MIToken::NamedGlobalValue: {
1395     const Module *M = MF.getFunction()->getParent();
1396     GV = M->getNamedValue(Token.stringValue());
1397     if (!GV)
1398       return error(Twine("use of undefined global value '") + Token.range() +
1399                    "'");
1400     break;
1401   }
1402   case MIToken::GlobalValue: {
1403     unsigned GVIdx;
1404     if (getUnsigned(GVIdx))
1405       return true;
1406     if (GVIdx >= PFS.IRSlots.GlobalValues.size())
1407       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
1408                    "'");
1409     GV = PFS.IRSlots.GlobalValues[GVIdx];
1410     break;
1411   }
1412   default:
1413     llvm_unreachable("The current token should be a global value");
1414   }
1415   return false;
1416 }
1417 
1418 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
1419   GlobalValue *GV = nullptr;
1420   if (parseGlobalValue(GV))
1421     return true;
1422   lex();
1423   Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
1424   if (parseOperandsOffset(Dest))
1425     return true;
1426   return false;
1427 }
1428 
1429 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1430   assert(Token.is(MIToken::ConstantPoolItem));
1431   unsigned ID;
1432   if (getUnsigned(ID))
1433     return true;
1434   auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1435   if (ConstantInfo == PFS.ConstantPoolSlots.end())
1436     return error("use of undefined constant '%const." + Twine(ID) + "'");
1437   lex();
1438   Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1439   if (parseOperandsOffset(Dest))
1440     return true;
1441   return false;
1442 }
1443 
1444 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1445   assert(Token.is(MIToken::JumpTableIndex));
1446   unsigned ID;
1447   if (getUnsigned(ID))
1448     return true;
1449   auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1450   if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1451     return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1452   lex();
1453   Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1454   return false;
1455 }
1456 
1457 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1458   assert(Token.is(MIToken::ExternalSymbol));
1459   const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1460   lex();
1461   Dest = MachineOperand::CreateES(Symbol);
1462   if (parseOperandsOffset(Dest))
1463     return true;
1464   return false;
1465 }
1466 
1467 bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
1468   assert(Token.is(MIToken::SubRegisterIndex));
1469   StringRef Name = Token.stringValue();
1470   unsigned SubRegIndex = getSubRegIndex(Token.stringValue());
1471   if (SubRegIndex == 0)
1472     return error(Twine("unknown subregister index '") + Name + "'");
1473   lex();
1474   Dest = MachineOperand::CreateImm(SubRegIndex);
1475   return false;
1476 }
1477 
1478 bool MIParser::parseMDNode(MDNode *&Node) {
1479   assert(Token.is(MIToken::exclaim));
1480   auto Loc = Token.location();
1481   lex();
1482   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1483     return error("expected metadata id after '!'");
1484   unsigned ID;
1485   if (getUnsigned(ID))
1486     return true;
1487   auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
1488   if (NodeInfo == PFS.IRSlots.MetadataNodes.end())
1489     return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1490   lex();
1491   Node = NodeInfo->second.get();
1492   return false;
1493 }
1494 
1495 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1496   MDNode *Node = nullptr;
1497   if (parseMDNode(Node))
1498     return true;
1499   Dest = MachineOperand::CreateMetadata(Node);
1500   return false;
1501 }
1502 
1503 bool MIParser::parseCFIOffset(int &Offset) {
1504   if (Token.isNot(MIToken::IntegerLiteral))
1505     return error("expected a cfi offset");
1506   if (Token.integerValue().getMinSignedBits() > 32)
1507     return error("expected a 32 bit integer (the cfi offset is too large)");
1508   Offset = (int)Token.integerValue().getExtValue();
1509   lex();
1510   return false;
1511 }
1512 
1513 bool MIParser::parseCFIRegister(unsigned &Reg) {
1514   if (Token.isNot(MIToken::NamedRegister))
1515     return error("expected a cfi register");
1516   unsigned LLVMReg;
1517   if (parseNamedRegister(LLVMReg))
1518     return true;
1519   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1520   assert(TRI && "Expected target register info");
1521   int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1522   if (DwarfReg < 0)
1523     return error("invalid DWARF register");
1524   Reg = (unsigned)DwarfReg;
1525   lex();
1526   return false;
1527 }
1528 
1529 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1530   auto Kind = Token.kind();
1531   lex();
1532   int Offset;
1533   unsigned Reg;
1534   unsigned CFIIndex;
1535   switch (Kind) {
1536   case MIToken::kw_cfi_same_value:
1537     if (parseCFIRegister(Reg))
1538       return true;
1539     CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1540     break;
1541   case MIToken::kw_cfi_offset:
1542     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1543         parseCFIOffset(Offset))
1544       return true;
1545     CFIIndex =
1546         MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1547     break;
1548   case MIToken::kw_cfi_def_cfa_register:
1549     if (parseCFIRegister(Reg))
1550       return true;
1551     CFIIndex =
1552         MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1553     break;
1554   case MIToken::kw_cfi_def_cfa_offset:
1555     if (parseCFIOffset(Offset))
1556       return true;
1557     // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1558     CFIIndex = MF.addFrameInst(
1559         MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1560     break;
1561   case MIToken::kw_cfi_def_cfa:
1562     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1563         parseCFIOffset(Offset))
1564       return true;
1565     // NB: MCCFIInstruction::createDefCfa negates the offset.
1566     CFIIndex =
1567         MF.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1568     break;
1569   default:
1570     // TODO: Parse the other CFI operands.
1571     llvm_unreachable("The current token should be a cfi operand");
1572   }
1573   Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1574   return false;
1575 }
1576 
1577 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1578   switch (Token.kind()) {
1579   case MIToken::NamedIRBlock: {
1580     BB = dyn_cast_or_null<BasicBlock>(
1581         F.getValueSymbolTable()->lookup(Token.stringValue()));
1582     if (!BB)
1583       return error(Twine("use of undefined IR block '") + Token.range() + "'");
1584     break;
1585   }
1586   case MIToken::IRBlock: {
1587     unsigned SlotNumber = 0;
1588     if (getUnsigned(SlotNumber))
1589       return true;
1590     BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1591     if (!BB)
1592       return error(Twine("use of undefined IR block '%ir-block.") +
1593                    Twine(SlotNumber) + "'");
1594     break;
1595   }
1596   default:
1597     llvm_unreachable("The current token should be an IR block reference");
1598   }
1599   return false;
1600 }
1601 
1602 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1603   assert(Token.is(MIToken::kw_blockaddress));
1604   lex();
1605   if (expectAndConsume(MIToken::lparen))
1606     return true;
1607   if (Token.isNot(MIToken::GlobalValue) &&
1608       Token.isNot(MIToken::NamedGlobalValue))
1609     return error("expected a global value");
1610   GlobalValue *GV = nullptr;
1611   if (parseGlobalValue(GV))
1612     return true;
1613   auto *F = dyn_cast<Function>(GV);
1614   if (!F)
1615     return error("expected an IR function reference");
1616   lex();
1617   if (expectAndConsume(MIToken::comma))
1618     return true;
1619   BasicBlock *BB = nullptr;
1620   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1621     return error("expected an IR block reference");
1622   if (parseIRBlock(BB, *F))
1623     return true;
1624   lex();
1625   if (expectAndConsume(MIToken::rparen))
1626     return true;
1627   Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1628   if (parseOperandsOffset(Dest))
1629     return true;
1630   return false;
1631 }
1632 
1633 bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
1634   assert(Token.is(MIToken::kw_intrinsic));
1635   lex();
1636   if (expectAndConsume(MIToken::lparen))
1637     return error("expected syntax intrinsic(@llvm.whatever)");
1638 
1639   if (Token.isNot(MIToken::NamedGlobalValue))
1640     return error("expected syntax intrinsic(@llvm.whatever)");
1641 
1642   std::string Name = Token.stringValue();
1643   lex();
1644 
1645   if (expectAndConsume(MIToken::rparen))
1646     return error("expected ')' to terminate intrinsic name");
1647 
1648   // Find out what intrinsic we're dealing with, first try the global namespace
1649   // and then the target's private intrinsics if that fails.
1650   const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
1651   Intrinsic::ID ID = Function::lookupIntrinsicID(Name);
1652   if (ID == Intrinsic::not_intrinsic && TII)
1653     ID = static_cast<Intrinsic::ID>(TII->lookupName(Name));
1654 
1655   if (ID == Intrinsic::not_intrinsic)
1656     return error("unknown intrinsic name");
1657   Dest = MachineOperand::CreateIntrinsicID(ID);
1658 
1659   return false;
1660 }
1661 
1662 bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
1663   assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
1664   bool IsFloat = Token.is(MIToken::kw_floatpred);
1665   lex();
1666 
1667   if (expectAndConsume(MIToken::lparen))
1668     return error("expected syntax intpred(whatever) or floatpred(whatever");
1669 
1670   if (Token.isNot(MIToken::Identifier))
1671     return error("whatever");
1672 
1673   CmpInst::Predicate Pred;
1674   if (IsFloat) {
1675     Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
1676                .Case("false", CmpInst::FCMP_FALSE)
1677                .Case("oeq", CmpInst::FCMP_OEQ)
1678                .Case("ogt", CmpInst::FCMP_OGT)
1679                .Case("oge", CmpInst::FCMP_OGE)
1680                .Case("olt", CmpInst::FCMP_OLT)
1681                .Case("ole", CmpInst::FCMP_OLE)
1682                .Case("one", CmpInst::FCMP_ONE)
1683                .Case("ord", CmpInst::FCMP_ORD)
1684                .Case("uno", CmpInst::FCMP_UNO)
1685                .Case("ueq", CmpInst::FCMP_UEQ)
1686                .Case("ugt", CmpInst::FCMP_UGT)
1687                .Case("uge", CmpInst::FCMP_UGE)
1688                .Case("ult", CmpInst::FCMP_ULT)
1689                .Case("ule", CmpInst::FCMP_ULE)
1690                .Case("une", CmpInst::FCMP_UNE)
1691                .Case("true", CmpInst::FCMP_TRUE)
1692                .Default(CmpInst::BAD_FCMP_PREDICATE);
1693     if (!CmpInst::isFPPredicate(Pred))
1694       return error("invalid floating-point predicate");
1695   } else {
1696     Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
1697                .Case("eq", CmpInst::ICMP_EQ)
1698                .Case("ne", CmpInst::ICMP_NE)
1699                .Case("sgt", CmpInst::ICMP_SGT)
1700                .Case("sge", CmpInst::ICMP_SGE)
1701                .Case("slt", CmpInst::ICMP_SLT)
1702                .Case("sle", CmpInst::ICMP_SLE)
1703                .Case("ugt", CmpInst::ICMP_UGT)
1704                .Case("uge", CmpInst::ICMP_UGE)
1705                .Case("ult", CmpInst::ICMP_ULT)
1706                .Case("ule", CmpInst::ICMP_ULE)
1707                .Default(CmpInst::BAD_ICMP_PREDICATE);
1708     if (!CmpInst::isIntPredicate(Pred))
1709       return error("invalid integer predicate");
1710   }
1711 
1712   lex();
1713   Dest = MachineOperand::CreatePredicate(Pred);
1714   if (expectAndConsume(MIToken::rparen))
1715     return error("predicate should be terminated by ')'.");
1716 
1717   return false;
1718 }
1719 
1720 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1721   assert(Token.is(MIToken::kw_target_index));
1722   lex();
1723   if (expectAndConsume(MIToken::lparen))
1724     return true;
1725   if (Token.isNot(MIToken::Identifier))
1726     return error("expected the name of the target index");
1727   int Index = 0;
1728   if (getTargetIndex(Token.stringValue(), Index))
1729     return error("use of undefined target index '" + Token.stringValue() + "'");
1730   lex();
1731   if (expectAndConsume(MIToken::rparen))
1732     return true;
1733   Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1734   if (parseOperandsOffset(Dest))
1735     return true;
1736   return false;
1737 }
1738 
1739 bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
1740   assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
1741   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1742   assert(TRI && "Expected target register info");
1743   lex();
1744   if (expectAndConsume(MIToken::lparen))
1745     return true;
1746 
1747   uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1748   while (true) {
1749     if (Token.isNot(MIToken::NamedRegister))
1750       return error("expected a named register");
1751     unsigned Reg;
1752     if (parseNamedRegister(Reg))
1753       return true;
1754     lex();
1755     Mask[Reg / 32] |= 1U << (Reg % 32);
1756     // TODO: Report an error if the same register is used more than once.
1757     if (Token.isNot(MIToken::comma))
1758       break;
1759     lex();
1760   }
1761 
1762   if (expectAndConsume(MIToken::rparen))
1763     return true;
1764   Dest = MachineOperand::CreateRegMask(Mask);
1765   return false;
1766 }
1767 
1768 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1769   assert(Token.is(MIToken::kw_liveout));
1770   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1771   assert(TRI && "Expected target register info");
1772   uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1773   lex();
1774   if (expectAndConsume(MIToken::lparen))
1775     return true;
1776   while (true) {
1777     if (Token.isNot(MIToken::NamedRegister))
1778       return error("expected a named register");
1779     unsigned Reg;
1780     if (parseNamedRegister(Reg))
1781       return true;
1782     lex();
1783     Mask[Reg / 32] |= 1U << (Reg % 32);
1784     // TODO: Report an error if the same register is used more than once.
1785     if (Token.isNot(MIToken::comma))
1786       break;
1787     lex();
1788   }
1789   if (expectAndConsume(MIToken::rparen))
1790     return true;
1791   Dest = MachineOperand::CreateRegLiveOut(Mask);
1792   return false;
1793 }
1794 
1795 bool MIParser::parseMachineOperand(MachineOperand &Dest,
1796                                    Optional<unsigned> &TiedDefIdx) {
1797   switch (Token.kind()) {
1798   case MIToken::kw_implicit:
1799   case MIToken::kw_implicit_define:
1800   case MIToken::kw_def:
1801   case MIToken::kw_dead:
1802   case MIToken::kw_killed:
1803   case MIToken::kw_undef:
1804   case MIToken::kw_internal:
1805   case MIToken::kw_early_clobber:
1806   case MIToken::kw_debug_use:
1807   case MIToken::underscore:
1808   case MIToken::NamedRegister:
1809   case MIToken::VirtualRegister:
1810     return parseRegisterOperand(Dest, TiedDefIdx);
1811   case MIToken::IntegerLiteral:
1812     return parseImmediateOperand(Dest);
1813   case MIToken::IntegerType:
1814     return parseTypedImmediateOperand(Dest);
1815   case MIToken::kw_half:
1816   case MIToken::kw_float:
1817   case MIToken::kw_double:
1818   case MIToken::kw_x86_fp80:
1819   case MIToken::kw_fp128:
1820   case MIToken::kw_ppc_fp128:
1821     return parseFPImmediateOperand(Dest);
1822   case MIToken::MachineBasicBlock:
1823     return parseMBBOperand(Dest);
1824   case MIToken::StackObject:
1825     return parseStackObjectOperand(Dest);
1826   case MIToken::FixedStackObject:
1827     return parseFixedStackObjectOperand(Dest);
1828   case MIToken::GlobalValue:
1829   case MIToken::NamedGlobalValue:
1830     return parseGlobalAddressOperand(Dest);
1831   case MIToken::ConstantPoolItem:
1832     return parseConstantPoolIndexOperand(Dest);
1833   case MIToken::JumpTableIndex:
1834     return parseJumpTableIndexOperand(Dest);
1835   case MIToken::ExternalSymbol:
1836     return parseExternalSymbolOperand(Dest);
1837   case MIToken::SubRegisterIndex:
1838     return parseSubRegisterIndexOperand(Dest);
1839   case MIToken::exclaim:
1840     return parseMetadataOperand(Dest);
1841   case MIToken::kw_cfi_same_value:
1842   case MIToken::kw_cfi_offset:
1843   case MIToken::kw_cfi_def_cfa_register:
1844   case MIToken::kw_cfi_def_cfa_offset:
1845   case MIToken::kw_cfi_def_cfa:
1846     return parseCFIOperand(Dest);
1847   case MIToken::kw_blockaddress:
1848     return parseBlockAddressOperand(Dest);
1849   case MIToken::kw_intrinsic:
1850     return parseIntrinsicOperand(Dest);
1851   case MIToken::kw_target_index:
1852     return parseTargetIndexOperand(Dest);
1853   case MIToken::kw_liveout:
1854     return parseLiveoutRegisterMaskOperand(Dest);
1855   case MIToken::kw_floatpred:
1856   case MIToken::kw_intpred:
1857     return parsePredicateOperand(Dest);
1858   case MIToken::Error:
1859     return true;
1860   case MIToken::Identifier:
1861     if (const auto *RegMask = getRegMask(Token.stringValue())) {
1862       Dest = MachineOperand::CreateRegMask(RegMask);
1863       lex();
1864       break;
1865     } else
1866       return parseCustomRegisterMaskOperand(Dest);
1867   default:
1868     // FIXME: Parse the MCSymbol machine operand.
1869     return error("expected a machine operand");
1870   }
1871   return false;
1872 }
1873 
1874 bool MIParser::parseMachineOperandAndTargetFlags(
1875     MachineOperand &Dest, Optional<unsigned> &TiedDefIdx) {
1876   unsigned TF = 0;
1877   bool HasTargetFlags = false;
1878   if (Token.is(MIToken::kw_target_flags)) {
1879     HasTargetFlags = true;
1880     lex();
1881     if (expectAndConsume(MIToken::lparen))
1882       return true;
1883     if (Token.isNot(MIToken::Identifier))
1884       return error("expected the name of the target flag");
1885     if (getDirectTargetFlag(Token.stringValue(), TF)) {
1886       if (getBitmaskTargetFlag(Token.stringValue(), TF))
1887         return error("use of undefined target flag '" + Token.stringValue() +
1888                      "'");
1889     }
1890     lex();
1891     while (Token.is(MIToken::comma)) {
1892       lex();
1893       if (Token.isNot(MIToken::Identifier))
1894         return error("expected the name of the target flag");
1895       unsigned BitFlag = 0;
1896       if (getBitmaskTargetFlag(Token.stringValue(), BitFlag))
1897         return error("use of undefined target flag '" + Token.stringValue() +
1898                      "'");
1899       // TODO: Report an error when using a duplicate bit target flag.
1900       TF |= BitFlag;
1901       lex();
1902     }
1903     if (expectAndConsume(MIToken::rparen))
1904       return true;
1905   }
1906   auto Loc = Token.location();
1907   if (parseMachineOperand(Dest, TiedDefIdx))
1908     return true;
1909   if (!HasTargetFlags)
1910     return false;
1911   if (Dest.isReg())
1912     return error(Loc, "register operands can't have target flags");
1913   Dest.setTargetFlags(TF);
1914   return false;
1915 }
1916 
1917 bool MIParser::parseOffset(int64_t &Offset) {
1918   if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1919     return false;
1920   StringRef Sign = Token.range();
1921   bool IsNegative = Token.is(MIToken::minus);
1922   lex();
1923   if (Token.isNot(MIToken::IntegerLiteral))
1924     return error("expected an integer literal after '" + Sign + "'");
1925   if (Token.integerValue().getMinSignedBits() > 64)
1926     return error("expected 64-bit integer (too large)");
1927   Offset = Token.integerValue().getExtValue();
1928   if (IsNegative)
1929     Offset = -Offset;
1930   lex();
1931   return false;
1932 }
1933 
1934 bool MIParser::parseAlignment(unsigned &Alignment) {
1935   assert(Token.is(MIToken::kw_align));
1936   lex();
1937   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1938     return error("expected an integer literal after 'align'");
1939   if (getUnsigned(Alignment))
1940     return true;
1941   lex();
1942   return false;
1943 }
1944 
1945 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1946   int64_t Offset = 0;
1947   if (parseOffset(Offset))
1948     return true;
1949   Op.setOffset(Offset);
1950   return false;
1951 }
1952 
1953 bool MIParser::parseIRValue(const Value *&V) {
1954   switch (Token.kind()) {
1955   case MIToken::NamedIRValue: {
1956     V = MF.getFunction()->getValueSymbolTable()->lookup(Token.stringValue());
1957     break;
1958   }
1959   case MIToken::IRValue: {
1960     unsigned SlotNumber = 0;
1961     if (getUnsigned(SlotNumber))
1962       return true;
1963     V = getIRValue(SlotNumber);
1964     break;
1965   }
1966   case MIToken::NamedGlobalValue:
1967   case MIToken::GlobalValue: {
1968     GlobalValue *GV = nullptr;
1969     if (parseGlobalValue(GV))
1970       return true;
1971     V = GV;
1972     break;
1973   }
1974   case MIToken::QuotedIRValue: {
1975     const Constant *C = nullptr;
1976     if (parseIRConstant(Token.location(), Token.stringValue(), C))
1977       return true;
1978     V = C;
1979     break;
1980   }
1981   default:
1982     llvm_unreachable("The current token should be an IR block reference");
1983   }
1984   if (!V)
1985     return error(Twine("use of undefined IR value '") + Token.range() + "'");
1986   return false;
1987 }
1988 
1989 bool MIParser::getUint64(uint64_t &Result) {
1990   if (Token.hasIntegerValue()) {
1991     if (Token.integerValue().getActiveBits() > 64)
1992       return error("expected 64-bit integer (too large)");
1993     Result = Token.integerValue().getZExtValue();
1994     return false;
1995   }
1996   if (Token.is(MIToken::HexLiteral)) {
1997     APInt A;
1998     if (getHexUint(A))
1999       return true;
2000     if (A.getBitWidth() > 64)
2001       return error("expected 64-bit integer (too large)");
2002     Result = A.getZExtValue();
2003     return false;
2004   }
2005   return true;
2006 }
2007 
2008 bool MIParser::getHexUint(APInt &Result) {
2009   assert(Token.is(MIToken::HexLiteral));
2010   StringRef S = Token.range();
2011   assert(S[0] == '0' && tolower(S[1]) == 'x');
2012   // This could be a floating point literal with a special prefix.
2013   if (!isxdigit(S[2]))
2014     return true;
2015   StringRef V = S.substr(2);
2016   APInt A(V.size()*4, V, 16);
2017   Result = APInt(A.getActiveBits(),
2018                  ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2019   return false;
2020 }
2021 
2022 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
2023   const auto OldFlags = Flags;
2024   switch (Token.kind()) {
2025   case MIToken::kw_volatile:
2026     Flags |= MachineMemOperand::MOVolatile;
2027     break;
2028   case MIToken::kw_non_temporal:
2029     Flags |= MachineMemOperand::MONonTemporal;
2030     break;
2031   case MIToken::kw_dereferenceable:
2032     Flags |= MachineMemOperand::MODereferenceable;
2033     break;
2034   case MIToken::kw_invariant:
2035     Flags |= MachineMemOperand::MOInvariant;
2036     break;
2037   // TODO: parse the target specific memory operand flags.
2038   default:
2039     llvm_unreachable("The current token should be a memory operand flag");
2040   }
2041   if (OldFlags == Flags)
2042     // We know that the same flag is specified more than once when the flags
2043     // weren't modified.
2044     return error("duplicate '" + Token.stringValue() + "' memory operand flag");
2045   lex();
2046   return false;
2047 }
2048 
2049 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
2050   switch (Token.kind()) {
2051   case MIToken::kw_stack:
2052     PSV = MF.getPSVManager().getStack();
2053     break;
2054   case MIToken::kw_got:
2055     PSV = MF.getPSVManager().getGOT();
2056     break;
2057   case MIToken::kw_jump_table:
2058     PSV = MF.getPSVManager().getJumpTable();
2059     break;
2060   case MIToken::kw_constant_pool:
2061     PSV = MF.getPSVManager().getConstantPool();
2062     break;
2063   case MIToken::FixedStackObject: {
2064     int FI;
2065     if (parseFixedStackFrameIndex(FI))
2066       return true;
2067     PSV = MF.getPSVManager().getFixedStack(FI);
2068     // The token was already consumed, so use return here instead of break.
2069     return false;
2070   }
2071   case MIToken::StackObject: {
2072     int FI;
2073     if (parseStackFrameIndex(FI))
2074       return true;
2075     PSV = MF.getPSVManager().getFixedStack(FI);
2076     // The token was already consumed, so use return here instead of break.
2077     return false;
2078   }
2079   case MIToken::kw_call_entry:
2080     lex();
2081     switch (Token.kind()) {
2082     case MIToken::GlobalValue:
2083     case MIToken::NamedGlobalValue: {
2084       GlobalValue *GV = nullptr;
2085       if (parseGlobalValue(GV))
2086         return true;
2087       PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
2088       break;
2089     }
2090     case MIToken::ExternalSymbol:
2091       PSV = MF.getPSVManager().getExternalSymbolCallEntry(
2092           MF.createExternalSymbolName(Token.stringValue()));
2093       break;
2094     default:
2095       return error(
2096           "expected a global value or an external symbol after 'call-entry'");
2097     }
2098     break;
2099   default:
2100     llvm_unreachable("The current token should be pseudo source value");
2101   }
2102   lex();
2103   return false;
2104 }
2105 
2106 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
2107   if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
2108       Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
2109       Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
2110       Token.is(MIToken::kw_call_entry)) {
2111     const PseudoSourceValue *PSV = nullptr;
2112     if (parseMemoryPseudoSourceValue(PSV))
2113       return true;
2114     int64_t Offset = 0;
2115     if (parseOffset(Offset))
2116       return true;
2117     Dest = MachinePointerInfo(PSV, Offset);
2118     return false;
2119   }
2120   if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
2121       Token.isNot(MIToken::GlobalValue) &&
2122       Token.isNot(MIToken::NamedGlobalValue) &&
2123       Token.isNot(MIToken::QuotedIRValue))
2124     return error("expected an IR value reference");
2125   const Value *V = nullptr;
2126   if (parseIRValue(V))
2127     return true;
2128   if (!V->getType()->isPointerTy())
2129     return error("expected a pointer IR value");
2130   lex();
2131   int64_t Offset = 0;
2132   if (parseOffset(Offset))
2133     return true;
2134   Dest = MachinePointerInfo(V, Offset);
2135   return false;
2136 }
2137 
2138 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
2139   Order = AtomicOrdering::NotAtomic;
2140   if (Token.isNot(MIToken::Identifier))
2141     return false;
2142 
2143   Order = StringSwitch<AtomicOrdering>(Token.stringValue())
2144               .Case("unordered", AtomicOrdering::Unordered)
2145               .Case("monotonic", AtomicOrdering::Monotonic)
2146               .Case("acquire", AtomicOrdering::Acquire)
2147               .Case("release", AtomicOrdering::Release)
2148               .Case("acq_rel", AtomicOrdering::AcquireRelease)
2149               .Case("seq_cst", AtomicOrdering::SequentiallyConsistent)
2150               .Default(AtomicOrdering::NotAtomic);
2151 
2152   if (Order != AtomicOrdering::NotAtomic) {
2153     lex();
2154     return false;
2155   }
2156 
2157   return error("expected an atomic scope, ordering or a size integer literal");
2158 }
2159 
2160 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
2161   if (expectAndConsume(MIToken::lparen))
2162     return true;
2163   MachineMemOperand::Flags Flags = MachineMemOperand::MONone;
2164   while (Token.isMemoryOperandFlag()) {
2165     if (parseMemoryOperandFlag(Flags))
2166       return true;
2167   }
2168   if (Token.isNot(MIToken::Identifier) ||
2169       (Token.stringValue() != "load" && Token.stringValue() != "store"))
2170     return error("expected 'load' or 'store' memory operation");
2171   if (Token.stringValue() == "load")
2172     Flags |= MachineMemOperand::MOLoad;
2173   else
2174     Flags |= MachineMemOperand::MOStore;
2175   lex();
2176 
2177   // Optional "singlethread" scope.
2178   SynchronizationScope Scope = SynchronizationScope::CrossThread;
2179   if (Token.is(MIToken::Identifier) && Token.stringValue() == "singlethread") {
2180     Scope = SynchronizationScope::SingleThread;
2181     lex();
2182   }
2183 
2184   // Up to two atomic orderings (cmpxchg provides guarantees on failure).
2185   AtomicOrdering Order, FailureOrder;
2186   if (parseOptionalAtomicOrdering(Order))
2187     return true;
2188 
2189   if (parseOptionalAtomicOrdering(FailureOrder))
2190     return true;
2191 
2192   if (Token.isNot(MIToken::IntegerLiteral))
2193     return error("expected the size integer literal after memory operation");
2194   uint64_t Size;
2195   if (getUint64(Size))
2196     return true;
2197   lex();
2198 
2199   MachinePointerInfo Ptr = MachinePointerInfo();
2200   if (Token.is(MIToken::Identifier)) {
2201     const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
2202     if (Token.stringValue() != Word)
2203       return error(Twine("expected '") + Word + "'");
2204     lex();
2205 
2206     if (parseMachinePointerInfo(Ptr))
2207       return true;
2208   }
2209   unsigned BaseAlignment = Size;
2210   AAMDNodes AAInfo;
2211   MDNode *Range = nullptr;
2212   while (consumeIfPresent(MIToken::comma)) {
2213     switch (Token.kind()) {
2214     case MIToken::kw_align:
2215       if (parseAlignment(BaseAlignment))
2216         return true;
2217       break;
2218     case MIToken::md_tbaa:
2219       lex();
2220       if (parseMDNode(AAInfo.TBAA))
2221         return true;
2222       break;
2223     case MIToken::md_alias_scope:
2224       lex();
2225       if (parseMDNode(AAInfo.Scope))
2226         return true;
2227       break;
2228     case MIToken::md_noalias:
2229       lex();
2230       if (parseMDNode(AAInfo.NoAlias))
2231         return true;
2232       break;
2233     case MIToken::md_range:
2234       lex();
2235       if (parseMDNode(Range))
2236         return true;
2237       break;
2238     // TODO: Report an error on duplicate metadata nodes.
2239     default:
2240       return error("expected 'align' or '!tbaa' or '!alias.scope' or "
2241                    "'!noalias' or '!range'");
2242     }
2243   }
2244   if (expectAndConsume(MIToken::rparen))
2245     return true;
2246   Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range,
2247                                  Scope, Order, FailureOrder);
2248   return false;
2249 }
2250 
2251 void MIParser::initNames2InstrOpCodes() {
2252   if (!Names2InstrOpCodes.empty())
2253     return;
2254   const auto *TII = MF.getSubtarget().getInstrInfo();
2255   assert(TII && "Expected target instruction info");
2256   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
2257     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
2258 }
2259 
2260 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
2261   initNames2InstrOpCodes();
2262   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
2263   if (InstrInfo == Names2InstrOpCodes.end())
2264     return true;
2265   OpCode = InstrInfo->getValue();
2266   return false;
2267 }
2268 
2269 void MIParser::initNames2Regs() {
2270   if (!Names2Regs.empty())
2271     return;
2272   // The '%noreg' register is the register 0.
2273   Names2Regs.insert(std::make_pair("noreg", 0));
2274   const auto *TRI = MF.getSubtarget().getRegisterInfo();
2275   assert(TRI && "Expected target register info");
2276   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
2277     bool WasInserted =
2278         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
2279             .second;
2280     (void)WasInserted;
2281     assert(WasInserted && "Expected registers to be unique case-insensitively");
2282   }
2283 }
2284 
2285 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
2286   initNames2Regs();
2287   auto RegInfo = Names2Regs.find(RegName);
2288   if (RegInfo == Names2Regs.end())
2289     return true;
2290   Reg = RegInfo->getValue();
2291   return false;
2292 }
2293 
2294 void MIParser::initNames2RegMasks() {
2295   if (!Names2RegMasks.empty())
2296     return;
2297   const auto *TRI = MF.getSubtarget().getRegisterInfo();
2298   assert(TRI && "Expected target register info");
2299   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
2300   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
2301   assert(RegMasks.size() == RegMaskNames.size());
2302   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
2303     Names2RegMasks.insert(
2304         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
2305 }
2306 
2307 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
2308   initNames2RegMasks();
2309   auto RegMaskInfo = Names2RegMasks.find(Identifier);
2310   if (RegMaskInfo == Names2RegMasks.end())
2311     return nullptr;
2312   return RegMaskInfo->getValue();
2313 }
2314 
2315 void MIParser::initNames2SubRegIndices() {
2316   if (!Names2SubRegIndices.empty())
2317     return;
2318   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2319   for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
2320     Names2SubRegIndices.insert(
2321         std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
2322 }
2323 
2324 unsigned MIParser::getSubRegIndex(StringRef Name) {
2325   initNames2SubRegIndices();
2326   auto SubRegInfo = Names2SubRegIndices.find(Name);
2327   if (SubRegInfo == Names2SubRegIndices.end())
2328     return 0;
2329   return SubRegInfo->getValue();
2330 }
2331 
2332 static void initSlots2BasicBlocks(
2333     const Function &F,
2334     DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
2335   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2336   MST.incorporateFunction(F);
2337   for (auto &BB : F) {
2338     if (BB.hasName())
2339       continue;
2340     int Slot = MST.getLocalSlot(&BB);
2341     if (Slot == -1)
2342       continue;
2343     Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
2344   }
2345 }
2346 
2347 static const BasicBlock *getIRBlockFromSlot(
2348     unsigned Slot,
2349     const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
2350   auto BlockInfo = Slots2BasicBlocks.find(Slot);
2351   if (BlockInfo == Slots2BasicBlocks.end())
2352     return nullptr;
2353   return BlockInfo->second;
2354 }
2355 
2356 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
2357   if (Slots2BasicBlocks.empty())
2358     initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
2359   return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
2360 }
2361 
2362 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
2363   if (&F == MF.getFunction())
2364     return getIRBlock(Slot);
2365   DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
2366   initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
2367   return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
2368 }
2369 
2370 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
2371                            DenseMap<unsigned, const Value *> &Slots2Values) {
2372   int Slot = MST.getLocalSlot(V);
2373   if (Slot == -1)
2374     return;
2375   Slots2Values.insert(std::make_pair(unsigned(Slot), V));
2376 }
2377 
2378 /// Creates the mapping from slot numbers to function's unnamed IR values.
2379 static void initSlots2Values(const Function &F,
2380                              DenseMap<unsigned, const Value *> &Slots2Values) {
2381   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2382   MST.incorporateFunction(F);
2383   for (const auto &Arg : F.args())
2384     mapValueToSlot(&Arg, MST, Slots2Values);
2385   for (const auto &BB : F) {
2386     mapValueToSlot(&BB, MST, Slots2Values);
2387     for (const auto &I : BB)
2388       mapValueToSlot(&I, MST, Slots2Values);
2389   }
2390 }
2391 
2392 const Value *MIParser::getIRValue(unsigned Slot) {
2393   if (Slots2Values.empty())
2394     initSlots2Values(*MF.getFunction(), Slots2Values);
2395   auto ValueInfo = Slots2Values.find(Slot);
2396   if (ValueInfo == Slots2Values.end())
2397     return nullptr;
2398   return ValueInfo->second;
2399 }
2400 
2401 void MIParser::initNames2TargetIndices() {
2402   if (!Names2TargetIndices.empty())
2403     return;
2404   const auto *TII = MF.getSubtarget().getInstrInfo();
2405   assert(TII && "Expected target instruction info");
2406   auto Indices = TII->getSerializableTargetIndices();
2407   for (const auto &I : Indices)
2408     Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
2409 }
2410 
2411 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
2412   initNames2TargetIndices();
2413   auto IndexInfo = Names2TargetIndices.find(Name);
2414   if (IndexInfo == Names2TargetIndices.end())
2415     return true;
2416   Index = IndexInfo->second;
2417   return false;
2418 }
2419 
2420 void MIParser::initNames2DirectTargetFlags() {
2421   if (!Names2DirectTargetFlags.empty())
2422     return;
2423   const auto *TII = MF.getSubtarget().getInstrInfo();
2424   assert(TII && "Expected target instruction info");
2425   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
2426   for (const auto &I : Flags)
2427     Names2DirectTargetFlags.insert(
2428         std::make_pair(StringRef(I.second), I.first));
2429 }
2430 
2431 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
2432   initNames2DirectTargetFlags();
2433   auto FlagInfo = Names2DirectTargetFlags.find(Name);
2434   if (FlagInfo == Names2DirectTargetFlags.end())
2435     return true;
2436   Flag = FlagInfo->second;
2437   return false;
2438 }
2439 
2440 void MIParser::initNames2BitmaskTargetFlags() {
2441   if (!Names2BitmaskTargetFlags.empty())
2442     return;
2443   const auto *TII = MF.getSubtarget().getInstrInfo();
2444   assert(TII && "Expected target instruction info");
2445   auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
2446   for (const auto &I : Flags)
2447     Names2BitmaskTargetFlags.insert(
2448         std::make_pair(StringRef(I.second), I.first));
2449 }
2450 
2451 bool MIParser::getBitmaskTargetFlag(StringRef Name, unsigned &Flag) {
2452   initNames2BitmaskTargetFlags();
2453   auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
2454   if (FlagInfo == Names2BitmaskTargetFlags.end())
2455     return true;
2456   Flag = FlagInfo->second;
2457   return false;
2458 }
2459 
2460 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS,
2461                                              StringRef Src,
2462                                              SMDiagnostic &Error) {
2463   return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
2464 }
2465 
2466 bool llvm::parseMachineInstructions(PerFunctionMIParsingState &PFS,
2467                                     StringRef Src, SMDiagnostic &Error) {
2468   return MIParser(PFS, Error, Src).parseBasicBlocks();
2469 }
2470 
2471 bool llvm::parseMBBReference(PerFunctionMIParsingState &PFS,
2472                              MachineBasicBlock *&MBB, StringRef Src,
2473                              SMDiagnostic &Error) {
2474   return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
2475 }
2476 
2477 bool llvm::parseRegisterReference(PerFunctionMIParsingState &PFS,
2478                                   unsigned &Reg, StringRef Src,
2479                                   SMDiagnostic &Error) {
2480   return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
2481 }
2482 
2483 bool llvm::parseNamedRegisterReference(PerFunctionMIParsingState &PFS,
2484                                        unsigned &Reg, StringRef Src,
2485                                        SMDiagnostic &Error) {
2486   return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
2487 }
2488 
2489 bool llvm::parseVirtualRegisterReference(PerFunctionMIParsingState &PFS,
2490                                          VRegInfo *&Info, StringRef Src,
2491                                          SMDiagnostic &Error) {
2492   return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
2493 }
2494 
2495 bool llvm::parseStackObjectReference(PerFunctionMIParsingState &PFS,
2496                                      int &FI, StringRef Src,
2497                                      SMDiagnostic &Error) {
2498   return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
2499 }
2500 
2501 bool llvm::parseMDNode(PerFunctionMIParsingState &PFS,
2502                        MDNode *&Node, StringRef Src, SMDiagnostic &Error) {
2503   return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
2504 }
2505