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