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