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