a9cbbc390d795edf1f41fa53b47fb2d29409d4bb
[oota-llvm.git] / lib / CodeGen / MIRParser / MIRParser.cpp
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/StringRef.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/MIRYamlMapping.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueSymbolTable.h"
34 #include "llvm/Support/LineIterator.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/YAMLTraits.h"
39 #include <memory>
40
41 using namespace llvm;
42
43 namespace llvm {
44
45 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
46 /// file.
47 class MIRParserImpl {
48   SourceMgr SM;
49   StringRef Filename;
50   LLVMContext &Context;
51   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
52   SlotMapping IRSlots;
53   /// Maps from register class names to register classes.
54   StringMap<const TargetRegisterClass *> Names2RegClasses;
55
56 public:
57   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58                 LLVMContext &Context);
59
60   void reportDiagnostic(const SMDiagnostic &Diag);
61
62   /// Report an error with the given message at unknown location.
63   ///
64   /// Always returns true.
65   bool error(const Twine &Message);
66
67   /// Report an error with the given message at the given location.
68   ///
69   /// Always returns true.
70   bool error(SMLoc Loc, const Twine &Message);
71
72   /// Report a given error with the location translated from the location in an
73   /// embedded string literal to a location in the MIR file.
74   ///
75   /// Always returns true.
76   bool error(const SMDiagnostic &Error, SMRange SourceRange);
77
78   /// Try to parse the optional LLVM module and the machine functions in the MIR
79   /// file.
80   ///
81   /// Return null if an error occurred.
82   std::unique_ptr<Module> parse();
83
84   /// Parse the machine function in the current YAML document.
85   ///
86   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
87   /// A dummy IR function is created and inserted into the given module when
88   /// this parameter is true.
89   ///
90   /// Return true if an error occurred.
91   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
92
93   /// Initialize the machine function to the state that's described in the MIR
94   /// file.
95   ///
96   /// Return true if error occurred.
97   bool initializeMachineFunction(MachineFunction &MF);
98
99   /// Initialize the machine basic block using it's YAML representation.
100   ///
101   /// Return true if an error occurred.
102   bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
103                                    const yaml::MachineBasicBlock &YamlMBB,
104                                    const PerFunctionMIParsingState &PFS);
105
106   bool initializeRegisterInfo(MachineFunction &MF,
107                               const yaml::MachineFunction &YamlMF,
108                               PerFunctionMIParsingState &PFS);
109
110   void inferRegisterInfo(MachineFunction &MF,
111                          const yaml::MachineFunction &YamlMF);
112
113   bool initializeFrameInfo(MachineFunction &MF,
114                            const yaml::MachineFunction &YamlMF,
115                            PerFunctionMIParsingState &PFS);
116
117   bool parseCalleeSavedRegister(MachineFunction &MF,
118                                 PerFunctionMIParsingState &PFS,
119                                 std::vector<CalleeSavedInfo> &CSIInfo,
120                                 const yaml::StringValue &RegisterSource,
121                                 int FrameIdx);
122
123   bool initializeConstantPool(MachineConstantPool &ConstantPool,
124                               const yaml::MachineFunction &YamlMF,
125                               const MachineFunction &MF,
126                               DenseMap<unsigned, unsigned> &ConstantPoolSlots);
127
128   bool initializeJumpTableInfo(MachineFunction &MF,
129                                const yaml::MachineJumpTable &YamlJTI,
130                                PerFunctionMIParsingState &PFS);
131
132 private:
133   bool parseMBBReference(MachineBasicBlock *&MBB,
134                          const yaml::StringValue &Source, MachineFunction &MF,
135                          const PerFunctionMIParsingState &PFS);
136
137   /// Return a MIR diagnostic converted from an MI string diagnostic.
138   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
139                                     SMRange SourceRange);
140
141   /// Return a MIR diagnostic converted from a diagnostic located in a YAML
142   /// block scalar string.
143   SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
144                                        SMRange SourceRange);
145
146   /// Create an empty function with the given name.
147   void createDummyFunction(StringRef Name, Module &M);
148
149   void initNames2RegClasses(const MachineFunction &MF);
150
151   /// Check if the given identifier is a name of a register class.
152   ///
153   /// Return null if the name isn't a register class.
154   const TargetRegisterClass *getRegClass(const MachineFunction &MF,
155                                          StringRef Name);
156 };
157
158 } // end namespace llvm
159
160 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
161                              StringRef Filename, LLVMContext &Context)
162     : SM(), Filename(Filename), Context(Context) {
163   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
164 }
165
166 bool MIRParserImpl::error(const Twine &Message) {
167   Context.diagnose(DiagnosticInfoMIRParser(
168       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
169   return true;
170 }
171
172 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
173   Context.diagnose(DiagnosticInfoMIRParser(
174       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
175   return true;
176 }
177
178 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
179   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
180   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
181   return true;
182 }
183
184 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
185   DiagnosticSeverity Kind;
186   switch (Diag.getKind()) {
187   case SourceMgr::DK_Error:
188     Kind = DS_Error;
189     break;
190   case SourceMgr::DK_Warning:
191     Kind = DS_Warning;
192     break;
193   case SourceMgr::DK_Note:
194     Kind = DS_Note;
195     break;
196   }
197   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
198 }
199
200 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
201   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
202 }
203
204 std::unique_ptr<Module> MIRParserImpl::parse() {
205   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
206                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
207   In.setContext(&In);
208
209   if (!In.setCurrentDocument()) {
210     if (In.error())
211       return nullptr;
212     // Create an empty module when the MIR file is empty.
213     return llvm::make_unique<Module>(Filename, Context);
214   }
215
216   std::unique_ptr<Module> M;
217   bool NoLLVMIR = false;
218   // Parse the block scalar manually so that we can return unique pointer
219   // without having to go trough YAML traits.
220   if (const auto *BSN =
221           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
222     SMDiagnostic Error;
223     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
224                       Context, &IRSlots);
225     if (!M) {
226       reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
227       return M;
228     }
229     In.nextDocument();
230     if (!In.setCurrentDocument())
231       return M;
232   } else {
233     // Create an new, empty module.
234     M = llvm::make_unique<Module>(Filename, Context);
235     NoLLVMIR = true;
236   }
237
238   // Parse the machine functions.
239   do {
240     if (parseMachineFunction(In, *M, NoLLVMIR))
241       return nullptr;
242     In.nextDocument();
243   } while (In.setCurrentDocument());
244
245   return M;
246 }
247
248 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
249                                          bool NoLLVMIR) {
250   auto MF = llvm::make_unique<yaml::MachineFunction>();
251   yaml::yamlize(In, *MF, false);
252   if (In.error())
253     return true;
254   auto FunctionName = MF->Name;
255   if (Functions.find(FunctionName) != Functions.end())
256     return error(Twine("redefinition of machine function '") + FunctionName +
257                  "'");
258   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
259   if (NoLLVMIR)
260     createDummyFunction(FunctionName, M);
261   else if (!M.getFunction(FunctionName))
262     return error(Twine("function '") + FunctionName +
263                  "' isn't defined in the provided LLVM IR");
264   return false;
265 }
266
267 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
268   auto &Context = M.getContext();
269   Function *F = cast<Function>(M.getOrInsertFunction(
270       Name, FunctionType::get(Type::getVoidTy(Context), false)));
271   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
272   new UnreachableInst(Context, BB);
273 }
274
275 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
276   auto It = Functions.find(MF.getName());
277   if (It == Functions.end())
278     return error(Twine("no machine function information for function '") +
279                  MF.getName() + "' in the MIR file");
280   // TODO: Recreate the machine function.
281   const yaml::MachineFunction &YamlMF = *It->getValue();
282   if (YamlMF.Alignment)
283     MF.setAlignment(YamlMF.Alignment);
284   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
285   MF.setHasInlineAsm(YamlMF.HasInlineAsm);
286   PerFunctionMIParsingState PFS;
287   if (initializeRegisterInfo(MF, YamlMF, PFS))
288     return true;
289   if (!YamlMF.Constants.empty()) {
290     auto *ConstantPool = MF.getConstantPool();
291     assert(ConstantPool && "Constant pool must be created");
292     if (initializeConstantPool(*ConstantPool, YamlMF, MF,
293                                PFS.ConstantPoolSlots))
294       return true;
295   }
296
297   const auto &F = *MF.getFunction();
298   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
299     const BasicBlock *BB = nullptr;
300     const yaml::StringValue &Name = YamlMBB.Name;
301     const yaml::StringValue &IRBlock = YamlMBB.IRBlock;
302     if (!Name.Value.empty()) {
303       BB = dyn_cast_or_null<BasicBlock>(
304           F.getValueSymbolTable().lookup(Name.Value));
305       if (!BB)
306         return error(Name.SourceRange.Start,
307                      Twine("basic block '") + Name.Value +
308                          "' is not defined in the function '" + MF.getName() +
309                          "'");
310     }
311     if (!IRBlock.Value.empty()) {
312       // TODO: Report an error when both name and ir block are specified.
313       SMDiagnostic Error;
314       if (parseIRBlockReference(BB, SM, MF, IRBlock.Value, PFS, IRSlots, Error))
315         return error(Error, IRBlock.SourceRange);
316     }
317     auto *MBB = MF.CreateMachineBasicBlock(BB);
318     MF.insert(MF.end(), MBB);
319     bool WasInserted =
320         PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
321     if (!WasInserted)
322       return error(Twine("redefinition of machine basic block with id #") +
323                    Twine(YamlMBB.ID));
324   }
325
326   if (YamlMF.BasicBlocks.empty())
327     return error(Twine("machine function '") + Twine(MF.getName()) +
328                  "' requires at least one machine basic block in its body");
329   // Initialize the frame information after creating all the MBBs so that the
330   // MBB references in the frame information can be resolved.
331   if (initializeFrameInfo(MF, YamlMF, PFS))
332     return true;
333   // Initialize the jump table after creating all the MBBs so that the MBB
334   // references can be resolved.
335   if (!YamlMF.JumpTableInfo.Entries.empty() &&
336       initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
337     return true;
338   // Initialize the machine basic blocks after creating them all so that the
339   // machine instructions parser can resolve the MBB references.
340   unsigned I = 0;
341   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
342     if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
343                                     PFS))
344       return true;
345   }
346   inferRegisterInfo(MF, YamlMF);
347   // FIXME: This is a temporary workaround until the reserved registers can be
348   // serialized.
349   MF.getRegInfo().freezeReservedRegs(MF);
350   MF.verify();
351   return false;
352 }
353
354 bool MIRParserImpl::initializeMachineBasicBlock(
355     MachineFunction &MF, MachineBasicBlock &MBB,
356     const yaml::MachineBasicBlock &YamlMBB,
357     const PerFunctionMIParsingState &PFS) {
358   MBB.setAlignment(YamlMBB.Alignment);
359   if (YamlMBB.AddressTaken)
360     MBB.setHasAddressTaken();
361   MBB.setIsLandingPad(YamlMBB.IsLandingPad);
362   SMDiagnostic Error;
363   // Parse the successors.
364   const auto &Weights = YamlMBB.SuccessorWeights;
365   bool HasWeights = !Weights.empty();
366   if (HasWeights && Weights.size() != YamlMBB.Successors.size()) {
367     bool IsFew = Weights.size() < YamlMBB.Successors.size();
368     return error(IsFew ? Weights.back().SourceRange.End
369                        : Weights[YamlMBB.Successors.size()].SourceRange.Start,
370                  Twine("too ") + (IsFew ? "few" : "many") +
371                      " successor weights, expected " +
372                      Twine(YamlMBB.Successors.size()) + ", have " +
373                      Twine(Weights.size()));
374   }
375   size_t SuccessorIndex = 0;
376   for (const auto &MBBSource : YamlMBB.Successors) {
377     MachineBasicBlock *SuccMBB = nullptr;
378     if (parseMBBReference(SuccMBB, MBBSource, MF, PFS))
379       return true;
380     // TODO: Report an error when adding the same successor more than once.
381     MBB.addSuccessor(SuccMBB, HasWeights ? Weights[SuccessorIndex++].Value : 0);
382   }
383   // Parse the liveins.
384   for (const auto &LiveInSource : YamlMBB.LiveIns) {
385     unsigned Reg = 0;
386     if (parseNamedRegisterReference(Reg, SM, MF, LiveInSource.Value, PFS,
387                                     IRSlots, Error))
388       return error(Error, LiveInSource.SourceRange);
389     MBB.addLiveIn(Reg);
390   }
391   // Parse the instructions.
392   for (const auto &MISource : YamlMBB.Instructions) {
393     MachineInstr *MI = nullptr;
394     if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
395       return error(Error, MISource.SourceRange);
396     MBB.insert(MBB.end(), MI);
397   }
398   return false;
399 }
400
401 bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
402                                            const yaml::MachineFunction &YamlMF,
403                                            PerFunctionMIParsingState &PFS) {
404   MachineRegisterInfo &RegInfo = MF.getRegInfo();
405   assert(RegInfo.isSSA());
406   if (!YamlMF.IsSSA)
407     RegInfo.leaveSSA();
408   assert(RegInfo.tracksLiveness());
409   if (!YamlMF.TracksRegLiveness)
410     RegInfo.invalidateLiveness();
411   RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
412
413   SMDiagnostic Error;
414   // Parse the virtual register information.
415   for (const auto &VReg : YamlMF.VirtualRegisters) {
416     const auto *RC = getRegClass(MF, VReg.Class.Value);
417     if (!RC)
418       return error(VReg.Class.SourceRange.Start,
419                    Twine("use of undefined register class '") +
420                        VReg.Class.Value + "'");
421     unsigned Reg = RegInfo.createVirtualRegister(RC);
422     if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
423              .second)
424       return error(VReg.ID.SourceRange.Start,
425                    Twine("redefinition of virtual register '%") +
426                        Twine(VReg.ID.Value) + "'");
427     if (!VReg.PreferredRegister.Value.empty()) {
428       unsigned PreferredReg = 0;
429       if (parseNamedRegisterReference(PreferredReg, SM, MF,
430                                       VReg.PreferredRegister.Value, PFS,
431                                       IRSlots, Error))
432         return error(Error, VReg.PreferredRegister.SourceRange);
433       RegInfo.setSimpleHint(Reg, PreferredReg);
434     }
435   }
436
437   // Parse the liveins.
438   for (const auto &LiveIn : YamlMF.LiveIns) {
439     unsigned Reg = 0;
440     if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
441                                     IRSlots, Error))
442       return error(Error, LiveIn.Register.SourceRange);
443     unsigned VReg = 0;
444     if (!LiveIn.VirtualRegister.Value.empty()) {
445       if (parseVirtualRegisterReference(
446               VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
447         return error(Error, LiveIn.VirtualRegister.SourceRange);
448     }
449     RegInfo.addLiveIn(Reg, VReg);
450   }
451
452   // Parse the callee saved register mask.
453   BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
454   if (!YamlMF.CalleeSavedRegisters)
455     return false;
456   for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
457     unsigned Reg = 0;
458     if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
459                                     Error))
460       return error(Error, RegSource.SourceRange);
461     CalleeSavedRegisterMask[Reg] = true;
462   }
463   RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
464   return false;
465 }
466
467 void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
468                                       const yaml::MachineFunction &YamlMF) {
469   if (YamlMF.CalleeSavedRegisters)
470     return;
471   for (const MachineBasicBlock &MBB : MF) {
472     for (const MachineInstr &MI : MBB) {
473       for (const MachineOperand &MO : MI.operands()) {
474         if (!MO.isRegMask())
475           continue;
476         MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
477       }
478     }
479   }
480 }
481
482 bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
483                                         const yaml::MachineFunction &YamlMF,
484                                         PerFunctionMIParsingState &PFS) {
485   MachineFrameInfo &MFI = *MF.getFrameInfo();
486   const Function &F = *MF.getFunction();
487   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
488   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
489   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
490   MFI.setHasStackMap(YamlMFI.HasStackMap);
491   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
492   MFI.setStackSize(YamlMFI.StackSize);
493   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
494   if (YamlMFI.MaxAlignment)
495     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
496   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
497   MFI.setHasCalls(YamlMFI.HasCalls);
498   MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
499   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
500   MFI.setHasVAStart(YamlMFI.HasVAStart);
501   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
502   if (!YamlMFI.SavePoint.Value.empty()) {
503     MachineBasicBlock *MBB = nullptr;
504     if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
505       return true;
506     MFI.setSavePoint(MBB);
507   }
508   if (!YamlMFI.RestorePoint.Value.empty()) {
509     MachineBasicBlock *MBB = nullptr;
510     if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
511       return true;
512     MFI.setRestorePoint(MBB);
513   }
514
515   std::vector<CalleeSavedInfo> CSIInfo;
516   // Initialize the fixed frame objects.
517   for (const auto &Object : YamlMF.FixedStackObjects) {
518     int ObjectIdx;
519     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
520       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
521                                         Object.IsImmutable, Object.IsAliased);
522     else
523       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
524     MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
525     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
526                                                          ObjectIdx))
527              .second)
528       return error(Object.ID.SourceRange.Start,
529                    Twine("redefinition of fixed stack object '%fixed-stack.") +
530                        Twine(Object.ID.Value) + "'");
531     if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
532                                  ObjectIdx))
533       return true;
534   }
535
536   // Initialize the ordinary frame objects.
537   for (const auto &Object : YamlMF.StackObjects) {
538     int ObjectIdx;
539     const AllocaInst *Alloca = nullptr;
540     const yaml::StringValue &Name = Object.Name;
541     if (!Name.Value.empty()) {
542       Alloca = dyn_cast_or_null<AllocaInst>(
543           F.getValueSymbolTable().lookup(Name.Value));
544       if (!Alloca)
545         return error(Name.SourceRange.Start,
546                      "alloca instruction named '" + Name.Value +
547                          "' isn't defined in the function '" + F.getName() +
548                          "'");
549     }
550     if (Object.Type == yaml::MachineStackObject::VariableSized)
551       ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
552     else
553       ObjectIdx = MFI.CreateStackObject(
554           Object.Size, Object.Alignment,
555           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
556     MFI.setObjectOffset(ObjectIdx, Object.Offset);
557     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
558              .second)
559       return error(Object.ID.SourceRange.Start,
560                    Twine("redefinition of stack object '%stack.") +
561                        Twine(Object.ID.Value) + "'");
562     if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
563                                  ObjectIdx))
564       return true;
565   }
566   MFI.setCalleeSavedInfo(CSIInfo);
567   if (!CSIInfo.empty())
568     MFI.setCalleeSavedInfoValid(true);
569   return false;
570 }
571
572 bool MIRParserImpl::parseCalleeSavedRegister(
573     MachineFunction &MF, PerFunctionMIParsingState &PFS,
574     std::vector<CalleeSavedInfo> &CSIInfo,
575     const yaml::StringValue &RegisterSource, int FrameIdx) {
576   if (RegisterSource.Value.empty())
577     return false;
578   unsigned Reg = 0;
579   SMDiagnostic Error;
580   if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
581                                   IRSlots, Error))
582     return error(Error, RegisterSource.SourceRange);
583   CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
584   return false;
585 }
586
587 bool MIRParserImpl::initializeConstantPool(
588     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
589     const MachineFunction &MF,
590     DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
591   const auto &M = *MF.getFunction()->getParent();
592   SMDiagnostic Error;
593   for (const auto &YamlConstant : YamlMF.Constants) {
594     const Constant *Value = dyn_cast_or_null<Constant>(
595         parseConstantValue(YamlConstant.Value.Value, Error, M));
596     if (!Value)
597       return error(Error, YamlConstant.Value.SourceRange);
598     unsigned Alignment =
599         YamlConstant.Alignment
600             ? YamlConstant.Alignment
601             : M.getDataLayout().getPrefTypeAlignment(Value->getType());
602     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
603     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
604              .second)
605       return error(YamlConstant.ID.SourceRange.Start,
606                    Twine("redefinition of constant pool item '%const.") +
607                        Twine(YamlConstant.ID.Value) + "'");
608   }
609   return false;
610 }
611
612 bool MIRParserImpl::initializeJumpTableInfo(
613     MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
614     PerFunctionMIParsingState &PFS) {
615   MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
616   for (const auto &Entry : YamlJTI.Entries) {
617     std::vector<MachineBasicBlock *> Blocks;
618     for (const auto &MBBSource : Entry.Blocks) {
619       MachineBasicBlock *MBB = nullptr;
620       if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
621         return true;
622       Blocks.push_back(MBB);
623     }
624     unsigned Index = JTI->createJumpTableIndex(Blocks);
625     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
626              .second)
627       return error(Entry.ID.SourceRange.Start,
628                    Twine("redefinition of jump table entry '%jump-table.") +
629                        Twine(Entry.ID.Value) + "'");
630   }
631   return false;
632 }
633
634 bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
635                                       const yaml::StringValue &Source,
636                                       MachineFunction &MF,
637                                       const PerFunctionMIParsingState &PFS) {
638   SMDiagnostic Error;
639   if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
640     return error(Error, Source.SourceRange);
641   return false;
642 }
643
644 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
645                                                  SMRange SourceRange) {
646   assert(SourceRange.isValid() && "Invalid source range");
647   SMLoc Loc = SourceRange.Start;
648   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
649                   *Loc.getPointer() == '\'';
650   // Translate the location of the error from the location in the MI string to
651   // the corresponding location in the MIR file.
652   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
653                            (HasQuote ? 1 : 0));
654
655   // TODO: Translate any source ranges as well.
656   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
657                        Error.getFixIts());
658 }
659
660 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
661                                                     SMRange SourceRange) {
662   assert(SourceRange.isValid());
663
664   // Translate the location of the error from the location in the llvm IR string
665   // to the corresponding location in the MIR file.
666   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
667   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
668   unsigned Column = Error.getColumnNo();
669   StringRef LineStr = Error.getLineContents();
670   SMLoc Loc = Error.getLoc();
671
672   // Get the full line and adjust the column number by taking the indentation of
673   // LLVM IR into account.
674   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
675        L != E; ++L) {
676     if (L.line_number() == Line) {
677       LineStr = *L;
678       Loc = SMLoc::getFromPointer(LineStr.data());
679       auto Indent = LineStr.find(Error.getLineContents());
680       if (Indent != StringRef::npos)
681         Column += Indent;
682       break;
683     }
684   }
685
686   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
687                       Error.getMessage(), LineStr, Error.getRanges(),
688                       Error.getFixIts());
689 }
690
691 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
692   if (!Names2RegClasses.empty())
693     return;
694   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
695   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
696     const auto *RC = TRI->getRegClass(I);
697     Names2RegClasses.insert(
698         std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
699   }
700 }
701
702 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
703                                                       StringRef Name) {
704   initNames2RegClasses(MF);
705   auto RegClassInfo = Names2RegClasses.find(Name);
706   if (RegClassInfo == Names2RegClasses.end())
707     return nullptr;
708   return RegClassInfo->getValue();
709 }
710
711 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
712     : Impl(std::move(Impl)) {}
713
714 MIRParser::~MIRParser() {}
715
716 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
717
718 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
719   return Impl->initializeMachineFunction(MF);
720 }
721
722 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
723                                                          SMDiagnostic &Error,
724                                                          LLVMContext &Context) {
725   auto FileOrErr = MemoryBuffer::getFile(Filename);
726   if (std::error_code EC = FileOrErr.getError()) {
727     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
728                          "Could not open input file: " + EC.message());
729     return nullptr;
730   }
731   return createMIRParser(std::move(FileOrErr.get()), Context);
732 }
733
734 std::unique_ptr<MIRParser>
735 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
736                       LLVMContext &Context) {
737   auto Filename = Contents->getBufferIdentifier();
738   return llvm::make_unique<MIRParser>(
739       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
740 }