1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the class that parses the optional LLVM IR and machine
10 // functions that are stored in MIR files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MIRParser/MIRParser.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/AsmParser/Parser.h"
21 #include "llvm/AsmParser/SlotMapping.h"
22 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
24 #include "llvm/CodeGen/MIRYamlMapping.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ValueSymbolTable.h"
37 #include "llvm/Support/LineIterator.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SMLoc.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/YAMLTraits.h"
48 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
56 /// Maps from register class names to register classes.
57 Name2RegClassMap Names2RegClasses
;
58 /// Maps from register bank names to register banks.
59 Name2RegBankMap Names2RegBanks
;
60 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
61 /// created and inserted into the given module when this is true.
62 bool NoLLVMIR
= false;
63 /// True when a well formed MIR file does not contain any MIR/machine function
65 bool NoMIRDocuments
= false;
68 MIRParserImpl(std::unique_ptr
<MemoryBuffer
> Contents
,
69 StringRef Filename
, LLVMContext
&Context
);
71 void reportDiagnostic(const SMDiagnostic
&Diag
);
73 /// Report an error with the given message at unknown location.
75 /// Always returns true.
76 bool error(const Twine
&Message
);
78 /// Report an error with the given message at the given location.
80 /// Always returns true.
81 bool error(SMLoc Loc
, const Twine
&Message
);
83 /// Report a given error with the location translated from the location in an
84 /// embedded string literal to a location in the MIR file.
86 /// Always returns true.
87 bool error(const SMDiagnostic
&Error
, SMRange SourceRange
);
89 /// Try to parse the optional LLVM module and the machine functions in the MIR
92 /// Return null if an error occurred.
93 std::unique_ptr
<Module
> parseIRModule();
95 bool parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
);
97 /// Parse the machine function in the current YAML document.
100 /// Return true if an error occurred.
101 bool parseMachineFunction(Module
&M
, MachineModuleInfo
&MMI
);
103 /// Initialize the machine function to the state that's described in the MIR
106 /// Return true if error occurred.
107 bool initializeMachineFunction(const yaml::MachineFunction
&YamlMF
,
108 MachineFunction
&MF
);
110 bool parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
111 const yaml::MachineFunction
&YamlMF
);
113 bool setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
114 const yaml::MachineFunction
&YamlMF
);
116 bool initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
117 const yaml::MachineFunction
&YamlMF
);
119 bool parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
120 std::vector
<CalleeSavedInfo
> &CSIInfo
,
121 const yaml::StringValue
&RegisterSource
,
122 bool IsRestored
, int FrameIdx
);
124 template <typename T
>
125 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
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
:
217 case SourceMgr::DK_Remark
:
218 llvm_unreachable("remark unexpected");
221 Context
.diagnose(DiagnosticInfoMIRParser(Kind
, Diag
));
224 std::unique_ptr
<Module
> MIRParserImpl::parseIRModule() {
225 if (!In
.setCurrentDocument()) {
228 // Create an empty module when the MIR file is empty.
229 NoMIRDocuments
= true;
230 return llvm::make_unique
<Module
>(Filename
, Context
);
233 std::unique_ptr
<Module
> M
;
234 // Parse the block scalar manually so that we can return unique pointer
235 // without having to go trough YAML traits.
236 if (const auto *BSN
=
237 dyn_cast_or_null
<yaml::BlockScalarNode
>(In
.getCurrentNode())) {
239 M
= parseAssembly(MemoryBufferRef(BSN
->getValue(), Filename
), Error
,
240 Context
, &IRSlots
, /*UpgradeDebugInfo=*/false);
242 reportDiagnostic(diagFromBlockStringDiag(Error
, BSN
->getSourceRange()));
246 if (!In
.setCurrentDocument())
247 NoMIRDocuments
= true;
249 // Create an new, empty module.
250 M
= llvm::make_unique
<Module
>(Filename
, Context
);
256 bool MIRParserImpl::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
260 // Parse the machine functions.
262 if (parseMachineFunction(M
, MMI
))
265 } while (In
.setCurrentDocument());
270 /// Create an empty function with the given name.
271 static Function
*createDummyFunction(StringRef Name
, Module
&M
) {
272 auto &Context
= M
.getContext();
274 Function::Create(FunctionType::get(Type::getVoidTy(Context
), false),
275 Function::ExternalLinkage
, Name
, M
);
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
);
358 MF
.setHasWinCFI(YamlMF
.HasWinCFI
);
360 if (YamlMF
.Legalized
)
361 MF
.getProperties().set(MachineFunctionProperties::Property::Legalized
);
362 if (YamlMF
.RegBankSelected
)
363 MF
.getProperties().set(
364 MachineFunctionProperties::Property::RegBankSelected
);
366 MF
.getProperties().set(MachineFunctionProperties::Property::Selected
);
367 if (YamlMF
.FailedISel
)
368 MF
.getProperties().set(MachineFunctionProperties::Property::FailedISel
);
370 PerFunctionMIParsingState
PFS(MF
, SM
, IRSlots
, Names2RegClasses
,
372 if (parseRegisterInfo(PFS
, YamlMF
))
374 if (!YamlMF
.Constants
.empty()) {
375 auto *ConstantPool
= MF
.getConstantPool();
376 assert(ConstantPool
&& "Constant pool must be created");
377 if (initializeConstantPool(PFS
, *ConstantPool
, YamlMF
))
381 StringRef BlockStr
= YamlMF
.Body
.Value
.Value
;
384 BlockSM
.AddNewSourceBuffer(
385 MemoryBuffer::getMemBuffer(BlockStr
, "",/*RequiresNullTerminator=*/false),
388 if (parseMachineBasicBlockDefinitions(PFS
, BlockStr
, Error
)) {
390 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
395 // Initialize the frame information after creating all the MBBs so that the
396 // MBB references in the frame information can be resolved.
397 if (initializeFrameInfo(PFS
, YamlMF
))
399 // Initialize the jump table after creating all the MBBs so that the MBB
400 // references can be resolved.
401 if (!YamlMF
.JumpTableInfo
.Entries
.empty() &&
402 initializeJumpTableInfo(PFS
, YamlMF
.JumpTableInfo
))
404 // Parse the machine instructions after creating all of the MBBs so that the
405 // parser can resolve the MBB references.
406 StringRef InsnStr
= YamlMF
.Body
.Value
.Value
;
408 InsnSM
.AddNewSourceBuffer(
409 MemoryBuffer::getMemBuffer(InsnStr
, "", /*RequiresNullTerminator=*/false),
412 if (parseMachineInstructions(PFS
, InsnStr
, Error
)) {
414 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
419 if (setupRegisterInfo(PFS
, YamlMF
))
422 computeFunctionProperties(MF
);
424 MF
.getSubtarget().mirFileLoaded(MF
);
430 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
431 const yaml::MachineFunction
&YamlMF
) {
432 MachineFunction
&MF
= PFS
.MF
;
433 MachineRegisterInfo
&RegInfo
= MF
.getRegInfo();
434 assert(RegInfo
.tracksLiveness());
435 if (!YamlMF
.TracksRegLiveness
)
436 RegInfo
.invalidateLiveness();
439 // Parse the virtual register information.
440 for (const auto &VReg
: YamlMF
.VirtualRegisters
) {
441 VRegInfo
&Info
= PFS
.getVRegInfo(VReg
.ID
.Value
);
443 return error(VReg
.ID
.SourceRange
.Start
,
444 Twine("redefinition of virtual register '%") +
445 Twine(VReg
.ID
.Value
) + "'");
446 Info
.Explicit
= true;
448 if (StringRef(VReg
.Class
.Value
).equals("_")) {
449 Info
.Kind
= VRegInfo::GENERIC
;
450 Info
.D
.RegBank
= nullptr;
452 const auto *RC
= getRegClass(MF
, VReg
.Class
.Value
);
454 Info
.Kind
= VRegInfo::NORMAL
;
457 const RegisterBank
*RegBank
= getRegBank(MF
, VReg
.Class
.Value
);
460 VReg
.Class
.SourceRange
.Start
,
461 Twine("use of undefined register class or register bank '") +
462 VReg
.Class
.Value
+ "'");
463 Info
.Kind
= VRegInfo::REGBANK
;
464 Info
.D
.RegBank
= RegBank
;
468 if (!VReg
.PreferredRegister
.Value
.empty()) {
469 if (Info
.Kind
!= VRegInfo::NORMAL
)
470 return error(VReg
.Class
.SourceRange
.Start
,
471 Twine("preferred register can only be set for normal vregs"));
473 if (parseRegisterReference(PFS
, Info
.PreferredReg
,
474 VReg
.PreferredRegister
.Value
, Error
))
475 return error(Error
, VReg
.PreferredRegister
.SourceRange
);
479 // Parse the liveins.
480 for (const auto &LiveIn
: YamlMF
.LiveIns
) {
482 if (parseNamedRegisterReference(PFS
, Reg
, LiveIn
.Register
.Value
, Error
))
483 return error(Error
, LiveIn
.Register
.SourceRange
);
485 if (!LiveIn
.VirtualRegister
.Value
.empty()) {
487 if (parseVirtualRegisterReference(PFS
, Info
, LiveIn
.VirtualRegister
.Value
,
489 return error(Error
, LiveIn
.VirtualRegister
.SourceRange
);
492 RegInfo
.addLiveIn(Reg
, VReg
);
495 // Parse the callee saved registers (Registers that will
496 // be saved for the caller).
497 if (YamlMF
.CalleeSavedRegisters
) {
498 SmallVector
<MCPhysReg
, 16> CalleeSavedRegisters
;
499 for (const auto &RegSource
: YamlMF
.CalleeSavedRegisters
.getValue()) {
501 if (parseNamedRegisterReference(PFS
, Reg
, RegSource
.Value
, Error
))
502 return error(Error
, RegSource
.SourceRange
);
503 CalleeSavedRegisters
.push_back(Reg
);
505 RegInfo
.setCalleeSavedRegs(CalleeSavedRegisters
);
511 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
512 const yaml::MachineFunction
&YamlMF
) {
513 MachineFunction
&MF
= PFS
.MF
;
514 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
517 auto populateVRegInfo
= [&] (const VRegInfo
&Info
, Twine Name
) {
518 unsigned Reg
= Info
.VReg
;
520 case VRegInfo::UNKNOWN
:
521 error(Twine("Cannot determine class/bank of virtual register ") +
522 Name
+ " in function '" + MF
.getName() + "'");
525 case VRegInfo::NORMAL
:
526 MRI
.setRegClass(Reg
, Info
.D
.RC
);
527 if (Info
.PreferredReg
!= 0)
528 MRI
.setSimpleHint(Reg
, Info
.PreferredReg
);
530 case VRegInfo::GENERIC
:
532 case VRegInfo::REGBANK
:
533 MRI
.setRegBank(Reg
, *Info
.D
.RegBank
);
538 for (auto I
= PFS
.VRegInfosNamed
.begin(), E
= PFS
.VRegInfosNamed
.end();
540 const VRegInfo
&Info
= *I
->second
;
541 populateVRegInfo(Info
, Twine(I
->first()));
544 for (auto P
: PFS
.VRegInfos
) {
545 const VRegInfo
&Info
= *P
.second
;
546 populateVRegInfo(Info
, Twine(P
.first
));
549 // Compute MachineRegisterInfo::UsedPhysRegMask
550 for (const MachineBasicBlock
&MBB
: MF
) {
551 for (const MachineInstr
&MI
: MBB
) {
552 for (const MachineOperand
&MO
: MI
.operands()) {
555 MRI
.addPhysRegsUsedFromRegMask(MO
.getRegMask());
560 // FIXME: This is a temporary workaround until the reserved registers can be
562 MRI
.freezeReservedRegs(MF
);
566 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
567 const yaml::MachineFunction
&YamlMF
) {
568 MachineFunction
&MF
= PFS
.MF
;
569 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
570 const Function
&F
= MF
.getFunction();
571 const yaml::MachineFrameInfo
&YamlMFI
= YamlMF
.FrameInfo
;
572 MFI
.setFrameAddressIsTaken(YamlMFI
.IsFrameAddressTaken
);
573 MFI
.setReturnAddressIsTaken(YamlMFI
.IsReturnAddressTaken
);
574 MFI
.setHasStackMap(YamlMFI
.HasStackMap
);
575 MFI
.setHasPatchPoint(YamlMFI
.HasPatchPoint
);
576 MFI
.setStackSize(YamlMFI
.StackSize
);
577 MFI
.setOffsetAdjustment(YamlMFI
.OffsetAdjustment
);
578 if (YamlMFI
.MaxAlignment
)
579 MFI
.ensureMaxAlignment(YamlMFI
.MaxAlignment
);
580 MFI
.setAdjustsStack(YamlMFI
.AdjustsStack
);
581 MFI
.setHasCalls(YamlMFI
.HasCalls
);
582 if (YamlMFI
.MaxCallFrameSize
!= ~0u)
583 MFI
.setMaxCallFrameSize(YamlMFI
.MaxCallFrameSize
);
584 MFI
.setCVBytesOfCalleeSavedRegisters(YamlMFI
.CVBytesOfCalleeSavedRegisters
);
585 MFI
.setHasOpaqueSPAdjustment(YamlMFI
.HasOpaqueSPAdjustment
);
586 MFI
.setHasVAStart(YamlMFI
.HasVAStart
);
587 MFI
.setHasMustTailInVarArgFunc(YamlMFI
.HasMustTailInVarArgFunc
);
588 MFI
.setLocalFrameSize(YamlMFI
.LocalFrameSize
);
589 if (!YamlMFI
.SavePoint
.Value
.empty()) {
590 MachineBasicBlock
*MBB
= nullptr;
591 if (parseMBBReference(PFS
, MBB
, YamlMFI
.SavePoint
))
593 MFI
.setSavePoint(MBB
);
595 if (!YamlMFI
.RestorePoint
.Value
.empty()) {
596 MachineBasicBlock
*MBB
= nullptr;
597 if (parseMBBReference(PFS
, MBB
, YamlMFI
.RestorePoint
))
599 MFI
.setRestorePoint(MBB
);
602 std::vector
<CalleeSavedInfo
> CSIInfo
;
603 // Initialize the fixed frame objects.
604 for (const auto &Object
: YamlMF
.FixedStackObjects
) {
606 if (Object
.Type
!= yaml::FixedMachineStackObject::SpillSlot
)
607 ObjectIdx
= MFI
.CreateFixedObject(Object
.Size
, Object
.Offset
,
608 Object
.IsImmutable
, Object
.IsAliased
);
610 ObjectIdx
= MFI
.CreateFixedSpillStackObject(Object
.Size
, Object
.Offset
);
611 MFI
.setObjectAlignment(ObjectIdx
, Object
.Alignment
);
612 MFI
.setStackID(ObjectIdx
, Object
.StackID
);
613 if (!PFS
.FixedStackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
,
616 return error(Object
.ID
.SourceRange
.Start
,
617 Twine("redefinition of fixed stack object '%fixed-stack.") +
618 Twine(Object
.ID
.Value
) + "'");
619 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
620 Object
.CalleeSavedRestored
, ObjectIdx
))
622 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
626 // Initialize the ordinary frame objects.
627 for (const auto &Object
: YamlMF
.StackObjects
) {
629 const AllocaInst
*Alloca
= nullptr;
630 const yaml::StringValue
&Name
= Object
.Name
;
631 if (!Name
.Value
.empty()) {
632 Alloca
= dyn_cast_or_null
<AllocaInst
>(
633 F
.getValueSymbolTable()->lookup(Name
.Value
));
635 return error(Name
.SourceRange
.Start
,
636 "alloca instruction named '" + Name
.Value
+
637 "' isn't defined in the function '" + F
.getName() +
640 if (Object
.Type
== yaml::MachineStackObject::VariableSized
)
641 ObjectIdx
= MFI
.CreateVariableSizedObject(Object
.Alignment
, Alloca
);
643 ObjectIdx
= MFI
.CreateStackObject(
644 Object
.Size
, Object
.Alignment
,
645 Object
.Type
== yaml::MachineStackObject::SpillSlot
, Alloca
);
646 MFI
.setObjectOffset(ObjectIdx
, Object
.Offset
);
647 MFI
.setStackID(ObjectIdx
, Object
.StackID
);
649 if (!PFS
.StackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
, ObjectIdx
))
651 return error(Object
.ID
.SourceRange
.Start
,
652 Twine("redefinition of stack object '%stack.") +
653 Twine(Object
.ID
.Value
) + "'");
654 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
655 Object
.CalleeSavedRestored
, ObjectIdx
))
657 if (Object
.LocalOffset
)
658 MFI
.mapLocalFrameObject(ObjectIdx
, Object
.LocalOffset
.getValue());
659 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
662 MFI
.setCalleeSavedInfo(CSIInfo
);
663 if (!CSIInfo
.empty())
664 MFI
.setCalleeSavedInfoValid(true);
666 // Initialize the various stack object references after initializing the
668 if (!YamlMFI
.StackProtector
.Value
.empty()) {
671 if (parseStackObjectReference(PFS
, FI
, YamlMFI
.StackProtector
.Value
, Error
))
672 return error(Error
, YamlMFI
.StackProtector
.SourceRange
);
673 MFI
.setStackProtectorIndex(FI
);
678 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
679 std::vector
<CalleeSavedInfo
> &CSIInfo
,
680 const yaml::StringValue
&RegisterSource
, bool IsRestored
, int FrameIdx
) {
681 if (RegisterSource
.Value
.empty())
685 if (parseNamedRegisterReference(PFS
, Reg
, RegisterSource
.Value
, Error
))
686 return error(Error
, RegisterSource
.SourceRange
);
687 CalleeSavedInfo
CSI(Reg
, FrameIdx
);
688 CSI
.setRestored(IsRestored
);
689 CSIInfo
.push_back(CSI
);
693 /// Verify that given node is of a certain type. Return true on error.
694 template <typename T
>
695 static bool typecheckMDNode(T
*&Result
, MDNode
*Node
,
696 const yaml::StringValue
&Source
,
697 StringRef TypeString
, MIRParserImpl
&Parser
) {
700 Result
= dyn_cast
<T
>(Node
);
702 return Parser
.error(Source
.SourceRange
.Start
,
703 "expected a reference to a '" + TypeString
+
708 template <typename T
>
709 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
710 const T
&Object
, int FrameIdx
) {
711 // Debug information can only be attached to stack objects; Fixed stack
712 // objects aren't supported.
713 MDNode
*Var
= nullptr, *Expr
= nullptr, *Loc
= nullptr;
714 if (parseMDNode(PFS
, Var
, Object
.DebugVar
) ||
715 parseMDNode(PFS
, Expr
, Object
.DebugExpr
) ||
716 parseMDNode(PFS
, Loc
, Object
.DebugLoc
))
718 if (!Var
&& !Expr
&& !Loc
)
720 DILocalVariable
*DIVar
= nullptr;
721 DIExpression
*DIExpr
= nullptr;
722 DILocation
*DILoc
= nullptr;
723 if (typecheckMDNode(DIVar
, Var
, Object
.DebugVar
, "DILocalVariable", *this) ||
724 typecheckMDNode(DIExpr
, Expr
, Object
.DebugExpr
, "DIExpression", *this) ||
725 typecheckMDNode(DILoc
, Loc
, Object
.DebugLoc
, "DILocation", *this))
727 PFS
.MF
.setVariableDbgInfo(DIVar
, DIExpr
, FrameIdx
, DILoc
);
731 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState
&PFS
,
732 MDNode
*&Node
, const yaml::StringValue
&Source
) {
733 if (Source
.Value
.empty())
736 if (llvm::parseMDNode(PFS
, Node
, Source
.Value
, Error
))
737 return error(Error
, Source
.SourceRange
);
741 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState
&PFS
,
742 MachineConstantPool
&ConstantPool
, const yaml::MachineFunction
&YamlMF
) {
743 DenseMap
<unsigned, unsigned> &ConstantPoolSlots
= PFS
.ConstantPoolSlots
;
744 const MachineFunction
&MF
= PFS
.MF
;
745 const auto &M
= *MF
.getFunction().getParent();
747 for (const auto &YamlConstant
: YamlMF
.Constants
) {
748 if (YamlConstant
.IsTargetSpecific
)
749 // FIXME: Support target-specific constant pools
750 return error(YamlConstant
.Value
.SourceRange
.Start
,
751 "Can't parse target-specific constant pool entries yet");
752 const Constant
*Value
= dyn_cast_or_null
<Constant
>(
753 parseConstantValue(YamlConstant
.Value
.Value
, Error
, M
));
755 return error(Error
, YamlConstant
.Value
.SourceRange
);
757 YamlConstant
.Alignment
758 ? YamlConstant
.Alignment
759 : M
.getDataLayout().getPrefTypeAlignment(Value
->getType());
760 unsigned Index
= ConstantPool
.getConstantPoolIndex(Value
, Alignment
);
761 if (!ConstantPoolSlots
.insert(std::make_pair(YamlConstant
.ID
.Value
, Index
))
763 return error(YamlConstant
.ID
.SourceRange
.Start
,
764 Twine("redefinition of constant pool item '%const.") +
765 Twine(YamlConstant
.ID
.Value
) + "'");
770 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
771 const yaml::MachineJumpTable
&YamlJTI
) {
772 MachineJumpTableInfo
*JTI
= PFS
.MF
.getOrCreateJumpTableInfo(YamlJTI
.Kind
);
773 for (const auto &Entry
: YamlJTI
.Entries
) {
774 std::vector
<MachineBasicBlock
*> Blocks
;
775 for (const auto &MBBSource
: Entry
.Blocks
) {
776 MachineBasicBlock
*MBB
= nullptr;
777 if (parseMBBReference(PFS
, MBB
, MBBSource
.Value
))
779 Blocks
.push_back(MBB
);
781 unsigned Index
= JTI
->createJumpTableIndex(Blocks
);
782 if (!PFS
.JumpTableSlots
.insert(std::make_pair(Entry
.ID
.Value
, Index
))
784 return error(Entry
.ID
.SourceRange
.Start
,
785 Twine("redefinition of jump table entry '%jump-table.") +
786 Twine(Entry
.ID
.Value
) + "'");
791 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState
&PFS
,
792 MachineBasicBlock
*&MBB
,
793 const yaml::StringValue
&Source
) {
795 if (llvm::parseMBBReference(PFS
, MBB
, Source
.Value
, Error
))
796 return error(Error
, Source
.SourceRange
);
800 SMDiagnostic
MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic
&Error
,
801 SMRange SourceRange
) {
802 assert(SourceRange
.isValid() && "Invalid source range");
803 SMLoc Loc
= SourceRange
.Start
;
804 bool HasQuote
= Loc
.getPointer() < SourceRange
.End
.getPointer() &&
805 *Loc
.getPointer() == '\'';
806 // Translate the location of the error from the location in the MI string to
807 // the corresponding location in the MIR file.
808 Loc
= Loc
.getFromPointer(Loc
.getPointer() + Error
.getColumnNo() +
811 // TODO: Translate any source ranges as well.
812 return SM
.GetMessage(Loc
, Error
.getKind(), Error
.getMessage(), None
,
816 SMDiagnostic
MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic
&Error
,
817 SMRange SourceRange
) {
818 assert(SourceRange
.isValid());
820 // Translate the location of the error from the location in the llvm IR string
821 // to the corresponding location in the MIR file.
822 auto LineAndColumn
= SM
.getLineAndColumn(SourceRange
.Start
);
823 unsigned Line
= LineAndColumn
.first
+ Error
.getLineNo() - 1;
824 unsigned Column
= Error
.getColumnNo();
825 StringRef LineStr
= Error
.getLineContents();
826 SMLoc Loc
= Error
.getLoc();
828 // Get the full line and adjust the column number by taking the indentation of
829 // LLVM IR into account.
830 for (line_iterator
L(*SM
.getMemoryBuffer(SM
.getMainFileID()), false), E
;
832 if (L
.line_number() == Line
) {
834 Loc
= SMLoc::getFromPointer(LineStr
.data());
835 auto Indent
= LineStr
.find(Error
.getLineContents());
836 if (Indent
!= StringRef::npos
)
842 return SMDiagnostic(SM
, Loc
, Filename
, Line
, Column
, Error
.getKind(),
843 Error
.getMessage(), LineStr
, Error
.getRanges(),
847 void MIRParserImpl::initNames2RegClasses(const MachineFunction
&MF
) {
848 if (!Names2RegClasses
.empty())
850 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
851 for (unsigned I
= 0, E
= TRI
->getNumRegClasses(); I
< E
; ++I
) {
852 const auto *RC
= TRI
->getRegClass(I
);
853 Names2RegClasses
.insert(
854 std::make_pair(StringRef(TRI
->getRegClassName(RC
)).lower(), RC
));
858 void MIRParserImpl::initNames2RegBanks(const MachineFunction
&MF
) {
859 if (!Names2RegBanks
.empty())
861 const RegisterBankInfo
*RBI
= MF
.getSubtarget().getRegBankInfo();
862 // If the target does not support GlobalISel, we may not have a
863 // register bank info.
866 for (unsigned I
= 0, E
= RBI
->getNumRegBanks(); I
< E
; ++I
) {
867 const auto &RegBank
= RBI
->getRegBank(I
);
868 Names2RegBanks
.insert(
869 std::make_pair(StringRef(RegBank
.getName()).lower(), &RegBank
));
873 const TargetRegisterClass
*MIRParserImpl::getRegClass(const MachineFunction
&MF
,
875 auto RegClassInfo
= Names2RegClasses
.find(Name
);
876 if (RegClassInfo
== Names2RegClasses
.end())
878 return RegClassInfo
->getValue();
881 const RegisterBank
*MIRParserImpl::getRegBank(const MachineFunction
&MF
,
883 auto RegBankInfo
= Names2RegBanks
.find(Name
);
884 if (RegBankInfo
== Names2RegBanks
.end())
886 return RegBankInfo
->getValue();
889 MIRParser::MIRParser(std::unique_ptr
<MIRParserImpl
> Impl
)
890 : Impl(std::move(Impl
)) {}
892 MIRParser::~MIRParser() {}
894 std::unique_ptr
<Module
> MIRParser::parseIRModule() {
895 return Impl
->parseIRModule();
898 bool MIRParser::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
899 return Impl
->parseMachineFunctions(M
, MMI
);
902 std::unique_ptr
<MIRParser
> llvm::createMIRParserFromFile(StringRef Filename
,
904 LLVMContext
&Context
) {
905 auto FileOrErr
= MemoryBuffer::getFileOrSTDIN(Filename
);
906 if (std::error_code EC
= FileOrErr
.getError()) {
907 Error
= SMDiagnostic(Filename
, SourceMgr::DK_Error
,
908 "Could not open input file: " + EC
.message());
911 return createMIRParser(std::move(FileOrErr
.get()), Context
);
914 std::unique_ptr
<MIRParser
>
915 llvm::createMIRParser(std::unique_ptr
<MemoryBuffer
> Contents
,
916 LLVMContext
&Context
) {
917 auto Filename
= Contents
->getBufferIdentifier();
918 if (Context
.shouldDiscardValueNames()) {
919 Context
.diagnose(DiagnosticInfoMIRParser(
922 Filename
, SourceMgr::DK_Error
,
923 "Can't read MIR with a Context that discards named Values")));
926 return llvm::make_unique
<MIRParser
>(
927 llvm::make_unique
<MIRParserImpl
>(std::move(Contents
), Filename
, Context
));