MIR Parser: Report an error when parsing duplicate register flags.
[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
74 public:
75   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
76            StringRef Source, const PerFunctionMIParsingState &PFS,
77            const SlotMapping &IRSlots);
78
79   void lex();
80
81   /// Report an error at the current location with the given message.
82   ///
83   /// This function always return true.
84   bool error(const Twine &Msg);
85
86   /// Report an error at the given location with the given message.
87   ///
88   /// This function always return true.
89   bool error(StringRef::iterator Loc, const Twine &Msg);
90
91   bool parse(MachineInstr *&MI);
92   bool parseStandaloneMBB(MachineBasicBlock *&MBB);
93   bool parseStandaloneNamedRegister(unsigned &Reg);
94   bool parseStandaloneVirtualRegister(unsigned &Reg);
95   bool parseStandaloneIRBlockReference(const BasicBlock *&BB);
96
97   bool parseRegister(unsigned &Reg);
98   bool parseRegisterFlag(unsigned &Flags);
99   bool parseSubRegisterIndex(unsigned &SubReg);
100   bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
101   bool parseImmediateOperand(MachineOperand &Dest);
102   bool parseFPImmediateOperand(MachineOperand &Dest);
103   bool parseMBBReference(MachineBasicBlock *&MBB);
104   bool parseMBBOperand(MachineOperand &Dest);
105   bool parseStackObjectOperand(MachineOperand &Dest);
106   bool parseFixedStackObjectOperand(MachineOperand &Dest);
107   bool parseGlobalValue(GlobalValue *&GV);
108   bool parseGlobalAddressOperand(MachineOperand &Dest);
109   bool parseConstantPoolIndexOperand(MachineOperand &Dest);
110   bool parseJumpTableIndexOperand(MachineOperand &Dest);
111   bool parseExternalSymbolOperand(MachineOperand &Dest);
112   bool parseMDNode(MDNode *&Node);
113   bool parseMetadataOperand(MachineOperand &Dest);
114   bool parseCFIOffset(int &Offset);
115   bool parseCFIRegister(unsigned &Reg);
116   bool parseCFIOperand(MachineOperand &Dest);
117   bool parseIRBlock(BasicBlock *&BB, const Function &F);
118   bool parseBlockAddressOperand(MachineOperand &Dest);
119   bool parseTargetIndexOperand(MachineOperand &Dest);
120   bool parseMachineOperand(MachineOperand &Dest);
121   bool parseIRValue(Value *&V);
122   bool parseMemoryOperandFlag(unsigned &Flags);
123   bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
124
125 private:
126   /// Convert the integer literal in the current token into an unsigned integer.
127   ///
128   /// Return true if an error occurred.
129   bool getUnsigned(unsigned &Result);
130
131   /// Convert the integer literal in the current token into an uint64.
132   ///
133   /// Return true if an error occurred.
134   bool getUint64(uint64_t &Result);
135
136   /// If the current token is of the given kind, consume it and return false.
137   /// Otherwise report an error and return true.
138   bool expectAndConsume(MIToken::TokenKind TokenKind);
139
140   void initNames2InstrOpCodes();
141
142   /// Try to convert an instruction name to an opcode. Return true if the
143   /// instruction name is invalid.
144   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
145
146   bool parseInstruction(unsigned &OpCode, unsigned &Flags);
147
148   bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
149                               const MCInstrDesc &MCID);
150
151   void initNames2Regs();
152
153   /// Try to convert a register name to a register number. Return true if the
154   /// register name is invalid.
155   bool getRegisterByName(StringRef RegName, unsigned &Reg);
156
157   void initNames2RegMasks();
158
159   /// Check if the given identifier is a name of a register mask.
160   ///
161   /// Return null if the identifier isn't a register mask.
162   const uint32_t *getRegMask(StringRef Identifier);
163
164   void initNames2SubRegIndices();
165
166   /// Check if the given identifier is a name of a subregister index.
167   ///
168   /// Return 0 if the name isn't a subregister index class.
169   unsigned getSubRegIndex(StringRef Name);
170
171   void initSlots2BasicBlocks();
172
173   const BasicBlock *getIRBlock(unsigned Slot);
174
175   void initNames2TargetIndices();
176
177   /// Try to convert a name of target index to the corresponding target index.
178   ///
179   /// Return true if the name isn't a name of a target index.
180   bool getTargetIndex(StringRef Name, int &Index);
181 };
182
183 } // end anonymous namespace
184
185 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
186                    StringRef Source, const PerFunctionMIParsingState &PFS,
187                    const SlotMapping &IRSlots)
188     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
189       Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
190
191 void MIParser::lex() {
192   CurrentSource = lexMIToken(
193       CurrentSource, Token,
194       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
195 }
196
197 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
198
199 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
200   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
201   Error = SMDiagnostic(
202       SM, SMLoc(),
203       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
204       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
205   return true;
206 }
207
208 static const char *toString(MIToken::TokenKind TokenKind) {
209   switch (TokenKind) {
210   case MIToken::comma:
211     return "','";
212   case MIToken::equal:
213     return "'='";
214   case MIToken::lparen:
215     return "'('";
216   case MIToken::rparen:
217     return "')'";
218   default:
219     return "<unknown token>";
220   }
221 }
222
223 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
224   if (Token.isNot(TokenKind))
225     return error(Twine("expected ") + toString(TokenKind));
226   lex();
227   return false;
228 }
229
230 bool MIParser::parse(MachineInstr *&MI) {
231   lex();
232
233   // Parse any register operands before '='
234   MachineOperand MO = MachineOperand::CreateImm(0);
235   SmallVector<MachineOperandWithLocation, 8> Operands;
236   while (Token.isRegister() || Token.isRegisterFlag()) {
237     auto Loc = Token.location();
238     if (parseRegisterOperand(MO, /*IsDef=*/true))
239       return true;
240     Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
241     if (Token.isNot(MIToken::comma))
242       break;
243     lex();
244   }
245   if (!Operands.empty() && expectAndConsume(MIToken::equal))
246     return true;
247
248   unsigned OpCode, Flags = 0;
249   if (Token.isError() || parseInstruction(OpCode, Flags))
250     return true;
251
252   // TODO: Parse the bundle instruction flags.
253
254   // Parse the remaining machine operands.
255   while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location) &&
256          Token.isNot(MIToken::coloncolon)) {
257     auto Loc = Token.location();
258     if (parseMachineOperand(MO))
259       return true;
260     Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
261     if (Token.is(MIToken::Eof) || Token.is(MIToken::coloncolon))
262       break;
263     if (Token.isNot(MIToken::comma))
264       return error("expected ',' before the next machine operand");
265     lex();
266   }
267
268   DebugLoc DebugLocation;
269   if (Token.is(MIToken::kw_debug_location)) {
270     lex();
271     if (Token.isNot(MIToken::exclaim))
272       return error("expected a metadata node after 'debug-location'");
273     MDNode *Node = nullptr;
274     if (parseMDNode(Node))
275       return true;
276     DebugLocation = DebugLoc(Node);
277   }
278
279   // Parse the machine memory operands.
280   SmallVector<MachineMemOperand *, 2> MemOperands;
281   if (Token.is(MIToken::coloncolon)) {
282     lex();
283     while (Token.isNot(MIToken::Eof)) {
284       MachineMemOperand *MemOp = nullptr;
285       if (parseMachineMemoryOperand(MemOp))
286         return true;
287       MemOperands.push_back(MemOp);
288       if (Token.is(MIToken::Eof))
289         break;
290       if (Token.isNot(MIToken::comma))
291         return error("expected ',' before the next machine memory operand");
292       lex();
293     }
294   }
295
296   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
297   if (!MCID.isVariadic()) {
298     // FIXME: Move the implicit operand verification to the machine verifier.
299     if (verifyImplicitOperands(Operands, MCID))
300       return true;
301   }
302
303   // TODO: Check for extraneous machine operands.
304   MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
305   MI->setFlags(Flags);
306   for (const auto &Operand : Operands)
307     MI->addOperand(MF, Operand.Operand);
308   if (MemOperands.empty())
309     return false;
310   MachineInstr::mmo_iterator MemRefs =
311       MF.allocateMemRefsArray(MemOperands.size());
312   std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
313   MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
314   return false;
315 }
316
317 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
318   lex();
319   if (Token.isNot(MIToken::MachineBasicBlock))
320     return error("expected a machine basic block reference");
321   if (parseMBBReference(MBB))
322     return true;
323   lex();
324   if (Token.isNot(MIToken::Eof))
325     return error(
326         "expected end of string after the machine basic block reference");
327   return false;
328 }
329
330 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
331   lex();
332   if (Token.isNot(MIToken::NamedRegister))
333     return error("expected a named register");
334   if (parseRegister(Reg))
335     return 0;
336   lex();
337   if (Token.isNot(MIToken::Eof))
338     return error("expected end of string after the register reference");
339   return false;
340 }
341
342 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
343   lex();
344   if (Token.isNot(MIToken::VirtualRegister))
345     return error("expected a virtual register");
346   if (parseRegister(Reg))
347     return 0;
348   lex();
349   if (Token.isNot(MIToken::Eof))
350     return error("expected end of string after the register reference");
351   return false;
352 }
353
354 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
355   lex();
356   if (Token.isNot(MIToken::IRBlock))
357     return error("expected an IR block reference");
358   unsigned SlotNumber = 0;
359   if (getUnsigned(SlotNumber))
360     return true;
361   BB = getIRBlock(SlotNumber);
362   if (!BB)
363     return error(Twine("use of undefined IR block '%ir-block.") +
364                  Twine(SlotNumber) + "'");
365   lex();
366   if (Token.isNot(MIToken::Eof))
367     return error("expected end of string after the IR block reference");
368   return false;
369 }
370
371 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
372   assert(MO.isImplicit());
373   return MO.isDef() ? "implicit-def" : "implicit";
374 }
375
376 static std::string getRegisterName(const TargetRegisterInfo *TRI,
377                                    unsigned Reg) {
378   assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
379   return StringRef(TRI->getName(Reg)).lower();
380 }
381
382 bool MIParser::verifyImplicitOperands(
383     ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
384   if (MCID.isCall())
385     // We can't verify call instructions as they can contain arbitrary implicit
386     // register and register mask operands.
387     return false;
388
389   // Gather all the expected implicit operands.
390   SmallVector<MachineOperand, 4> ImplicitOperands;
391   if (MCID.ImplicitDefs)
392     for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
393       ImplicitOperands.push_back(
394           MachineOperand::CreateReg(*ImpDefs, true, true));
395   if (MCID.ImplicitUses)
396     for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
397       ImplicitOperands.push_back(
398           MachineOperand::CreateReg(*ImpUses, false, true));
399
400   const auto *TRI = MF.getSubtarget().getRegisterInfo();
401   assert(TRI && "Expected target register info");
402   size_t I = ImplicitOperands.size(), J = Operands.size();
403   while (I) {
404     --I;
405     if (J) {
406       --J;
407       const auto &ImplicitOperand = ImplicitOperands[I];
408       const auto &Operand = Operands[J].Operand;
409       if (ImplicitOperand.isIdenticalTo(Operand))
410         continue;
411       if (Operand.isReg() && Operand.isImplicit()) {
412         return error(Operands[J].Begin,
413                      Twine("expected an implicit register operand '") +
414                          printImplicitRegisterFlag(ImplicitOperand) + " %" +
415                          getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
416       }
417     }
418     // TODO: Fix source location when Operands[J].end is right before '=', i.e:
419     // insead of reporting an error at this location:
420     //            %eax = MOV32r0
421     //                 ^
422     // report the error at the following location:
423     //            %eax = MOV32r0
424     //                          ^
425     return error(J < Operands.size() ? Operands[J].End : Token.location(),
426                  Twine("missing implicit register operand '") +
427                      printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
428                      getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
429   }
430   return false;
431 }
432
433 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
434   if (Token.is(MIToken::kw_frame_setup)) {
435     Flags |= MachineInstr::FrameSetup;
436     lex();
437   }
438   if (Token.isNot(MIToken::Identifier))
439     return error("expected a machine instruction");
440   StringRef InstrName = Token.stringValue();
441   if (parseInstrName(InstrName, OpCode))
442     return error(Twine("unknown machine instruction name '") + InstrName + "'");
443   lex();
444   return false;
445 }
446
447 bool MIParser::parseRegister(unsigned &Reg) {
448   switch (Token.kind()) {
449   case MIToken::underscore:
450     Reg = 0;
451     break;
452   case MIToken::NamedRegister: {
453     StringRef Name = Token.stringValue();
454     if (getRegisterByName(Name, Reg))
455       return error(Twine("unknown register name '") + Name + "'");
456     break;
457   }
458   case MIToken::VirtualRegister: {
459     unsigned ID;
460     if (getUnsigned(ID))
461       return true;
462     const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
463     if (RegInfo == PFS.VirtualRegisterSlots.end())
464       return error(Twine("use of undefined virtual register '%") + Twine(ID) +
465                    "'");
466     Reg = RegInfo->second;
467     break;
468   }
469   // TODO: Parse other register kinds.
470   default:
471     llvm_unreachable("The current token should be a register");
472   }
473   return false;
474 }
475
476 bool MIParser::parseRegisterFlag(unsigned &Flags) {
477   const unsigned OldFlags = Flags;
478   switch (Token.kind()) {
479   case MIToken::kw_implicit:
480     Flags |= RegState::Implicit;
481     break;
482   case MIToken::kw_implicit_define:
483     Flags |= RegState::ImplicitDefine;
484     break;
485   case MIToken::kw_dead:
486     Flags |= RegState::Dead;
487     break;
488   case MIToken::kw_killed:
489     Flags |= RegState::Kill;
490     break;
491   case MIToken::kw_undef:
492     Flags |= RegState::Undef;
493     break;
494   case MIToken::kw_early_clobber:
495     Flags |= RegState::EarlyClobber;
496     break;
497   case MIToken::kw_debug_use:
498     Flags |= RegState::Debug;
499     break;
500   // TODO: parse the other register flags.
501   default:
502     llvm_unreachable("The current token should be a register flag");
503   }
504   if (OldFlags == Flags)
505     // We know that the same flag is specified more than once when the flags
506     // weren't modified.
507     return error("duplicate '" + Token.stringValue() + "' register flag");
508   lex();
509   return false;
510 }
511
512 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
513   assert(Token.is(MIToken::colon));
514   lex();
515   if (Token.isNot(MIToken::Identifier))
516     return error("expected a subregister index after ':'");
517   auto Name = Token.stringValue();
518   SubReg = getSubRegIndex(Name);
519   if (!SubReg)
520     return error(Twine("use of unknown subregister index '") + Name + "'");
521   lex();
522   return false;
523 }
524
525 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
526   unsigned Reg;
527   unsigned Flags = IsDef ? RegState::Define : 0;
528   while (Token.isRegisterFlag()) {
529     if (parseRegisterFlag(Flags))
530       return true;
531   }
532   if (!Token.isRegister())
533     return error("expected a register after register flags");
534   if (parseRegister(Reg))
535     return true;
536   lex();
537   unsigned SubReg = 0;
538   if (Token.is(MIToken::colon)) {
539     if (parseSubRegisterIndex(SubReg))
540       return true;
541   }
542   Dest = MachineOperand::CreateReg(
543       Reg, Flags & RegState::Define, Flags & RegState::Implicit,
544       Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
545       Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
546   return false;
547 }
548
549 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
550   assert(Token.is(MIToken::IntegerLiteral));
551   const APSInt &Int = Token.integerValue();
552   if (Int.getMinSignedBits() > 64)
553     // TODO: Replace this with an error when we can parse CIMM Machine Operands.
554     llvm_unreachable("Can't parse large integer literals yet!");
555   Dest = MachineOperand::CreateImm(Int.getExtValue());
556   lex();
557   return false;
558 }
559
560 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
561   auto Loc = Token.location();
562   lex();
563   if (Token.isNot(MIToken::FloatingPointLiteral))
564     return error("expected a floating point literal");
565   auto Source = StringRef(Loc, Token.stringValue().end() - Loc).str();
566   lex();
567   SMDiagnostic Err;
568   const Constant *C =
569       parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
570   if (!C)
571     return error(Loc + Err.getColumnNo(), Err.getMessage());
572   Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
573   return false;
574 }
575
576 bool MIParser::getUnsigned(unsigned &Result) {
577   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
578   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
579   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
580   if (Val64 == Limit)
581     return error("expected 32-bit integer (too large)");
582   Result = Val64;
583   return false;
584 }
585
586 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
587   assert(Token.is(MIToken::MachineBasicBlock));
588   unsigned Number;
589   if (getUnsigned(Number))
590     return true;
591   auto MBBInfo = PFS.MBBSlots.find(Number);
592   if (MBBInfo == PFS.MBBSlots.end())
593     return error(Twine("use of undefined machine basic block #") +
594                  Twine(Number));
595   MBB = MBBInfo->second;
596   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
597     return error(Twine("the name of machine basic block #") + Twine(Number) +
598                  " isn't '" + Token.stringValue() + "'");
599   return false;
600 }
601
602 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
603   MachineBasicBlock *MBB;
604   if (parseMBBReference(MBB))
605     return true;
606   Dest = MachineOperand::CreateMBB(MBB);
607   lex();
608   return false;
609 }
610
611 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
612   assert(Token.is(MIToken::StackObject));
613   unsigned ID;
614   if (getUnsigned(ID))
615     return true;
616   auto ObjectInfo = PFS.StackObjectSlots.find(ID);
617   if (ObjectInfo == PFS.StackObjectSlots.end())
618     return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
619                  "'");
620   StringRef Name;
621   if (const auto *Alloca =
622           MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
623     Name = Alloca->getName();
624   if (!Token.stringValue().empty() && Token.stringValue() != Name)
625     return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
626                  "' isn't '" + Token.stringValue() + "'");
627   lex();
628   Dest = MachineOperand::CreateFI(ObjectInfo->second);
629   return false;
630 }
631
632 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
633   assert(Token.is(MIToken::FixedStackObject));
634   unsigned ID;
635   if (getUnsigned(ID))
636     return true;
637   auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
638   if (ObjectInfo == PFS.FixedStackObjectSlots.end())
639     return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
640                  Twine(ID) + "'");
641   lex();
642   Dest = MachineOperand::CreateFI(ObjectInfo->second);
643   return false;
644 }
645
646 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
647   switch (Token.kind()) {
648   case MIToken::NamedGlobalValue: {
649     const Module *M = MF.getFunction()->getParent();
650     GV = M->getNamedValue(Token.stringValue());
651     if (!GV)
652       return error(Twine("use of undefined global value '@") +
653                    Token.rawStringValue() + "'");
654     break;
655   }
656   case MIToken::GlobalValue: {
657     unsigned GVIdx;
658     if (getUnsigned(GVIdx))
659       return true;
660     if (GVIdx >= IRSlots.GlobalValues.size())
661       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
662                    "'");
663     GV = IRSlots.GlobalValues[GVIdx];
664     break;
665   }
666   default:
667     llvm_unreachable("The current token should be a global value");
668   }
669   return false;
670 }
671
672 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
673   GlobalValue *GV = nullptr;
674   if (parseGlobalValue(GV))
675     return true;
676   Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
677   // TODO: Parse offset and target flags.
678   lex();
679   return false;
680 }
681
682 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
683   assert(Token.is(MIToken::ConstantPoolItem));
684   unsigned ID;
685   if (getUnsigned(ID))
686     return true;
687   auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
688   if (ConstantInfo == PFS.ConstantPoolSlots.end())
689     return error("use of undefined constant '%const." + Twine(ID) + "'");
690   lex();
691   // TODO: Parse offset and target flags.
692   Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
693   return false;
694 }
695
696 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
697   assert(Token.is(MIToken::JumpTableIndex));
698   unsigned ID;
699   if (getUnsigned(ID))
700     return true;
701   auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
702   if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
703     return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
704   lex();
705   // TODO: Parse target flags.
706   Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
707   return false;
708 }
709
710 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
711   assert(Token.is(MIToken::ExternalSymbol));
712   const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
713   lex();
714   // TODO: Parse the target flags.
715   Dest = MachineOperand::CreateES(Symbol);
716   return false;
717 }
718
719 bool MIParser::parseMDNode(MDNode *&Node) {
720   assert(Token.is(MIToken::exclaim));
721   auto Loc = Token.location();
722   lex();
723   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
724     return error("expected metadata id after '!'");
725   unsigned ID;
726   if (getUnsigned(ID))
727     return true;
728   auto NodeInfo = IRSlots.MetadataNodes.find(ID);
729   if (NodeInfo == IRSlots.MetadataNodes.end())
730     return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
731   lex();
732   Node = NodeInfo->second.get();
733   return false;
734 }
735
736 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
737   MDNode *Node = nullptr;
738   if (parseMDNode(Node))
739     return true;
740   Dest = MachineOperand::CreateMetadata(Node);
741   return false;
742 }
743
744 bool MIParser::parseCFIOffset(int &Offset) {
745   if (Token.isNot(MIToken::IntegerLiteral))
746     return error("expected a cfi offset");
747   if (Token.integerValue().getMinSignedBits() > 32)
748     return error("expected a 32 bit integer (the cfi offset is too large)");
749   Offset = (int)Token.integerValue().getExtValue();
750   lex();
751   return false;
752 }
753
754 bool MIParser::parseCFIRegister(unsigned &Reg) {
755   if (Token.isNot(MIToken::NamedRegister))
756     return error("expected a cfi register");
757   unsigned LLVMReg;
758   if (parseRegister(LLVMReg))
759     return true;
760   const auto *TRI = MF.getSubtarget().getRegisterInfo();
761   assert(TRI && "Expected target register info");
762   int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
763   if (DwarfReg < 0)
764     return error("invalid DWARF register");
765   Reg = (unsigned)DwarfReg;
766   lex();
767   return false;
768 }
769
770 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
771   auto Kind = Token.kind();
772   lex();
773   auto &MMI = MF.getMMI();
774   int Offset;
775   unsigned Reg;
776   unsigned CFIIndex;
777   switch (Kind) {
778   case MIToken::kw_cfi_offset:
779     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
780         parseCFIOffset(Offset))
781       return true;
782     CFIIndex =
783         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
784     break;
785   case MIToken::kw_cfi_def_cfa_register:
786     if (parseCFIRegister(Reg))
787       return true;
788     CFIIndex =
789         MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
790     break;
791   case MIToken::kw_cfi_def_cfa_offset:
792     if (parseCFIOffset(Offset))
793       return true;
794     // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
795     CFIIndex = MMI.addFrameInst(
796         MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
797     break;
798   case MIToken::kw_cfi_def_cfa:
799     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
800         parseCFIOffset(Offset))
801       return true;
802     // NB: MCCFIInstruction::createDefCfa negates the offset.
803     CFIIndex =
804         MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
805     break;
806   default:
807     // TODO: Parse the other CFI operands.
808     llvm_unreachable("The current token should be a cfi operand");
809   }
810   Dest = MachineOperand::CreateCFIIndex(CFIIndex);
811   return false;
812 }
813
814 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
815   switch (Token.kind()) {
816   case MIToken::NamedIRBlock: {
817     BB = dyn_cast_or_null<BasicBlock>(
818         F.getValueSymbolTable().lookup(Token.stringValue()));
819     if (!BB)
820       return error(Twine("use of undefined IR block '%ir-block.") +
821                    Token.rawStringValue() + "'");
822     break;
823   }
824   case MIToken::IRBlock: {
825     unsigned SlotNumber = 0;
826     if (getUnsigned(SlotNumber))
827       return true;
828     BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber));
829     if (!BB)
830       return error(Twine("use of undefined IR block '%ir-block.") +
831                    Twine(SlotNumber) + "'");
832     break;
833   }
834   default:
835     llvm_unreachable("The current token should be an IR block reference");
836   }
837   return false;
838 }
839
840 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
841   assert(Token.is(MIToken::kw_blockaddress));
842   lex();
843   if (expectAndConsume(MIToken::lparen))
844     return true;
845   if (Token.isNot(MIToken::GlobalValue) &&
846       Token.isNot(MIToken::NamedGlobalValue))
847     return error("expected a global value");
848   GlobalValue *GV = nullptr;
849   if (parseGlobalValue(GV))
850     return true;
851   auto *F = dyn_cast<Function>(GV);
852   if (!F)
853     return error("expected an IR function reference");
854   lex();
855   if (expectAndConsume(MIToken::comma))
856     return true;
857   BasicBlock *BB = nullptr;
858   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
859     return error("expected an IR block reference");
860   if (parseIRBlock(BB, *F))
861     return true;
862   lex();
863   if (expectAndConsume(MIToken::rparen))
864     return true;
865   // TODO: parse offset and target flags.
866   Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
867   return false;
868 }
869
870 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
871   assert(Token.is(MIToken::kw_target_index));
872   lex();
873   if (expectAndConsume(MIToken::lparen))
874     return true;
875   if (Token.isNot(MIToken::Identifier))
876     return error("expected the name of the target index");
877   int Index = 0;
878   if (getTargetIndex(Token.stringValue(), Index))
879     return error("use of undefined target index '" + Token.stringValue() + "'");
880   lex();
881   if (expectAndConsume(MIToken::rparen))
882     return true;
883   // TODO: Parse the offset and target flags.
884   Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
885   return false;
886 }
887
888 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
889   switch (Token.kind()) {
890   case MIToken::kw_implicit:
891   case MIToken::kw_implicit_define:
892   case MIToken::kw_dead:
893   case MIToken::kw_killed:
894   case MIToken::kw_undef:
895   case MIToken::kw_early_clobber:
896   case MIToken::kw_debug_use:
897   case MIToken::underscore:
898   case MIToken::NamedRegister:
899   case MIToken::VirtualRegister:
900     return parseRegisterOperand(Dest);
901   case MIToken::IntegerLiteral:
902     return parseImmediateOperand(Dest);
903   case MIToken::kw_half:
904   case MIToken::kw_float:
905   case MIToken::kw_double:
906   case MIToken::kw_x86_fp80:
907   case MIToken::kw_fp128:
908   case MIToken::kw_ppc_fp128:
909     return parseFPImmediateOperand(Dest);
910   case MIToken::MachineBasicBlock:
911     return parseMBBOperand(Dest);
912   case MIToken::StackObject:
913     return parseStackObjectOperand(Dest);
914   case MIToken::FixedStackObject:
915     return parseFixedStackObjectOperand(Dest);
916   case MIToken::GlobalValue:
917   case MIToken::NamedGlobalValue:
918     return parseGlobalAddressOperand(Dest);
919   case MIToken::ConstantPoolItem:
920     return parseConstantPoolIndexOperand(Dest);
921   case MIToken::JumpTableIndex:
922     return parseJumpTableIndexOperand(Dest);
923   case MIToken::ExternalSymbol:
924     return parseExternalSymbolOperand(Dest);
925   case MIToken::exclaim:
926     return parseMetadataOperand(Dest);
927   case MIToken::kw_cfi_offset:
928   case MIToken::kw_cfi_def_cfa_register:
929   case MIToken::kw_cfi_def_cfa_offset:
930   case MIToken::kw_cfi_def_cfa:
931     return parseCFIOperand(Dest);
932   case MIToken::kw_blockaddress:
933     return parseBlockAddressOperand(Dest);
934   case MIToken::kw_target_index:
935     return parseTargetIndexOperand(Dest);
936   case MIToken::Error:
937     return true;
938   case MIToken::Identifier:
939     if (const auto *RegMask = getRegMask(Token.stringValue())) {
940       Dest = MachineOperand::CreateRegMask(RegMask);
941       lex();
942       break;
943     }
944   // fallthrough
945   default:
946     // TODO: parse the other machine operands.
947     return error("expected a machine operand");
948   }
949   return false;
950 }
951
952 bool MIParser::parseIRValue(Value *&V) {
953   switch (Token.kind()) {
954   case MIToken::NamedIRValue: {
955     V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
956     if (!V)
957       return error(Twine("use of undefined IR value '%ir.") +
958                    Token.rawStringValue() + "'");
959     break;
960   }
961   // TODO: Parse unnamed IR value references.
962   default:
963     llvm_unreachable("The current token should be an IR block reference");
964   }
965   return false;
966 }
967
968 bool MIParser::getUint64(uint64_t &Result) {
969   assert(Token.hasIntegerValue());
970   if (Token.integerValue().getActiveBits() > 64)
971     return error("expected 64-bit integer (too large)");
972   Result = Token.integerValue().getZExtValue();
973   return false;
974 }
975
976 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
977   switch (Token.kind()) {
978   case MIToken::kw_volatile:
979     Flags |= MachineMemOperand::MOVolatile;
980     break;
981   // TODO: report an error when we specify the same flag more than once.
982   // TODO: parse the other memory operand flags.
983   default:
984     llvm_unreachable("The current token should be a memory operand flag");
985   }
986   lex();
987   return false;
988 }
989
990 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
991   if (expectAndConsume(MIToken::lparen))
992     return true;
993   unsigned Flags = 0;
994   while (Token.isMemoryOperandFlag()) {
995     if (parseMemoryOperandFlag(Flags))
996       return true;
997   }
998   if (Token.isNot(MIToken::Identifier) ||
999       (Token.stringValue() != "load" && Token.stringValue() != "store"))
1000     return error("expected 'load' or 'store' memory operation");
1001   if (Token.stringValue() == "load")
1002     Flags |= MachineMemOperand::MOLoad;
1003   else
1004     Flags |= MachineMemOperand::MOStore;
1005   lex();
1006
1007   if (Token.isNot(MIToken::IntegerLiteral))
1008     return error("expected the size integer literal after memory operation");
1009   uint64_t Size;
1010   if (getUint64(Size))
1011     return true;
1012   lex();
1013
1014   const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1015   if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1016     return error(Twine("expected '") + Word + "'");
1017   lex();
1018
1019   // TODO: Parse pseudo source values.
1020   if (Token.isNot(MIToken::NamedIRValue))
1021     return error("expected an IR value reference");
1022   Value *V = nullptr;
1023   if (parseIRValue(V))
1024     return true;
1025   if (!V->getType()->isPointerTy())
1026     return error("expected a pointer IR value");
1027   lex();
1028   // TODO: Parse the base alignment.
1029   // TODO: Parse the attached metadata nodes.
1030   if (expectAndConsume(MIToken::rparen))
1031     return true;
1032
1033   Dest = MF.getMachineMemOperand(MachinePointerInfo(V), Flags, Size, Size);
1034   return false;
1035 }
1036
1037 void MIParser::initNames2InstrOpCodes() {
1038   if (!Names2InstrOpCodes.empty())
1039     return;
1040   const auto *TII = MF.getSubtarget().getInstrInfo();
1041   assert(TII && "Expected target instruction info");
1042   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1043     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1044 }
1045
1046 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1047   initNames2InstrOpCodes();
1048   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1049   if (InstrInfo == Names2InstrOpCodes.end())
1050     return true;
1051   OpCode = InstrInfo->getValue();
1052   return false;
1053 }
1054
1055 void MIParser::initNames2Regs() {
1056   if (!Names2Regs.empty())
1057     return;
1058   // The '%noreg' register is the register 0.
1059   Names2Regs.insert(std::make_pair("noreg", 0));
1060   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1061   assert(TRI && "Expected target register info");
1062   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1063     bool WasInserted =
1064         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1065             .second;
1066     (void)WasInserted;
1067     assert(WasInserted && "Expected registers to be unique case-insensitively");
1068   }
1069 }
1070
1071 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1072   initNames2Regs();
1073   auto RegInfo = Names2Regs.find(RegName);
1074   if (RegInfo == Names2Regs.end())
1075     return true;
1076   Reg = RegInfo->getValue();
1077   return false;
1078 }
1079
1080 void MIParser::initNames2RegMasks() {
1081   if (!Names2RegMasks.empty())
1082     return;
1083   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1084   assert(TRI && "Expected target register info");
1085   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1086   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1087   assert(RegMasks.size() == RegMaskNames.size());
1088   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1089     Names2RegMasks.insert(
1090         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1091 }
1092
1093 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1094   initNames2RegMasks();
1095   auto RegMaskInfo = Names2RegMasks.find(Identifier);
1096   if (RegMaskInfo == Names2RegMasks.end())
1097     return nullptr;
1098   return RegMaskInfo->getValue();
1099 }
1100
1101 void MIParser::initNames2SubRegIndices() {
1102   if (!Names2SubRegIndices.empty())
1103     return;
1104   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1105   for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1106     Names2SubRegIndices.insert(
1107         std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1108 }
1109
1110 unsigned MIParser::getSubRegIndex(StringRef Name) {
1111   initNames2SubRegIndices();
1112   auto SubRegInfo = Names2SubRegIndices.find(Name);
1113   if (SubRegInfo == Names2SubRegIndices.end())
1114     return 0;
1115   return SubRegInfo->getValue();
1116 }
1117
1118 void MIParser::initSlots2BasicBlocks() {
1119   if (!Slots2BasicBlocks.empty())
1120     return;
1121   const auto &F = *MF.getFunction();
1122   ModuleSlotTracker MST(F.getParent());
1123   MST.incorporateFunction(F);
1124   for (auto &BB : F) {
1125     if (BB.hasName())
1126       continue;
1127     int Slot = MST.getLocalSlot(&BB);
1128     if (Slot == -1)
1129       continue;
1130     Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1131   }
1132 }
1133
1134 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1135   initSlots2BasicBlocks();
1136   auto BlockInfo = Slots2BasicBlocks.find(Slot);
1137   if (BlockInfo == Slots2BasicBlocks.end())
1138     return nullptr;
1139   return BlockInfo->second;
1140 }
1141
1142 void MIParser::initNames2TargetIndices() {
1143   if (!Names2TargetIndices.empty())
1144     return;
1145   const auto *TII = MF.getSubtarget().getInstrInfo();
1146   assert(TII && "Expected target instruction info");
1147   auto Indices = TII->getSerializableTargetIndices();
1148   for (const auto &I : Indices)
1149     Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1150 }
1151
1152 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1153   initNames2TargetIndices();
1154   auto IndexInfo = Names2TargetIndices.find(Name);
1155   if (IndexInfo == Names2TargetIndices.end())
1156     return true;
1157   Index = IndexInfo->second;
1158   return false;
1159 }
1160
1161 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1162                              MachineFunction &MF, StringRef Src,
1163                              const PerFunctionMIParsingState &PFS,
1164                              const SlotMapping &IRSlots, SMDiagnostic &Error) {
1165   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1166 }
1167
1168 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1169                              MachineFunction &MF, StringRef Src,
1170                              const PerFunctionMIParsingState &PFS,
1171                              const SlotMapping &IRSlots, SMDiagnostic &Error) {
1172   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1173 }
1174
1175 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1176                                        MachineFunction &MF, StringRef Src,
1177                                        const PerFunctionMIParsingState &PFS,
1178                                        const SlotMapping &IRSlots,
1179                                        SMDiagnostic &Error) {
1180   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1181       .parseStandaloneNamedRegister(Reg);
1182 }
1183
1184 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1185                                          MachineFunction &MF, StringRef Src,
1186                                          const PerFunctionMIParsingState &PFS,
1187                                          const SlotMapping &IRSlots,
1188                                          SMDiagnostic &Error) {
1189   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1190       .parseStandaloneVirtualRegister(Reg);
1191 }
1192
1193 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1194                                  MachineFunction &MF, StringRef Src,
1195                                  const PerFunctionMIParsingState &PFS,
1196                                  const SlotMapping &IRSlots,
1197                                  SMDiagnostic &Error) {
1198   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1199       .parseStandaloneIRBlockReference(BB);
1200 }