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"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/AsmParser/Parser.h"
19 #include "llvm/AsmParser/SlotMapping.h"
20 #include "llvm/CodeGen/MIRParser/MIParser.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetFrameLowering.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueSymbolTable.h"
35 #include "llvm/Support/LineIterator.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SMLoc.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/YAMLTraits.h"
40 #include "llvm/Target/TargetMachine.h"
49 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
57 std::unique_ptr
<PerTargetMIParsingState
> Target
;
59 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
60 /// created and inserted into the given module when this is true.
61 bool NoLLVMIR
= false;
62 /// True when a well formed MIR file does not contain any MIR/machine function
64 bool NoMIRDocuments
= false;
66 std::function
<void(Function
&)> ProcessIRFunction
;
69 MIRParserImpl(std::unique_ptr
<MemoryBuffer
> Contents
, StringRef Filename
,
71 std::function
<void(Function
&)> ProcessIRFunction
);
73 void reportDiagnostic(const SMDiagnostic
&Diag
);
75 /// Report an error with the given message at unknown location.
77 /// Always returns true.
78 bool error(const Twine
&Message
);
80 /// Report an error with the given message at the given location.
82 /// Always returns true.
83 bool error(SMLoc Loc
, const Twine
&Message
);
85 /// Report a given error with the location translated from the location in an
86 /// embedded string literal to a location in the MIR file.
88 /// Always returns true.
89 bool error(const SMDiagnostic
&Error
, SMRange SourceRange
);
91 /// Try to parse the optional LLVM module and the machine functions in the MIR
94 /// Return null if an error occurred.
95 std::unique_ptr
<Module
>
96 parseIRModule(DataLayoutCallbackTy DataLayoutCallback
);
98 /// Create an empty function with the given name.
99 Function
*createDummyFunction(StringRef Name
, Module
&M
);
101 bool parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
);
103 /// Parse the machine function in the current YAML document.
106 /// Return true if an error occurred.
107 bool parseMachineFunction(Module
&M
, MachineModuleInfo
&MMI
);
109 /// Initialize the machine function to the state that's described in the MIR
112 /// Return true if error occurred.
113 bool initializeMachineFunction(const yaml::MachineFunction
&YamlMF
,
114 MachineFunction
&MF
);
116 bool parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
117 const yaml::MachineFunction
&YamlMF
);
119 bool setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
120 const yaml::MachineFunction
&YamlMF
);
122 bool initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
123 const yaml::MachineFunction
&YamlMF
);
125 bool initializeCallSiteInfo(PerFunctionMIParsingState
&PFS
,
126 const yaml::MachineFunction
&YamlMF
);
128 bool parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
129 std::vector
<CalleeSavedInfo
> &CSIInfo
,
130 const yaml::StringValue
&RegisterSource
,
131 bool IsRestored
, int FrameIdx
);
133 template <typename T
>
134 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
138 bool initializeConstantPool(PerFunctionMIParsingState
&PFS
,
139 MachineConstantPool
&ConstantPool
,
140 const yaml::MachineFunction
&YamlMF
);
142 bool initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
143 const yaml::MachineJumpTable
&YamlJTI
);
145 bool parseMachineMetadataNodes(PerFunctionMIParsingState
&PFS
,
147 const yaml::MachineFunction
&YMF
);
150 bool parseMDNode(PerFunctionMIParsingState
&PFS
, MDNode
*&Node
,
151 const yaml::StringValue
&Source
);
153 bool parseMBBReference(PerFunctionMIParsingState
&PFS
,
154 MachineBasicBlock
*&MBB
,
155 const yaml::StringValue
&Source
);
157 bool parseMachineMetadata(PerFunctionMIParsingState
&PFS
,
158 const yaml::StringValue
&Source
);
160 /// Return a MIR diagnostic converted from an MI string diagnostic.
161 SMDiagnostic
diagFromMIStringDiag(const SMDiagnostic
&Error
,
162 SMRange SourceRange
);
164 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
165 /// block scalar string.
166 SMDiagnostic
diagFromBlockStringDiag(const SMDiagnostic
&Error
,
167 SMRange SourceRange
);
169 void computeFunctionProperties(MachineFunction
&MF
);
171 void setupDebugValueTracking(MachineFunction
&MF
,
172 PerFunctionMIParsingState
&PFS
, const yaml::MachineFunction
&YamlMF
);
175 } // end namespace llvm
177 static void handleYAMLDiag(const SMDiagnostic
&Diag
, void *Context
) {
178 reinterpret_cast<MIRParserImpl
*>(Context
)->reportDiagnostic(Diag
);
181 MIRParserImpl::MIRParserImpl(std::unique_ptr
<MemoryBuffer
> Contents
,
182 StringRef Filename
, LLVMContext
&Context
,
183 std::function
<void(Function
&)> Callback
)
185 In(SM
.getMemoryBuffer(SM
.AddNewSourceBuffer(std::move(Contents
), SMLoc()))
187 nullptr, handleYAMLDiag
, this),
188 Filename(Filename
), ProcessIRFunction(Callback
) {
192 bool MIRParserImpl::error(const Twine
&Message
) {
193 Context
.diagnose(DiagnosticInfoMIRParser(
194 DS_Error
, SMDiagnostic(Filename
, SourceMgr::DK_Error
, Message
.str())));
198 bool MIRParserImpl::error(SMLoc Loc
, const Twine
&Message
) {
199 Context
.diagnose(DiagnosticInfoMIRParser(
200 DS_Error
, SM
.GetMessage(Loc
, SourceMgr::DK_Error
, Message
)));
204 bool MIRParserImpl::error(const SMDiagnostic
&Error
, SMRange SourceRange
) {
205 assert(Error
.getKind() == SourceMgr::DK_Error
&& "Expected an error");
206 reportDiagnostic(diagFromMIStringDiag(Error
, SourceRange
));
210 void MIRParserImpl::reportDiagnostic(const SMDiagnostic
&Diag
) {
211 DiagnosticSeverity Kind
;
212 switch (Diag
.getKind()) {
213 case SourceMgr::DK_Error
:
216 case SourceMgr::DK_Warning
:
219 case SourceMgr::DK_Note
:
222 case SourceMgr::DK_Remark
:
223 llvm_unreachable("remark unexpected");
226 Context
.diagnose(DiagnosticInfoMIRParser(Kind
, Diag
));
229 std::unique_ptr
<Module
>
230 MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback
) {
231 if (!In
.setCurrentDocument()) {
234 // Create an empty module when the MIR file is empty.
235 NoMIRDocuments
= true;
236 auto M
= std::make_unique
<Module
>(Filename
, Context
);
237 if (auto LayoutOverride
= DataLayoutCallback(M
->getTargetTriple()))
238 M
->setDataLayout(*LayoutOverride
);
242 std::unique_ptr
<Module
> M
;
243 // Parse the block scalar manually so that we can return unique pointer
244 // without having to go trough YAML traits.
245 if (const auto *BSN
=
246 dyn_cast_or_null
<yaml::BlockScalarNode
>(In
.getCurrentNode())) {
248 M
= parseAssembly(MemoryBufferRef(BSN
->getValue(), Filename
), Error
,
249 Context
, &IRSlots
, DataLayoutCallback
);
251 reportDiagnostic(diagFromBlockStringDiag(Error
, BSN
->getSourceRange()));
255 if (!In
.setCurrentDocument())
256 NoMIRDocuments
= true;
258 // Create an new, empty module.
259 M
= std::make_unique
<Module
>(Filename
, Context
);
260 if (auto LayoutOverride
= DataLayoutCallback(M
->getTargetTriple()))
261 M
->setDataLayout(*LayoutOverride
);
267 bool MIRParserImpl::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
271 // Parse the machine functions.
273 if (parseMachineFunction(M
, MMI
))
276 } while (In
.setCurrentDocument());
281 Function
*MIRParserImpl::createDummyFunction(StringRef Name
, Module
&M
) {
282 auto &Context
= M
.getContext();
284 Function::Create(FunctionType::get(Type::getVoidTy(Context
), false),
285 Function::ExternalLinkage
, Name
, M
);
286 BasicBlock
*BB
= BasicBlock::Create(Context
, "entry", F
);
287 new UnreachableInst(Context
, BB
);
289 if (ProcessIRFunction
)
290 ProcessIRFunction(*F
);
295 bool MIRParserImpl::parseMachineFunction(Module
&M
, MachineModuleInfo
&MMI
) {
297 yaml::MachineFunction YamlMF
;
298 yaml::EmptyContext Ctx
;
300 const LLVMTargetMachine
&TM
= MMI
.getTarget();
301 YamlMF
.MachineFuncInfo
= std::unique_ptr
<yaml::MachineFunctionInfo
>(
302 TM
.createDefaultFuncInfoYAML());
304 yaml::yamlize(In
, YamlMF
, false, Ctx
);
308 // Search for the corresponding IR function.
309 StringRef FunctionName
= YamlMF
.Name
;
310 Function
*F
= M
.getFunction(FunctionName
);
313 F
= createDummyFunction(FunctionName
, M
);
315 return error(Twine("function '") + FunctionName
+
316 "' isn't defined in the provided LLVM IR");
319 if (MMI
.getMachineFunction(*F
) != nullptr)
320 return error(Twine("redefinition of machine function '") + FunctionName
+
323 // Create the MachineFunction.
324 MachineFunction
&MF
= MMI
.getOrCreateMachineFunction(*F
);
325 if (initializeMachineFunction(YamlMF
, MF
))
331 static bool isSSA(const MachineFunction
&MF
) {
332 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
333 for (unsigned I
= 0, E
= MRI
.getNumVirtRegs(); I
!= E
; ++I
) {
334 Register Reg
= Register::index2VirtReg(I
);
335 if (!MRI
.hasOneDef(Reg
) && !MRI
.def_empty(Reg
))
338 // Subregister defs are invalid in SSA.
339 const MachineOperand
*RegDef
= MRI
.getOneDef(Reg
);
340 if (RegDef
&& RegDef
->getSubReg() != 0)
346 void MIRParserImpl::computeFunctionProperties(MachineFunction
&MF
) {
347 MachineFunctionProperties
&Properties
= MF
.getProperties();
350 bool HasInlineAsm
= false;
351 bool AllTiedOpsRewritten
= true, HasTiedOps
= false;
352 for (const MachineBasicBlock
&MBB
: MF
) {
353 for (const MachineInstr
&MI
: MBB
) {
356 if (MI
.isInlineAsm())
358 for (unsigned I
= 0; I
< MI
.getNumOperands(); ++I
) {
359 const MachineOperand
&MO
= MI
.getOperand(I
);
360 if (!MO
.isReg() || !MO
.getReg())
363 if (MO
.isUse() && MI
.isRegTiedToDefOperand(I
, &DefIdx
)) {
365 if (MO
.getReg() != MI
.getOperand(DefIdx
).getReg())
366 AllTiedOpsRewritten
= false;
372 Properties
.set(MachineFunctionProperties::Property::NoPHIs
);
373 MF
.setHasInlineAsm(HasInlineAsm
);
375 if (HasTiedOps
&& AllTiedOpsRewritten
)
376 Properties
.set(MachineFunctionProperties::Property::TiedOpsRewritten
);
379 Properties
.set(MachineFunctionProperties::Property::IsSSA
);
381 Properties
.reset(MachineFunctionProperties::Property::IsSSA
);
383 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
384 if (MRI
.getNumVirtRegs() == 0)
385 Properties
.set(MachineFunctionProperties::Property::NoVRegs
);
388 bool MIRParserImpl::initializeCallSiteInfo(
389 PerFunctionMIParsingState
&PFS
, const yaml::MachineFunction
&YamlMF
) {
390 MachineFunction
&MF
= PFS
.MF
;
392 const LLVMTargetMachine
&TM
= MF
.getTarget();
393 for (auto YamlCSInfo
: YamlMF
.CallSitesInfo
) {
394 yaml::CallSiteInfo::MachineInstrLoc MILoc
= YamlCSInfo
.CallLocation
;
395 if (MILoc
.BlockNum
>= MF
.size())
396 return error(Twine(MF
.getName()) +
397 Twine(" call instruction block out of range.") +
398 " Unable to reference bb:" + Twine(MILoc
.BlockNum
));
399 auto CallB
= std::next(MF
.begin(), MILoc
.BlockNum
);
400 if (MILoc
.Offset
>= CallB
->size())
401 return error(Twine(MF
.getName()) +
402 Twine(" call instruction offset out of range.") +
403 " Unable to reference instruction at bb: " +
404 Twine(MILoc
.BlockNum
) + " at offset:" + Twine(MILoc
.Offset
));
405 auto CallI
= std::next(CallB
->instr_begin(), MILoc
.Offset
);
406 if (!CallI
->isCall(MachineInstr::IgnoreBundle
))
407 return error(Twine(MF
.getName()) +
408 Twine(" call site info should reference call "
409 "instruction. Instruction at bb:") +
410 Twine(MILoc
.BlockNum
) + " at offset:" + Twine(MILoc
.Offset
) +
411 " is not a call instruction");
412 MachineFunction::CallSiteInfo CSInfo
;
413 for (auto ArgRegPair
: YamlCSInfo
.ArgForwardingRegs
) {
415 if (parseNamedRegisterReference(PFS
, Reg
, ArgRegPair
.Reg
.Value
, Error
))
416 return error(Error
, ArgRegPair
.Reg
.SourceRange
);
417 CSInfo
.emplace_back(Reg
, ArgRegPair
.ArgNo
);
420 if (TM
.Options
.EmitCallSiteInfo
)
421 MF
.addCallArgsForwardingRegs(&*CallI
, std::move(CSInfo
));
424 if (YamlMF
.CallSitesInfo
.size() && !TM
.Options
.EmitCallSiteInfo
)
425 return error(Twine("Call site info provided but not used"));
429 void MIRParserImpl::setupDebugValueTracking(
430 MachineFunction
&MF
, PerFunctionMIParsingState
&PFS
,
431 const yaml::MachineFunction
&YamlMF
) {
432 // Compute the value of the "next instruction number" field.
433 unsigned MaxInstrNum
= 0;
436 MaxInstrNum
= std::max((unsigned)MI
.peekDebugInstrNum(), MaxInstrNum
);
437 MF
.setDebugInstrNumberingCount(MaxInstrNum
);
439 // Load any substitutions.
440 for (const auto &Sub
: YamlMF
.DebugValueSubstitutions
) {
441 MF
.makeDebugValueSubstitution({Sub
.SrcInst
, Sub
.SrcOp
},
442 {Sub
.DstInst
, Sub
.DstOp
}, Sub
.Subreg
);
447 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction
&YamlMF
,
448 MachineFunction
&MF
) {
449 // TODO: Recreate the machine function.
451 // Avoid clearing state if we're using the same subtarget again.
452 Target
->setTarget(MF
.getSubtarget());
454 Target
.reset(new PerTargetMIParsingState(MF
.getSubtarget()));
457 MF
.setAlignment(YamlMF
.Alignment
.valueOrOne());
458 MF
.setExposesReturnsTwice(YamlMF
.ExposesReturnsTwice
);
459 MF
.setHasWinCFI(YamlMF
.HasWinCFI
);
461 MF
.setCallsEHReturn(YamlMF
.CallsEHReturn
);
462 MF
.setCallsUnwindInit(YamlMF
.CallsUnwindInit
);
463 MF
.setHasEHCatchret(YamlMF
.HasEHCatchret
);
464 MF
.setHasEHScopes(YamlMF
.HasEHScopes
);
465 MF
.setHasEHFunclets(YamlMF
.HasEHFunclets
);
467 if (YamlMF
.Legalized
)
468 MF
.getProperties().set(MachineFunctionProperties::Property::Legalized
);
469 if (YamlMF
.RegBankSelected
)
470 MF
.getProperties().set(
471 MachineFunctionProperties::Property::RegBankSelected
);
473 MF
.getProperties().set(MachineFunctionProperties::Property::Selected
);
474 if (YamlMF
.FailedISel
)
475 MF
.getProperties().set(MachineFunctionProperties::Property::FailedISel
);
476 if (YamlMF
.FailsVerification
)
477 MF
.getProperties().set(
478 MachineFunctionProperties::Property::FailsVerification
);
479 if (YamlMF
.TracksDebugUserValues
)
480 MF
.getProperties().set(
481 MachineFunctionProperties::Property::TracksDebugUserValues
);
483 PerFunctionMIParsingState
PFS(MF
, SM
, IRSlots
, *Target
);
484 if (parseRegisterInfo(PFS
, YamlMF
))
486 if (!YamlMF
.Constants
.empty()) {
487 auto *ConstantPool
= MF
.getConstantPool();
488 assert(ConstantPool
&& "Constant pool must be created");
489 if (initializeConstantPool(PFS
, *ConstantPool
, YamlMF
))
492 if (!YamlMF
.MachineMetadataNodes
.empty() &&
493 parseMachineMetadataNodes(PFS
, MF
, YamlMF
))
496 StringRef BlockStr
= YamlMF
.Body
.Value
.Value
;
499 BlockSM
.AddNewSourceBuffer(
500 MemoryBuffer::getMemBuffer(BlockStr
, "",/*RequiresNullTerminator=*/false),
503 if (parseMachineBasicBlockDefinitions(PFS
, BlockStr
, Error
)) {
505 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
508 // Check Basic Block Section Flags.
509 if (MF
.getTarget().getBBSectionsType() == BasicBlockSection::Labels
) {
510 MF
.setBBSectionsType(BasicBlockSection::Labels
);
511 } else if (MF
.hasBBSections()) {
512 MF
.assignBeginEndSections();
516 // Initialize the frame information after creating all the MBBs so that the
517 // MBB references in the frame information can be resolved.
518 if (initializeFrameInfo(PFS
, YamlMF
))
520 // Initialize the jump table after creating all the MBBs so that the MBB
521 // references can be resolved.
522 if (!YamlMF
.JumpTableInfo
.Entries
.empty() &&
523 initializeJumpTableInfo(PFS
, YamlMF
.JumpTableInfo
))
525 // Parse the machine instructions after creating all of the MBBs so that the
526 // parser can resolve the MBB references.
527 StringRef InsnStr
= YamlMF
.Body
.Value
.Value
;
529 InsnSM
.AddNewSourceBuffer(
530 MemoryBuffer::getMemBuffer(InsnStr
, "", /*RequiresNullTerminator=*/false),
533 if (parseMachineInstructions(PFS
, InsnStr
, Error
)) {
535 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
540 if (setupRegisterInfo(PFS
, YamlMF
))
543 if (YamlMF
.MachineFuncInfo
) {
544 const LLVMTargetMachine
&TM
= MF
.getTarget();
545 // Note this is called after the initial constructor of the
546 // MachineFunctionInfo based on the MachineFunction, which may depend on the
550 if (TM
.parseMachineFunctionInfo(*YamlMF
.MachineFuncInfo
, PFS
, Error
,
552 return error(Error
, SrcRange
);
556 // Set the reserved registers after parsing MachineFuncInfo. The target may
557 // have been recording information used to select the reserved registers
559 // FIXME: This is a temporary workaround until the reserved registers can be
561 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
562 MRI
.freezeReservedRegs(MF
);
564 computeFunctionProperties(MF
);
566 if (initializeCallSiteInfo(PFS
, YamlMF
))
569 setupDebugValueTracking(MF
, PFS
, YamlMF
);
571 MF
.getSubtarget().mirFileLoaded(MF
);
577 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
578 const yaml::MachineFunction
&YamlMF
) {
579 MachineFunction
&MF
= PFS
.MF
;
580 MachineRegisterInfo
&RegInfo
= MF
.getRegInfo();
581 assert(RegInfo
.tracksLiveness());
582 if (!YamlMF
.TracksRegLiveness
)
583 RegInfo
.invalidateLiveness();
586 // Parse the virtual register information.
587 for (const auto &VReg
: YamlMF
.VirtualRegisters
) {
588 VRegInfo
&Info
= PFS
.getVRegInfo(VReg
.ID
.Value
);
590 return error(VReg
.ID
.SourceRange
.Start
,
591 Twine("redefinition of virtual register '%") +
592 Twine(VReg
.ID
.Value
) + "'");
593 Info
.Explicit
= true;
595 if (StringRef(VReg
.Class
.Value
).equals("_")) {
596 Info
.Kind
= VRegInfo::GENERIC
;
597 Info
.D
.RegBank
= nullptr;
599 const auto *RC
= Target
->getRegClass(VReg
.Class
.Value
);
601 Info
.Kind
= VRegInfo::NORMAL
;
604 const RegisterBank
*RegBank
= Target
->getRegBank(VReg
.Class
.Value
);
607 VReg
.Class
.SourceRange
.Start
,
608 Twine("use of undefined register class or register bank '") +
609 VReg
.Class
.Value
+ "'");
610 Info
.Kind
= VRegInfo::REGBANK
;
611 Info
.D
.RegBank
= RegBank
;
615 if (!VReg
.PreferredRegister
.Value
.empty()) {
616 if (Info
.Kind
!= VRegInfo::NORMAL
)
617 return error(VReg
.Class
.SourceRange
.Start
,
618 Twine("preferred register can only be set for normal vregs"));
620 if (parseRegisterReference(PFS
, Info
.PreferredReg
,
621 VReg
.PreferredRegister
.Value
, Error
))
622 return error(Error
, VReg
.PreferredRegister
.SourceRange
);
626 // Parse the liveins.
627 for (const auto &LiveIn
: YamlMF
.LiveIns
) {
629 if (parseNamedRegisterReference(PFS
, Reg
, LiveIn
.Register
.Value
, Error
))
630 return error(Error
, LiveIn
.Register
.SourceRange
);
632 if (!LiveIn
.VirtualRegister
.Value
.empty()) {
634 if (parseVirtualRegisterReference(PFS
, Info
, LiveIn
.VirtualRegister
.Value
,
636 return error(Error
, LiveIn
.VirtualRegister
.SourceRange
);
639 RegInfo
.addLiveIn(Reg
, VReg
);
642 // Parse the callee saved registers (Registers that will
643 // be saved for the caller).
644 if (YamlMF
.CalleeSavedRegisters
) {
645 SmallVector
<MCPhysReg
, 16> CalleeSavedRegisters
;
646 for (const auto &RegSource
: *YamlMF
.CalleeSavedRegisters
) {
648 if (parseNamedRegisterReference(PFS
, Reg
, RegSource
.Value
, Error
))
649 return error(Error
, RegSource
.SourceRange
);
650 CalleeSavedRegisters
.push_back(Reg
);
652 RegInfo
.setCalleeSavedRegs(CalleeSavedRegisters
);
658 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
659 const yaml::MachineFunction
&YamlMF
) {
660 MachineFunction
&MF
= PFS
.MF
;
661 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
664 auto populateVRegInfo
= [&] (const VRegInfo
&Info
, Twine Name
) {
665 Register Reg
= Info
.VReg
;
667 case VRegInfo::UNKNOWN
:
668 error(Twine("Cannot determine class/bank of virtual register ") +
669 Name
+ " in function '" + MF
.getName() + "'");
672 case VRegInfo::NORMAL
:
673 MRI
.setRegClass(Reg
, Info
.D
.RC
);
674 if (Info
.PreferredReg
!= 0)
675 MRI
.setSimpleHint(Reg
, Info
.PreferredReg
);
677 case VRegInfo::GENERIC
:
679 case VRegInfo::REGBANK
:
680 MRI
.setRegBank(Reg
, *Info
.D
.RegBank
);
685 for (const auto &P
: PFS
.VRegInfosNamed
) {
686 const VRegInfo
&Info
= *P
.second
;
687 populateVRegInfo(Info
, Twine(P
.first()));
690 for (auto P
: PFS
.VRegInfos
) {
691 const VRegInfo
&Info
= *P
.second
;
692 populateVRegInfo(Info
, Twine(P
.first
));
695 // Compute MachineRegisterInfo::UsedPhysRegMask
696 for (const MachineBasicBlock
&MBB
: MF
) {
697 // Make sure MRI knows about registers clobbered by unwinder.
698 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
700 if (auto *RegMask
= TRI
->getCustomEHPadPreservedMask(MF
))
701 MRI
.addPhysRegsUsedFromRegMask(RegMask
);
703 for (const MachineInstr
&MI
: MBB
) {
704 for (const MachineOperand
&MO
: MI
.operands()) {
707 MRI
.addPhysRegsUsedFromRegMask(MO
.getRegMask());
715 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
716 const yaml::MachineFunction
&YamlMF
) {
717 MachineFunction
&MF
= PFS
.MF
;
718 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
719 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
720 const Function
&F
= MF
.getFunction();
721 const yaml::MachineFrameInfo
&YamlMFI
= YamlMF
.FrameInfo
;
722 MFI
.setFrameAddressIsTaken(YamlMFI
.IsFrameAddressTaken
);
723 MFI
.setReturnAddressIsTaken(YamlMFI
.IsReturnAddressTaken
);
724 MFI
.setHasStackMap(YamlMFI
.HasStackMap
);
725 MFI
.setHasPatchPoint(YamlMFI
.HasPatchPoint
);
726 MFI
.setStackSize(YamlMFI
.StackSize
);
727 MFI
.setOffsetAdjustment(YamlMFI
.OffsetAdjustment
);
728 if (YamlMFI
.MaxAlignment
)
729 MFI
.ensureMaxAlignment(Align(YamlMFI
.MaxAlignment
));
730 MFI
.setAdjustsStack(YamlMFI
.AdjustsStack
);
731 MFI
.setHasCalls(YamlMFI
.HasCalls
);
732 if (YamlMFI
.MaxCallFrameSize
!= ~0u)
733 MFI
.setMaxCallFrameSize(YamlMFI
.MaxCallFrameSize
);
734 MFI
.setCVBytesOfCalleeSavedRegisters(YamlMFI
.CVBytesOfCalleeSavedRegisters
);
735 MFI
.setHasOpaqueSPAdjustment(YamlMFI
.HasOpaqueSPAdjustment
);
736 MFI
.setHasVAStart(YamlMFI
.HasVAStart
);
737 MFI
.setHasMustTailInVarArgFunc(YamlMFI
.HasMustTailInVarArgFunc
);
738 MFI
.setHasTailCall(YamlMFI
.HasTailCall
);
739 MFI
.setLocalFrameSize(YamlMFI
.LocalFrameSize
);
740 if (!YamlMFI
.SavePoint
.Value
.empty()) {
741 MachineBasicBlock
*MBB
= nullptr;
742 if (parseMBBReference(PFS
, MBB
, YamlMFI
.SavePoint
))
744 MFI
.setSavePoint(MBB
);
746 if (!YamlMFI
.RestorePoint
.Value
.empty()) {
747 MachineBasicBlock
*MBB
= nullptr;
748 if (parseMBBReference(PFS
, MBB
, YamlMFI
.RestorePoint
))
750 MFI
.setRestorePoint(MBB
);
753 std::vector
<CalleeSavedInfo
> CSIInfo
;
754 // Initialize the fixed frame objects.
755 for (const auto &Object
: YamlMF
.FixedStackObjects
) {
757 if (Object
.Type
!= yaml::FixedMachineStackObject::SpillSlot
)
758 ObjectIdx
= MFI
.CreateFixedObject(Object
.Size
, Object
.Offset
,
759 Object
.IsImmutable
, Object
.IsAliased
);
761 ObjectIdx
= MFI
.CreateFixedSpillStackObject(Object
.Size
, Object
.Offset
);
763 if (!TFI
->isSupportedStackID(Object
.StackID
))
764 return error(Object
.ID
.SourceRange
.Start
,
765 Twine("StackID is not supported by target"));
766 MFI
.setStackID(ObjectIdx
, Object
.StackID
);
767 MFI
.setObjectAlignment(ObjectIdx
, Object
.Alignment
.valueOrOne());
768 if (!PFS
.FixedStackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
,
771 return error(Object
.ID
.SourceRange
.Start
,
772 Twine("redefinition of fixed stack object '%fixed-stack.") +
773 Twine(Object
.ID
.Value
) + "'");
774 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
775 Object
.CalleeSavedRestored
, ObjectIdx
))
777 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
781 // Initialize the ordinary frame objects.
782 for (const auto &Object
: YamlMF
.StackObjects
) {
784 const AllocaInst
*Alloca
= nullptr;
785 const yaml::StringValue
&Name
= Object
.Name
;
786 if (!Name
.Value
.empty()) {
787 Alloca
= dyn_cast_or_null
<AllocaInst
>(
788 F
.getValueSymbolTable()->lookup(Name
.Value
));
790 return error(Name
.SourceRange
.Start
,
791 "alloca instruction named '" + Name
.Value
+
792 "' isn't defined in the function '" + F
.getName() +
795 if (!TFI
->isSupportedStackID(Object
.StackID
))
796 return error(Object
.ID
.SourceRange
.Start
,
797 Twine("StackID is not supported by target"));
798 if (Object
.Type
== yaml::MachineStackObject::VariableSized
)
800 MFI
.CreateVariableSizedObject(Object
.Alignment
.valueOrOne(), Alloca
);
802 ObjectIdx
= MFI
.CreateStackObject(
803 Object
.Size
, Object
.Alignment
.valueOrOne(),
804 Object
.Type
== yaml::MachineStackObject::SpillSlot
, Alloca
,
806 MFI
.setObjectOffset(ObjectIdx
, Object
.Offset
);
808 if (!PFS
.StackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
, ObjectIdx
))
810 return error(Object
.ID
.SourceRange
.Start
,
811 Twine("redefinition of stack object '%stack.") +
812 Twine(Object
.ID
.Value
) + "'");
813 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
814 Object
.CalleeSavedRestored
, ObjectIdx
))
816 if (Object
.LocalOffset
)
817 MFI
.mapLocalFrameObject(ObjectIdx
, *Object
.LocalOffset
);
818 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
821 MFI
.setCalleeSavedInfo(CSIInfo
);
822 if (!CSIInfo
.empty())
823 MFI
.setCalleeSavedInfoValid(true);
825 // Initialize the various stack object references after initializing the
827 if (!YamlMFI
.StackProtector
.Value
.empty()) {
830 if (parseStackObjectReference(PFS
, FI
, YamlMFI
.StackProtector
.Value
, Error
))
831 return error(Error
, YamlMFI
.StackProtector
.SourceRange
);
832 MFI
.setStackProtectorIndex(FI
);
835 if (!YamlMFI
.FunctionContext
.Value
.empty()) {
838 if (parseStackObjectReference(PFS
, FI
, YamlMFI
.FunctionContext
.Value
, Error
))
839 return error(Error
, YamlMFI
.FunctionContext
.SourceRange
);
840 MFI
.setFunctionContextIndex(FI
);
846 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
847 std::vector
<CalleeSavedInfo
> &CSIInfo
,
848 const yaml::StringValue
&RegisterSource
, bool IsRestored
, int FrameIdx
) {
849 if (RegisterSource
.Value
.empty())
853 if (parseNamedRegisterReference(PFS
, Reg
, RegisterSource
.Value
, Error
))
854 return error(Error
, RegisterSource
.SourceRange
);
855 CalleeSavedInfo
CSI(Reg
, FrameIdx
);
856 CSI
.setRestored(IsRestored
);
857 CSIInfo
.push_back(CSI
);
861 /// Verify that given node is of a certain type. Return true on error.
862 template <typename T
>
863 static bool typecheckMDNode(T
*&Result
, MDNode
*Node
,
864 const yaml::StringValue
&Source
,
865 StringRef TypeString
, MIRParserImpl
&Parser
) {
868 Result
= dyn_cast
<T
>(Node
);
870 return Parser
.error(Source
.SourceRange
.Start
,
871 "expected a reference to a '" + TypeString
+
876 template <typename T
>
877 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
878 const T
&Object
, int FrameIdx
) {
879 // Debug information can only be attached to stack objects; Fixed stack
880 // objects aren't supported.
881 MDNode
*Var
= nullptr, *Expr
= nullptr, *Loc
= nullptr;
882 if (parseMDNode(PFS
, Var
, Object
.DebugVar
) ||
883 parseMDNode(PFS
, Expr
, Object
.DebugExpr
) ||
884 parseMDNode(PFS
, Loc
, Object
.DebugLoc
))
886 if (!Var
&& !Expr
&& !Loc
)
888 DILocalVariable
*DIVar
= nullptr;
889 DIExpression
*DIExpr
= nullptr;
890 DILocation
*DILoc
= nullptr;
891 if (typecheckMDNode(DIVar
, Var
, Object
.DebugVar
, "DILocalVariable", *this) ||
892 typecheckMDNode(DIExpr
, Expr
, Object
.DebugExpr
, "DIExpression", *this) ||
893 typecheckMDNode(DILoc
, Loc
, Object
.DebugLoc
, "DILocation", *this))
895 PFS
.MF
.setVariableDbgInfo(DIVar
, DIExpr
, FrameIdx
, DILoc
);
899 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState
&PFS
,
900 MDNode
*&Node
, const yaml::StringValue
&Source
) {
901 if (Source
.Value
.empty())
904 if (llvm::parseMDNode(PFS
, Node
, Source
.Value
, Error
))
905 return error(Error
, Source
.SourceRange
);
909 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState
&PFS
,
910 MachineConstantPool
&ConstantPool
, const yaml::MachineFunction
&YamlMF
) {
911 DenseMap
<unsigned, unsigned> &ConstantPoolSlots
= PFS
.ConstantPoolSlots
;
912 const MachineFunction
&MF
= PFS
.MF
;
913 const auto &M
= *MF
.getFunction().getParent();
915 for (const auto &YamlConstant
: YamlMF
.Constants
) {
916 if (YamlConstant
.IsTargetSpecific
)
917 // FIXME: Support target-specific constant pools
918 return error(YamlConstant
.Value
.SourceRange
.Start
,
919 "Can't parse target-specific constant pool entries yet");
920 const Constant
*Value
= dyn_cast_or_null
<Constant
>(
921 parseConstantValue(YamlConstant
.Value
.Value
, Error
, M
));
923 return error(Error
, YamlConstant
.Value
.SourceRange
);
924 const Align PrefTypeAlign
=
925 M
.getDataLayout().getPrefTypeAlign(Value
->getType());
926 const Align Alignment
= YamlConstant
.Alignment
.value_or(PrefTypeAlign
);
927 unsigned Index
= ConstantPool
.getConstantPoolIndex(Value
, Alignment
);
928 if (!ConstantPoolSlots
.insert(std::make_pair(YamlConstant
.ID
.Value
, Index
))
930 return error(YamlConstant
.ID
.SourceRange
.Start
,
931 Twine("redefinition of constant pool item '%const.") +
932 Twine(YamlConstant
.ID
.Value
) + "'");
937 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
938 const yaml::MachineJumpTable
&YamlJTI
) {
939 MachineJumpTableInfo
*JTI
= PFS
.MF
.getOrCreateJumpTableInfo(YamlJTI
.Kind
);
940 for (const auto &Entry
: YamlJTI
.Entries
) {
941 std::vector
<MachineBasicBlock
*> Blocks
;
942 for (const auto &MBBSource
: Entry
.Blocks
) {
943 MachineBasicBlock
*MBB
= nullptr;
944 if (parseMBBReference(PFS
, MBB
, MBBSource
.Value
))
946 Blocks
.push_back(MBB
);
948 unsigned Index
= JTI
->createJumpTableIndex(Blocks
);
949 if (!PFS
.JumpTableSlots
.insert(std::make_pair(Entry
.ID
.Value
, Index
))
951 return error(Entry
.ID
.SourceRange
.Start
,
952 Twine("redefinition of jump table entry '%jump-table.") +
953 Twine(Entry
.ID
.Value
) + "'");
958 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState
&PFS
,
959 MachineBasicBlock
*&MBB
,
960 const yaml::StringValue
&Source
) {
962 if (llvm::parseMBBReference(PFS
, MBB
, Source
.Value
, Error
))
963 return error(Error
, Source
.SourceRange
);
967 bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState
&PFS
,
968 const yaml::StringValue
&Source
) {
970 if (llvm::parseMachineMetadata(PFS
, Source
.Value
, Source
.SourceRange
, Error
))
971 return error(Error
, Source
.SourceRange
);
975 bool MIRParserImpl::parseMachineMetadataNodes(
976 PerFunctionMIParsingState
&PFS
, MachineFunction
&MF
,
977 const yaml::MachineFunction
&YMF
) {
978 for (const auto &MDS
: YMF
.MachineMetadataNodes
) {
979 if (parseMachineMetadata(PFS
, MDS
))
982 // Report missing definitions from forward referenced nodes.
983 if (!PFS
.MachineForwardRefMDNodes
.empty())
984 return error(PFS
.MachineForwardRefMDNodes
.begin()->second
.second
,
985 "use of undefined metadata '!" +
986 Twine(PFS
.MachineForwardRefMDNodes
.begin()->first
) + "'");
990 SMDiagnostic
MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic
&Error
,
991 SMRange SourceRange
) {
992 assert(SourceRange
.isValid() && "Invalid source range");
993 SMLoc Loc
= SourceRange
.Start
;
994 bool HasQuote
= Loc
.getPointer() < SourceRange
.End
.getPointer() &&
995 *Loc
.getPointer() == '\'';
996 // Translate the location of the error from the location in the MI string to
997 // the corresponding location in the MIR file.
998 Loc
= Loc
.getFromPointer(Loc
.getPointer() + Error
.getColumnNo() +
1001 // TODO: Translate any source ranges as well.
1002 return SM
.GetMessage(Loc
, Error
.getKind(), Error
.getMessage(), None
,
1006 SMDiagnostic
MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic
&Error
,
1007 SMRange SourceRange
) {
1008 assert(SourceRange
.isValid());
1010 // Translate the location of the error from the location in the llvm IR string
1011 // to the corresponding location in the MIR file.
1012 auto LineAndColumn
= SM
.getLineAndColumn(SourceRange
.Start
);
1013 unsigned Line
= LineAndColumn
.first
+ Error
.getLineNo() - 1;
1014 unsigned Column
= Error
.getColumnNo();
1015 StringRef LineStr
= Error
.getLineContents();
1016 SMLoc Loc
= Error
.getLoc();
1018 // Get the full line and adjust the column number by taking the indentation of
1019 // LLVM IR into account.
1020 for (line_iterator
L(*SM
.getMemoryBuffer(SM
.getMainFileID()), false), E
;
1022 if (L
.line_number() == Line
) {
1024 Loc
= SMLoc::getFromPointer(LineStr
.data());
1025 auto Indent
= LineStr
.find(Error
.getLineContents());
1026 if (Indent
!= StringRef::npos
)
1032 return SMDiagnostic(SM
, Loc
, Filename
, Line
, Column
, Error
.getKind(),
1033 Error
.getMessage(), LineStr
, Error
.getRanges(),
1037 MIRParser::MIRParser(std::unique_ptr
<MIRParserImpl
> Impl
)
1038 : Impl(std::move(Impl
)) {}
1040 MIRParser::~MIRParser() = default;
1042 std::unique_ptr
<Module
>
1043 MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback
) {
1044 return Impl
->parseIRModule(DataLayoutCallback
);
1047 bool MIRParser::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
1048 return Impl
->parseMachineFunctions(M
, MMI
);
1051 std::unique_ptr
<MIRParser
> llvm::createMIRParserFromFile(
1052 StringRef Filename
, SMDiagnostic
&Error
, LLVMContext
&Context
,
1053 std::function
<void(Function
&)> ProcessIRFunction
) {
1054 auto FileOrErr
= MemoryBuffer::getFileOrSTDIN(Filename
, /*IsText=*/true);
1055 if (std::error_code EC
= FileOrErr
.getError()) {
1056 Error
= SMDiagnostic(Filename
, SourceMgr::DK_Error
,
1057 "Could not open input file: " + EC
.message());
1060 return createMIRParser(std::move(FileOrErr
.get()), Context
,
1064 std::unique_ptr
<MIRParser
>
1065 llvm::createMIRParser(std::unique_ptr
<MemoryBuffer
> Contents
,
1066 LLVMContext
&Context
,
1067 std::function
<void(Function
&)> ProcessIRFunction
) {
1068 auto Filename
= Contents
->getBufferIdentifier();
1069 if (Context
.shouldDiscardValueNames()) {
1070 Context
.diagnose(DiagnosticInfoMIRParser(
1073 Filename
, SourceMgr::DK_Error
,
1074 "Can't read MIR with a Context that discards named Values")));
1077 return std::make_unique
<MIRParser
>(std::make_unique
<MIRParserImpl
>(
1078 std::move(Contents
), Filename
, Context
, ProcessIRFunction
));