1 //===- MIRParser.cpp - MIR serialization format 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 class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/MIRParser/MIRParser.h"
16 #include "MIParser.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
25 #include "llvm/CodeGen/MIRYamlMapping.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/ValueSymbolTable.h"
38 #include "llvm/Support/LineIterator.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/SMLoc.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/YAMLTraits.h"
43 #include <memory>
44 
45 using namespace llvm;
46 
47 namespace llvm {
48 
49 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
50 /// file.
51 class MIRParserImpl {
52   SourceMgr SM;
53   StringRef Filename;
54   LLVMContext &Context;
55   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
56   SlotMapping IRSlots;
57   /// Maps from register class names to register classes.
58   StringMap<const TargetRegisterClass *> Names2RegClasses;
59   /// Maps from register bank names to register banks.
60   StringMap<const RegisterBank *> Names2RegBanks;
61 
62 public:
63   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
64                 LLVMContext &Context);
65 
66   void reportDiagnostic(const SMDiagnostic &Diag);
67 
68   /// Report an error with the given message at unknown location.
69   ///
70   /// Always returns true.
71   bool error(const Twine &Message);
72 
73   /// Report an error with the given message at the given location.
74   ///
75   /// Always returns true.
76   bool error(SMLoc Loc, const Twine &Message);
77 
78   /// Report a given error with the location translated from the location in an
79   /// embedded string literal to a location in the MIR file.
80   ///
81   /// Always returns true.
82   bool error(const SMDiagnostic &Error, SMRange SourceRange);
83 
84   /// Try to parse the optional LLVM module and the machine functions in the MIR
85   /// file.
86   ///
87   /// Return null if an error occurred.
88   std::unique_ptr<Module> parse();
89 
90   /// Parse the machine function in the current YAML document.
91   ///
92   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
93   /// A dummy IR function is created and inserted into the given module when
94   /// this parameter is true.
95   ///
96   /// Return true if an error occurred.
97   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
98 
99   /// Initialize the machine function to the state that's described in the MIR
100   /// file.
101   ///
102   /// Return true if error occurred.
103   bool initializeMachineFunction(MachineFunction &MF);
104 
105   bool initializeRegisterInfo(MachineFunction &MF,
106                               const yaml::MachineFunction &YamlMF,
107                               PerFunctionMIParsingState &PFS);
108 
109   void inferRegisterInfo(MachineFunction &MF,
110                          const yaml::MachineFunction &YamlMF);
111 
112   bool initializeFrameInfo(MachineFunction &MF,
113                            const yaml::MachineFunction &YamlMF,
114                            PerFunctionMIParsingState &PFS);
115 
116   bool parseCalleeSavedRegister(MachineFunction &MF,
117                                 PerFunctionMIParsingState &PFS,
118                                 std::vector<CalleeSavedInfo> &CSIInfo,
119                                 const yaml::StringValue &RegisterSource,
120                                 int FrameIdx);
121 
122   bool parseStackObjectsDebugInfo(MachineFunction &MF,
123                                   PerFunctionMIParsingState &PFS,
124                                   const yaml::MachineStackObject &Object,
125                                   int FrameIdx);
126 
127   bool initializeConstantPool(MachineConstantPool &ConstantPool,
128                               const yaml::MachineFunction &YamlMF,
129                               const MachineFunction &MF,
130                               DenseMap<unsigned, unsigned> &ConstantPoolSlots);
131 
132   bool initializeJumpTableInfo(MachineFunction &MF,
133                                const yaml::MachineJumpTable &YamlJTI,
134                                PerFunctionMIParsingState &PFS);
135 
136 private:
137   bool parseMDNode(MDNode *&Node, const yaml::StringValue &Source,
138                    MachineFunction &MF, const PerFunctionMIParsingState &PFS);
139 
140   bool parseMBBReference(MachineBasicBlock *&MBB,
141                          const yaml::StringValue &Source, MachineFunction &MF,
142                          const PerFunctionMIParsingState &PFS);
143 
144   /// Return a MIR diagnostic converted from an MI string diagnostic.
145   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
146                                     SMRange SourceRange);
147 
148   /// Return a MIR diagnostic converted from a diagnostic located in a YAML
149   /// block scalar string.
150   SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
151                                        SMRange SourceRange);
152 
153   /// Create an empty function with the given name.
154   void createDummyFunction(StringRef Name, Module &M);
155 
156   void initNames2RegClasses(const MachineFunction &MF);
157   void initNames2RegBanks(const MachineFunction &MF);
158 
159   /// Check if the given identifier is a name of a register class.
160   ///
161   /// Return null if the name isn't a register class.
162   const TargetRegisterClass *getRegClass(const MachineFunction &MF,
163                                          StringRef Name);
164 
165   /// Check if the given identifier is a name of a register bank.
166   ///
167   /// Return null if the name isn't a register bank.
168   const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name);
169 };
170 
171 } // end namespace llvm
172 
173 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
174                              StringRef Filename, LLVMContext &Context)
175     : SM(), Filename(Filename), Context(Context) {
176   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
177 }
178 
179 bool MIRParserImpl::error(const Twine &Message) {
180   Context.diagnose(DiagnosticInfoMIRParser(
181       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
182   return true;
183 }
184 
185 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
186   Context.diagnose(DiagnosticInfoMIRParser(
187       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
188   return true;
189 }
190 
191 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
192   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
193   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
194   return true;
195 }
196 
197 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
198   DiagnosticSeverity Kind;
199   switch (Diag.getKind()) {
200   case SourceMgr::DK_Error:
201     Kind = DS_Error;
202     break;
203   case SourceMgr::DK_Warning:
204     Kind = DS_Warning;
205     break;
206   case SourceMgr::DK_Note:
207     Kind = DS_Note;
208     break;
209   }
210   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
211 }
212 
213 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
214   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
215 }
216 
217 std::unique_ptr<Module> MIRParserImpl::parse() {
218   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
219                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
220   In.setContext(&In);
221 
222   if (!In.setCurrentDocument()) {
223     if (In.error())
224       return nullptr;
225     // Create an empty module when the MIR file is empty.
226     return llvm::make_unique<Module>(Filename, Context);
227   }
228 
229   std::unique_ptr<Module> M;
230   bool NoLLVMIR = false;
231   // Parse the block scalar manually so that we can return unique pointer
232   // without having to go trough YAML traits.
233   if (const auto *BSN =
234           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
235     SMDiagnostic Error;
236     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
237                       Context, &IRSlots);
238     if (!M) {
239       reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
240       return M;
241     }
242     In.nextDocument();
243     if (!In.setCurrentDocument())
244       return M;
245   } else {
246     // Create an new, empty module.
247     M = llvm::make_unique<Module>(Filename, Context);
248     NoLLVMIR = true;
249   }
250 
251   // Parse the machine functions.
252   do {
253     if (parseMachineFunction(In, *M, NoLLVMIR))
254       return nullptr;
255     In.nextDocument();
256   } while (In.setCurrentDocument());
257 
258   return M;
259 }
260 
261 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
262                                          bool NoLLVMIR) {
263   auto MF = llvm::make_unique<yaml::MachineFunction>();
264   yaml::yamlize(In, *MF, false);
265   if (In.error())
266     return true;
267   auto FunctionName = MF->Name;
268   if (Functions.find(FunctionName) != Functions.end())
269     return error(Twine("redefinition of machine function '") + FunctionName +
270                  "'");
271   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
272   if (NoLLVMIR)
273     createDummyFunction(FunctionName, M);
274   else if (!M.getFunction(FunctionName))
275     return error(Twine("function '") + FunctionName +
276                  "' isn't defined in the provided LLVM IR");
277   return false;
278 }
279 
280 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
281   auto &Context = M.getContext();
282   Function *F = cast<Function>(M.getOrInsertFunction(
283       Name, FunctionType::get(Type::getVoidTy(Context), false)));
284   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
285   new UnreachableInst(Context, BB);
286 }
287 
288 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
289   auto It = Functions.find(MF.getName());
290   if (It == Functions.end())
291     return error(Twine("no machine function information for function '") +
292                  MF.getName() + "' in the MIR file");
293   // TODO: Recreate the machine function.
294   const yaml::MachineFunction &YamlMF = *It->getValue();
295   if (YamlMF.Alignment)
296     MF.setAlignment(YamlMF.Alignment);
297   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
298   MF.setHasInlineAsm(YamlMF.HasInlineAsm);
299   if (YamlMF.AllVRegsAllocated)
300     MF.getProperties().set(MachineFunctionProperties::Property::AllVRegsAllocated);
301   PerFunctionMIParsingState PFS;
302   if (initializeRegisterInfo(MF, YamlMF, PFS))
303     return true;
304   if (!YamlMF.Constants.empty()) {
305     auto *ConstantPool = MF.getConstantPool();
306     assert(ConstantPool && "Constant pool must be created");
307     if (initializeConstantPool(*ConstantPool, YamlMF, MF,
308                                PFS.ConstantPoolSlots))
309       return true;
310   }
311 
312   SMDiagnostic Error;
313   if (parseMachineBasicBlockDefinitions(MF, YamlMF.Body.Value.Value, PFS,
314                                         IRSlots, Error)) {
315     reportDiagnostic(
316         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
317     return true;
318   }
319 
320   if (MF.empty())
321     return error(Twine("machine function '") + Twine(MF.getName()) +
322                  "' requires at least one machine basic block in its body");
323   // Initialize the frame information after creating all the MBBs so that the
324   // MBB references in the frame information can be resolved.
325   if (initializeFrameInfo(MF, YamlMF, PFS))
326     return true;
327   // Initialize the jump table after creating all the MBBs so that the MBB
328   // references can be resolved.
329   if (!YamlMF.JumpTableInfo.Entries.empty() &&
330       initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
331     return true;
332   // Parse the machine instructions after creating all of the MBBs so that the
333   // parser can resolve the MBB references.
334   if (parseMachineInstructions(MF, YamlMF.Body.Value.Value, PFS, IRSlots,
335                                Error)) {
336     reportDiagnostic(
337         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
338     return true;
339   }
340   inferRegisterInfo(MF, YamlMF);
341   // FIXME: This is a temporary workaround until the reserved registers can be
342   // serialized.
343   MF.getRegInfo().freezeReservedRegs(MF);
344   MF.verify();
345   return false;
346 }
347 
348 bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
349                                            const yaml::MachineFunction &YamlMF,
350                                            PerFunctionMIParsingState &PFS) {
351   MachineRegisterInfo &RegInfo = MF.getRegInfo();
352   assert(RegInfo.isSSA());
353   if (!YamlMF.IsSSA)
354     RegInfo.leaveSSA();
355   assert(RegInfo.tracksLiveness());
356   if (!YamlMF.TracksRegLiveness)
357     RegInfo.invalidateLiveness();
358   RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
359 
360   SMDiagnostic Error;
361   // Parse the virtual register information.
362   for (const auto &VReg : YamlMF.VirtualRegisters) {
363     unsigned Reg;
364     if (StringRef(VReg.Class.Value).equals("_")) {
365       // This is a generic virtual register.
366       // The size will be set appropriately when we reach the definition.
367       Reg = RegInfo.createGenericVirtualRegister(/*Size*/ 1);
368       PFS.GenericVRegs.insert(Reg);
369     } else {
370       const auto *RC = getRegClass(MF, VReg.Class.Value);
371       if (RC) {
372         Reg = RegInfo.createVirtualRegister(RC);
373       } else {
374         const auto *RegBank = getRegBank(MF, VReg.Class.Value);
375         if (!RegBank)
376           return error(
377               VReg.Class.SourceRange.Start,
378               Twine("use of undefined register class or register bank '") +
379                   VReg.Class.Value + "'");
380         Reg = RegInfo.createGenericVirtualRegister(/*Size*/ 1);
381         RegInfo.setRegBank(Reg, *RegBank);
382         PFS.GenericVRegs.insert(Reg);
383       }
384     }
385     if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
386              .second)
387       return error(VReg.ID.SourceRange.Start,
388                    Twine("redefinition of virtual register '%") +
389                        Twine(VReg.ID.Value) + "'");
390     if (!VReg.PreferredRegister.Value.empty()) {
391       unsigned PreferredReg = 0;
392       if (parseNamedRegisterReference(PreferredReg, SM, MF,
393                                       VReg.PreferredRegister.Value, PFS,
394                                       IRSlots, Error))
395         return error(Error, VReg.PreferredRegister.SourceRange);
396       RegInfo.setSimpleHint(Reg, PreferredReg);
397     }
398   }
399 
400   // Parse the liveins.
401   for (const auto &LiveIn : YamlMF.LiveIns) {
402     unsigned Reg = 0;
403     if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
404                                     IRSlots, Error))
405       return error(Error, LiveIn.Register.SourceRange);
406     unsigned VReg = 0;
407     if (!LiveIn.VirtualRegister.Value.empty()) {
408       if (parseVirtualRegisterReference(
409               VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
410         return error(Error, LiveIn.VirtualRegister.SourceRange);
411     }
412     RegInfo.addLiveIn(Reg, VReg);
413   }
414 
415   // Parse the callee saved register mask.
416   BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
417   if (!YamlMF.CalleeSavedRegisters)
418     return false;
419   for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
420     unsigned Reg = 0;
421     if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
422                                     Error))
423       return error(Error, RegSource.SourceRange);
424     CalleeSavedRegisterMask[Reg] = true;
425   }
426   RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
427   return false;
428 }
429 
430 void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
431                                       const yaml::MachineFunction &YamlMF) {
432   if (YamlMF.CalleeSavedRegisters)
433     return;
434   for (const MachineBasicBlock &MBB : MF) {
435     for (const MachineInstr &MI : MBB) {
436       for (const MachineOperand &MO : MI.operands()) {
437         if (!MO.isRegMask())
438           continue;
439         MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
440       }
441     }
442   }
443 }
444 
445 bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
446                                         const yaml::MachineFunction &YamlMF,
447                                         PerFunctionMIParsingState &PFS) {
448   MachineFrameInfo &MFI = *MF.getFrameInfo();
449   const Function &F = *MF.getFunction();
450   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
451   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
452   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
453   MFI.setHasStackMap(YamlMFI.HasStackMap);
454   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
455   MFI.setStackSize(YamlMFI.StackSize);
456   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
457   if (YamlMFI.MaxAlignment)
458     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
459   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
460   MFI.setHasCalls(YamlMFI.HasCalls);
461   MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
462   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
463   MFI.setHasVAStart(YamlMFI.HasVAStart);
464   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
465   if (!YamlMFI.SavePoint.Value.empty()) {
466     MachineBasicBlock *MBB = nullptr;
467     if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
468       return true;
469     MFI.setSavePoint(MBB);
470   }
471   if (!YamlMFI.RestorePoint.Value.empty()) {
472     MachineBasicBlock *MBB = nullptr;
473     if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
474       return true;
475     MFI.setRestorePoint(MBB);
476   }
477 
478   std::vector<CalleeSavedInfo> CSIInfo;
479   // Initialize the fixed frame objects.
480   for (const auto &Object : YamlMF.FixedStackObjects) {
481     int ObjectIdx;
482     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
483       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
484                                         Object.IsImmutable, Object.IsAliased);
485     else
486       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
487     MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
488     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
489                                                          ObjectIdx))
490              .second)
491       return error(Object.ID.SourceRange.Start,
492                    Twine("redefinition of fixed stack object '%fixed-stack.") +
493                        Twine(Object.ID.Value) + "'");
494     if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
495                                  ObjectIdx))
496       return true;
497   }
498 
499   // Initialize the ordinary frame objects.
500   for (const auto &Object : YamlMF.StackObjects) {
501     int ObjectIdx;
502     const AllocaInst *Alloca = nullptr;
503     const yaml::StringValue &Name = Object.Name;
504     if (!Name.Value.empty()) {
505       Alloca = dyn_cast_or_null<AllocaInst>(
506           F.getValueSymbolTable().lookup(Name.Value));
507       if (!Alloca)
508         return error(Name.SourceRange.Start,
509                      "alloca instruction named '" + Name.Value +
510                          "' isn't defined in the function '" + F.getName() +
511                          "'");
512     }
513     if (Object.Type == yaml::MachineStackObject::VariableSized)
514       ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
515     else
516       ObjectIdx = MFI.CreateStackObject(
517           Object.Size, Object.Alignment,
518           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
519     MFI.setObjectOffset(ObjectIdx, Object.Offset);
520     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
521              .second)
522       return error(Object.ID.SourceRange.Start,
523                    Twine("redefinition of stack object '%stack.") +
524                        Twine(Object.ID.Value) + "'");
525     if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
526                                  ObjectIdx))
527       return true;
528     if (Object.LocalOffset)
529       MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
530     if (parseStackObjectsDebugInfo(MF, PFS, Object, ObjectIdx))
531       return true;
532   }
533   MFI.setCalleeSavedInfo(CSIInfo);
534   if (!CSIInfo.empty())
535     MFI.setCalleeSavedInfoValid(true);
536 
537   // Initialize the various stack object references after initializing the
538   // stack objects.
539   if (!YamlMFI.StackProtector.Value.empty()) {
540     SMDiagnostic Error;
541     int FI;
542     if (parseStackObjectReference(FI, SM, MF, YamlMFI.StackProtector.Value, PFS,
543                                   IRSlots, Error))
544       return error(Error, YamlMFI.StackProtector.SourceRange);
545     MFI.setStackProtectorIndex(FI);
546   }
547   return false;
548 }
549 
550 bool MIRParserImpl::parseCalleeSavedRegister(
551     MachineFunction &MF, PerFunctionMIParsingState &PFS,
552     std::vector<CalleeSavedInfo> &CSIInfo,
553     const yaml::StringValue &RegisterSource, int FrameIdx) {
554   if (RegisterSource.Value.empty())
555     return false;
556   unsigned Reg = 0;
557   SMDiagnostic Error;
558   if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
559                                   IRSlots, Error))
560     return error(Error, RegisterSource.SourceRange);
561   CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
562   return false;
563 }
564 
565 /// Verify that given node is of a certain type. Return true on error.
566 template <typename T>
567 static bool typecheckMDNode(T *&Result, MDNode *Node,
568                             const yaml::StringValue &Source,
569                             StringRef TypeString, MIRParserImpl &Parser) {
570   if (!Node)
571     return false;
572   Result = dyn_cast<T>(Node);
573   if (!Result)
574     return Parser.error(Source.SourceRange.Start,
575                         "expected a reference to a '" + TypeString +
576                             "' metadata node");
577   return false;
578 }
579 
580 bool MIRParserImpl::parseStackObjectsDebugInfo(
581     MachineFunction &MF, PerFunctionMIParsingState &PFS,
582     const yaml::MachineStackObject &Object, int FrameIdx) {
583   // Debug information can only be attached to stack objects; Fixed stack
584   // objects aren't supported.
585   assert(FrameIdx >= 0 && "Expected a stack object frame index");
586   MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
587   if (parseMDNode(Var, Object.DebugVar, MF, PFS) ||
588       parseMDNode(Expr, Object.DebugExpr, MF, PFS) ||
589       parseMDNode(Loc, Object.DebugLoc, MF, PFS))
590     return true;
591   if (!Var && !Expr && !Loc)
592     return false;
593   DILocalVariable *DIVar = nullptr;
594   DIExpression *DIExpr = nullptr;
595   DILocation *DILoc = nullptr;
596   if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
597       typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
598       typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
599     return true;
600   MF.getMMI().setVariableDbgInfo(DIVar, DIExpr, unsigned(FrameIdx), DILoc);
601   return false;
602 }
603 
604 bool MIRParserImpl::parseMDNode(MDNode *&Node, const yaml::StringValue &Source,
605                                 MachineFunction &MF,
606                                 const PerFunctionMIParsingState &PFS) {
607   if (Source.Value.empty())
608     return false;
609   SMDiagnostic Error;
610   if (llvm::parseMDNode(Node, SM, MF, Source.Value, PFS, IRSlots, Error))
611     return error(Error, Source.SourceRange);
612   return false;
613 }
614 
615 bool MIRParserImpl::initializeConstantPool(
616     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
617     const MachineFunction &MF,
618     DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
619   const auto &M = *MF.getFunction()->getParent();
620   SMDiagnostic Error;
621   for (const auto &YamlConstant : YamlMF.Constants) {
622     const Constant *Value = dyn_cast_or_null<Constant>(
623         parseConstantValue(YamlConstant.Value.Value, Error, M));
624     if (!Value)
625       return error(Error, YamlConstant.Value.SourceRange);
626     unsigned Alignment =
627         YamlConstant.Alignment
628             ? YamlConstant.Alignment
629             : M.getDataLayout().getPrefTypeAlignment(Value->getType());
630     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
631     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
632              .second)
633       return error(YamlConstant.ID.SourceRange.Start,
634                    Twine("redefinition of constant pool item '%const.") +
635                        Twine(YamlConstant.ID.Value) + "'");
636   }
637   return false;
638 }
639 
640 bool MIRParserImpl::initializeJumpTableInfo(
641     MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
642     PerFunctionMIParsingState &PFS) {
643   MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
644   for (const auto &Entry : YamlJTI.Entries) {
645     std::vector<MachineBasicBlock *> Blocks;
646     for (const auto &MBBSource : Entry.Blocks) {
647       MachineBasicBlock *MBB = nullptr;
648       if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
649         return true;
650       Blocks.push_back(MBB);
651     }
652     unsigned Index = JTI->createJumpTableIndex(Blocks);
653     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
654              .second)
655       return error(Entry.ID.SourceRange.Start,
656                    Twine("redefinition of jump table entry '%jump-table.") +
657                        Twine(Entry.ID.Value) + "'");
658   }
659   return false;
660 }
661 
662 bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
663                                       const yaml::StringValue &Source,
664                                       MachineFunction &MF,
665                                       const PerFunctionMIParsingState &PFS) {
666   SMDiagnostic Error;
667   if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
668     return error(Error, Source.SourceRange);
669   return false;
670 }
671 
672 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
673                                                  SMRange SourceRange) {
674   assert(SourceRange.isValid() && "Invalid source range");
675   SMLoc Loc = SourceRange.Start;
676   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
677                   *Loc.getPointer() == '\'';
678   // Translate the location of the error from the location in the MI string to
679   // the corresponding location in the MIR file.
680   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
681                            (HasQuote ? 1 : 0));
682 
683   // TODO: Translate any source ranges as well.
684   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
685                        Error.getFixIts());
686 }
687 
688 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
689                                                     SMRange SourceRange) {
690   assert(SourceRange.isValid());
691 
692   // Translate the location of the error from the location in the llvm IR string
693   // to the corresponding location in the MIR file.
694   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
695   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
696   unsigned Column = Error.getColumnNo();
697   StringRef LineStr = Error.getLineContents();
698   SMLoc Loc = Error.getLoc();
699 
700   // Get the full line and adjust the column number by taking the indentation of
701   // LLVM IR into account.
702   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
703        L != E; ++L) {
704     if (L.line_number() == Line) {
705       LineStr = *L;
706       Loc = SMLoc::getFromPointer(LineStr.data());
707       auto Indent = LineStr.find(Error.getLineContents());
708       if (Indent != StringRef::npos)
709         Column += Indent;
710       break;
711     }
712   }
713 
714   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
715                       Error.getMessage(), LineStr, Error.getRanges(),
716                       Error.getFixIts());
717 }
718 
719 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
720   if (!Names2RegClasses.empty())
721     return;
722   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
723   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
724     const auto *RC = TRI->getRegClass(I);
725     Names2RegClasses.insert(
726         std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
727   }
728 }
729 
730 void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) {
731   if (!Names2RegBanks.empty())
732     return;
733   const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
734   // If the target does not support GlobalISel, we may not have a
735   // register bank info.
736   if (!RBI)
737     return;
738   for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
739     const auto &RegBank = RBI->getRegBank(I);
740     Names2RegBanks.insert(
741         std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
742   }
743 }
744 
745 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
746                                                       StringRef Name) {
747   initNames2RegClasses(MF);
748   auto RegClassInfo = Names2RegClasses.find(Name);
749   if (RegClassInfo == Names2RegClasses.end())
750     return nullptr;
751   return RegClassInfo->getValue();
752 }
753 
754 const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF,
755                                               StringRef Name) {
756   initNames2RegBanks(MF);
757   auto RegBankInfo = Names2RegBanks.find(Name);
758   if (RegBankInfo == Names2RegBanks.end())
759     return nullptr;
760   return RegBankInfo->getValue();
761 }
762 
763 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
764     : Impl(std::move(Impl)) {}
765 
766 MIRParser::~MIRParser() {}
767 
768 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
769 
770 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
771   return Impl->initializeMachineFunction(MF);
772 }
773 
774 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
775                                                          SMDiagnostic &Error,
776                                                          LLVMContext &Context) {
777   auto FileOrErr = MemoryBuffer::getFile(Filename);
778   if (std::error_code EC = FileOrErr.getError()) {
779     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
780                          "Could not open input file: " + EC.message());
781     return nullptr;
782   }
783   return createMIRParser(std::move(FileOrErr.get()), Context);
784 }
785 
786 std::unique_ptr<MIRParser>
787 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
788                       LLVMContext &Context) {
789   auto Filename = Contents->getBufferIdentifier();
790   return llvm::make_unique<MIRParser>(
791       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
792 }
793