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   if (YamlMF.FailsVerification)
458     MF.getProperties().set(
459         MachineFunctionProperties::Property::FailsVerification);
460   if (YamlMF.TracksDebugUserValues)
461     MF.getProperties().set(
462         MachineFunctionProperties::Property::TracksDebugUserValues);
463 
464   PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
465   if (parseRegisterInfo(PFS, YamlMF))
466     return true;
467   if (!YamlMF.Constants.empty()) {
468     auto *ConstantPool = MF.getConstantPool();
469     assert(ConstantPool && "Constant pool must be created");
470     if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
471       return true;
472   }
473   if (!YamlMF.MachineMetadataNodes.empty() &&
474       parseMachineMetadataNodes(PFS, MF, YamlMF))
475     return true;
476 
477   StringRef BlockStr = YamlMF.Body.Value.Value;
478   SMDiagnostic Error;
479   SourceMgr BlockSM;
480   BlockSM.AddNewSourceBuffer(
481       MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
482       SMLoc());
483   PFS.SM = &BlockSM;
484   if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
485     reportDiagnostic(
486         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
487     return true;
488   }
489   // Check Basic Block Section Flags.
490   if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels) {
491     MF.setBBSectionsType(BasicBlockSection::Labels);
492   } else if (MF.hasBBSections()) {
493     MF.assignBeginEndSections();
494   }
495   PFS.SM = &SM;
496 
497   // Initialize the frame information after creating all the MBBs so that the
498   // MBB references in the frame information can be resolved.
499   if (initializeFrameInfo(PFS, YamlMF))
500     return true;
501   // Initialize the jump table after creating all the MBBs so that the MBB
502   // references can be resolved.
503   if (!YamlMF.JumpTableInfo.Entries.empty() &&
504       initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
505     return true;
506   // Parse the machine instructions after creating all of the MBBs so that the
507   // parser can resolve the MBB references.
508   StringRef InsnStr = YamlMF.Body.Value.Value;
509   SourceMgr InsnSM;
510   InsnSM.AddNewSourceBuffer(
511       MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
512       SMLoc());
513   PFS.SM = &InsnSM;
514   if (parseMachineInstructions(PFS, InsnStr, Error)) {
515     reportDiagnostic(
516         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
517     return true;
518   }
519   PFS.SM = &SM;
520 
521   if (setupRegisterInfo(PFS, YamlMF))
522     return true;
523 
524   if (YamlMF.MachineFuncInfo) {
525     const LLVMTargetMachine &TM = MF.getTarget();
526     // Note this is called after the initial constructor of the
527     // MachineFunctionInfo based on the MachineFunction, which may depend on the
528     // IR.
529 
530     SMRange SrcRange;
531     if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
532                                     SrcRange)) {
533       return error(Error, SrcRange);
534     }
535   }
536 
537   // Set the reserved registers after parsing MachineFuncInfo. The target may
538   // have been recording information used to select the reserved registers
539   // there.
540   // FIXME: This is a temporary workaround until the reserved registers can be
541   // serialized.
542   MachineRegisterInfo &MRI = MF.getRegInfo();
543   MRI.freezeReservedRegs(MF);
544 
545   computeFunctionProperties(MF);
546 
547   if (initializeCallSiteInfo(PFS, YamlMF))
548     return false;
549 
550   setupDebugValueTracking(MF, PFS, YamlMF);
551 
552   MF.getSubtarget().mirFileLoaded(MF);
553 
554   MF.verify();
555   return false;
556 }
557 
558 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
559                                       const yaml::MachineFunction &YamlMF) {
560   MachineFunction &MF = PFS.MF;
561   MachineRegisterInfo &RegInfo = MF.getRegInfo();
562   assert(RegInfo.tracksLiveness());
563   if (!YamlMF.TracksRegLiveness)
564     RegInfo.invalidateLiveness();
565 
566   SMDiagnostic Error;
567   // Parse the virtual register information.
568   for (const auto &VReg : YamlMF.VirtualRegisters) {
569     VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
570     if (Info.Explicit)
571       return error(VReg.ID.SourceRange.Start,
572                    Twine("redefinition of virtual register '%") +
573                        Twine(VReg.ID.Value) + "'");
574     Info.Explicit = true;
575 
576     if (StringRef(VReg.Class.Value).equals("_")) {
577       Info.Kind = VRegInfo::GENERIC;
578       Info.D.RegBank = nullptr;
579     } else {
580       const auto *RC = Target->getRegClass(VReg.Class.Value);
581       if (RC) {
582         Info.Kind = VRegInfo::NORMAL;
583         Info.D.RC = RC;
584       } else {
585         const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
586         if (!RegBank)
587           return error(
588               VReg.Class.SourceRange.Start,
589               Twine("use of undefined register class or register bank '") +
590                   VReg.Class.Value + "'");
591         Info.Kind = VRegInfo::REGBANK;
592         Info.D.RegBank = RegBank;
593       }
594     }
595 
596     if (!VReg.PreferredRegister.Value.empty()) {
597       if (Info.Kind != VRegInfo::NORMAL)
598         return error(VReg.Class.SourceRange.Start,
599               Twine("preferred register can only be set for normal vregs"));
600 
601       if (parseRegisterReference(PFS, Info.PreferredReg,
602                                  VReg.PreferredRegister.Value, Error))
603         return error(Error, VReg.PreferredRegister.SourceRange);
604     }
605   }
606 
607   // Parse the liveins.
608   for (const auto &LiveIn : YamlMF.LiveIns) {
609     Register Reg;
610     if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
611       return error(Error, LiveIn.Register.SourceRange);
612     Register VReg;
613     if (!LiveIn.VirtualRegister.Value.empty()) {
614       VRegInfo *Info;
615       if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
616                                         Error))
617         return error(Error, LiveIn.VirtualRegister.SourceRange);
618       VReg = Info->VReg;
619     }
620     RegInfo.addLiveIn(Reg, VReg);
621   }
622 
623   // Parse the callee saved registers (Registers that will
624   // be saved for the caller).
625   if (YamlMF.CalleeSavedRegisters) {
626     SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
627     for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
628       Register Reg;
629       if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
630         return error(Error, RegSource.SourceRange);
631       CalleeSavedRegisters.push_back(Reg);
632     }
633     RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
634   }
635 
636   return false;
637 }
638 
639 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
640                                       const yaml::MachineFunction &YamlMF) {
641   MachineFunction &MF = PFS.MF;
642   MachineRegisterInfo &MRI = MF.getRegInfo();
643   bool Error = false;
644   // Create VRegs
645   auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
646     Register Reg = Info.VReg;
647     switch (Info.Kind) {
648     case VRegInfo::UNKNOWN:
649       error(Twine("Cannot determine class/bank of virtual register ") +
650             Name + " in function '" + MF.getName() + "'");
651       Error = true;
652       break;
653     case VRegInfo::NORMAL:
654       MRI.setRegClass(Reg, Info.D.RC);
655       if (Info.PreferredReg != 0)
656         MRI.setSimpleHint(Reg, Info.PreferredReg);
657       break;
658     case VRegInfo::GENERIC:
659       break;
660     case VRegInfo::REGBANK:
661       MRI.setRegBank(Reg, *Info.D.RegBank);
662       break;
663     }
664   };
665 
666   for (const auto &P : PFS.VRegInfosNamed) {
667     const VRegInfo &Info = *P.second;
668     populateVRegInfo(Info, Twine(P.first()));
669   }
670 
671   for (auto P : PFS.VRegInfos) {
672     const VRegInfo &Info = *P.second;
673     populateVRegInfo(Info, Twine(P.first));
674   }
675 
676   // Compute MachineRegisterInfo::UsedPhysRegMask
677   for (const MachineBasicBlock &MBB : MF) {
678     // Make sure MRI knows about registers clobbered by unwinder.
679     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
680     if (MBB.isEHPad())
681       if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
682         MRI.addPhysRegsUsedFromRegMask(RegMask);
683 
684     for (const MachineInstr &MI : MBB) {
685       for (const MachineOperand &MO : MI.operands()) {
686         if (!MO.isRegMask())
687           continue;
688         MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
689       }
690     }
691   }
692 
693   return Error;
694 }
695 
696 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
697                                         const yaml::MachineFunction &YamlMF) {
698   MachineFunction &MF = PFS.MF;
699   MachineFrameInfo &MFI = MF.getFrameInfo();
700   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
701   const Function &F = MF.getFunction();
702   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
703   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
704   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
705   MFI.setHasStackMap(YamlMFI.HasStackMap);
706   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
707   MFI.setStackSize(YamlMFI.StackSize);
708   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
709   if (YamlMFI.MaxAlignment)
710     MFI.ensureMaxAlignment(Align(YamlMFI.MaxAlignment));
711   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
712   MFI.setHasCalls(YamlMFI.HasCalls);
713   if (YamlMFI.MaxCallFrameSize != ~0u)
714     MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
715   MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
716   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
717   MFI.setHasVAStart(YamlMFI.HasVAStart);
718   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
719   MFI.setHasTailCall(YamlMFI.HasTailCall);
720   MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
721   if (!YamlMFI.SavePoint.Value.empty()) {
722     MachineBasicBlock *MBB = nullptr;
723     if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
724       return true;
725     MFI.setSavePoint(MBB);
726   }
727   if (!YamlMFI.RestorePoint.Value.empty()) {
728     MachineBasicBlock *MBB = nullptr;
729     if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
730       return true;
731     MFI.setRestorePoint(MBB);
732   }
733 
734   std::vector<CalleeSavedInfo> CSIInfo;
735   // Initialize the fixed frame objects.
736   for (const auto &Object : YamlMF.FixedStackObjects) {
737     int ObjectIdx;
738     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
739       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
740                                         Object.IsImmutable, Object.IsAliased);
741     else
742       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
743 
744     if (!TFI->isSupportedStackID(Object.StackID))
745       return error(Object.ID.SourceRange.Start,
746                    Twine("StackID is not supported by target"));
747     MFI.setStackID(ObjectIdx, Object.StackID);
748     MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
749     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
750                                                          ObjectIdx))
751              .second)
752       return error(Object.ID.SourceRange.Start,
753                    Twine("redefinition of fixed stack object '%fixed-stack.") +
754                        Twine(Object.ID.Value) + "'");
755     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
756                                  Object.CalleeSavedRestored, ObjectIdx))
757       return true;
758     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
759       return true;
760   }
761 
762   // Initialize the ordinary frame objects.
763   for (const auto &Object : YamlMF.StackObjects) {
764     int ObjectIdx;
765     const AllocaInst *Alloca = nullptr;
766     const yaml::StringValue &Name = Object.Name;
767     if (!Name.Value.empty()) {
768       Alloca = dyn_cast_or_null<AllocaInst>(
769           F.getValueSymbolTable()->lookup(Name.Value));
770       if (!Alloca)
771         return error(Name.SourceRange.Start,
772                      "alloca instruction named '" + Name.Value +
773                          "' isn't defined in the function '" + F.getName() +
774                          "'");
775     }
776     if (!TFI->isSupportedStackID(Object.StackID))
777       return error(Object.ID.SourceRange.Start,
778                    Twine("StackID is not supported by target"));
779     if (Object.Type == yaml::MachineStackObject::VariableSized)
780       ObjectIdx =
781           MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
782     else
783       ObjectIdx = MFI.CreateStackObject(
784           Object.Size, Object.Alignment.valueOrOne(),
785           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
786           Object.StackID);
787     MFI.setObjectOffset(ObjectIdx, Object.Offset);
788 
789     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
790              .second)
791       return error(Object.ID.SourceRange.Start,
792                    Twine("redefinition of stack object '%stack.") +
793                        Twine(Object.ID.Value) + "'");
794     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
795                                  Object.CalleeSavedRestored, ObjectIdx))
796       return true;
797     if (Object.LocalOffset)
798       MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
799     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
800       return true;
801   }
802   MFI.setCalleeSavedInfo(CSIInfo);
803   if (!CSIInfo.empty())
804     MFI.setCalleeSavedInfoValid(true);
805 
806   // Initialize the various stack object references after initializing the
807   // stack objects.
808   if (!YamlMFI.StackProtector.Value.empty()) {
809     SMDiagnostic Error;
810     int FI;
811     if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
812       return error(Error, YamlMFI.StackProtector.SourceRange);
813     MFI.setStackProtectorIndex(FI);
814   }
815   return false;
816 }
817 
818 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
819     std::vector<CalleeSavedInfo> &CSIInfo,
820     const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
821   if (RegisterSource.Value.empty())
822     return false;
823   Register Reg;
824   SMDiagnostic Error;
825   if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
826     return error(Error, RegisterSource.SourceRange);
827   CalleeSavedInfo CSI(Reg, FrameIdx);
828   CSI.setRestored(IsRestored);
829   CSIInfo.push_back(CSI);
830   return false;
831 }
832 
833 /// Verify that given node is of a certain type. Return true on error.
834 template <typename T>
835 static bool typecheckMDNode(T *&Result, MDNode *Node,
836                             const yaml::StringValue &Source,
837                             StringRef TypeString, MIRParserImpl &Parser) {
838   if (!Node)
839     return false;
840   Result = dyn_cast<T>(Node);
841   if (!Result)
842     return Parser.error(Source.SourceRange.Start,
843                         "expected a reference to a '" + TypeString +
844                             "' metadata node");
845   return false;
846 }
847 
848 template <typename T>
849 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
850     const T &Object, int FrameIdx) {
851   // Debug information can only be attached to stack objects; Fixed stack
852   // objects aren't supported.
853   MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
854   if (parseMDNode(PFS, Var, Object.DebugVar) ||
855       parseMDNode(PFS, Expr, Object.DebugExpr) ||
856       parseMDNode(PFS, Loc, Object.DebugLoc))
857     return true;
858   if (!Var && !Expr && !Loc)
859     return false;
860   DILocalVariable *DIVar = nullptr;
861   DIExpression *DIExpr = nullptr;
862   DILocation *DILoc = nullptr;
863   if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
864       typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
865       typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
866     return true;
867   PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
868   return false;
869 }
870 
871 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
872     MDNode *&Node, const yaml::StringValue &Source) {
873   if (Source.Value.empty())
874     return false;
875   SMDiagnostic Error;
876   if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
877     return error(Error, Source.SourceRange);
878   return false;
879 }
880 
881 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
882     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
883   DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
884   const MachineFunction &MF = PFS.MF;
885   const auto &M = *MF.getFunction().getParent();
886   SMDiagnostic Error;
887   for (const auto &YamlConstant : YamlMF.Constants) {
888     if (YamlConstant.IsTargetSpecific)
889       // FIXME: Support target-specific constant pools
890       return error(YamlConstant.Value.SourceRange.Start,
891                    "Can't parse target-specific constant pool entries yet");
892     const Constant *Value = dyn_cast_or_null<Constant>(
893         parseConstantValue(YamlConstant.Value.Value, Error, M));
894     if (!Value)
895       return error(Error, YamlConstant.Value.SourceRange);
896     const Align PrefTypeAlign =
897         M.getDataLayout().getPrefTypeAlign(Value->getType());
898     const Align Alignment = YamlConstant.Alignment.getValueOr(PrefTypeAlign);
899     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
900     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
901              .second)
902       return error(YamlConstant.ID.SourceRange.Start,
903                    Twine("redefinition of constant pool item '%const.") +
904                        Twine(YamlConstant.ID.Value) + "'");
905   }
906   return false;
907 }
908 
909 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
910     const yaml::MachineJumpTable &YamlJTI) {
911   MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
912   for (const auto &Entry : YamlJTI.Entries) {
913     std::vector<MachineBasicBlock *> Blocks;
914     for (const auto &MBBSource : Entry.Blocks) {
915       MachineBasicBlock *MBB = nullptr;
916       if (parseMBBReference(PFS, MBB, MBBSource.Value))
917         return true;
918       Blocks.push_back(MBB);
919     }
920     unsigned Index = JTI->createJumpTableIndex(Blocks);
921     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
922              .second)
923       return error(Entry.ID.SourceRange.Start,
924                    Twine("redefinition of jump table entry '%jump-table.") +
925                        Twine(Entry.ID.Value) + "'");
926   }
927   return false;
928 }
929 
930 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
931                                       MachineBasicBlock *&MBB,
932                                       const yaml::StringValue &Source) {
933   SMDiagnostic Error;
934   if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
935     return error(Error, Source.SourceRange);
936   return false;
937 }
938 
939 bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
940                                          const yaml::StringValue &Source) {
941   SMDiagnostic Error;
942   if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
943     return error(Error, Source.SourceRange);
944   return false;
945 }
946 
947 bool MIRParserImpl::parseMachineMetadataNodes(
948     PerFunctionMIParsingState &PFS, MachineFunction &MF,
949     const yaml::MachineFunction &YMF) {
950   for (auto &MDS : YMF.MachineMetadataNodes) {
951     if (parseMachineMetadata(PFS, MDS))
952       return true;
953   }
954   // Report missing definitions from forward referenced nodes.
955   if (!PFS.MachineForwardRefMDNodes.empty())
956     return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
957                  "use of undefined metadata '!" +
958                      Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
959   return false;
960 }
961 
962 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
963                                                  SMRange SourceRange) {
964   assert(SourceRange.isValid() && "Invalid source range");
965   SMLoc Loc = SourceRange.Start;
966   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
967                   *Loc.getPointer() == '\'';
968   // Translate the location of the error from the location in the MI string to
969   // the corresponding location in the MIR file.
970   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
971                            (HasQuote ? 1 : 0));
972 
973   // TODO: Translate any source ranges as well.
974   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
975                        Error.getFixIts());
976 }
977 
978 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
979                                                     SMRange SourceRange) {
980   assert(SourceRange.isValid());
981 
982   // Translate the location of the error from the location in the llvm IR string
983   // to the corresponding location in the MIR file.
984   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
985   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
986   unsigned Column = Error.getColumnNo();
987   StringRef LineStr = Error.getLineContents();
988   SMLoc Loc = Error.getLoc();
989 
990   // Get the full line and adjust the column number by taking the indentation of
991   // LLVM IR into account.
992   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
993        L != E; ++L) {
994     if (L.line_number() == Line) {
995       LineStr = *L;
996       Loc = SMLoc::getFromPointer(LineStr.data());
997       auto Indent = LineStr.find(Error.getLineContents());
998       if (Indent != StringRef::npos)
999         Column += Indent;
1000       break;
1001     }
1002   }
1003 
1004   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1005                       Error.getMessage(), LineStr, Error.getRanges(),
1006                       Error.getFixIts());
1007 }
1008 
1009 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1010     : Impl(std::move(Impl)) {}
1011 
1012 MIRParser::~MIRParser() {}
1013 
1014 std::unique_ptr<Module>
1015 MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
1016   return Impl->parseIRModule(DataLayoutCallback);
1017 }
1018 
1019 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
1020   return Impl->parseMachineFunctions(M, MMI);
1021 }
1022 
1023 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1024     StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1025     std::function<void(Function &)> ProcessIRFunction) {
1026   auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1027   if (std::error_code EC = FileOrErr.getError()) {
1028     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
1029                          "Could not open input file: " + EC.message());
1030     return nullptr;
1031   }
1032   return createMIRParser(std::move(FileOrErr.get()), Context,
1033                          ProcessIRFunction);
1034 }
1035 
1036 std::unique_ptr<MIRParser>
1037 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1038                       LLVMContext &Context,
1039                       std::function<void(Function &)> ProcessIRFunction) {
1040   auto Filename = Contents->getBufferIdentifier();
1041   if (Context.shouldDiscardValueNames()) {
1042     Context.diagnose(DiagnosticInfoMIRParser(
1043         DS_Error,
1044         SMDiagnostic(
1045             Filename, SourceMgr::DK_Error,
1046             "Can't read MIR with a Context that discards named Values")));
1047     return nullptr;
1048   }
1049   return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1050       std::move(Contents), Filename, Context, ProcessIRFunction));
1051 }
1052