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   computeFunctionProperties(MF);
430 
431   MF.getSubtarget().mirFileLoaded(MF);
432 
433   MF.verify();
434   return false;
435 }
436 
437 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
438                                       const yaml::MachineFunction &YamlMF) {
439   MachineFunction &MF = PFS.MF;
440   MachineRegisterInfo &RegInfo = MF.getRegInfo();
441   assert(RegInfo.tracksLiveness());
442   if (!YamlMF.TracksRegLiveness)
443     RegInfo.invalidateLiveness();
444 
445   SMDiagnostic Error;
446   // Parse the virtual register information.
447   for (const auto &VReg : YamlMF.VirtualRegisters) {
448     VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
449     if (Info.Explicit)
450       return error(VReg.ID.SourceRange.Start,
451                    Twine("redefinition of virtual register '%") +
452                        Twine(VReg.ID.Value) + "'");
453     Info.Explicit = true;
454 
455     if (StringRef(VReg.Class.Value).equals("_")) {
456       Info.Kind = VRegInfo::GENERIC;
457       Info.D.RegBank = nullptr;
458     } else {
459       const auto *RC = Target->getRegClass(VReg.Class.Value);
460       if (RC) {
461         Info.Kind = VRegInfo::NORMAL;
462         Info.D.RC = RC;
463       } else {
464         const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
465         if (!RegBank)
466           return error(
467               VReg.Class.SourceRange.Start,
468               Twine("use of undefined register class or register bank '") +
469                   VReg.Class.Value + "'");
470         Info.Kind = VRegInfo::REGBANK;
471         Info.D.RegBank = RegBank;
472       }
473     }
474 
475     if (!VReg.PreferredRegister.Value.empty()) {
476       if (Info.Kind != VRegInfo::NORMAL)
477         return error(VReg.Class.SourceRange.Start,
478               Twine("preferred register can only be set for normal vregs"));
479 
480       if (parseRegisterReference(PFS, Info.PreferredReg,
481                                  VReg.PreferredRegister.Value, Error))
482         return error(Error, VReg.PreferredRegister.SourceRange);
483     }
484   }
485 
486   // Parse the liveins.
487   for (const auto &LiveIn : YamlMF.LiveIns) {
488     unsigned Reg = 0;
489     if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
490       return error(Error, LiveIn.Register.SourceRange);
491     unsigned VReg = 0;
492     if (!LiveIn.VirtualRegister.Value.empty()) {
493       VRegInfo *Info;
494       if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
495                                         Error))
496         return error(Error, LiveIn.VirtualRegister.SourceRange);
497       VReg = Info->VReg;
498     }
499     RegInfo.addLiveIn(Reg, VReg);
500   }
501 
502   // Parse the callee saved registers (Registers that will
503   // be saved for the caller).
504   if (YamlMF.CalleeSavedRegisters) {
505     SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
506     for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
507       unsigned Reg = 0;
508       if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
509         return error(Error, RegSource.SourceRange);
510       CalleeSavedRegisters.push_back(Reg);
511     }
512     RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
513   }
514 
515   return false;
516 }
517 
518 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
519                                       const yaml::MachineFunction &YamlMF) {
520   MachineFunction &MF = PFS.MF;
521   MachineRegisterInfo &MRI = MF.getRegInfo();
522   bool Error = false;
523   // Create VRegs
524   auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
525     unsigned Reg = Info.VReg;
526     switch (Info.Kind) {
527     case VRegInfo::UNKNOWN:
528       error(Twine("Cannot determine class/bank of virtual register ") +
529             Name + " in function '" + MF.getName() + "'");
530       Error = true;
531       break;
532     case VRegInfo::NORMAL:
533       MRI.setRegClass(Reg, Info.D.RC);
534       if (Info.PreferredReg != 0)
535         MRI.setSimpleHint(Reg, Info.PreferredReg);
536       break;
537     case VRegInfo::GENERIC:
538       break;
539     case VRegInfo::REGBANK:
540       MRI.setRegBank(Reg, *Info.D.RegBank);
541       break;
542     }
543   };
544 
545   for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end();
546        I != E; I++) {
547     const VRegInfo &Info = *I->second;
548     populateVRegInfo(Info, Twine(I->first()));
549   }
550 
551   for (auto P : PFS.VRegInfos) {
552     const VRegInfo &Info = *P.second;
553     populateVRegInfo(Info, Twine(P.first));
554   }
555 
556   // Compute MachineRegisterInfo::UsedPhysRegMask
557   for (const MachineBasicBlock &MBB : MF) {
558     for (const MachineInstr &MI : MBB) {
559       for (const MachineOperand &MO : MI.operands()) {
560         if (!MO.isRegMask())
561           continue;
562         MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
563       }
564     }
565   }
566 
567   // FIXME: This is a temporary workaround until the reserved registers can be
568   // serialized.
569   MRI.freezeReservedRegs(MF);
570   return Error;
571 }
572 
573 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
574                                         const yaml::MachineFunction &YamlMF) {
575   MachineFunction &MF = PFS.MF;
576   MachineFrameInfo &MFI = MF.getFrameInfo();
577   const Function &F = MF.getFunction();
578   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
579   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
580   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
581   MFI.setHasStackMap(YamlMFI.HasStackMap);
582   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
583   MFI.setStackSize(YamlMFI.StackSize);
584   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
585   if (YamlMFI.MaxAlignment)
586     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
587   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
588   MFI.setHasCalls(YamlMFI.HasCalls);
589   if (YamlMFI.MaxCallFrameSize != ~0u)
590     MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
591   MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
592   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
593   MFI.setHasVAStart(YamlMFI.HasVAStart);
594   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
595   MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
596   if (!YamlMFI.SavePoint.Value.empty()) {
597     MachineBasicBlock *MBB = nullptr;
598     if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
599       return true;
600     MFI.setSavePoint(MBB);
601   }
602   if (!YamlMFI.RestorePoint.Value.empty()) {
603     MachineBasicBlock *MBB = nullptr;
604     if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
605       return true;
606     MFI.setRestorePoint(MBB);
607   }
608 
609   std::vector<CalleeSavedInfo> CSIInfo;
610   // Initialize the fixed frame objects.
611   for (const auto &Object : YamlMF.FixedStackObjects) {
612     int ObjectIdx;
613     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
614       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
615                                         Object.IsImmutable, Object.IsAliased);
616     else
617       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
618     MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
619     MFI.setStackID(ObjectIdx, Object.StackID);
620     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
621                                                          ObjectIdx))
622              .second)
623       return error(Object.ID.SourceRange.Start,
624                    Twine("redefinition of fixed stack object '%fixed-stack.") +
625                        Twine(Object.ID.Value) + "'");
626     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
627                                  Object.CalleeSavedRestored, ObjectIdx))
628       return true;
629     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
630       return true;
631   }
632 
633   // Initialize the ordinary frame objects.
634   for (const auto &Object : YamlMF.StackObjects) {
635     int ObjectIdx;
636     const AllocaInst *Alloca = nullptr;
637     const yaml::StringValue &Name = Object.Name;
638     if (!Name.Value.empty()) {
639       Alloca = dyn_cast_or_null<AllocaInst>(
640           F.getValueSymbolTable()->lookup(Name.Value));
641       if (!Alloca)
642         return error(Name.SourceRange.Start,
643                      "alloca instruction named '" + Name.Value +
644                          "' isn't defined in the function '" + F.getName() +
645                          "'");
646     }
647     if (Object.Type == yaml::MachineStackObject::VariableSized)
648       ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
649     else
650       ObjectIdx = MFI.CreateStackObject(
651           Object.Size, Object.Alignment,
652           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
653     MFI.setObjectOffset(ObjectIdx, Object.Offset);
654     MFI.setStackID(ObjectIdx, Object.StackID);
655 
656     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
657              .second)
658       return error(Object.ID.SourceRange.Start,
659                    Twine("redefinition of stack object '%stack.") +
660                        Twine(Object.ID.Value) + "'");
661     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
662                                  Object.CalleeSavedRestored, ObjectIdx))
663       return true;
664     if (Object.LocalOffset)
665       MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
666     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
667       return true;
668   }
669   MFI.setCalleeSavedInfo(CSIInfo);
670   if (!CSIInfo.empty())
671     MFI.setCalleeSavedInfoValid(true);
672 
673   // Initialize the various stack object references after initializing the
674   // stack objects.
675   if (!YamlMFI.StackProtector.Value.empty()) {
676     SMDiagnostic Error;
677     int FI;
678     if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
679       return error(Error, YamlMFI.StackProtector.SourceRange);
680     MFI.setStackProtectorIndex(FI);
681   }
682   return false;
683 }
684 
685 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
686     std::vector<CalleeSavedInfo> &CSIInfo,
687     const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
688   if (RegisterSource.Value.empty())
689     return false;
690   unsigned Reg = 0;
691   SMDiagnostic Error;
692   if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
693     return error(Error, RegisterSource.SourceRange);
694   CalleeSavedInfo CSI(Reg, FrameIdx);
695   CSI.setRestored(IsRestored);
696   CSIInfo.push_back(CSI);
697   return false;
698 }
699 
700 /// Verify that given node is of a certain type. Return true on error.
701 template <typename T>
702 static bool typecheckMDNode(T *&Result, MDNode *Node,
703                             const yaml::StringValue &Source,
704                             StringRef TypeString, MIRParserImpl &Parser) {
705   if (!Node)
706     return false;
707   Result = dyn_cast<T>(Node);
708   if (!Result)
709     return Parser.error(Source.SourceRange.Start,
710                         "expected a reference to a '" + TypeString +
711                             "' metadata node");
712   return false;
713 }
714 
715 template <typename T>
716 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
717     const T &Object, int FrameIdx) {
718   // Debug information can only be attached to stack objects; Fixed stack
719   // objects aren't supported.
720   MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
721   if (parseMDNode(PFS, Var, Object.DebugVar) ||
722       parseMDNode(PFS, Expr, Object.DebugExpr) ||
723       parseMDNode(PFS, Loc, Object.DebugLoc))
724     return true;
725   if (!Var && !Expr && !Loc)
726     return false;
727   DILocalVariable *DIVar = nullptr;
728   DIExpression *DIExpr = nullptr;
729   DILocation *DILoc = nullptr;
730   if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
731       typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
732       typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
733     return true;
734   PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
735   return false;
736 }
737 
738 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
739     MDNode *&Node, const yaml::StringValue &Source) {
740   if (Source.Value.empty())
741     return false;
742   SMDiagnostic Error;
743   if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
744     return error(Error, Source.SourceRange);
745   return false;
746 }
747 
748 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
749     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
750   DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
751   const MachineFunction &MF = PFS.MF;
752   const auto &M = *MF.getFunction().getParent();
753   SMDiagnostic Error;
754   for (const auto &YamlConstant : YamlMF.Constants) {
755     if (YamlConstant.IsTargetSpecific)
756       // FIXME: Support target-specific constant pools
757       return error(YamlConstant.Value.SourceRange.Start,
758                    "Can't parse target-specific constant pool entries yet");
759     const Constant *Value = dyn_cast_or_null<Constant>(
760         parseConstantValue(YamlConstant.Value.Value, Error, M));
761     if (!Value)
762       return error(Error, YamlConstant.Value.SourceRange);
763     unsigned Alignment =
764         YamlConstant.Alignment
765             ? YamlConstant.Alignment
766             : M.getDataLayout().getPrefTypeAlignment(Value->getType());
767     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
768     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
769              .second)
770       return error(YamlConstant.ID.SourceRange.Start,
771                    Twine("redefinition of constant pool item '%const.") +
772                        Twine(YamlConstant.ID.Value) + "'");
773   }
774   return false;
775 }
776 
777 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
778     const yaml::MachineJumpTable &YamlJTI) {
779   MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
780   for (const auto &Entry : YamlJTI.Entries) {
781     std::vector<MachineBasicBlock *> Blocks;
782     for (const auto &MBBSource : Entry.Blocks) {
783       MachineBasicBlock *MBB = nullptr;
784       if (parseMBBReference(PFS, MBB, MBBSource.Value))
785         return true;
786       Blocks.push_back(MBB);
787     }
788     unsigned Index = JTI->createJumpTableIndex(Blocks);
789     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
790              .second)
791       return error(Entry.ID.SourceRange.Start,
792                    Twine("redefinition of jump table entry '%jump-table.") +
793                        Twine(Entry.ID.Value) + "'");
794   }
795   return false;
796 }
797 
798 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
799                                       MachineBasicBlock *&MBB,
800                                       const yaml::StringValue &Source) {
801   SMDiagnostic Error;
802   if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
803     return error(Error, Source.SourceRange);
804   return false;
805 }
806 
807 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
808                                                  SMRange SourceRange) {
809   assert(SourceRange.isValid() && "Invalid source range");
810   SMLoc Loc = SourceRange.Start;
811   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
812                   *Loc.getPointer() == '\'';
813   // Translate the location of the error from the location in the MI string to
814   // the corresponding location in the MIR file.
815   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
816                            (HasQuote ? 1 : 0));
817 
818   // TODO: Translate any source ranges as well.
819   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
820                        Error.getFixIts());
821 }
822 
823 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
824                                                     SMRange SourceRange) {
825   assert(SourceRange.isValid());
826 
827   // Translate the location of the error from the location in the llvm IR string
828   // to the corresponding location in the MIR file.
829   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
830   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
831   unsigned Column = Error.getColumnNo();
832   StringRef LineStr = Error.getLineContents();
833   SMLoc Loc = Error.getLoc();
834 
835   // Get the full line and adjust the column number by taking the indentation of
836   // LLVM IR into account.
837   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
838        L != E; ++L) {
839     if (L.line_number() == Line) {
840       LineStr = *L;
841       Loc = SMLoc::getFromPointer(LineStr.data());
842       auto Indent = LineStr.find(Error.getLineContents());
843       if (Indent != StringRef::npos)
844         Column += Indent;
845       break;
846     }
847   }
848 
849   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
850                       Error.getMessage(), LineStr, Error.getRanges(),
851                       Error.getFixIts());
852 }
853 
854 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
855     : Impl(std::move(Impl)) {}
856 
857 MIRParser::~MIRParser() {}
858 
859 std::unique_ptr<Module> MIRParser::parseIRModule() {
860   return Impl->parseIRModule();
861 }
862 
863 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
864   return Impl->parseMachineFunctions(M, MMI);
865 }
866 
867 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
868                                                          SMDiagnostic &Error,
869                                                          LLVMContext &Context) {
870   auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
871   if (std::error_code EC = FileOrErr.getError()) {
872     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
873                          "Could not open input file: " + EC.message());
874     return nullptr;
875   }
876   return createMIRParser(std::move(FileOrErr.get()), Context);
877 }
878 
879 std::unique_ptr<MIRParser>
880 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
881                       LLVMContext &Context) {
882   auto Filename = Contents->getBufferIdentifier();
883   if (Context.shouldDiscardValueNames()) {
884     Context.diagnose(DiagnosticInfoMIRParser(
885         DS_Error,
886         SMDiagnostic(
887             Filename, SourceMgr::DK_Error,
888             "Can't read MIR with a Context that discards named Values")));
889     return nullptr;
890   }
891   return llvm::make_unique<MIRParser>(
892       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
893 }
894