1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MIRParser/MIRParser.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"
45 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
51 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
53 /// Maps from register class names to register classes.
54 StringMap<const TargetRegisterClass *> Names2RegClasses;
57 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58 LLVMContext &Context);
60 void reportDiagnostic(const SMDiagnostic &Diag);
62 /// Report an error with the given message at unknown location.
64 /// Always returns true.
65 bool error(const Twine &Message);
67 /// Report an error with the given message at the given location.
69 /// Always returns true.
70 bool error(SMLoc Loc, const Twine &Message);
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.
75 /// Always returns true.
76 bool error(const SMDiagnostic &Error, SMRange SourceRange);
78 /// Try to parse the optional LLVM module and the machine functions in the MIR
81 /// Return null if an error occurred.
82 std::unique_ptr<Module> parse();
84 /// Parse the machine function in the current YAML document.
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.
90 /// Return true if an error occurred.
91 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
93 /// Initialize the machine function to the state that's described in the MIR
96 /// Return true if error occurred.
97 bool initializeMachineFunction(MachineFunction &MF);
99 /// Initialize the machine basic block using it's YAML representation.
101 /// Return true if an error occurred.
102 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
103 const yaml::MachineBasicBlock &YamlMBB,
104 const PerFunctionMIParsingState &PFS);
106 bool initializeRegisterInfo(MachineFunction &MF,
107 const yaml::MachineFunction &YamlMF,
108 PerFunctionMIParsingState &PFS);
110 bool initializeFrameInfo(MachineFunction &MF,
111 const yaml::MachineFunction &YamlMF,
112 PerFunctionMIParsingState &PFS);
114 bool parseCalleeSavedRegister(MachineFunction &MF,
115 PerFunctionMIParsingState &PFS,
116 std::vector<CalleeSavedInfo> &CSIInfo,
117 const yaml::StringValue &RegisterSource,
120 bool initializeConstantPool(MachineConstantPool &ConstantPool,
121 const yaml::MachineFunction &YamlMF,
122 const MachineFunction &MF,
123 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
125 bool initializeJumpTableInfo(MachineFunction &MF,
126 const yaml::MachineJumpTable &YamlJTI,
127 PerFunctionMIParsingState &PFS);
130 bool parseMBBReference(MachineBasicBlock *&MBB,
131 const yaml::StringValue &Source, MachineFunction &MF,
132 const PerFunctionMIParsingState &PFS);
134 /// Return a MIR diagnostic converted from an MI string diagnostic.
135 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
136 SMRange SourceRange);
138 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
139 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
140 SMRange SourceRange);
142 /// Create an empty function with the given name.
143 void createDummyFunction(StringRef Name, Module &M);
145 void initNames2RegClasses(const MachineFunction &MF);
147 /// Check if the given identifier is a name of a register class.
149 /// Return null if the name isn't a register class.
150 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
154 } // end namespace llvm
156 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
157 StringRef Filename, LLVMContext &Context)
158 : SM(), Filename(Filename), Context(Context) {
159 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
162 bool MIRParserImpl::error(const Twine &Message) {
163 Context.diagnose(DiagnosticInfoMIRParser(
164 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
168 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
169 Context.diagnose(DiagnosticInfoMIRParser(
170 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
174 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
175 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
176 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
180 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
181 DiagnosticSeverity Kind;
182 switch (Diag.getKind()) {
183 case SourceMgr::DK_Error:
186 case SourceMgr::DK_Warning:
189 case SourceMgr::DK_Note:
193 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
196 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
197 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
200 std::unique_ptr<Module> MIRParserImpl::parse() {
201 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
202 /*Ctxt=*/nullptr, handleYAMLDiag, this);
205 if (!In.setCurrentDocument()) {
208 // Create an empty module when the MIR file is empty.
209 return llvm::make_unique<Module>(Filename, Context);
212 std::unique_ptr<Module> M;
213 bool NoLLVMIR = false;
214 // Parse the block scalar manually so that we can return unique pointer
215 // without having to go trough YAML traits.
216 if (const auto *BSN =
217 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
219 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
222 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
226 if (!In.setCurrentDocument())
229 // Create an new, empty module.
230 M = llvm::make_unique<Module>(Filename, Context);
234 // Parse the machine functions.
236 if (parseMachineFunction(In, *M, NoLLVMIR))
239 } while (In.setCurrentDocument());
244 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
246 auto MF = llvm::make_unique<yaml::MachineFunction>();
247 yaml::yamlize(In, *MF, false);
250 auto FunctionName = MF->Name;
251 if (Functions.find(FunctionName) != Functions.end())
252 return error(Twine("redefinition of machine function '") + FunctionName +
254 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
256 createDummyFunction(FunctionName, M);
257 else if (!M.getFunction(FunctionName))
258 return error(Twine("function '") + FunctionName +
259 "' isn't defined in the provided LLVM IR");
263 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
264 auto &Context = M.getContext();
265 Function *F = cast<Function>(M.getOrInsertFunction(
266 Name, FunctionType::get(Type::getVoidTy(Context), false)));
267 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
268 new UnreachableInst(Context, BB);
271 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
272 auto It = Functions.find(MF.getName());
273 if (It == Functions.end())
274 return error(Twine("no machine function information for function '") +
275 MF.getName() + "' in the MIR file");
276 // TODO: Recreate the machine function.
277 const yaml::MachineFunction &YamlMF = *It->getValue();
278 if (YamlMF.Alignment)
279 MF.setAlignment(YamlMF.Alignment);
280 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
281 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
282 PerFunctionMIParsingState PFS;
283 if (initializeRegisterInfo(MF, YamlMF, PFS))
285 if (!YamlMF.Constants.empty()) {
286 auto *ConstantPool = MF.getConstantPool();
287 assert(ConstantPool && "Constant pool must be created");
288 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
289 PFS.ConstantPoolSlots))
293 const auto &F = *MF.getFunction();
294 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
295 const BasicBlock *BB = nullptr;
296 const yaml::StringValue &Name = YamlMBB.Name;
297 const yaml::StringValue &IRBlock = YamlMBB.IRBlock;
298 if (!Name.Value.empty()) {
299 BB = dyn_cast_or_null<BasicBlock>(
300 F.getValueSymbolTable().lookup(Name.Value));
302 return error(Name.SourceRange.Start,
303 Twine("basic block '") + Name.Value +
304 "' is not defined in the function '" + MF.getName() +
307 if (!IRBlock.Value.empty()) {
308 // TODO: Report an error when both name and ir block are specified.
310 if (parseIRBlockReference(BB, SM, MF, IRBlock.Value, PFS, IRSlots, Error))
311 return error(Error, IRBlock.SourceRange);
313 auto *MBB = MF.CreateMachineBasicBlock(BB);
314 MF.insert(MF.end(), MBB);
316 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
318 return error(Twine("redefinition of machine basic block with id #") +
322 if (YamlMF.BasicBlocks.empty())
323 return error(Twine("machine function '") + Twine(MF.getName()) +
324 "' requires at least one machine basic block in its body");
325 // Initialize the frame information after creating all the MBBs so that the
326 // MBB references in the frame information can be resolved.
327 if (initializeFrameInfo(MF, YamlMF, PFS))
329 // Initialize the jump table after creating all the MBBs so that the MBB
330 // references can be resolved.
331 if (!YamlMF.JumpTableInfo.Entries.empty() &&
332 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
334 // Initialize the machine basic blocks after creating them all so that the
335 // machine instructions parser can resolve the MBB references.
337 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
338 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
342 // FIXME: This is a temporary workaround until the reserved registers can be
344 MF.getRegInfo().freezeReservedRegs(MF);
349 bool MIRParserImpl::initializeMachineBasicBlock(
350 MachineFunction &MF, MachineBasicBlock &MBB,
351 const yaml::MachineBasicBlock &YamlMBB,
352 const PerFunctionMIParsingState &PFS) {
353 MBB.setAlignment(YamlMBB.Alignment);
354 if (YamlMBB.AddressTaken)
355 MBB.setHasAddressTaken();
356 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
358 // Parse the successors.
359 const auto &Weights = YamlMBB.SuccessorWeights;
360 bool HasWeights = !Weights.empty();
361 if (HasWeights && Weights.size() != YamlMBB.Successors.size()) {
362 bool IsFew = Weights.size() < YamlMBB.Successors.size();
363 return error(IsFew ? Weights.back().SourceRange.End
364 : Weights[YamlMBB.Successors.size()].SourceRange.Start,
365 Twine("too ") + (IsFew ? "few" : "many") +
366 " successor weights, expected " +
367 Twine(YamlMBB.Successors.size()) + ", have " +
368 Twine(Weights.size()));
370 size_t SuccessorIndex = 0;
371 for (const auto &MBBSource : YamlMBB.Successors) {
372 MachineBasicBlock *SuccMBB = nullptr;
373 if (parseMBBReference(SuccMBB, MBBSource, MF, PFS))
375 // TODO: Report an error when adding the same successor more than once.
376 MBB.addSuccessor(SuccMBB, HasWeights ? Weights[SuccessorIndex++].Value : 0);
378 // Parse the liveins.
379 for (const auto &LiveInSource : YamlMBB.LiveIns) {
381 if (parseNamedRegisterReference(Reg, SM, MF, LiveInSource.Value, PFS,
383 return error(Error, LiveInSource.SourceRange);
386 // Parse the instructions.
387 for (const auto &MISource : YamlMBB.Instructions) {
388 MachineInstr *MI = nullptr;
389 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
390 return error(Error, MISource.SourceRange);
391 MBB.insert(MBB.end(), MI);
396 bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
397 const yaml::MachineFunction &YamlMF,
398 PerFunctionMIParsingState &PFS) {
399 MachineRegisterInfo &RegInfo = MF.getRegInfo();
400 assert(RegInfo.isSSA());
403 assert(RegInfo.tracksLiveness());
404 if (!YamlMF.TracksRegLiveness)
405 RegInfo.invalidateLiveness();
406 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
409 // Parse the virtual register information.
410 for (const auto &VReg : YamlMF.VirtualRegisters) {
411 const auto *RC = getRegClass(MF, VReg.Class.Value);
413 return error(VReg.Class.SourceRange.Start,
414 Twine("use of undefined register class '") +
415 VReg.Class.Value + "'");
416 unsigned Reg = RegInfo.createVirtualRegister(RC);
417 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
419 return error(VReg.ID.SourceRange.Start,
420 Twine("redefinition of virtual register '%") +
421 Twine(VReg.ID.Value) + "'");
422 if (!VReg.PreferredRegister.Value.empty()) {
423 unsigned PreferredReg = 0;
424 if (parseNamedRegisterReference(PreferredReg, SM, MF,
425 VReg.PreferredRegister.Value, PFS,
427 return error(Error, VReg.PreferredRegister.SourceRange);
428 RegInfo.setSimpleHint(Reg, PreferredReg);
432 // Parse the liveins.
433 for (const auto &LiveIn : YamlMF.LiveIns) {
435 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
437 return error(Error, LiveIn.Register.SourceRange);
439 if (!LiveIn.VirtualRegister.Value.empty()) {
440 if (parseVirtualRegisterReference(
441 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
442 return error(Error, LiveIn.VirtualRegister.SourceRange);
444 RegInfo.addLiveIn(Reg, VReg);
449 bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
450 const yaml::MachineFunction &YamlMF,
451 PerFunctionMIParsingState &PFS) {
452 MachineFrameInfo &MFI = *MF.getFrameInfo();
453 const Function &F = *MF.getFunction();
454 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
455 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
456 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
457 MFI.setHasStackMap(YamlMFI.HasStackMap);
458 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
459 MFI.setStackSize(YamlMFI.StackSize);
460 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
461 if (YamlMFI.MaxAlignment)
462 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
463 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
464 MFI.setHasCalls(YamlMFI.HasCalls);
465 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
466 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
467 MFI.setHasVAStart(YamlMFI.HasVAStart);
468 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
469 if (!YamlMFI.SavePoint.Value.empty()) {
470 MachineBasicBlock *MBB = nullptr;
471 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
473 MFI.setSavePoint(MBB);
475 if (!YamlMFI.RestorePoint.Value.empty()) {
476 MachineBasicBlock *MBB = nullptr;
477 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
479 MFI.setRestorePoint(MBB);
482 std::vector<CalleeSavedInfo> CSIInfo;
483 // Initialize the fixed frame objects.
484 for (const auto &Object : YamlMF.FixedStackObjects) {
486 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
487 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
488 Object.IsImmutable, Object.IsAliased);
490 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
491 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
492 // TODO: Report an error when objects are redefined.
493 PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID, ObjectIdx));
494 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
499 // Initialize the ordinary frame objects.
500 for (const auto &Object : YamlMF.StackObjects) {
502 const AllocaInst *Alloca = nullptr;
503 const yaml::StringValue &Name = Object.Name;
504 if (!Name.Value.empty()) {
505 Alloca = dyn_cast_or_null<AllocaInst>(
506 F.getValueSymbolTable().lookup(Name.Value));
508 return error(Name.SourceRange.Start,
509 "alloca instruction named '" + Name.Value +
510 "' isn't defined in the function '" + F.getName() +
513 if (Object.Type == yaml::MachineStackObject::VariableSized)
514 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
516 ObjectIdx = MFI.CreateStackObject(
517 Object.Size, Object.Alignment,
518 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
519 MFI.setObjectOffset(ObjectIdx, Object.Offset);
520 // TODO: Report an error when objects are redefined.
521 PFS.StackObjectSlots.insert(std::make_pair(Object.ID, ObjectIdx));
522 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
526 MFI.setCalleeSavedInfo(CSIInfo);
527 if (!CSIInfo.empty())
528 MFI.setCalleeSavedInfoValid(true);
532 bool MIRParserImpl::parseCalleeSavedRegister(
533 MachineFunction &MF, PerFunctionMIParsingState &PFS,
534 std::vector<CalleeSavedInfo> &CSIInfo,
535 const yaml::StringValue &RegisterSource, int FrameIdx) {
536 if (RegisterSource.Value.empty())
540 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
542 return error(Error, RegisterSource.SourceRange);
543 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
547 bool MIRParserImpl::initializeConstantPool(
548 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
549 const MachineFunction &MF,
550 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
551 const auto &M = *MF.getFunction()->getParent();
553 for (const auto &YamlConstant : YamlMF.Constants) {
554 const Constant *Value = dyn_cast_or_null<Constant>(
555 parseConstantValue(YamlConstant.Value.Value, Error, M));
557 return error(Error, YamlConstant.Value.SourceRange);
559 YamlConstant.Alignment
560 ? YamlConstant.Alignment
561 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
562 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
563 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
565 return error(YamlConstant.ID.SourceRange.Start,
566 Twine("redefinition of constant pool item '%const.") +
567 Twine(YamlConstant.ID.Value) + "'");
572 bool MIRParserImpl::initializeJumpTableInfo(
573 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
574 PerFunctionMIParsingState &PFS) {
575 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
576 for (const auto &Entry : YamlJTI.Entries) {
577 std::vector<MachineBasicBlock *> Blocks;
578 for (const auto &MBBSource : Entry.Blocks) {
579 MachineBasicBlock *MBB = nullptr;
580 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
582 Blocks.push_back(MBB);
584 unsigned Index = JTI->createJumpTableIndex(Blocks);
585 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
587 return error(Entry.ID.SourceRange.Start,
588 Twine("redefinition of jump table entry '%jump-table.") +
589 Twine(Entry.ID.Value) + "'");
594 bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
595 const yaml::StringValue &Source,
597 const PerFunctionMIParsingState &PFS) {
599 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
600 return error(Error, Source.SourceRange);
604 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
605 SMRange SourceRange) {
606 assert(SourceRange.isValid() && "Invalid source range");
607 SMLoc Loc = SourceRange.Start;
608 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
609 *Loc.getPointer() == '\'';
610 // Translate the location of the error from the location in the MI string to
611 // the corresponding location in the MIR file.
612 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
615 // TODO: Translate any source ranges as well.
616 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
620 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
621 SMRange SourceRange) {
622 assert(SourceRange.isValid());
624 // Translate the location of the error from the location in the llvm IR string
625 // to the corresponding location in the MIR file.
626 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
627 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
628 unsigned Column = Error.getColumnNo();
629 StringRef LineStr = Error.getLineContents();
630 SMLoc Loc = Error.getLoc();
632 // Get the full line and adjust the column number by taking the indentation of
633 // LLVM IR into account.
634 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
636 if (L.line_number() == Line) {
638 Loc = SMLoc::getFromPointer(LineStr.data());
639 auto Indent = LineStr.find(Error.getLineContents());
640 if (Indent != StringRef::npos)
646 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
647 Error.getMessage(), LineStr, Error.getRanges(),
651 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
652 if (!Names2RegClasses.empty())
654 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
655 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
656 const auto *RC = TRI->getRegClass(I);
657 Names2RegClasses.insert(
658 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
662 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
664 initNames2RegClasses(MF);
665 auto RegClassInfo = Names2RegClasses.find(Name);
666 if (RegClassInfo == Names2RegClasses.end())
668 return RegClassInfo->getValue();
671 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
672 : Impl(std::move(Impl)) {}
674 MIRParser::~MIRParser() {}
676 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
678 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
679 return Impl->initializeMachineFunction(MF);
682 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
684 LLVMContext &Context) {
685 auto FileOrErr = MemoryBuffer::getFile(Filename);
686 if (std::error_code EC = FileOrErr.getError()) {
687 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
688 "Could not open input file: " + EC.message());
691 return createMIRParser(std::move(FileOrErr.get()), Context);
694 std::unique_ptr<MIRParser>
695 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
696 LLVMContext &Context) {
697 auto Filename = Contents->getBufferIdentifier();
698 return llvm::make_unique<MIRParser>(
699 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));