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