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