1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the class that parses the optional LLVM IR and machine
10 // functions that are stored in MIR files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MIRParser/MIRParser.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/AsmParser/Parser.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
22 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
23 #include "llvm/CodeGen/MIRParser/MIParser.h"
24 #include "llvm/CodeGen/MIRYamlMapping.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ValueSymbolTable.h"
37 #include "llvm/Support/LineIterator.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SMLoc.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/YAMLTraits.h"
42 #include "llvm/Target/TargetMachine.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   yaml::Input In;
54   StringRef Filename;
55   LLVMContext &Context;
56   SlotMapping IRSlots;
57   std::unique_ptr<PerTargetMIParsingState> Target;
58 
59   /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
60   /// created and inserted into the given module when this is true.
61   bool NoLLVMIR = false;
62   /// True when a well formed MIR file does not contain any MIR/machine function
63   /// parts.
64   bool NoMIRDocuments = false;
65 
66 public:
67   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
68                 StringRef Filename, LLVMContext &Context);
69 
70   void reportDiagnostic(const SMDiagnostic &Diag);
71 
72   /// Report an error with the given message at unknown location.
73   ///
74   /// Always returns true.
75   bool error(const Twine &Message);
76 
77   /// Report an error with the given message at the given location.
78   ///
79   /// Always returns true.
80   bool error(SMLoc Loc, const Twine &Message);
81 
82   /// Report a given error with the location translated from the location in an
83   /// embedded string literal to a location in the MIR file.
84   ///
85   /// Always returns true.
86   bool error(const SMDiagnostic &Error, SMRange SourceRange);
87 
88   /// Try to parse the optional LLVM module and the machine functions in the MIR
89   /// file.
90   ///
91   /// Return null if an error occurred.
92   std::unique_ptr<Module> parseIRModule();
93 
94   bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI);
95 
96   /// Parse the machine function in the current YAML document.
97   ///
98   ///
99   /// Return true if an error occurred.
100   bool parseMachineFunction(Module &M, MachineModuleInfo &MMI);
101 
102   /// Initialize the machine function to the state that's described in the MIR
103   /// file.
104   ///
105   /// Return true if error occurred.
106   bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
107                                  MachineFunction &MF);
108 
109   bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
110                          const yaml::MachineFunction &YamlMF);
111 
112   bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
113                          const yaml::MachineFunction &YamlMF);
114 
115   bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
116                            const yaml::MachineFunction &YamlMF);
117 
118   bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
119                                 std::vector<CalleeSavedInfo> &CSIInfo,
120                                 const yaml::StringValue &RegisterSource,
121                                 bool IsRestored, int FrameIdx);
122 
123   template <typename T>
124   bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
125                                   const T &Object,
126                                   int FrameIdx);
127 
128   bool initializeConstantPool(PerFunctionMIParsingState &PFS,
129                               MachineConstantPool &ConstantPool,
130                               const yaml::MachineFunction &YamlMF);
131 
132   bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
133                                const yaml::MachineJumpTable &YamlJTI);
134 
135 private:
136   bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
137                    const yaml::StringValue &Source);
138 
139   bool parseMBBReference(PerFunctionMIParsingState &PFS,
140                          MachineBasicBlock *&MBB,
141                          const yaml::StringValue &Source);
142 
143   /// Return a MIR diagnostic converted from an MI string diagnostic.
144   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
145                                     SMRange SourceRange);
146 
147   /// Return a MIR diagnostic converted from a diagnostic located in a YAML
148   /// block scalar string.
149   SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
150                                        SMRange SourceRange);
151 
152   void computeFunctionProperties(MachineFunction &MF);
153 };
154 
155 } // end namespace llvm
156 
157 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
158   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
159 }
160 
161 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
162                              StringRef Filename, LLVMContext &Context)
163     : SM(),
164       In(SM.getMemoryBuffer(
165             SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))->getBuffer(),
166             nullptr, handleYAMLDiag, this),
167       Filename(Filename),
168       Context(Context) {
169   In.setContext(&In);
170 }
171 
172 bool MIRParserImpl::error(const Twine &Message) {
173   Context.diagnose(DiagnosticInfoMIRParser(
174       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
175   return true;
176 }
177 
178 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
179   Context.diagnose(DiagnosticInfoMIRParser(
180       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
181   return true;
182 }
183 
184 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
185   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
186   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
187   return true;
188 }
189 
190 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
191   DiagnosticSeverity Kind;
192   switch (Diag.getKind()) {
193   case SourceMgr::DK_Error:
194     Kind = DS_Error;
195     break;
196   case SourceMgr::DK_Warning:
197     Kind = DS_Warning;
198     break;
199   case SourceMgr::DK_Note:
200     Kind = DS_Note;
201     break;
202   case SourceMgr::DK_Remark:
203     llvm_unreachable("remark unexpected");
204     break;
205   }
206   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
207 }
208 
209 std::unique_ptr<Module> MIRParserImpl::parseIRModule() {
210   if (!In.setCurrentDocument()) {
211     if (In.error())
212       return nullptr;
213     // Create an empty module when the MIR file is empty.
214     NoMIRDocuments = true;
215     return llvm::make_unique<Module>(Filename, Context);
216   }
217 
218   std::unique_ptr<Module> M;
219   // Parse the block scalar manually so that we can return unique pointer
220   // without having to go trough YAML traits.
221   if (const auto *BSN =
222           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
223     SMDiagnostic Error;
224     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
225                       Context, &IRSlots, /*UpgradeDebugInfo=*/false);
226     if (!M) {
227       reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
228       return nullptr;
229     }
230     In.nextDocument();
231     if (!In.setCurrentDocument())
232       NoMIRDocuments = true;
233   } else {
234     // Create an new, empty module.
235     M = llvm::make_unique<Module>(Filename, Context);
236     NoLLVMIR = true;
237   }
238   return M;
239 }
240 
241 bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
242   if (NoMIRDocuments)
243     return false;
244 
245   // Parse the machine functions.
246   do {
247     if (parseMachineFunction(M, MMI))
248       return true;
249     In.nextDocument();
250   } while (In.setCurrentDocument());
251 
252   return false;
253 }
254 
255 /// Create an empty function with the given name.
256 static Function *createDummyFunction(StringRef Name, Module &M) {
257   auto &Context = M.getContext();
258   Function *F =
259       Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
260                        Function::ExternalLinkage, Name, M);
261   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
262   new UnreachableInst(Context, BB);
263   return F;
264 }
265 
266 bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) {
267   // Parse the yaml.
268   yaml::MachineFunction YamlMF;
269   yaml::EmptyContext Ctx;
270 
271   const LLVMTargetMachine &TM = MMI.getTarget();
272   YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
273       TM.createDefaultFuncInfoYAML());
274 
275   yaml::yamlize(In, YamlMF, false, Ctx);
276   if (In.error())
277     return true;
278 
279   // Search for the corresponding IR function.
280   StringRef FunctionName = YamlMF.Name;
281   Function *F = M.getFunction(FunctionName);
282   if (!F) {
283     if (NoLLVMIR) {
284       F = createDummyFunction(FunctionName, M);
285     } else {
286       return error(Twine("function '") + FunctionName +
287                    "' isn't defined in the provided LLVM IR");
288     }
289   }
290   if (MMI.getMachineFunction(*F) != nullptr)
291     return error(Twine("redefinition of machine function '") + FunctionName +
292                  "'");
293 
294   // Create the MachineFunction.
295   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
296   if (initializeMachineFunction(YamlMF, MF))
297     return true;
298 
299   return false;
300 }
301 
302 static bool isSSA(const MachineFunction &MF) {
303   const MachineRegisterInfo &MRI = MF.getRegInfo();
304   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
305     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
306     if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
307       return false;
308   }
309   return true;
310 }
311 
312 void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
313   MachineFunctionProperties &Properties = MF.getProperties();
314 
315   bool HasPHI = false;
316   bool HasInlineAsm = false;
317   for (const MachineBasicBlock &MBB : MF) {
318     for (const MachineInstr &MI : MBB) {
319       if (MI.isPHI())
320         HasPHI = true;
321       if (MI.isInlineAsm())
322         HasInlineAsm = true;
323     }
324   }
325   if (!HasPHI)
326     Properties.set(MachineFunctionProperties::Property::NoPHIs);
327   MF.setHasInlineAsm(HasInlineAsm);
328 
329   if (isSSA(MF))
330     Properties.set(MachineFunctionProperties::Property::IsSSA);
331   else
332     Properties.reset(MachineFunctionProperties::Property::IsSSA);
333 
334   const MachineRegisterInfo &MRI = MF.getRegInfo();
335   if (MRI.getNumVirtRegs() == 0)
336     Properties.set(MachineFunctionProperties::Property::NoVRegs);
337 }
338 
339 bool
340 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
341                                          MachineFunction &MF) {
342   // TODO: Recreate the machine function.
343   if (Target) {
344     // Avoid clearing state if we're using the same subtarget again.
345     Target->setTarget(MF.getSubtarget());
346   } else {
347     Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
348   }
349 
350   if (YamlMF.Alignment)
351     MF.setAlignment(YamlMF.Alignment);
352   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
353   MF.setHasWinCFI(YamlMF.HasWinCFI);
354 
355   if (YamlMF.Legalized)
356     MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
357   if (YamlMF.RegBankSelected)
358     MF.getProperties().set(
359         MachineFunctionProperties::Property::RegBankSelected);
360   if (YamlMF.Selected)
361     MF.getProperties().set(MachineFunctionProperties::Property::Selected);
362   if (YamlMF.FailedISel)
363     MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
364 
365   PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
366   if (parseRegisterInfo(PFS, YamlMF))
367     return true;
368   if (!YamlMF.Constants.empty()) {
369     auto *ConstantPool = MF.getConstantPool();
370     assert(ConstantPool && "Constant pool must be created");
371     if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
372       return true;
373   }
374 
375   StringRef BlockStr = YamlMF.Body.Value.Value;
376   SMDiagnostic Error;
377   SourceMgr BlockSM;
378   BlockSM.AddNewSourceBuffer(
379       MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
380       SMLoc());
381   PFS.SM = &BlockSM;
382   if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
383     reportDiagnostic(
384         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
385     return true;
386   }
387   PFS.SM = &SM;
388 
389   // Initialize the frame information after creating all the MBBs so that the
390   // MBB references in the frame information can be resolved.
391   if (initializeFrameInfo(PFS, YamlMF))
392     return true;
393   // Initialize the jump table after creating all the MBBs so that the MBB
394   // references can be resolved.
395   if (!YamlMF.JumpTableInfo.Entries.empty() &&
396       initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
397     return true;
398   // Parse the machine instructions after creating all of the MBBs so that the
399   // parser can resolve the MBB references.
400   StringRef InsnStr = YamlMF.Body.Value.Value;
401   SourceMgr InsnSM;
402   InsnSM.AddNewSourceBuffer(
403       MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
404       SMLoc());
405   PFS.SM = &InsnSM;
406   if (parseMachineInstructions(PFS, InsnStr, Error)) {
407     reportDiagnostic(
408         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
409     return true;
410   }
411   PFS.SM = &SM;
412 
413   if (setupRegisterInfo(PFS, YamlMF))
414     return true;
415 
416   if (YamlMF.MachineFuncInfo) {
417     const LLVMTargetMachine &TM = MF.getTarget();
418     // Note this is called after the initial constructor of the
419     // MachineFunctionInfo based on the MachineFunction, which may depend on the
420     // IR.
421 
422     SMRange SrcRange;
423     if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
424                                     SrcRange)) {
425       return error(Error, SrcRange);
426     }
427   }
428 
429   // Set the reserved registers after parsing MachineFuncInfo. The target may
430   // have been recording information used to select the reserved registers
431   // there.
432   // FIXME: This is a temporary workaround until the reserved registers can be
433   // serialized.
434   MachineRegisterInfo &MRI = MF.getRegInfo();
435   MRI.freezeReservedRegs(MF);
436 
437   computeFunctionProperties(MF);
438 
439   MF.getSubtarget().mirFileLoaded(MF);
440 
441   MF.verify();
442   return false;
443 }
444 
445 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
446                                       const yaml::MachineFunction &YamlMF) {
447   MachineFunction &MF = PFS.MF;
448   MachineRegisterInfo &RegInfo = MF.getRegInfo();
449   assert(RegInfo.tracksLiveness());
450   if (!YamlMF.TracksRegLiveness)
451     RegInfo.invalidateLiveness();
452 
453   SMDiagnostic Error;
454   // Parse the virtual register information.
455   for (const auto &VReg : YamlMF.VirtualRegisters) {
456     VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
457     if (Info.Explicit)
458       return error(VReg.ID.SourceRange.Start,
459                    Twine("redefinition of virtual register '%") +
460                        Twine(VReg.ID.Value) + "'");
461     Info.Explicit = true;
462 
463     if (StringRef(VReg.Class.Value).equals("_")) {
464       Info.Kind = VRegInfo::GENERIC;
465       Info.D.RegBank = nullptr;
466     } else {
467       const auto *RC = Target->getRegClass(VReg.Class.Value);
468       if (RC) {
469         Info.Kind = VRegInfo::NORMAL;
470         Info.D.RC = RC;
471       } else {
472         const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
473         if (!RegBank)
474           return error(
475               VReg.Class.SourceRange.Start,
476               Twine("use of undefined register class or register bank '") +
477                   VReg.Class.Value + "'");
478         Info.Kind = VRegInfo::REGBANK;
479         Info.D.RegBank = RegBank;
480       }
481     }
482 
483     if (!VReg.PreferredRegister.Value.empty()) {
484       if (Info.Kind != VRegInfo::NORMAL)
485         return error(VReg.Class.SourceRange.Start,
486               Twine("preferred register can only be set for normal vregs"));
487 
488       if (parseRegisterReference(PFS, Info.PreferredReg,
489                                  VReg.PreferredRegister.Value, Error))
490         return error(Error, VReg.PreferredRegister.SourceRange);
491     }
492   }
493 
494   // Parse the liveins.
495   for (const auto &LiveIn : YamlMF.LiveIns) {
496     unsigned Reg = 0;
497     if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
498       return error(Error, LiveIn.Register.SourceRange);
499     unsigned VReg = 0;
500     if (!LiveIn.VirtualRegister.Value.empty()) {
501       VRegInfo *Info;
502       if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
503                                         Error))
504         return error(Error, LiveIn.VirtualRegister.SourceRange);
505       VReg = Info->VReg;
506     }
507     RegInfo.addLiveIn(Reg, VReg);
508   }
509 
510   // Parse the callee saved registers (Registers that will
511   // be saved for the caller).
512   if (YamlMF.CalleeSavedRegisters) {
513     SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
514     for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
515       unsigned Reg = 0;
516       if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
517         return error(Error, RegSource.SourceRange);
518       CalleeSavedRegisters.push_back(Reg);
519     }
520     RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
521   }
522 
523   return false;
524 }
525 
526 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
527                                       const yaml::MachineFunction &YamlMF) {
528   MachineFunction &MF = PFS.MF;
529   MachineRegisterInfo &MRI = MF.getRegInfo();
530   bool Error = false;
531   // Create VRegs
532   auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
533     unsigned Reg = Info.VReg;
534     switch (Info.Kind) {
535     case VRegInfo::UNKNOWN:
536       error(Twine("Cannot determine class/bank of virtual register ") +
537             Name + " in function '" + MF.getName() + "'");
538       Error = true;
539       break;
540     case VRegInfo::NORMAL:
541       MRI.setRegClass(Reg, Info.D.RC);
542       if (Info.PreferredReg != 0)
543         MRI.setSimpleHint(Reg, Info.PreferredReg);
544       break;
545     case VRegInfo::GENERIC:
546       break;
547     case VRegInfo::REGBANK:
548       MRI.setRegBank(Reg, *Info.D.RegBank);
549       break;
550     }
551   };
552 
553   for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end();
554        I != E; I++) {
555     const VRegInfo &Info = *I->second;
556     populateVRegInfo(Info, Twine(I->first()));
557   }
558 
559   for (auto P : PFS.VRegInfos) {
560     const VRegInfo &Info = *P.second;
561     populateVRegInfo(Info, Twine(P.first));
562   }
563 
564   // Compute MachineRegisterInfo::UsedPhysRegMask
565   for (const MachineBasicBlock &MBB : MF) {
566     for (const MachineInstr &MI : MBB) {
567       for (const MachineOperand &MO : MI.operands()) {
568         if (!MO.isRegMask())
569           continue;
570         MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
571       }
572     }
573   }
574 
575   return Error;
576 }
577 
578 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
579                                         const yaml::MachineFunction &YamlMF) {
580   MachineFunction &MF = PFS.MF;
581   MachineFrameInfo &MFI = MF.getFrameInfo();
582   const Function &F = MF.getFunction();
583   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
584   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
585   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
586   MFI.setHasStackMap(YamlMFI.HasStackMap);
587   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
588   MFI.setStackSize(YamlMFI.StackSize);
589   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
590   if (YamlMFI.MaxAlignment)
591     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
592   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
593   MFI.setHasCalls(YamlMFI.HasCalls);
594   if (YamlMFI.MaxCallFrameSize != ~0u)
595     MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
596   MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
597   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
598   MFI.setHasVAStart(YamlMFI.HasVAStart);
599   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
600   MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
601   if (!YamlMFI.SavePoint.Value.empty()) {
602     MachineBasicBlock *MBB = nullptr;
603     if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
604       return true;
605     MFI.setSavePoint(MBB);
606   }
607   if (!YamlMFI.RestorePoint.Value.empty()) {
608     MachineBasicBlock *MBB = nullptr;
609     if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
610       return true;
611     MFI.setRestorePoint(MBB);
612   }
613 
614   std::vector<CalleeSavedInfo> CSIInfo;
615   // Initialize the fixed frame objects.
616   for (const auto &Object : YamlMF.FixedStackObjects) {
617     int ObjectIdx;
618     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
619       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
620                                         Object.IsImmutable, Object.IsAliased);
621     else
622       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
623     MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
624     MFI.setStackID(ObjectIdx, Object.StackID);
625     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
626                                                          ObjectIdx))
627              .second)
628       return error(Object.ID.SourceRange.Start,
629                    Twine("redefinition of fixed stack object '%fixed-stack.") +
630                        Twine(Object.ID.Value) + "'");
631     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
632                                  Object.CalleeSavedRestored, ObjectIdx))
633       return true;
634     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
635       return true;
636   }
637 
638   // Initialize the ordinary frame objects.
639   for (const auto &Object : YamlMF.StackObjects) {
640     int ObjectIdx;
641     const AllocaInst *Alloca = nullptr;
642     const yaml::StringValue &Name = Object.Name;
643     if (!Name.Value.empty()) {
644       Alloca = dyn_cast_or_null<AllocaInst>(
645           F.getValueSymbolTable()->lookup(Name.Value));
646       if (!Alloca)
647         return error(Name.SourceRange.Start,
648                      "alloca instruction named '" + Name.Value +
649                          "' isn't defined in the function '" + F.getName() +
650                          "'");
651     }
652     if (Object.Type == yaml::MachineStackObject::VariableSized)
653       ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
654     else
655       ObjectIdx = MFI.CreateStackObject(
656           Object.Size, Object.Alignment,
657           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
658     MFI.setObjectOffset(ObjectIdx, Object.Offset);
659     MFI.setStackID(ObjectIdx, Object.StackID);
660 
661     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
662              .second)
663       return error(Object.ID.SourceRange.Start,
664                    Twine("redefinition of stack object '%stack.") +
665                        Twine(Object.ID.Value) + "'");
666     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
667                                  Object.CalleeSavedRestored, ObjectIdx))
668       return true;
669     if (Object.LocalOffset)
670       MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
671     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
672       return true;
673   }
674   MFI.setCalleeSavedInfo(CSIInfo);
675   if (!CSIInfo.empty())
676     MFI.setCalleeSavedInfoValid(true);
677 
678   // Initialize the various stack object references after initializing the
679   // stack objects.
680   if (!YamlMFI.StackProtector.Value.empty()) {
681     SMDiagnostic Error;
682     int FI;
683     if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
684       return error(Error, YamlMFI.StackProtector.SourceRange);
685     MFI.setStackProtectorIndex(FI);
686   }
687   return false;
688 }
689 
690 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
691     std::vector<CalleeSavedInfo> &CSIInfo,
692     const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
693   if (RegisterSource.Value.empty())
694     return false;
695   unsigned Reg = 0;
696   SMDiagnostic Error;
697   if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
698     return error(Error, RegisterSource.SourceRange);
699   CalleeSavedInfo CSI(Reg, FrameIdx);
700   CSI.setRestored(IsRestored);
701   CSIInfo.push_back(CSI);
702   return false;
703 }
704 
705 /// Verify that given node is of a certain type. Return true on error.
706 template <typename T>
707 static bool typecheckMDNode(T *&Result, MDNode *Node,
708                             const yaml::StringValue &Source,
709                             StringRef TypeString, MIRParserImpl &Parser) {
710   if (!Node)
711     return false;
712   Result = dyn_cast<T>(Node);
713   if (!Result)
714     return Parser.error(Source.SourceRange.Start,
715                         "expected a reference to a '" + TypeString +
716                             "' metadata node");
717   return false;
718 }
719 
720 template <typename T>
721 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
722     const T &Object, int FrameIdx) {
723   // Debug information can only be attached to stack objects; Fixed stack
724   // objects aren't supported.
725   MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
726   if (parseMDNode(PFS, Var, Object.DebugVar) ||
727       parseMDNode(PFS, Expr, Object.DebugExpr) ||
728       parseMDNode(PFS, Loc, Object.DebugLoc))
729     return true;
730   if (!Var && !Expr && !Loc)
731     return false;
732   DILocalVariable *DIVar = nullptr;
733   DIExpression *DIExpr = nullptr;
734   DILocation *DILoc = nullptr;
735   if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
736       typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
737       typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
738     return true;
739   PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
740   return false;
741 }
742 
743 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
744     MDNode *&Node, const yaml::StringValue &Source) {
745   if (Source.Value.empty())
746     return false;
747   SMDiagnostic Error;
748   if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
749     return error(Error, Source.SourceRange);
750   return false;
751 }
752 
753 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
754     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
755   DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
756   const MachineFunction &MF = PFS.MF;
757   const auto &M = *MF.getFunction().getParent();
758   SMDiagnostic Error;
759   for (const auto &YamlConstant : YamlMF.Constants) {
760     if (YamlConstant.IsTargetSpecific)
761       // FIXME: Support target-specific constant pools
762       return error(YamlConstant.Value.SourceRange.Start,
763                    "Can't parse target-specific constant pool entries yet");
764     const Constant *Value = dyn_cast_or_null<Constant>(
765         parseConstantValue(YamlConstant.Value.Value, Error, M));
766     if (!Value)
767       return error(Error, YamlConstant.Value.SourceRange);
768     unsigned Alignment =
769         YamlConstant.Alignment
770             ? YamlConstant.Alignment
771             : M.getDataLayout().getPrefTypeAlignment(Value->getType());
772     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
773     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
774              .second)
775       return error(YamlConstant.ID.SourceRange.Start,
776                    Twine("redefinition of constant pool item '%const.") +
777                        Twine(YamlConstant.ID.Value) + "'");
778   }
779   return false;
780 }
781 
782 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
783     const yaml::MachineJumpTable &YamlJTI) {
784   MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
785   for (const auto &Entry : YamlJTI.Entries) {
786     std::vector<MachineBasicBlock *> Blocks;
787     for (const auto &MBBSource : Entry.Blocks) {
788       MachineBasicBlock *MBB = nullptr;
789       if (parseMBBReference(PFS, MBB, MBBSource.Value))
790         return true;
791       Blocks.push_back(MBB);
792     }
793     unsigned Index = JTI->createJumpTableIndex(Blocks);
794     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
795              .second)
796       return error(Entry.ID.SourceRange.Start,
797                    Twine("redefinition of jump table entry '%jump-table.") +
798                        Twine(Entry.ID.Value) + "'");
799   }
800   return false;
801 }
802 
803 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
804                                       MachineBasicBlock *&MBB,
805                                       const yaml::StringValue &Source) {
806   SMDiagnostic Error;
807   if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
808     return error(Error, Source.SourceRange);
809   return false;
810 }
811 
812 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
813                                                  SMRange SourceRange) {
814   assert(SourceRange.isValid() && "Invalid source range");
815   SMLoc Loc = SourceRange.Start;
816   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
817                   *Loc.getPointer() == '\'';
818   // Translate the location of the error from the location in the MI string to
819   // the corresponding location in the MIR file.
820   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
821                            (HasQuote ? 1 : 0));
822 
823   // TODO: Translate any source ranges as well.
824   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
825                        Error.getFixIts());
826 }
827 
828 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
829                                                     SMRange SourceRange) {
830   assert(SourceRange.isValid());
831 
832   // Translate the location of the error from the location in the llvm IR string
833   // to the corresponding location in the MIR file.
834   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
835   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
836   unsigned Column = Error.getColumnNo();
837   StringRef LineStr = Error.getLineContents();
838   SMLoc Loc = Error.getLoc();
839 
840   // Get the full line and adjust the column number by taking the indentation of
841   // LLVM IR into account.
842   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
843        L != E; ++L) {
844     if (L.line_number() == Line) {
845       LineStr = *L;
846       Loc = SMLoc::getFromPointer(LineStr.data());
847       auto Indent = LineStr.find(Error.getLineContents());
848       if (Indent != StringRef::npos)
849         Column += Indent;
850       break;
851     }
852   }
853 
854   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
855                       Error.getMessage(), LineStr, Error.getRanges(),
856                       Error.getFixIts());
857 }
858 
859 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
860     : Impl(std::move(Impl)) {}
861 
862 MIRParser::~MIRParser() {}
863 
864 std::unique_ptr<Module> MIRParser::parseIRModule() {
865   return Impl->parseIRModule();
866 }
867 
868 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
869   return Impl->parseMachineFunctions(M, MMI);
870 }
871 
872 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
873                                                          SMDiagnostic &Error,
874                                                          LLVMContext &Context) {
875   auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
876   if (std::error_code EC = FileOrErr.getError()) {
877     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
878                          "Could not open input file: " + EC.message());
879     return nullptr;
880   }
881   return createMIRParser(std::move(FileOrErr.get()), Context);
882 }
883 
884 std::unique_ptr<MIRParser>
885 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
886                       LLVMContext &Context) {
887   auto Filename = Contents->getBufferIdentifier();
888   if (Context.shouldDiscardValueNames()) {
889     Context.diagnose(DiagnosticInfoMIRParser(
890         DS_Error,
891         SMDiagnostic(
892             Filename, SourceMgr::DK_Error,
893             "Can't read MIR with a Context that discards named Values")));
894     return nullptr;
895   }
896   return llvm::make_unique<MIRParser>(
897       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
898 }
899