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/STLExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
25 #include "llvm/CodeGen/MIRYamlMapping.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/ValueSymbolTable.h"
38 #include "llvm/Support/LineIterator.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/SMLoc.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/YAMLTraits.h"
49 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
57 /// Maps from register class names to register classes.
58 Name2RegClassMap Names2RegClasses;
59 /// Maps from register bank names to register banks.
60 Name2RegBankMap Names2RegBanks;
61 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
62 /// created and inserted into the given module when this is true.
63 bool NoLLVMIR = false;
64 /// True when a well formed MIR file does not contain any MIR/machine function
66 bool NoMIRDocuments = false;
69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
70 StringRef Filename, LLVMContext &Context);
72 void reportDiagnostic(const SMDiagnostic &Diag);
74 /// Report an error with the given message at unknown location.
76 /// Always returns true.
77 bool error(const Twine &Message);
79 /// Report an error with the given message at the given location.
81 /// Always returns true.
82 bool error(SMLoc Loc, const Twine &Message);
84 /// Report a given error with the location translated from the location in an
85 /// embedded string literal to a location in the MIR file.
87 /// Always returns true.
88 bool error(const SMDiagnostic &Error, SMRange SourceRange);
90 /// Try to parse the optional LLVM module and the machine functions in the MIR
93 /// Return null if an error occurred.
94 std::unique_ptr<Module> parseIRModule();
96 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI);
98 /// Parse the machine function in the current YAML document.
101 /// Return true if an error occurred.
102 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI);
104 /// Initialize the machine function to the state that's described in the MIR
107 /// Return true if error occurred.
108 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
109 MachineFunction &MF);
111 bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
112 const yaml::MachineFunction &YamlMF);
114 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
115 const yaml::MachineFunction &YamlMF);
117 bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
118 const yaml::MachineFunction &YamlMF);
120 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
121 std::vector<CalleeSavedInfo> &CSIInfo,
122 const yaml::StringValue &RegisterSource,
125 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
126 const yaml::MachineStackObject &Object,
129 bool initializeConstantPool(PerFunctionMIParsingState &PFS,
130 MachineConstantPool &ConstantPool,
131 const yaml::MachineFunction &YamlMF);
133 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
134 const yaml::MachineJumpTable &YamlJTI);
137 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
138 const yaml::StringValue &Source);
140 bool parseMBBReference(PerFunctionMIParsingState &PFS,
141 MachineBasicBlock *&MBB,
142 const yaml::StringValue &Source);
144 /// Return a MIR diagnostic converted from an MI string diagnostic.
145 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
146 SMRange SourceRange);
148 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
149 /// block scalar string.
150 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
151 SMRange SourceRange);
153 void initNames2RegClasses(const MachineFunction &MF);
154 void initNames2RegBanks(const MachineFunction &MF);
156 /// Check if the given identifier is a name of a register class.
158 /// Return null if the name isn't a register class.
159 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
162 /// Check if the given identifier is a name of a register bank.
164 /// Return null if the name isn't a register bank.
165 const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name);
167 void computeFunctionProperties(MachineFunction &MF);
170 } // end namespace llvm
172 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
173 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
176 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
177 StringRef Filename, LLVMContext &Context)
179 In(SM.getMemoryBuffer(
180 SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))->getBuffer(),
181 nullptr, handleYAMLDiag, this),
187 bool MIRParserImpl::error(const Twine &Message) {
188 Context.diagnose(DiagnosticInfoMIRParser(
189 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
193 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
194 Context.diagnose(DiagnosticInfoMIRParser(
195 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
199 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
200 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
201 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
205 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
206 DiagnosticSeverity Kind;
207 switch (Diag.getKind()) {
208 case SourceMgr::DK_Error:
211 case SourceMgr::DK_Warning:
214 case SourceMgr::DK_Note:
218 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
221 std::unique_ptr<Module> MIRParserImpl::parseIRModule() {
222 if (!In.setCurrentDocument()) {
225 // Create an empty module when the MIR file is empty.
226 NoMIRDocuments = true;
227 return llvm::make_unique<Module>(Filename, Context);
230 std::unique_ptr<Module> M;
231 // Parse the block scalar manually so that we can return unique pointer
232 // without having to go trough YAML traits.
233 if (const auto *BSN =
234 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
236 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
239 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
243 if (!In.setCurrentDocument())
244 NoMIRDocuments = true;
246 // Create an new, empty module.
247 M = llvm::make_unique<Module>(Filename, Context);
253 bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
257 // Parse the machine functions.
259 if (parseMachineFunction(M, MMI))
262 } while (In.setCurrentDocument());
267 /// Create an empty function with the given name.
268 static Function *createDummyFunction(StringRef Name, Module &M) {
269 auto &Context = M.getContext();
270 Function *F = cast<Function>(M.getOrInsertFunction(
271 Name, FunctionType::get(Type::getVoidTy(Context), false)));
272 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
273 new UnreachableInst(Context, BB);
277 bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) {
279 yaml::MachineFunction YamlMF;
280 yaml::EmptyContext Ctx;
281 yaml::yamlize(In, YamlMF, false, Ctx);
285 // Search for the corresponding IR function.
286 StringRef FunctionName = YamlMF.Name;
287 Function *F = M.getFunction(FunctionName);
290 F = createDummyFunction(FunctionName, M);
292 return error(Twine("function '") + FunctionName +
293 "' isn't defined in the provided LLVM IR");
296 if (MMI.getMachineFunction(*F) != nullptr)
297 return error(Twine("redefinition of machine function '") + FunctionName +
300 // Create the MachineFunction.
301 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
302 if (initializeMachineFunction(YamlMF, MF))
308 static bool isSSA(const MachineFunction &MF) {
309 const MachineRegisterInfo &MRI = MF.getRegInfo();
310 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
311 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
312 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
318 void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
319 MachineFunctionProperties &Properties = MF.getProperties();
322 bool HasInlineAsm = false;
323 for (const MachineBasicBlock &MBB : MF) {
324 for (const MachineInstr &MI : MBB) {
327 if (MI.isInlineAsm())
332 Properties.set(MachineFunctionProperties::Property::NoPHIs);
333 MF.setHasInlineAsm(HasInlineAsm);
336 Properties.set(MachineFunctionProperties::Property::IsSSA);
338 Properties.reset(MachineFunctionProperties::Property::IsSSA);
340 const MachineRegisterInfo &MRI = MF.getRegInfo();
341 if (MRI.getNumVirtRegs() == 0)
342 Properties.set(MachineFunctionProperties::Property::NoVRegs);
346 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
347 MachineFunction &MF) {
348 // TODO: Recreate the machine function.
349 initNames2RegClasses(MF);
350 initNames2RegBanks(MF);
351 if (YamlMF.Alignment)
352 MF.setAlignment(YamlMF.Alignment);
353 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
355 if (YamlMF.Legalized)
356 MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
357 if (YamlMF.RegBankSelected)
358 MF.getProperties().set(
359 MachineFunctionProperties::Property::RegBankSelected);
361 MF.getProperties().set(MachineFunctionProperties::Property::Selected);
363 PerFunctionMIParsingState PFS(MF, SM, IRSlots, Names2RegClasses,
365 if (parseRegisterInfo(PFS, YamlMF))
367 if (!YamlMF.Constants.empty()) {
368 auto *ConstantPool = MF.getConstantPool();
369 assert(ConstantPool && "Constant pool must be created");
370 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
374 StringRef BlockStr = YamlMF.Body.Value.Value;
377 BlockSM.AddNewSourceBuffer(
378 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
381 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
383 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
388 // Initialize the frame information after creating all the MBBs so that the
389 // MBB references in the frame information can be resolved.
390 if (initializeFrameInfo(PFS, YamlMF))
392 // Initialize the jump table after creating all the MBBs so that the MBB
393 // references can be resolved.
394 if (!YamlMF.JumpTableInfo.Entries.empty() &&
395 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
397 // Parse the machine instructions after creating all of the MBBs so that the
398 // parser can resolve the MBB references.
399 StringRef InsnStr = YamlMF.Body.Value.Value;
401 InsnSM.AddNewSourceBuffer(
402 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
405 if (parseMachineInstructions(PFS, InsnStr, Error)) {
407 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
412 if (setupRegisterInfo(PFS, YamlMF))
415 computeFunctionProperties(MF);
421 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
422 const yaml::MachineFunction &YamlMF) {
423 MachineFunction &MF = PFS.MF;
424 MachineRegisterInfo &RegInfo = MF.getRegInfo();
425 assert(RegInfo.tracksLiveness());
426 if (!YamlMF.TracksRegLiveness)
427 RegInfo.invalidateLiveness();
430 // Parse the virtual register information.
431 for (const auto &VReg : YamlMF.VirtualRegisters) {
432 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
434 return error(VReg.ID.SourceRange.Start,
435 Twine("redefinition of virtual register '%") +
436 Twine(VReg.ID.Value) + "'");
437 Info.Explicit = true;
439 if (StringRef(VReg.Class.Value).equals("_")) {
440 Info.Kind = VRegInfo::GENERIC;
442 const auto *RC = getRegClass(MF, VReg.Class.Value);
444 Info.Kind = VRegInfo::NORMAL;
447 const RegisterBank *RegBank = getRegBank(MF, VReg.Class.Value);
450 VReg.Class.SourceRange.Start,
451 Twine("use of undefined register class or register bank '") +
452 VReg.Class.Value + "'");
453 Info.Kind = VRegInfo::REGBANK;
454 Info.D.RegBank = RegBank;
458 if (!VReg.PreferredRegister.Value.empty()) {
459 if (Info.Kind != VRegInfo::NORMAL)
460 return error(VReg.Class.SourceRange.Start,
461 Twine("preferred register can only be set for normal vregs"));
463 if (parseRegisterReference(PFS, Info.PreferredReg,
464 VReg.PreferredRegister.Value, Error))
465 return error(Error, VReg.PreferredRegister.SourceRange);
469 // Parse the liveins.
470 for (const auto &LiveIn : YamlMF.LiveIns) {
472 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
473 return error(Error, LiveIn.Register.SourceRange);
475 if (!LiveIn.VirtualRegister.Value.empty()) {
477 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
479 return error(Error, LiveIn.VirtualRegister.SourceRange);
482 RegInfo.addLiveIn(Reg, VReg);
485 // Parse the callee saved registers (Registers that will
486 // be saved for the caller).
487 if (YamlMF.CalleeSavedRegisters) {
488 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
489 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
491 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
492 return error(Error, RegSource.SourceRange);
493 CalleeSavedRegisters.push_back(Reg);
495 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
501 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
502 const yaml::MachineFunction &YamlMF) {
503 MachineFunction &MF = PFS.MF;
504 MachineRegisterInfo &MRI = MF.getRegInfo();
507 for (auto P : PFS.VRegInfos) {
508 const VRegInfo &Info = *P.second;
509 unsigned Reg = Info.VReg;
511 case VRegInfo::UNKNOWN:
512 error(Twine("Cannot determine class/bank of virtual register ") +
513 Twine(P.first) + " in function '" + MF.getName() + "'");
516 case VRegInfo::NORMAL:
517 MRI.setRegClass(Reg, Info.D.RC);
518 if (Info.PreferredReg != 0)
519 MRI.setSimpleHint(Reg, Info.PreferredReg);
521 case VRegInfo::GENERIC:
523 case VRegInfo::REGBANK:
524 MRI.setRegBank(Reg, *Info.D.RegBank);
529 // Compute MachineRegisterInfo::UsedPhysRegMask
530 for (const MachineBasicBlock &MBB : MF) {
531 for (const MachineInstr &MI : MBB) {
532 for (const MachineOperand &MO : MI.operands()) {
535 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
540 // FIXME: This is a temporary workaround until the reserved registers can be
542 MRI.freezeReservedRegs(MF);
546 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
547 const yaml::MachineFunction &YamlMF) {
548 MachineFunction &MF = PFS.MF;
549 MachineFrameInfo &MFI = MF.getFrameInfo();
550 const Function &F = *MF.getFunction();
551 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
552 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
553 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
554 MFI.setHasStackMap(YamlMFI.HasStackMap);
555 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
556 MFI.setStackSize(YamlMFI.StackSize);
557 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
558 if (YamlMFI.MaxAlignment)
559 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
560 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
561 MFI.setHasCalls(YamlMFI.HasCalls);
562 if (YamlMFI.MaxCallFrameSize != ~0u)
563 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
564 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
565 MFI.setHasVAStart(YamlMFI.HasVAStart);
566 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
567 if (!YamlMFI.SavePoint.Value.empty()) {
568 MachineBasicBlock *MBB = nullptr;
569 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
571 MFI.setSavePoint(MBB);
573 if (!YamlMFI.RestorePoint.Value.empty()) {
574 MachineBasicBlock *MBB = nullptr;
575 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
577 MFI.setRestorePoint(MBB);
580 std::vector<CalleeSavedInfo> CSIInfo;
581 // Initialize the fixed frame objects.
582 for (const auto &Object : YamlMF.FixedStackObjects) {
584 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
585 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
586 Object.IsImmutable, Object.IsAliased);
588 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
589 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
590 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
593 return error(Object.ID.SourceRange.Start,
594 Twine("redefinition of fixed stack object '%fixed-stack.") +
595 Twine(Object.ID.Value) + "'");
596 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
601 // Initialize the ordinary frame objects.
602 for (const auto &Object : YamlMF.StackObjects) {
604 const AllocaInst *Alloca = nullptr;
605 const yaml::StringValue &Name = Object.Name;
606 if (!Name.Value.empty()) {
607 Alloca = dyn_cast_or_null<AllocaInst>(
608 F.getValueSymbolTable()->lookup(Name.Value));
610 return error(Name.SourceRange.Start,
611 "alloca instruction named '" + Name.Value +
612 "' isn't defined in the function '" + F.getName() +
615 if (Object.Type == yaml::MachineStackObject::VariableSized)
616 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
618 ObjectIdx = MFI.CreateStackObject(
619 Object.Size, Object.Alignment,
620 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
621 MFI.setObjectOffset(ObjectIdx, Object.Offset);
622 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
624 return error(Object.ID.SourceRange.Start,
625 Twine("redefinition of stack object '%stack.") +
626 Twine(Object.ID.Value) + "'");
627 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
630 if (Object.LocalOffset)
631 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
632 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
635 MFI.setCalleeSavedInfo(CSIInfo);
636 if (!CSIInfo.empty())
637 MFI.setCalleeSavedInfoValid(true);
639 // Initialize the various stack object references after initializing the
641 if (!YamlMFI.StackProtector.Value.empty()) {
644 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
645 return error(Error, YamlMFI.StackProtector.SourceRange);
646 MFI.setStackProtectorIndex(FI);
651 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
652 std::vector<CalleeSavedInfo> &CSIInfo,
653 const yaml::StringValue &RegisterSource, int FrameIdx) {
654 if (RegisterSource.Value.empty())
658 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
659 return error(Error, RegisterSource.SourceRange);
660 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
664 /// Verify that given node is of a certain type. Return true on error.
665 template <typename T>
666 static bool typecheckMDNode(T *&Result, MDNode *Node,
667 const yaml::StringValue &Source,
668 StringRef TypeString, MIRParserImpl &Parser) {
671 Result = dyn_cast<T>(Node);
673 return Parser.error(Source.SourceRange.Start,
674 "expected a reference to a '" + TypeString +
679 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
680 const yaml::MachineStackObject &Object, int FrameIdx) {
681 // Debug information can only be attached to stack objects; Fixed stack
682 // objects aren't supported.
683 assert(FrameIdx >= 0 && "Expected a stack object frame index");
684 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
685 if (parseMDNode(PFS, Var, Object.DebugVar) ||
686 parseMDNode(PFS, Expr, Object.DebugExpr) ||
687 parseMDNode(PFS, Loc, Object.DebugLoc))
689 if (!Var && !Expr && !Loc)
691 DILocalVariable *DIVar = nullptr;
692 DIExpression *DIExpr = nullptr;
693 DILocation *DILoc = nullptr;
694 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
695 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
696 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
698 PFS.MF.setVariableDbgInfo(DIVar, DIExpr, unsigned(FrameIdx), DILoc);
702 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
703 MDNode *&Node, const yaml::StringValue &Source) {
704 if (Source.Value.empty())
707 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
708 return error(Error, Source.SourceRange);
712 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
713 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
714 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
715 const MachineFunction &MF = PFS.MF;
716 const auto &M = *MF.getFunction()->getParent();
718 for (const auto &YamlConstant : YamlMF.Constants) {
719 const Constant *Value = dyn_cast_or_null<Constant>(
720 parseConstantValue(YamlConstant.Value.Value, Error, M));
722 return error(Error, YamlConstant.Value.SourceRange);
724 YamlConstant.Alignment
725 ? YamlConstant.Alignment
726 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
727 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
728 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
730 return error(YamlConstant.ID.SourceRange.Start,
731 Twine("redefinition of constant pool item '%const.") +
732 Twine(YamlConstant.ID.Value) + "'");
737 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
738 const yaml::MachineJumpTable &YamlJTI) {
739 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
740 for (const auto &Entry : YamlJTI.Entries) {
741 std::vector<MachineBasicBlock *> Blocks;
742 for (const auto &MBBSource : Entry.Blocks) {
743 MachineBasicBlock *MBB = nullptr;
744 if (parseMBBReference(PFS, MBB, MBBSource.Value))
746 Blocks.push_back(MBB);
748 unsigned Index = JTI->createJumpTableIndex(Blocks);
749 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
751 return error(Entry.ID.SourceRange.Start,
752 Twine("redefinition of jump table entry '%jump-table.") +
753 Twine(Entry.ID.Value) + "'");
758 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
759 MachineBasicBlock *&MBB,
760 const yaml::StringValue &Source) {
762 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
763 return error(Error, Source.SourceRange);
767 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
768 SMRange SourceRange) {
769 assert(SourceRange.isValid() && "Invalid source range");
770 SMLoc Loc = SourceRange.Start;
771 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
772 *Loc.getPointer() == '\'';
773 // Translate the location of the error from the location in the MI string to
774 // the corresponding location in the MIR file.
775 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
778 // TODO: Translate any source ranges as well.
779 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
783 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
784 SMRange SourceRange) {
785 assert(SourceRange.isValid());
787 // Translate the location of the error from the location in the llvm IR string
788 // to the corresponding location in the MIR file.
789 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
790 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
791 unsigned Column = Error.getColumnNo();
792 StringRef LineStr = Error.getLineContents();
793 SMLoc Loc = Error.getLoc();
795 // Get the full line and adjust the column number by taking the indentation of
796 // LLVM IR into account.
797 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
799 if (L.line_number() == Line) {
801 Loc = SMLoc::getFromPointer(LineStr.data());
802 auto Indent = LineStr.find(Error.getLineContents());
803 if (Indent != StringRef::npos)
809 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
810 Error.getMessage(), LineStr, Error.getRanges(),
814 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
815 if (!Names2RegClasses.empty())
817 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
818 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
819 const auto *RC = TRI->getRegClass(I);
820 Names2RegClasses.insert(
821 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
825 void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) {
826 if (!Names2RegBanks.empty())
828 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
829 // If the target does not support GlobalISel, we may not have a
830 // register bank info.
833 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
834 const auto &RegBank = RBI->getRegBank(I);
835 Names2RegBanks.insert(
836 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
840 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
842 auto RegClassInfo = Names2RegClasses.find(Name);
843 if (RegClassInfo == Names2RegClasses.end())
845 return RegClassInfo->getValue();
848 const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF,
850 auto RegBankInfo = Names2RegBanks.find(Name);
851 if (RegBankInfo == Names2RegBanks.end())
853 return RegBankInfo->getValue();
856 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
857 : Impl(std::move(Impl)) {}
859 MIRParser::~MIRParser() {}
861 std::unique_ptr<Module> MIRParser::parseIRModule() {
862 return Impl->parseIRModule();
865 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
866 return Impl->parseMachineFunctions(M, MMI);
869 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
871 LLVMContext &Context) {
872 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
873 if (std::error_code EC = FileOrErr.getError()) {
874 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
875 "Could not open input file: " + EC.message());
878 return createMIRParser(std::move(FileOrErr.get()), Context);
881 std::unique_ptr<MIRParser>
882 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
883 LLVMContext &Context) {
884 auto Filename = Contents->getBufferIdentifier();
885 if (Context.shouldDiscardValueNames()) {
886 Context.diagnose(DiagnosticInfoMIRParser(
889 Filename, SourceMgr::DK_Error,
890 "Can't read MIR with a Context that discards named Values")));
893 return llvm::make_unique<MIRParser>(
894 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));