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