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