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