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