1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/MIRParser/MIRParser.h"
16 #include "MIParser.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
25 #include "llvm/CodeGen/MIRYamlMapping.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.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 <memory>
44 
45 using namespace llvm;
46 
47 namespace llvm {
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   StringRef Filename;
54   LLVMContext &Context;
55   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
56   SlotMapping IRSlots;
57   /// Maps from register class names to register classes.
58   Name2RegClassMap Names2RegClasses;
59   /// Maps from register bank names to register banks.
60   Name2RegBankMap Names2RegBanks;
61 
62 public:
63   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
64                 LLVMContext &Context);
65 
66   void reportDiagnostic(const SMDiagnostic &Diag);
67 
68   /// Report an error with the given message at unknown location.
69   ///
70   /// Always returns true.
71   bool error(const Twine &Message);
72 
73   /// Report an error with the given message at the given location.
74   ///
75   /// Always returns true.
76   bool error(SMLoc Loc, const Twine &Message);
77 
78   /// Report a given error with the location translated from the location in an
79   /// embedded string literal to a location in the MIR file.
80   ///
81   /// Always returns true.
82   bool error(const SMDiagnostic &Error, SMRange SourceRange);
83 
84   /// Try to parse the optional LLVM module and the machine functions in the MIR
85   /// file.
86   ///
87   /// Return null if an error occurred.
88   std::unique_ptr<Module> parse();
89 
90   /// Parse the machine function in the current YAML document.
91   ///
92   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
93   /// A dummy IR function is created and inserted into the given module when
94   /// this parameter is true.
95   ///
96   /// Return true if an error occurred.
97   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
98 
99   /// Initialize the machine function to the state that's described in the MIR
100   /// file.
101   ///
102   /// Return true if error occurred.
103   bool initializeMachineFunction(MachineFunction &MF);
104 
105   bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
106                          const yaml::MachineFunction &YamlMF);
107 
108   bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
109                          const yaml::MachineFunction &YamlMF);
110 
111   bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
112                            const yaml::MachineFunction &YamlMF);
113 
114   bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
115                                 std::vector<CalleeSavedInfo> &CSIInfo,
116                                 const yaml::StringValue &RegisterSource,
117                                 int FrameIdx);
118 
119   bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
120                                   const yaml::MachineStackObject &Object,
121                                   int FrameIdx);
122 
123   bool initializeConstantPool(PerFunctionMIParsingState &PFS,
124                               MachineConstantPool &ConstantPool,
125                               const yaml::MachineFunction &YamlMF);
126 
127   bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
128                                const yaml::MachineJumpTable &YamlJTI);
129 
130 private:
131   bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
132                    const yaml::StringValue &Source);
133 
134   bool parseMBBReference(PerFunctionMIParsingState &PFS,
135                          MachineBasicBlock *&MBB,
136                          const yaml::StringValue &Source);
137 
138   /// Return a MIR diagnostic converted from an MI string diagnostic.
139   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
140                                     SMRange SourceRange);
141 
142   /// Return a MIR diagnostic converted from a diagnostic located in a YAML
143   /// block scalar string.
144   SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
145                                        SMRange SourceRange);
146 
147   /// Create an empty function with the given name.
148   void createDummyFunction(StringRef Name, Module &M);
149 
150   void initNames2RegClasses(const MachineFunction &MF);
151   void initNames2RegBanks(const MachineFunction &MF);
152 
153   /// Check if the given identifier is a name of a register class.
154   ///
155   /// Return null if the name isn't a register class.
156   const TargetRegisterClass *getRegClass(const MachineFunction &MF,
157                                          StringRef Name);
158 
159   /// Check if the given identifier is a name of a register bank.
160   ///
161   /// Return null if the name isn't a register bank.
162   const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name);
163 
164   void computeFunctionProperties(MachineFunction &MF);
165 };
166 
167 } // end namespace llvm
168 
169 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
170                              StringRef Filename, LLVMContext &Context)
171     : SM(), Filename(Filename), Context(Context) {
172   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
173 }
174 
175 bool MIRParserImpl::error(const Twine &Message) {
176   Context.diagnose(DiagnosticInfoMIRParser(
177       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
178   return true;
179 }
180 
181 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
182   Context.diagnose(DiagnosticInfoMIRParser(
183       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
184   return true;
185 }
186 
187 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
188   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
189   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
190   return true;
191 }
192 
193 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
194   DiagnosticSeverity Kind;
195   switch (Diag.getKind()) {
196   case SourceMgr::DK_Error:
197     Kind = DS_Error;
198     break;
199   case SourceMgr::DK_Warning:
200     Kind = DS_Warning;
201     break;
202   case SourceMgr::DK_Note:
203     Kind = DS_Note;
204     break;
205   }
206   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
207 }
208 
209 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
210   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
211 }
212 
213 std::unique_ptr<Module> MIRParserImpl::parse() {
214   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
215                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
216   In.setContext(&In);
217 
218   if (!In.setCurrentDocument()) {
219     if (In.error())
220       return nullptr;
221     // Create an empty module when the MIR file is empty.
222     return llvm::make_unique<Module>(Filename, Context);
223   }
224 
225   std::unique_ptr<Module> M;
226   bool NoLLVMIR = false;
227   // Parse the block scalar manually so that we can return unique pointer
228   // without having to go trough YAML traits.
229   if (const auto *BSN =
230           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
231     SMDiagnostic Error;
232     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
233                       Context, &IRSlots);
234     if (!M) {
235       reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
236       return nullptr;
237     }
238     In.nextDocument();
239     if (!In.setCurrentDocument())
240       return M;
241   } else {
242     // Create an new, empty module.
243     M = llvm::make_unique<Module>(Filename, Context);
244     NoLLVMIR = true;
245   }
246 
247   // Parse the machine functions.
248   do {
249     if (parseMachineFunction(In, *M, NoLLVMIR))
250       return nullptr;
251     In.nextDocument();
252   } while (In.setCurrentDocument());
253 
254   return M;
255 }
256 
257 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
258                                          bool NoLLVMIR) {
259   auto MF = llvm::make_unique<yaml::MachineFunction>();
260   yaml::EmptyContext Ctx;
261   yaml::yamlize(In, *MF, false, Ctx);
262   if (In.error())
263     return true;
264   auto FunctionName = MF->Name;
265   if (Functions.find(FunctionName) != Functions.end())
266     return error(Twine("redefinition of machine function '") + FunctionName +
267                  "'");
268   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
269   if (NoLLVMIR)
270     createDummyFunction(FunctionName, M);
271   else if (!M.getFunction(FunctionName))
272     return error(Twine("function '") + FunctionName +
273                  "' isn't defined in the provided LLVM IR");
274   return false;
275 }
276 
277 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
278   auto &Context = M.getContext();
279   Function *F = cast<Function>(M.getOrInsertFunction(
280       Name, FunctionType::get(Type::getVoidTy(Context), false)));
281   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
282   new UnreachableInst(Context, BB);
283 }
284 
285 static bool isSSA(const MachineFunction &MF) {
286   const MachineRegisterInfo &MRI = MF.getRegInfo();
287   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
288     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
289     if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
290       return false;
291   }
292   return true;
293 }
294 
295 void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
296   MachineFunctionProperties &Properties = MF.getProperties();
297 
298   bool HasPHI = false;
299   bool HasInlineAsm = false;
300   for (const MachineBasicBlock &MBB : MF) {
301     for (const MachineInstr &MI : MBB) {
302       if (MI.isPHI())
303         HasPHI = true;
304       if (MI.isInlineAsm())
305         HasInlineAsm = true;
306     }
307   }
308   if (!HasPHI)
309     Properties.set(MachineFunctionProperties::Property::NoPHIs);
310   MF.setHasInlineAsm(HasInlineAsm);
311 
312   if (isSSA(MF))
313     Properties.set(MachineFunctionProperties::Property::IsSSA);
314   else
315     Properties.reset(MachineFunctionProperties::Property::IsSSA);
316 
317   const MachineRegisterInfo &MRI = MF.getRegInfo();
318   if (MRI.getNumVirtRegs() == 0)
319     Properties.set(MachineFunctionProperties::Property::NoVRegs);
320 }
321 
322 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
323   auto It = Functions.find(MF.getName());
324   if (It == Functions.end())
325     return error(Twine("no machine function information for function '") +
326                  MF.getName() + "' in the MIR file");
327   // TODO: Recreate the machine function.
328   initNames2RegClasses(MF);
329   initNames2RegBanks(MF);
330   const yaml::MachineFunction &YamlMF = *It->getValue();
331   if (YamlMF.Alignment)
332     MF.setAlignment(YamlMF.Alignment);
333   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
334 
335   if (YamlMF.NoVRegs)
336     MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
337   if (YamlMF.Legalized)
338     MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
339   if (YamlMF.RegBankSelected)
340     MF.getProperties().set(
341         MachineFunctionProperties::Property::RegBankSelected);
342   if (YamlMF.Selected)
343     MF.getProperties().set(MachineFunctionProperties::Property::Selected);
344 
345   PerFunctionMIParsingState PFS(MF, SM, IRSlots, Names2RegClasses,
346                                 Names2RegBanks);
347   if (parseRegisterInfo(PFS, YamlMF))
348     return true;
349   if (!YamlMF.Constants.empty()) {
350     auto *ConstantPool = MF.getConstantPool();
351     assert(ConstantPool && "Constant pool must be created");
352     if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
353       return true;
354   }
355 
356   StringRef BlockStr = YamlMF.Body.Value.Value;
357   SMDiagnostic Error;
358   SourceMgr BlockSM;
359   BlockSM.AddNewSourceBuffer(
360       MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
361       SMLoc());
362   PFS.SM = &BlockSM;
363   if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
364     reportDiagnostic(
365         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
366     return true;
367   }
368   PFS.SM = &SM;
369 
370   // Initialize the frame information after creating all the MBBs so that the
371   // MBB references in the frame information can be resolved.
372   if (initializeFrameInfo(PFS, YamlMF))
373     return true;
374   // Initialize the jump table after creating all the MBBs so that the MBB
375   // references can be resolved.
376   if (!YamlMF.JumpTableInfo.Entries.empty() &&
377       initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
378     return true;
379   // Parse the machine instructions after creating all of the MBBs so that the
380   // parser can resolve the MBB references.
381   StringRef InsnStr = YamlMF.Body.Value.Value;
382   SourceMgr InsnSM;
383   InsnSM.AddNewSourceBuffer(
384       MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
385       SMLoc());
386   PFS.SM = &InsnSM;
387   if (parseMachineInstructions(PFS, InsnStr, Error)) {
388     reportDiagnostic(
389         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
390     return true;
391   }
392   PFS.SM = &SM;
393 
394   if (setupRegisterInfo(PFS, YamlMF))
395     return true;
396 
397   computeFunctionProperties(MF);
398 
399   MF.verify();
400   return false;
401 }
402 
403 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
404                                       const yaml::MachineFunction &YamlMF) {
405   MachineFunction &MF = PFS.MF;
406   MachineRegisterInfo &RegInfo = MF.getRegInfo();
407   assert(RegInfo.tracksLiveness());
408   if (!YamlMF.TracksRegLiveness)
409     RegInfo.invalidateLiveness();
410 
411   SMDiagnostic Error;
412   // Parse the virtual register information.
413   for (const auto &VReg : YamlMF.VirtualRegisters) {
414     VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
415     if (Info.Explicit)
416       return error(VReg.ID.SourceRange.Start,
417                    Twine("redefinition of virtual register '%") +
418                        Twine(VReg.ID.Value) + "'");
419     Info.Explicit = true;
420 
421     if (StringRef(VReg.Class.Value).equals("_")) {
422       Info.Kind = VRegInfo::GENERIC;
423     } else {
424       const auto *RC = getRegClass(MF, VReg.Class.Value);
425       if (RC) {
426         Info.Kind = VRegInfo::NORMAL;
427         Info.D.RC = RC;
428       } else {
429         const RegisterBank *RegBank = getRegBank(MF, VReg.Class.Value);
430         if (!RegBank)
431           return error(
432               VReg.Class.SourceRange.Start,
433               Twine("use of undefined register class or register bank '") +
434                   VReg.Class.Value + "'");
435         Info.Kind = VRegInfo::REGBANK;
436         Info.D.RegBank = RegBank;
437       }
438     }
439 
440     if (!VReg.PreferredRegister.Value.empty()) {
441       if (Info.Kind != VRegInfo::NORMAL)
442         return error(VReg.Class.SourceRange.Start,
443               Twine("preferred register can only be set for normal vregs"));
444 
445       if (parseRegisterReference(PFS, Info.PreferredReg,
446                                  VReg.PreferredRegister.Value, Error))
447         return error(Error, VReg.PreferredRegister.SourceRange);
448     }
449   }
450 
451   // Parse the liveins.
452   for (const auto &LiveIn : YamlMF.LiveIns) {
453     unsigned Reg = 0;
454     if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
455       return error(Error, LiveIn.Register.SourceRange);
456     unsigned VReg = 0;
457     if (!LiveIn.VirtualRegister.Value.empty()) {
458       VRegInfo *Info;
459       if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
460                                         Error))
461         return error(Error, LiveIn.VirtualRegister.SourceRange);
462       VReg = Info->VReg;
463     }
464     RegInfo.addLiveIn(Reg, VReg);
465   }
466 
467   // Parse the callee saved registers (Registers that will
468   // be saved for the caller).
469   if (YamlMF.CalleeSavedRegisters) {
470     SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
471     for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
472       unsigned Reg = 0;
473       if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
474         return error(Error, RegSource.SourceRange);
475       CalleeSavedRegisters.push_back(Reg);
476     }
477     RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
478   }
479 
480   return false;
481 }
482 
483 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
484                                       const yaml::MachineFunction &YamlMF) {
485   MachineFunction &MF = PFS.MF;
486   MachineRegisterInfo &MRI = MF.getRegInfo();
487   bool Error = false;
488   // Create VRegs
489   for (auto P : PFS.VRegInfos) {
490     const VRegInfo &Info = *P.second;
491     unsigned Reg = Info.VReg;
492     switch (Info.Kind) {
493     case VRegInfo::UNKNOWN:
494       error(Twine("Cannot determine class/bank of virtual register ") +
495             Twine(P.first) + " in function '" + MF.getName() + "'");
496       Error = true;
497       break;
498     case VRegInfo::NORMAL:
499       MRI.setRegClass(Reg, Info.D.RC);
500       if (Info.PreferredReg != 0)
501         MRI.setSimpleHint(Reg, Info.PreferredReg);
502       break;
503     case VRegInfo::GENERIC:
504       break;
505     case VRegInfo::REGBANK:
506       MRI.setRegBank(Reg, *Info.D.RegBank);
507       break;
508     }
509   }
510 
511   // Compute MachineRegisterInfo::UsedPhysRegMask
512   for (const MachineBasicBlock &MBB : MF) {
513     for (const MachineInstr &MI : MBB) {
514       for (const MachineOperand &MO : MI.operands()) {
515         if (!MO.isRegMask())
516           continue;
517         MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
518       }
519     }
520   }
521 
522   // FIXME: This is a temporary workaround until the reserved registers can be
523   // serialized.
524   MRI.freezeReservedRegs(MF);
525   return Error;
526 }
527 
528 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
529                                         const yaml::MachineFunction &YamlMF) {
530   MachineFunction &MF = PFS.MF;
531   MachineFrameInfo &MFI = MF.getFrameInfo();
532   const Function &F = *MF.getFunction();
533   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
534   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
535   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
536   MFI.setHasStackMap(YamlMFI.HasStackMap);
537   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
538   MFI.setStackSize(YamlMFI.StackSize);
539   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
540   if (YamlMFI.MaxAlignment)
541     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
542   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
543   MFI.setHasCalls(YamlMFI.HasCalls);
544   MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
545   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
546   MFI.setHasVAStart(YamlMFI.HasVAStart);
547   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
548   if (!YamlMFI.SavePoint.Value.empty()) {
549     MachineBasicBlock *MBB = nullptr;
550     if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
551       return true;
552     MFI.setSavePoint(MBB);
553   }
554   if (!YamlMFI.RestorePoint.Value.empty()) {
555     MachineBasicBlock *MBB = nullptr;
556     if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
557       return true;
558     MFI.setRestorePoint(MBB);
559   }
560 
561   std::vector<CalleeSavedInfo> CSIInfo;
562   // Initialize the fixed frame objects.
563   for (const auto &Object : YamlMF.FixedStackObjects) {
564     int ObjectIdx;
565     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
566       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
567                                         Object.IsImmutable, Object.IsAliased);
568     else
569       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
570     MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
571     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
572                                                          ObjectIdx))
573              .second)
574       return error(Object.ID.SourceRange.Start,
575                    Twine("redefinition of fixed stack object '%fixed-stack.") +
576                        Twine(Object.ID.Value) + "'");
577     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
578                                  ObjectIdx))
579       return true;
580   }
581 
582   // Initialize the ordinary frame objects.
583   for (const auto &Object : YamlMF.StackObjects) {
584     int ObjectIdx;
585     const AllocaInst *Alloca = nullptr;
586     const yaml::StringValue &Name = Object.Name;
587     if (!Name.Value.empty()) {
588       Alloca = dyn_cast_or_null<AllocaInst>(
589           F.getValueSymbolTable()->lookup(Name.Value));
590       if (!Alloca)
591         return error(Name.SourceRange.Start,
592                      "alloca instruction named '" + Name.Value +
593                          "' isn't defined in the function '" + F.getName() +
594                          "'");
595     }
596     if (Object.Type == yaml::MachineStackObject::VariableSized)
597       ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
598     else
599       ObjectIdx = MFI.CreateStackObject(
600           Object.Size, Object.Alignment,
601           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
602     MFI.setObjectOffset(ObjectIdx, Object.Offset);
603     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
604              .second)
605       return error(Object.ID.SourceRange.Start,
606                    Twine("redefinition of stack object '%stack.") +
607                        Twine(Object.ID.Value) + "'");
608     if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
609                                  ObjectIdx))
610       return true;
611     if (Object.LocalOffset)
612       MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
613     if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
614       return true;
615   }
616   MFI.setCalleeSavedInfo(CSIInfo);
617   if (!CSIInfo.empty())
618     MFI.setCalleeSavedInfoValid(true);
619 
620   // Initialize the various stack object references after initializing the
621   // stack objects.
622   if (!YamlMFI.StackProtector.Value.empty()) {
623     SMDiagnostic Error;
624     int FI;
625     if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
626       return error(Error, YamlMFI.StackProtector.SourceRange);
627     MFI.setStackProtectorIndex(FI);
628   }
629   return false;
630 }
631 
632 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
633     std::vector<CalleeSavedInfo> &CSIInfo,
634     const yaml::StringValue &RegisterSource, int FrameIdx) {
635   if (RegisterSource.Value.empty())
636     return false;
637   unsigned Reg = 0;
638   SMDiagnostic Error;
639   if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
640     return error(Error, RegisterSource.SourceRange);
641   CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
642   return false;
643 }
644 
645 /// Verify that given node is of a certain type. Return true on error.
646 template <typename T>
647 static bool typecheckMDNode(T *&Result, MDNode *Node,
648                             const yaml::StringValue &Source,
649                             StringRef TypeString, MIRParserImpl &Parser) {
650   if (!Node)
651     return false;
652   Result = dyn_cast<T>(Node);
653   if (!Result)
654     return Parser.error(Source.SourceRange.Start,
655                         "expected a reference to a '" + TypeString +
656                             "' metadata node");
657   return false;
658 }
659 
660 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
661     const yaml::MachineStackObject &Object, int FrameIdx) {
662   // Debug information can only be attached to stack objects; Fixed stack
663   // objects aren't supported.
664   assert(FrameIdx >= 0 && "Expected a stack object frame index");
665   MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
666   if (parseMDNode(PFS, Var, Object.DebugVar) ||
667       parseMDNode(PFS, Expr, Object.DebugExpr) ||
668       parseMDNode(PFS, Loc, Object.DebugLoc))
669     return true;
670   if (!Var && !Expr && !Loc)
671     return false;
672   DILocalVariable *DIVar = nullptr;
673   DIExpression *DIExpr = nullptr;
674   DILocation *DILoc = nullptr;
675   if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
676       typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
677       typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
678     return true;
679   PFS.MF.setVariableDbgInfo(DIVar, DIExpr, unsigned(FrameIdx), DILoc);
680   return false;
681 }
682 
683 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
684     MDNode *&Node, const yaml::StringValue &Source) {
685   if (Source.Value.empty())
686     return false;
687   SMDiagnostic Error;
688   if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
689     return error(Error, Source.SourceRange);
690   return false;
691 }
692 
693 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
694     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
695   DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
696   const MachineFunction &MF = PFS.MF;
697   const auto &M = *MF.getFunction()->getParent();
698   SMDiagnostic Error;
699   for (const auto &YamlConstant : YamlMF.Constants) {
700     const Constant *Value = dyn_cast_or_null<Constant>(
701         parseConstantValue(YamlConstant.Value.Value, Error, M));
702     if (!Value)
703       return error(Error, YamlConstant.Value.SourceRange);
704     unsigned Alignment =
705         YamlConstant.Alignment
706             ? YamlConstant.Alignment
707             : M.getDataLayout().getPrefTypeAlignment(Value->getType());
708     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
709     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
710              .second)
711       return error(YamlConstant.ID.SourceRange.Start,
712                    Twine("redefinition of constant pool item '%const.") +
713                        Twine(YamlConstant.ID.Value) + "'");
714   }
715   return false;
716 }
717 
718 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
719     const yaml::MachineJumpTable &YamlJTI) {
720   MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
721   for (const auto &Entry : YamlJTI.Entries) {
722     std::vector<MachineBasicBlock *> Blocks;
723     for (const auto &MBBSource : Entry.Blocks) {
724       MachineBasicBlock *MBB = nullptr;
725       if (parseMBBReference(PFS, MBB, MBBSource.Value))
726         return true;
727       Blocks.push_back(MBB);
728     }
729     unsigned Index = JTI->createJumpTableIndex(Blocks);
730     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
731              .second)
732       return error(Entry.ID.SourceRange.Start,
733                    Twine("redefinition of jump table entry '%jump-table.") +
734                        Twine(Entry.ID.Value) + "'");
735   }
736   return false;
737 }
738 
739 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
740                                       MachineBasicBlock *&MBB,
741                                       const yaml::StringValue &Source) {
742   SMDiagnostic Error;
743   if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
744     return error(Error, Source.SourceRange);
745   return false;
746 }
747 
748 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
749                                                  SMRange SourceRange) {
750   assert(SourceRange.isValid() && "Invalid source range");
751   SMLoc Loc = SourceRange.Start;
752   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
753                   *Loc.getPointer() == '\'';
754   // Translate the location of the error from the location in the MI string to
755   // the corresponding location in the MIR file.
756   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
757                            (HasQuote ? 1 : 0));
758 
759   // TODO: Translate any source ranges as well.
760   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
761                        Error.getFixIts());
762 }
763 
764 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
765                                                     SMRange SourceRange) {
766   assert(SourceRange.isValid());
767 
768   // Translate the location of the error from the location in the llvm IR string
769   // to the corresponding location in the MIR file.
770   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
771   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
772   unsigned Column = Error.getColumnNo();
773   StringRef LineStr = Error.getLineContents();
774   SMLoc Loc = Error.getLoc();
775 
776   // Get the full line and adjust the column number by taking the indentation of
777   // LLVM IR into account.
778   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
779        L != E; ++L) {
780     if (L.line_number() == Line) {
781       LineStr = *L;
782       Loc = SMLoc::getFromPointer(LineStr.data());
783       auto Indent = LineStr.find(Error.getLineContents());
784       if (Indent != StringRef::npos)
785         Column += Indent;
786       break;
787     }
788   }
789 
790   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
791                       Error.getMessage(), LineStr, Error.getRanges(),
792                       Error.getFixIts());
793 }
794 
795 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
796   if (!Names2RegClasses.empty())
797     return;
798   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
799   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
800     const auto *RC = TRI->getRegClass(I);
801     Names2RegClasses.insert(
802         std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
803   }
804 }
805 
806 void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) {
807   if (!Names2RegBanks.empty())
808     return;
809   const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
810   // If the target does not support GlobalISel, we may not have a
811   // register bank info.
812   if (!RBI)
813     return;
814   for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
815     const auto &RegBank = RBI->getRegBank(I);
816     Names2RegBanks.insert(
817         std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
818   }
819 }
820 
821 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
822                                                       StringRef Name) {
823   auto RegClassInfo = Names2RegClasses.find(Name);
824   if (RegClassInfo == Names2RegClasses.end())
825     return nullptr;
826   return RegClassInfo->getValue();
827 }
828 
829 const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF,
830                                               StringRef Name) {
831   auto RegBankInfo = Names2RegBanks.find(Name);
832   if (RegBankInfo == Names2RegBanks.end())
833     return nullptr;
834   return RegBankInfo->getValue();
835 }
836 
837 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
838     : Impl(std::move(Impl)) {}
839 
840 MIRParser::~MIRParser() {}
841 
842 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
843 
844 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
845   return Impl->initializeMachineFunction(MF);
846 }
847 
848 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
849                                                          SMDiagnostic &Error,
850                                                          LLVMContext &Context) {
851   auto FileOrErr = MemoryBuffer::getFile(Filename);
852   if (std::error_code EC = FileOrErr.getError()) {
853     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
854                          "Could not open input file: " + EC.message());
855     return nullptr;
856   }
857   return createMIRParser(std::move(FileOrErr.get()), Context);
858 }
859 
860 std::unique_ptr<MIRParser>
861 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
862                       LLVMContext &Context) {
863   auto Filename = Contents->getBufferIdentifier();
864   if (Context.shouldDiscardValueNames()) {
865     Context.diagnose(DiagnosticInfoMIRParser(
866         DS_Error,
867         SMDiagnostic(
868             Filename, SourceMgr::DK_Error,
869             "Can't read MIR with a Context that discards named Values")));
870     return nullptr;
871   }
872   return llvm::make_unique<MIRParser>(
873       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
874 }
875