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