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,
123 bool IsRestored, int FrameIdx);
125 template <typename T>
126 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
130 bool initializeConstantPool(PerFunctionMIParsingState &PFS,
131 MachineConstantPool &ConstantPool,
132 const yaml::MachineFunction &YamlMF);
134 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
135 const yaml::MachineJumpTable &YamlJTI);
138 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
139 const yaml::StringValue &Source);
141 bool parseMBBReference(PerFunctionMIParsingState &PFS,
142 MachineBasicBlock *&MBB,
143 const yaml::StringValue &Source);
145 /// Return a MIR diagnostic converted from an MI string diagnostic.
146 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
147 SMRange SourceRange);
149 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
150 /// block scalar string.
151 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
152 SMRange SourceRange);
154 void initNames2RegClasses(const MachineFunction &MF);
155 void initNames2RegBanks(const MachineFunction &MF);
157 /// Check if the given identifier is a name of a register class.
159 /// Return null if the name isn't a register class.
160 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
163 /// Check if the given identifier is a name of a register bank.
165 /// Return null if the name isn't a register bank.
166 const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name);
168 void computeFunctionProperties(MachineFunction &MF);
171 } // end namespace llvm
173 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
174 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
177 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
178 StringRef Filename, LLVMContext &Context)
180 In(SM.getMemoryBuffer(
181 SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))->getBuffer(),
182 nullptr, handleYAMLDiag, this),
188 bool MIRParserImpl::error(const Twine &Message) {
189 Context.diagnose(DiagnosticInfoMIRParser(
190 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
194 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
195 Context.diagnose(DiagnosticInfoMIRParser(
196 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
200 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
201 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
202 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
206 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
207 DiagnosticSeverity Kind;
208 switch (Diag.getKind()) {
209 case SourceMgr::DK_Error:
212 case SourceMgr::DK_Warning:
215 case SourceMgr::DK_Note:
218 case SourceMgr::DK_Remark:
219 llvm_unreachable("remark unexpected");
222 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
225 std::unique_ptr<Module> MIRParserImpl::parseIRModule() {
226 if (!In.setCurrentDocument()) {
229 // Create an empty module when the MIR file is empty.
230 NoMIRDocuments = true;
231 return llvm::make_unique<Module>(Filename, Context);
234 std::unique_ptr<Module> M;
235 // Parse the block scalar manually so that we can return unique pointer
236 // without having to go trough YAML traits.
237 if (const auto *BSN =
238 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
240 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
241 Context, &IRSlots, /*UpgradeDebugInfo=*/false);
243 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
247 if (!In.setCurrentDocument())
248 NoMIRDocuments = true;
250 // Create an new, empty module.
251 M = llvm::make_unique<Module>(Filename, Context);
257 bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
261 // Parse the machine functions.
263 if (parseMachineFunction(M, MMI))
266 } while (In.setCurrentDocument());
271 /// Create an empty function with the given name.
272 static Function *createDummyFunction(StringRef Name, Module &M) {
273 auto &Context = M.getContext();
274 Function *F = cast<Function>(M.getOrInsertFunction(
275 Name, FunctionType::get(Type::getVoidTy(Context), false)));
276 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
277 new UnreachableInst(Context, BB);
281 bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) {
283 yaml::MachineFunction YamlMF;
284 yaml::EmptyContext Ctx;
285 yaml::yamlize(In, YamlMF, false, Ctx);
289 // Search for the corresponding IR function.
290 StringRef FunctionName = YamlMF.Name;
291 Function *F = M.getFunction(FunctionName);
294 F = createDummyFunction(FunctionName, M);
296 return error(Twine("function '") + FunctionName +
297 "' isn't defined in the provided LLVM IR");
300 if (MMI.getMachineFunction(*F) != nullptr)
301 return error(Twine("redefinition of machine function '") + FunctionName +
304 // Create the MachineFunction.
305 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
306 if (initializeMachineFunction(YamlMF, MF))
312 static bool isSSA(const MachineFunction &MF) {
313 const MachineRegisterInfo &MRI = MF.getRegInfo();
314 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
315 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
316 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
322 void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
323 MachineFunctionProperties &Properties = MF.getProperties();
326 bool HasInlineAsm = false;
327 for (const MachineBasicBlock &MBB : MF) {
328 for (const MachineInstr &MI : MBB) {
331 if (MI.isInlineAsm())
336 Properties.set(MachineFunctionProperties::Property::NoPHIs);
337 MF.setHasInlineAsm(HasInlineAsm);
340 Properties.set(MachineFunctionProperties::Property::IsSSA);
342 Properties.reset(MachineFunctionProperties::Property::IsSSA);
344 const MachineRegisterInfo &MRI = MF.getRegInfo();
345 if (MRI.getNumVirtRegs() == 0)
346 Properties.set(MachineFunctionProperties::Property::NoVRegs);
350 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
351 MachineFunction &MF) {
352 // TODO: Recreate the machine function.
353 initNames2RegClasses(MF);
354 initNames2RegBanks(MF);
355 if (YamlMF.Alignment)
356 MF.setAlignment(YamlMF.Alignment);
357 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
359 if (YamlMF.Legalized)
360 MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
361 if (YamlMF.RegBankSelected)
362 MF.getProperties().set(
363 MachineFunctionProperties::Property::RegBankSelected);
365 MF.getProperties().set(MachineFunctionProperties::Property::Selected);
366 if (YamlMF.FailedISel)
367 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
369 PerFunctionMIParsingState PFS(MF, SM, IRSlots, Names2RegClasses,
371 if (parseRegisterInfo(PFS, YamlMF))
373 if (!YamlMF.Constants.empty()) {
374 auto *ConstantPool = MF.getConstantPool();
375 assert(ConstantPool && "Constant pool must be created");
376 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
380 StringRef BlockStr = YamlMF.Body.Value.Value;
383 BlockSM.AddNewSourceBuffer(
384 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
387 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
389 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
394 // Initialize the frame information after creating all the MBBs so that the
395 // MBB references in the frame information can be resolved.
396 if (initializeFrameInfo(PFS, YamlMF))
398 // Initialize the jump table after creating all the MBBs so that the MBB
399 // references can be resolved.
400 if (!YamlMF.JumpTableInfo.Entries.empty() &&
401 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
403 // Parse the machine instructions after creating all of the MBBs so that the
404 // parser can resolve the MBB references.
405 StringRef InsnStr = YamlMF.Body.Value.Value;
407 InsnSM.AddNewSourceBuffer(
408 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
411 if (parseMachineInstructions(PFS, InsnStr, Error)) {
413 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
418 if (setupRegisterInfo(PFS, YamlMF))
421 computeFunctionProperties(MF);
423 MF.getSubtarget().mirFileLoaded(MF);
429 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
430 const yaml::MachineFunction &YamlMF) {
431 MachineFunction &MF = PFS.MF;
432 MachineRegisterInfo &RegInfo = MF.getRegInfo();
433 assert(RegInfo.tracksLiveness());
434 if (!YamlMF.TracksRegLiveness)
435 RegInfo.invalidateLiveness();
438 // Parse the virtual register information.
439 for (const auto &VReg : YamlMF.VirtualRegisters) {
440 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
442 return error(VReg.ID.SourceRange.Start,
443 Twine("redefinition of virtual register '%") +
444 Twine(VReg.ID.Value) + "'");
445 Info.Explicit = true;
447 if (StringRef(VReg.Class.Value).equals("_")) {
448 Info.Kind = VRegInfo::GENERIC;
449 Info.D.RegBank = nullptr;
451 const auto *RC = getRegClass(MF, VReg.Class.Value);
453 Info.Kind = VRegInfo::NORMAL;
456 const RegisterBank *RegBank = getRegBank(MF, VReg.Class.Value);
459 VReg.Class.SourceRange.Start,
460 Twine("use of undefined register class or register bank '") +
461 VReg.Class.Value + "'");
462 Info.Kind = VRegInfo::REGBANK;
463 Info.D.RegBank = RegBank;
467 if (!VReg.PreferredRegister.Value.empty()) {
468 if (Info.Kind != VRegInfo::NORMAL)
469 return error(VReg.Class.SourceRange.Start,
470 Twine("preferred register can only be set for normal vregs"));
472 if (parseRegisterReference(PFS, Info.PreferredReg,
473 VReg.PreferredRegister.Value, Error))
474 return error(Error, VReg.PreferredRegister.SourceRange);
478 // Parse the liveins.
479 for (const auto &LiveIn : YamlMF.LiveIns) {
481 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
482 return error(Error, LiveIn.Register.SourceRange);
484 if (!LiveIn.VirtualRegister.Value.empty()) {
486 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
488 return error(Error, LiveIn.VirtualRegister.SourceRange);
491 RegInfo.addLiveIn(Reg, VReg);
494 // Parse the callee saved registers (Registers that will
495 // be saved for the caller).
496 if (YamlMF.CalleeSavedRegisters) {
497 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
498 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
500 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
501 return error(Error, RegSource.SourceRange);
502 CalleeSavedRegisters.push_back(Reg);
504 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
510 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
511 const yaml::MachineFunction &YamlMF) {
512 MachineFunction &MF = PFS.MF;
513 MachineRegisterInfo &MRI = MF.getRegInfo();
516 auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
517 unsigned Reg = Info.VReg;
519 case VRegInfo::UNKNOWN:
520 error(Twine("Cannot determine class/bank of virtual register ") +
521 Name + " in function '" + MF.getName() + "'");
524 case VRegInfo::NORMAL:
525 MRI.setRegClass(Reg, Info.D.RC);
526 if (Info.PreferredReg != 0)
527 MRI.setSimpleHint(Reg, Info.PreferredReg);
529 case VRegInfo::GENERIC:
531 case VRegInfo::REGBANK:
532 MRI.setRegBank(Reg, *Info.D.RegBank);
537 for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end();
539 const VRegInfo &Info = *I->second;
540 populateVRegInfo(Info, Twine(I->first()));
543 for (auto P : PFS.VRegInfos) {
544 const VRegInfo &Info = *P.second;
545 populateVRegInfo(Info, Twine(P.first));
548 // Compute MachineRegisterInfo::UsedPhysRegMask
549 for (const MachineBasicBlock &MBB : MF) {
550 for (const MachineInstr &MI : MBB) {
551 for (const MachineOperand &MO : MI.operands()) {
554 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
559 // FIXME: This is a temporary workaround until the reserved registers can be
561 MRI.freezeReservedRegs(MF);
565 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
566 const yaml::MachineFunction &YamlMF) {
567 MachineFunction &MF = PFS.MF;
568 MachineFrameInfo &MFI = MF.getFrameInfo();
569 const Function &F = MF.getFunction();
570 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
571 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
572 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
573 MFI.setHasStackMap(YamlMFI.HasStackMap);
574 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
575 MFI.setStackSize(YamlMFI.StackSize);
576 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
577 if (YamlMFI.MaxAlignment)
578 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
579 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
580 MFI.setHasCalls(YamlMFI.HasCalls);
581 if (YamlMFI.MaxCallFrameSize != ~0u)
582 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
583 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
584 MFI.setHasVAStart(YamlMFI.HasVAStart);
585 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
586 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
587 if (!YamlMFI.SavePoint.Value.empty()) {
588 MachineBasicBlock *MBB = nullptr;
589 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
591 MFI.setSavePoint(MBB);
593 if (!YamlMFI.RestorePoint.Value.empty()) {
594 MachineBasicBlock *MBB = nullptr;
595 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
597 MFI.setRestorePoint(MBB);
600 std::vector<CalleeSavedInfo> CSIInfo;
601 // Initialize the fixed frame objects.
602 for (const auto &Object : YamlMF.FixedStackObjects) {
604 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
605 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
606 Object.IsImmutable, Object.IsAliased);
608 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
609 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
610 MFI.setStackID(ObjectIdx, Object.StackID);
611 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
614 return error(Object.ID.SourceRange.Start,
615 Twine("redefinition of fixed stack object '%fixed-stack.") +
616 Twine(Object.ID.Value) + "'");
617 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
618 Object.CalleeSavedRestored, ObjectIdx))
620 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
624 // Initialize the ordinary frame objects.
625 for (const auto &Object : YamlMF.StackObjects) {
627 const AllocaInst *Alloca = nullptr;
628 const yaml::StringValue &Name = Object.Name;
629 if (!Name.Value.empty()) {
630 Alloca = dyn_cast_or_null<AllocaInst>(
631 F.getValueSymbolTable()->lookup(Name.Value));
633 return error(Name.SourceRange.Start,
634 "alloca instruction named '" + Name.Value +
635 "' isn't defined in the function '" + F.getName() +
638 if (Object.Type == yaml::MachineStackObject::VariableSized)
639 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
641 ObjectIdx = MFI.CreateStackObject(
642 Object.Size, Object.Alignment,
643 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
644 MFI.setObjectOffset(ObjectIdx, Object.Offset);
645 MFI.setStackID(ObjectIdx, Object.StackID);
647 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
649 return error(Object.ID.SourceRange.Start,
650 Twine("redefinition of stack object '%stack.") +
651 Twine(Object.ID.Value) + "'");
652 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
653 Object.CalleeSavedRestored, ObjectIdx))
655 if (Object.LocalOffset)
656 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
657 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
660 MFI.setCalleeSavedInfo(CSIInfo);
661 if (!CSIInfo.empty())
662 MFI.setCalleeSavedInfoValid(true);
664 // Initialize the various stack object references after initializing the
666 if (!YamlMFI.StackProtector.Value.empty()) {
669 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
670 return error(Error, YamlMFI.StackProtector.SourceRange);
671 MFI.setStackProtectorIndex(FI);
676 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
677 std::vector<CalleeSavedInfo> &CSIInfo,
678 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
679 if (RegisterSource.Value.empty())
683 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
684 return error(Error, RegisterSource.SourceRange);
685 CalleeSavedInfo CSI(Reg, FrameIdx);
686 CSI.setRestored(IsRestored);
687 CSIInfo.push_back(CSI);
691 /// Verify that given node is of a certain type. Return true on error.
692 template <typename T>
693 static bool typecheckMDNode(T *&Result, MDNode *Node,
694 const yaml::StringValue &Source,
695 StringRef TypeString, MIRParserImpl &Parser) {
698 Result = dyn_cast<T>(Node);
700 return Parser.error(Source.SourceRange.Start,
701 "expected a reference to a '" + TypeString +
706 template <typename T>
707 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
708 const T &Object, int FrameIdx) {
709 // Debug information can only be attached to stack objects; Fixed stack
710 // objects aren't supported.
711 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
712 if (parseMDNode(PFS, Var, Object.DebugVar) ||
713 parseMDNode(PFS, Expr, Object.DebugExpr) ||
714 parseMDNode(PFS, Loc, Object.DebugLoc))
716 if (!Var && !Expr && !Loc)
718 DILocalVariable *DIVar = nullptr;
719 DIExpression *DIExpr = nullptr;
720 DILocation *DILoc = nullptr;
721 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
722 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
723 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
725 PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
729 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
730 MDNode *&Node, const yaml::StringValue &Source) {
731 if (Source.Value.empty())
734 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
735 return error(Error, Source.SourceRange);
739 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
740 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
741 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
742 const MachineFunction &MF = PFS.MF;
743 const auto &M = *MF.getFunction().getParent();
745 for (const auto &YamlConstant : YamlMF.Constants) {
746 if (YamlConstant.IsTargetSpecific)
747 // FIXME: Support target-specific constant pools
748 return error(YamlConstant.Value.SourceRange.Start,
749 "Can't parse target-specific constant pool entries yet");
750 const Constant *Value = dyn_cast_or_null<Constant>(
751 parseConstantValue(YamlConstant.Value.Value, Error, M));
753 return error(Error, YamlConstant.Value.SourceRange);
755 YamlConstant.Alignment
756 ? YamlConstant.Alignment
757 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
758 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
759 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
761 return error(YamlConstant.ID.SourceRange.Start,
762 Twine("redefinition of constant pool item '%const.") +
763 Twine(YamlConstant.ID.Value) + "'");
768 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
769 const yaml::MachineJumpTable &YamlJTI) {
770 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
771 for (const auto &Entry : YamlJTI.Entries) {
772 std::vector<MachineBasicBlock *> Blocks;
773 for (const auto &MBBSource : Entry.Blocks) {
774 MachineBasicBlock *MBB = nullptr;
775 if (parseMBBReference(PFS, MBB, MBBSource.Value))
777 Blocks.push_back(MBB);
779 unsigned Index = JTI->createJumpTableIndex(Blocks);
780 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
782 return error(Entry.ID.SourceRange.Start,
783 Twine("redefinition of jump table entry '%jump-table.") +
784 Twine(Entry.ID.Value) + "'");
789 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
790 MachineBasicBlock *&MBB,
791 const yaml::StringValue &Source) {
793 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
794 return error(Error, Source.SourceRange);
798 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
799 SMRange SourceRange) {
800 assert(SourceRange.isValid() && "Invalid source range");
801 SMLoc Loc = SourceRange.Start;
802 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
803 *Loc.getPointer() == '\'';
804 // Translate the location of the error from the location in the MI string to
805 // the corresponding location in the MIR file.
806 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
809 // TODO: Translate any source ranges as well.
810 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
814 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
815 SMRange SourceRange) {
816 assert(SourceRange.isValid());
818 // Translate the location of the error from the location in the llvm IR string
819 // to the corresponding location in the MIR file.
820 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
821 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
822 unsigned Column = Error.getColumnNo();
823 StringRef LineStr = Error.getLineContents();
824 SMLoc Loc = Error.getLoc();
826 // Get the full line and adjust the column number by taking the indentation of
827 // LLVM IR into account.
828 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
830 if (L.line_number() == Line) {
832 Loc = SMLoc::getFromPointer(LineStr.data());
833 auto Indent = LineStr.find(Error.getLineContents());
834 if (Indent != StringRef::npos)
840 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
841 Error.getMessage(), LineStr, Error.getRanges(),
845 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
846 if (!Names2RegClasses.empty())
848 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
849 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
850 const auto *RC = TRI->getRegClass(I);
851 Names2RegClasses.insert(
852 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
856 void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) {
857 if (!Names2RegBanks.empty())
859 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
860 // If the target does not support GlobalISel, we may not have a
861 // register bank info.
864 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
865 const auto &RegBank = RBI->getRegBank(I);
866 Names2RegBanks.insert(
867 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
871 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
873 auto RegClassInfo = Names2RegClasses.find(Name);
874 if (RegClassInfo == Names2RegClasses.end())
876 return RegClassInfo->getValue();
879 const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF,
881 auto RegBankInfo = Names2RegBanks.find(Name);
882 if (RegBankInfo == Names2RegBanks.end())
884 return RegBankInfo->getValue();
887 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
888 : Impl(std::move(Impl)) {}
890 MIRParser::~MIRParser() {}
892 std::unique_ptr<Module> MIRParser::parseIRModule() {
893 return Impl->parseIRModule();
896 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
897 return Impl->parseMachineFunctions(M, MMI);
900 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
902 LLVMContext &Context) {
903 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
904 if (std::error_code EC = FileOrErr.getError()) {
905 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
906 "Could not open input file: " + EC.message());
909 return createMIRParser(std::move(FileOrErr.get()), Context);
912 std::unique_ptr<MIRParser>
913 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
914 LLVMContext &Context) {
915 auto Filename = Contents->getBufferIdentifier();
916 if (Context.shouldDiscardValueNames()) {
917 Context.diagnose(DiagnosticInfoMIRParser(
920 Filename, SourceMgr::DK_Error,
921 "Can't read MIR with a Context that discards named Values")));
924 return llvm::make_unique<MIRParser>(
925 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));