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