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