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/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/AsmParser/Parser.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
22 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
23 #include "llvm/CodeGen/MIRParser/MIParser.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/CodeGen/TargetFrameLowering.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"
43 #include "llvm/Target/TargetMachine.h"
50 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
58 std::unique_ptr
<PerTargetMIParsingState
> Target
;
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 initializeCallSiteInfo(PerFunctionMIParsingState
&PFS
,
120 const yaml::MachineFunction
&YamlMF
);
122 bool parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
123 std::vector
<CalleeSavedInfo
> &CSIInfo
,
124 const yaml::StringValue
&RegisterSource
,
125 bool IsRestored
, int FrameIdx
);
127 template <typename T
>
128 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
132 bool initializeConstantPool(PerFunctionMIParsingState
&PFS
,
133 MachineConstantPool
&ConstantPool
,
134 const yaml::MachineFunction
&YamlMF
);
136 bool initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
137 const yaml::MachineJumpTable
&YamlJTI
);
140 bool parseMDNode(PerFunctionMIParsingState
&PFS
, MDNode
*&Node
,
141 const yaml::StringValue
&Source
);
143 bool parseMBBReference(PerFunctionMIParsingState
&PFS
,
144 MachineBasicBlock
*&MBB
,
145 const yaml::StringValue
&Source
);
147 /// Return a MIR diagnostic converted from an MI string diagnostic.
148 SMDiagnostic
diagFromMIStringDiag(const SMDiagnostic
&Error
,
149 SMRange SourceRange
);
151 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
152 /// block scalar string.
153 SMDiagnostic
diagFromBlockStringDiag(const SMDiagnostic
&Error
,
154 SMRange SourceRange
);
156 void computeFunctionProperties(MachineFunction
&MF
);
159 } // end namespace llvm
161 static void handleYAMLDiag(const SMDiagnostic
&Diag
, void *Context
) {
162 reinterpret_cast<MIRParserImpl
*>(Context
)->reportDiagnostic(Diag
);
165 MIRParserImpl::MIRParserImpl(std::unique_ptr
<MemoryBuffer
> Contents
,
166 StringRef Filename
, LLVMContext
&Context
)
168 In(SM
.getMemoryBuffer(
169 SM
.AddNewSourceBuffer(std::move(Contents
), SMLoc()))->getBuffer(),
170 nullptr, handleYAMLDiag
, this),
176 bool MIRParserImpl::error(const Twine
&Message
) {
177 Context
.diagnose(DiagnosticInfoMIRParser(
178 DS_Error
, SMDiagnostic(Filename
, SourceMgr::DK_Error
, Message
.str())));
182 bool MIRParserImpl::error(SMLoc Loc
, const Twine
&Message
) {
183 Context
.diagnose(DiagnosticInfoMIRParser(
184 DS_Error
, SM
.GetMessage(Loc
, SourceMgr::DK_Error
, Message
)));
188 bool MIRParserImpl::error(const SMDiagnostic
&Error
, SMRange SourceRange
) {
189 assert(Error
.getKind() == SourceMgr::DK_Error
&& "Expected an error");
190 reportDiagnostic(diagFromMIStringDiag(Error
, SourceRange
));
194 void MIRParserImpl::reportDiagnostic(const SMDiagnostic
&Diag
) {
195 DiagnosticSeverity Kind
;
196 switch (Diag
.getKind()) {
197 case SourceMgr::DK_Error
:
200 case SourceMgr::DK_Warning
:
203 case SourceMgr::DK_Note
:
206 case SourceMgr::DK_Remark
:
207 llvm_unreachable("remark unexpected");
210 Context
.diagnose(DiagnosticInfoMIRParser(Kind
, Diag
));
213 std::unique_ptr
<Module
> MIRParserImpl::parseIRModule() {
214 if (!In
.setCurrentDocument()) {
217 // Create an empty module when the MIR file is empty.
218 NoMIRDocuments
= true;
219 return std::make_unique
<Module
>(Filename
, Context
);
222 std::unique_ptr
<Module
> M
;
223 // Parse the block scalar manually so that we can return unique pointer
224 // without having to go trough YAML traits.
225 if (const auto *BSN
=
226 dyn_cast_or_null
<yaml::BlockScalarNode
>(In
.getCurrentNode())) {
228 M
= parseAssembly(MemoryBufferRef(BSN
->getValue(), Filename
), Error
,
229 Context
, &IRSlots
, /*UpgradeDebugInfo=*/false);
231 reportDiagnostic(diagFromBlockStringDiag(Error
, BSN
->getSourceRange()));
235 if (!In
.setCurrentDocument())
236 NoMIRDocuments
= true;
238 // Create an new, empty module.
239 M
= std::make_unique
<Module
>(Filename
, Context
);
245 bool MIRParserImpl::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
249 // Parse the machine functions.
251 if (parseMachineFunction(M
, MMI
))
254 } while (In
.setCurrentDocument());
259 /// Create an empty function with the given name.
260 static Function
*createDummyFunction(StringRef Name
, Module
&M
) {
261 auto &Context
= M
.getContext();
263 Function::Create(FunctionType::get(Type::getVoidTy(Context
), false),
264 Function::ExternalLinkage
, Name
, M
);
265 BasicBlock
*BB
= BasicBlock::Create(Context
, "entry", F
);
266 new UnreachableInst(Context
, BB
);
270 bool MIRParserImpl::parseMachineFunction(Module
&M
, MachineModuleInfo
&MMI
) {
272 yaml::MachineFunction YamlMF
;
273 yaml::EmptyContext Ctx
;
275 const LLVMTargetMachine
&TM
= MMI
.getTarget();
276 YamlMF
.MachineFuncInfo
= std::unique_ptr
<yaml::MachineFunctionInfo
>(
277 TM
.createDefaultFuncInfoYAML());
279 yaml::yamlize(In
, YamlMF
, false, Ctx
);
283 // Search for the corresponding IR function.
284 StringRef FunctionName
= YamlMF
.Name
;
285 Function
*F
= M
.getFunction(FunctionName
);
288 F
= createDummyFunction(FunctionName
, M
);
290 return error(Twine("function '") + FunctionName
+
291 "' isn't defined in the provided LLVM IR");
294 if (MMI
.getMachineFunction(*F
) != nullptr)
295 return error(Twine("redefinition of machine function '") + FunctionName
+
298 // Create the MachineFunction.
299 MachineFunction
&MF
= MMI
.getOrCreateMachineFunction(*F
);
300 if (initializeMachineFunction(YamlMF
, MF
))
306 static bool isSSA(const MachineFunction
&MF
) {
307 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
308 for (unsigned I
= 0, E
= MRI
.getNumVirtRegs(); I
!= E
; ++I
) {
309 unsigned Reg
= Register::index2VirtReg(I
);
310 if (!MRI
.hasOneDef(Reg
) && !MRI
.def_empty(Reg
))
316 void MIRParserImpl::computeFunctionProperties(MachineFunction
&MF
) {
317 MachineFunctionProperties
&Properties
= MF
.getProperties();
320 bool HasInlineAsm
= false;
321 for (const MachineBasicBlock
&MBB
: MF
) {
322 for (const MachineInstr
&MI
: MBB
) {
325 if (MI
.isInlineAsm())
330 Properties
.set(MachineFunctionProperties::Property::NoPHIs
);
331 MF
.setHasInlineAsm(HasInlineAsm
);
334 Properties
.set(MachineFunctionProperties::Property::IsSSA
);
336 Properties
.reset(MachineFunctionProperties::Property::IsSSA
);
338 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
339 if (MRI
.getNumVirtRegs() == 0)
340 Properties
.set(MachineFunctionProperties::Property::NoVRegs
);
343 bool MIRParserImpl::initializeCallSiteInfo(
344 PerFunctionMIParsingState
&PFS
, const yaml::MachineFunction
&YamlMF
) {
345 MachineFunction
&MF
= PFS
.MF
;
347 const LLVMTargetMachine
&TM
= MF
.getTarget();
348 for (auto YamlCSInfo
: YamlMF
.CallSitesInfo
) {
349 yaml::CallSiteInfo::MachineInstrLoc MILoc
= YamlCSInfo
.CallLocation
;
350 if (MILoc
.BlockNum
>= MF
.size())
351 return error(Twine(MF
.getName()) +
352 Twine(" call instruction block out of range.") +
353 " Unable to reference bb:" + Twine(MILoc
.BlockNum
));
354 auto CallB
= std::next(MF
.begin(), MILoc
.BlockNum
);
355 if (MILoc
.Offset
>= CallB
->size())
356 return error(Twine(MF
.getName()) +
357 Twine(" call instruction offset out of range.") +
358 " Unable to reference instruction at bb: " +
359 Twine(MILoc
.BlockNum
) + " at offset:" + Twine(MILoc
.Offset
));
360 auto CallI
= std::next(CallB
->instr_begin(), MILoc
.Offset
);
361 if (!CallI
->isCall(MachineInstr::IgnoreBundle
))
362 return error(Twine(MF
.getName()) +
363 Twine(" call site info should reference call "
364 "instruction. Instruction at bb:") +
365 Twine(MILoc
.BlockNum
) + " at offset:" + Twine(MILoc
.Offset
) +
366 " is not a call instruction");
367 MachineFunction::CallSiteInfo CSInfo
;
368 for (auto ArgRegPair
: YamlCSInfo
.ArgForwardingRegs
) {
370 if (parseNamedRegisterReference(PFS
, Reg
, ArgRegPair
.Reg
.Value
, Error
))
371 return error(Error
, ArgRegPair
.Reg
.SourceRange
);
372 CSInfo
.emplace_back(Reg
, ArgRegPair
.ArgNo
);
375 if (TM
.Options
.EnableDebugEntryValues
)
376 MF
.addCallArgsForwardingRegs(&*CallI
, std::move(CSInfo
));
379 if (YamlMF
.CallSitesInfo
.size() && !TM
.Options
.EnableDebugEntryValues
)
380 return error(Twine("Call site info provided but not used"));
385 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction
&YamlMF
,
386 MachineFunction
&MF
) {
387 // TODO: Recreate the machine function.
389 // Avoid clearing state if we're using the same subtarget again.
390 Target
->setTarget(MF
.getSubtarget());
392 Target
.reset(new PerTargetMIParsingState(MF
.getSubtarget()));
395 if (YamlMF
.Alignment
)
396 MF
.setAlignment(Align(YamlMF
.Alignment
));
397 MF
.setExposesReturnsTwice(YamlMF
.ExposesReturnsTwice
);
398 MF
.setHasWinCFI(YamlMF
.HasWinCFI
);
400 if (YamlMF
.Legalized
)
401 MF
.getProperties().set(MachineFunctionProperties::Property::Legalized
);
402 if (YamlMF
.RegBankSelected
)
403 MF
.getProperties().set(
404 MachineFunctionProperties::Property::RegBankSelected
);
406 MF
.getProperties().set(MachineFunctionProperties::Property::Selected
);
407 if (YamlMF
.FailedISel
)
408 MF
.getProperties().set(MachineFunctionProperties::Property::FailedISel
);
410 PerFunctionMIParsingState
PFS(MF
, SM
, IRSlots
, *Target
);
411 if (parseRegisterInfo(PFS
, YamlMF
))
413 if (!YamlMF
.Constants
.empty()) {
414 auto *ConstantPool
= MF
.getConstantPool();
415 assert(ConstantPool
&& "Constant pool must be created");
416 if (initializeConstantPool(PFS
, *ConstantPool
, YamlMF
))
420 StringRef BlockStr
= YamlMF
.Body
.Value
.Value
;
423 BlockSM
.AddNewSourceBuffer(
424 MemoryBuffer::getMemBuffer(BlockStr
, "",/*RequiresNullTerminator=*/false),
427 if (parseMachineBasicBlockDefinitions(PFS
, BlockStr
, Error
)) {
429 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
434 // Initialize the frame information after creating all the MBBs so that the
435 // MBB references in the frame information can be resolved.
436 if (initializeFrameInfo(PFS
, YamlMF
))
438 // Initialize the jump table after creating all the MBBs so that the MBB
439 // references can be resolved.
440 if (!YamlMF
.JumpTableInfo
.Entries
.empty() &&
441 initializeJumpTableInfo(PFS
, YamlMF
.JumpTableInfo
))
443 // Parse the machine instructions after creating all of the MBBs so that the
444 // parser can resolve the MBB references.
445 StringRef InsnStr
= YamlMF
.Body
.Value
.Value
;
447 InsnSM
.AddNewSourceBuffer(
448 MemoryBuffer::getMemBuffer(InsnStr
, "", /*RequiresNullTerminator=*/false),
451 if (parseMachineInstructions(PFS
, InsnStr
, Error
)) {
453 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
458 if (setupRegisterInfo(PFS
, YamlMF
))
461 if (YamlMF
.MachineFuncInfo
) {
462 const LLVMTargetMachine
&TM
= MF
.getTarget();
463 // Note this is called after the initial constructor of the
464 // MachineFunctionInfo based on the MachineFunction, which may depend on the
468 if (TM
.parseMachineFunctionInfo(*YamlMF
.MachineFuncInfo
, PFS
, Error
,
470 return error(Error
, SrcRange
);
474 // Set the reserved registers after parsing MachineFuncInfo. The target may
475 // have been recording information used to select the reserved registers
477 // FIXME: This is a temporary workaround until the reserved registers can be
479 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
480 MRI
.freezeReservedRegs(MF
);
482 computeFunctionProperties(MF
);
484 if (initializeCallSiteInfo(PFS
, YamlMF
))
487 MF
.getSubtarget().mirFileLoaded(MF
);
493 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
494 const yaml::MachineFunction
&YamlMF
) {
495 MachineFunction
&MF
= PFS
.MF
;
496 MachineRegisterInfo
&RegInfo
= MF
.getRegInfo();
497 assert(RegInfo
.tracksLiveness());
498 if (!YamlMF
.TracksRegLiveness
)
499 RegInfo
.invalidateLiveness();
502 // Parse the virtual register information.
503 for (const auto &VReg
: YamlMF
.VirtualRegisters
) {
504 VRegInfo
&Info
= PFS
.getVRegInfo(VReg
.ID
.Value
);
506 return error(VReg
.ID
.SourceRange
.Start
,
507 Twine("redefinition of virtual register '%") +
508 Twine(VReg
.ID
.Value
) + "'");
509 Info
.Explicit
= true;
511 if (StringRef(VReg
.Class
.Value
).equals("_")) {
512 Info
.Kind
= VRegInfo::GENERIC
;
513 Info
.D
.RegBank
= nullptr;
515 const auto *RC
= Target
->getRegClass(VReg
.Class
.Value
);
517 Info
.Kind
= VRegInfo::NORMAL
;
520 const RegisterBank
*RegBank
= Target
->getRegBank(VReg
.Class
.Value
);
523 VReg
.Class
.SourceRange
.Start
,
524 Twine("use of undefined register class or register bank '") +
525 VReg
.Class
.Value
+ "'");
526 Info
.Kind
= VRegInfo::REGBANK
;
527 Info
.D
.RegBank
= RegBank
;
531 if (!VReg
.PreferredRegister
.Value
.empty()) {
532 if (Info
.Kind
!= VRegInfo::NORMAL
)
533 return error(VReg
.Class
.SourceRange
.Start
,
534 Twine("preferred register can only be set for normal vregs"));
536 if (parseRegisterReference(PFS
, Info
.PreferredReg
,
537 VReg
.PreferredRegister
.Value
, Error
))
538 return error(Error
, VReg
.PreferredRegister
.SourceRange
);
542 // Parse the liveins.
543 for (const auto &LiveIn
: YamlMF
.LiveIns
) {
545 if (parseNamedRegisterReference(PFS
, Reg
, LiveIn
.Register
.Value
, Error
))
546 return error(Error
, LiveIn
.Register
.SourceRange
);
548 if (!LiveIn
.VirtualRegister
.Value
.empty()) {
550 if (parseVirtualRegisterReference(PFS
, Info
, LiveIn
.VirtualRegister
.Value
,
552 return error(Error
, LiveIn
.VirtualRegister
.SourceRange
);
555 RegInfo
.addLiveIn(Reg
, VReg
);
558 // Parse the callee saved registers (Registers that will
559 // be saved for the caller).
560 if (YamlMF
.CalleeSavedRegisters
) {
561 SmallVector
<MCPhysReg
, 16> CalleeSavedRegisters
;
562 for (const auto &RegSource
: YamlMF
.CalleeSavedRegisters
.getValue()) {
564 if (parseNamedRegisterReference(PFS
, Reg
, RegSource
.Value
, Error
))
565 return error(Error
, RegSource
.SourceRange
);
566 CalleeSavedRegisters
.push_back(Reg
);
568 RegInfo
.setCalleeSavedRegs(CalleeSavedRegisters
);
574 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
575 const yaml::MachineFunction
&YamlMF
) {
576 MachineFunction
&MF
= PFS
.MF
;
577 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
580 auto populateVRegInfo
= [&] (const VRegInfo
&Info
, Twine Name
) {
581 unsigned Reg
= Info
.VReg
;
583 case VRegInfo::UNKNOWN
:
584 error(Twine("Cannot determine class/bank of virtual register ") +
585 Name
+ " in function '" + MF
.getName() + "'");
588 case VRegInfo::NORMAL
:
589 MRI
.setRegClass(Reg
, Info
.D
.RC
);
590 if (Info
.PreferredReg
!= 0)
591 MRI
.setSimpleHint(Reg
, Info
.PreferredReg
);
593 case VRegInfo::GENERIC
:
595 case VRegInfo::REGBANK
:
596 MRI
.setRegBank(Reg
, *Info
.D
.RegBank
);
601 for (auto I
= PFS
.VRegInfosNamed
.begin(), E
= PFS
.VRegInfosNamed
.end();
603 const VRegInfo
&Info
= *I
->second
;
604 populateVRegInfo(Info
, Twine(I
->first()));
607 for (auto P
: PFS
.VRegInfos
) {
608 const VRegInfo
&Info
= *P
.second
;
609 populateVRegInfo(Info
, Twine(P
.first
));
612 // Compute MachineRegisterInfo::UsedPhysRegMask
613 for (const MachineBasicBlock
&MBB
: MF
) {
614 for (const MachineInstr
&MI
: MBB
) {
615 for (const MachineOperand
&MO
: MI
.operands()) {
618 MRI
.addPhysRegsUsedFromRegMask(MO
.getRegMask());
626 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
627 const yaml::MachineFunction
&YamlMF
) {
628 MachineFunction
&MF
= PFS
.MF
;
629 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
630 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
631 const Function
&F
= MF
.getFunction();
632 const yaml::MachineFrameInfo
&YamlMFI
= YamlMF
.FrameInfo
;
633 MFI
.setFrameAddressIsTaken(YamlMFI
.IsFrameAddressTaken
);
634 MFI
.setReturnAddressIsTaken(YamlMFI
.IsReturnAddressTaken
);
635 MFI
.setHasStackMap(YamlMFI
.HasStackMap
);
636 MFI
.setHasPatchPoint(YamlMFI
.HasPatchPoint
);
637 MFI
.setStackSize(YamlMFI
.StackSize
);
638 MFI
.setOffsetAdjustment(YamlMFI
.OffsetAdjustment
);
639 if (YamlMFI
.MaxAlignment
)
640 MFI
.ensureMaxAlignment(YamlMFI
.MaxAlignment
);
641 MFI
.setAdjustsStack(YamlMFI
.AdjustsStack
);
642 MFI
.setHasCalls(YamlMFI
.HasCalls
);
643 if (YamlMFI
.MaxCallFrameSize
!= ~0u)
644 MFI
.setMaxCallFrameSize(YamlMFI
.MaxCallFrameSize
);
645 MFI
.setCVBytesOfCalleeSavedRegisters(YamlMFI
.CVBytesOfCalleeSavedRegisters
);
646 MFI
.setHasOpaqueSPAdjustment(YamlMFI
.HasOpaqueSPAdjustment
);
647 MFI
.setHasVAStart(YamlMFI
.HasVAStart
);
648 MFI
.setHasMustTailInVarArgFunc(YamlMFI
.HasMustTailInVarArgFunc
);
649 MFI
.setLocalFrameSize(YamlMFI
.LocalFrameSize
);
650 if (!YamlMFI
.SavePoint
.Value
.empty()) {
651 MachineBasicBlock
*MBB
= nullptr;
652 if (parseMBBReference(PFS
, MBB
, YamlMFI
.SavePoint
))
654 MFI
.setSavePoint(MBB
);
656 if (!YamlMFI
.RestorePoint
.Value
.empty()) {
657 MachineBasicBlock
*MBB
= nullptr;
658 if (parseMBBReference(PFS
, MBB
, YamlMFI
.RestorePoint
))
660 MFI
.setRestorePoint(MBB
);
663 std::vector
<CalleeSavedInfo
> CSIInfo
;
664 // Initialize the fixed frame objects.
665 for (const auto &Object
: YamlMF
.FixedStackObjects
) {
667 if (Object
.Type
!= yaml::FixedMachineStackObject::SpillSlot
)
668 ObjectIdx
= MFI
.CreateFixedObject(Object
.Size
, Object
.Offset
,
669 Object
.IsImmutable
, Object
.IsAliased
);
671 ObjectIdx
= MFI
.CreateFixedSpillStackObject(Object
.Size
, Object
.Offset
);
673 if (!TFI
->isSupportedStackID(Object
.StackID
))
674 return error(Object
.ID
.SourceRange
.Start
,
675 Twine("StackID is not supported by target"));
676 MFI
.setStackID(ObjectIdx
, Object
.StackID
);
677 MFI
.setObjectAlignment(ObjectIdx
, Object
.Alignment
);
678 if (!PFS
.FixedStackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
,
681 return error(Object
.ID
.SourceRange
.Start
,
682 Twine("redefinition of fixed stack object '%fixed-stack.") +
683 Twine(Object
.ID
.Value
) + "'");
684 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
685 Object
.CalleeSavedRestored
, ObjectIdx
))
687 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
691 // Initialize the ordinary frame objects.
692 for (const auto &Object
: YamlMF
.StackObjects
) {
694 const AllocaInst
*Alloca
= nullptr;
695 const yaml::StringValue
&Name
= Object
.Name
;
696 if (!Name
.Value
.empty()) {
697 Alloca
= dyn_cast_or_null
<AllocaInst
>(
698 F
.getValueSymbolTable()->lookup(Name
.Value
));
700 return error(Name
.SourceRange
.Start
,
701 "alloca instruction named '" + Name
.Value
+
702 "' isn't defined in the function '" + F
.getName() +
705 if (!TFI
->isSupportedStackID(Object
.StackID
))
706 return error(Object
.ID
.SourceRange
.Start
,
707 Twine("StackID is not supported by target"));
708 if (Object
.Type
== yaml::MachineStackObject::VariableSized
)
709 ObjectIdx
= MFI
.CreateVariableSizedObject(Object
.Alignment
, Alloca
);
711 ObjectIdx
= MFI
.CreateStackObject(
712 Object
.Size
, Object
.Alignment
,
713 Object
.Type
== yaml::MachineStackObject::SpillSlot
, Alloca
,
715 MFI
.setObjectOffset(ObjectIdx
, Object
.Offset
);
717 if (!PFS
.StackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
, ObjectIdx
))
719 return error(Object
.ID
.SourceRange
.Start
,
720 Twine("redefinition of stack object '%stack.") +
721 Twine(Object
.ID
.Value
) + "'");
722 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
723 Object
.CalleeSavedRestored
, ObjectIdx
))
725 if (Object
.LocalOffset
)
726 MFI
.mapLocalFrameObject(ObjectIdx
, Object
.LocalOffset
.getValue());
727 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
730 MFI
.setCalleeSavedInfo(CSIInfo
);
731 if (!CSIInfo
.empty())
732 MFI
.setCalleeSavedInfoValid(true);
734 // Initialize the various stack object references after initializing the
736 if (!YamlMFI
.StackProtector
.Value
.empty()) {
739 if (parseStackObjectReference(PFS
, FI
, YamlMFI
.StackProtector
.Value
, Error
))
740 return error(Error
, YamlMFI
.StackProtector
.SourceRange
);
741 MFI
.setStackProtectorIndex(FI
);
746 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
747 std::vector
<CalleeSavedInfo
> &CSIInfo
,
748 const yaml::StringValue
&RegisterSource
, bool IsRestored
, int FrameIdx
) {
749 if (RegisterSource
.Value
.empty())
753 if (parseNamedRegisterReference(PFS
, Reg
, RegisterSource
.Value
, Error
))
754 return error(Error
, RegisterSource
.SourceRange
);
755 CalleeSavedInfo
CSI(Reg
, FrameIdx
);
756 CSI
.setRestored(IsRestored
);
757 CSIInfo
.push_back(CSI
);
761 /// Verify that given node is of a certain type. Return true on error.
762 template <typename T
>
763 static bool typecheckMDNode(T
*&Result
, MDNode
*Node
,
764 const yaml::StringValue
&Source
,
765 StringRef TypeString
, MIRParserImpl
&Parser
) {
768 Result
= dyn_cast
<T
>(Node
);
770 return Parser
.error(Source
.SourceRange
.Start
,
771 "expected a reference to a '" + TypeString
+
776 template <typename T
>
777 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
778 const T
&Object
, int FrameIdx
) {
779 // Debug information can only be attached to stack objects; Fixed stack
780 // objects aren't supported.
781 MDNode
*Var
= nullptr, *Expr
= nullptr, *Loc
= nullptr;
782 if (parseMDNode(PFS
, Var
, Object
.DebugVar
) ||
783 parseMDNode(PFS
, Expr
, Object
.DebugExpr
) ||
784 parseMDNode(PFS
, Loc
, Object
.DebugLoc
))
786 if (!Var
&& !Expr
&& !Loc
)
788 DILocalVariable
*DIVar
= nullptr;
789 DIExpression
*DIExpr
= nullptr;
790 DILocation
*DILoc
= nullptr;
791 if (typecheckMDNode(DIVar
, Var
, Object
.DebugVar
, "DILocalVariable", *this) ||
792 typecheckMDNode(DIExpr
, Expr
, Object
.DebugExpr
, "DIExpression", *this) ||
793 typecheckMDNode(DILoc
, Loc
, Object
.DebugLoc
, "DILocation", *this))
795 PFS
.MF
.setVariableDbgInfo(DIVar
, DIExpr
, FrameIdx
, DILoc
);
799 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState
&PFS
,
800 MDNode
*&Node
, const yaml::StringValue
&Source
) {
801 if (Source
.Value
.empty())
804 if (llvm::parseMDNode(PFS
, Node
, Source
.Value
, Error
))
805 return error(Error
, Source
.SourceRange
);
809 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState
&PFS
,
810 MachineConstantPool
&ConstantPool
, const yaml::MachineFunction
&YamlMF
) {
811 DenseMap
<unsigned, unsigned> &ConstantPoolSlots
= PFS
.ConstantPoolSlots
;
812 const MachineFunction
&MF
= PFS
.MF
;
813 const auto &M
= *MF
.getFunction().getParent();
815 for (const auto &YamlConstant
: YamlMF
.Constants
) {
816 if (YamlConstant
.IsTargetSpecific
)
817 // FIXME: Support target-specific constant pools
818 return error(YamlConstant
.Value
.SourceRange
.Start
,
819 "Can't parse target-specific constant pool entries yet");
820 const Constant
*Value
= dyn_cast_or_null
<Constant
>(
821 parseConstantValue(YamlConstant
.Value
.Value
, Error
, M
));
823 return error(Error
, YamlConstant
.Value
.SourceRange
);
825 YamlConstant
.Alignment
826 ? YamlConstant
.Alignment
827 : M
.getDataLayout().getPrefTypeAlignment(Value
->getType());
828 unsigned Index
= ConstantPool
.getConstantPoolIndex(Value
, Alignment
);
829 if (!ConstantPoolSlots
.insert(std::make_pair(YamlConstant
.ID
.Value
, Index
))
831 return error(YamlConstant
.ID
.SourceRange
.Start
,
832 Twine("redefinition of constant pool item '%const.") +
833 Twine(YamlConstant
.ID
.Value
) + "'");
838 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
839 const yaml::MachineJumpTable
&YamlJTI
) {
840 MachineJumpTableInfo
*JTI
= PFS
.MF
.getOrCreateJumpTableInfo(YamlJTI
.Kind
);
841 for (const auto &Entry
: YamlJTI
.Entries
) {
842 std::vector
<MachineBasicBlock
*> Blocks
;
843 for (const auto &MBBSource
: Entry
.Blocks
) {
844 MachineBasicBlock
*MBB
= nullptr;
845 if (parseMBBReference(PFS
, MBB
, MBBSource
.Value
))
847 Blocks
.push_back(MBB
);
849 unsigned Index
= JTI
->createJumpTableIndex(Blocks
);
850 if (!PFS
.JumpTableSlots
.insert(std::make_pair(Entry
.ID
.Value
, Index
))
852 return error(Entry
.ID
.SourceRange
.Start
,
853 Twine("redefinition of jump table entry '%jump-table.") +
854 Twine(Entry
.ID
.Value
) + "'");
859 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState
&PFS
,
860 MachineBasicBlock
*&MBB
,
861 const yaml::StringValue
&Source
) {
863 if (llvm::parseMBBReference(PFS
, MBB
, Source
.Value
, Error
))
864 return error(Error
, Source
.SourceRange
);
868 SMDiagnostic
MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic
&Error
,
869 SMRange SourceRange
) {
870 assert(SourceRange
.isValid() && "Invalid source range");
871 SMLoc Loc
= SourceRange
.Start
;
872 bool HasQuote
= Loc
.getPointer() < SourceRange
.End
.getPointer() &&
873 *Loc
.getPointer() == '\'';
874 // Translate the location of the error from the location in the MI string to
875 // the corresponding location in the MIR file.
876 Loc
= Loc
.getFromPointer(Loc
.getPointer() + Error
.getColumnNo() +
879 // TODO: Translate any source ranges as well.
880 return SM
.GetMessage(Loc
, Error
.getKind(), Error
.getMessage(), None
,
884 SMDiagnostic
MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic
&Error
,
885 SMRange SourceRange
) {
886 assert(SourceRange
.isValid());
888 // Translate the location of the error from the location in the llvm IR string
889 // to the corresponding location in the MIR file.
890 auto LineAndColumn
= SM
.getLineAndColumn(SourceRange
.Start
);
891 unsigned Line
= LineAndColumn
.first
+ Error
.getLineNo() - 1;
892 unsigned Column
= Error
.getColumnNo();
893 StringRef LineStr
= Error
.getLineContents();
894 SMLoc Loc
= Error
.getLoc();
896 // Get the full line and adjust the column number by taking the indentation of
897 // LLVM IR into account.
898 for (line_iterator
L(*SM
.getMemoryBuffer(SM
.getMainFileID()), false), E
;
900 if (L
.line_number() == Line
) {
902 Loc
= SMLoc::getFromPointer(LineStr
.data());
903 auto Indent
= LineStr
.find(Error
.getLineContents());
904 if (Indent
!= StringRef::npos
)
910 return SMDiagnostic(SM
, Loc
, Filename
, Line
, Column
, Error
.getKind(),
911 Error
.getMessage(), LineStr
, Error
.getRanges(),
915 MIRParser::MIRParser(std::unique_ptr
<MIRParserImpl
> Impl
)
916 : Impl(std::move(Impl
)) {}
918 MIRParser::~MIRParser() {}
920 std::unique_ptr
<Module
> MIRParser::parseIRModule() {
921 return Impl
->parseIRModule();
924 bool MIRParser::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
925 return Impl
->parseMachineFunctions(M
, MMI
);
928 std::unique_ptr
<MIRParser
> llvm::createMIRParserFromFile(StringRef Filename
,
930 LLVMContext
&Context
) {
931 auto FileOrErr
= MemoryBuffer::getFileOrSTDIN(Filename
);
932 if (std::error_code EC
= FileOrErr
.getError()) {
933 Error
= SMDiagnostic(Filename
, SourceMgr::DK_Error
,
934 "Could not open input file: " + EC
.message());
937 return createMIRParser(std::move(FileOrErr
.get()), Context
);
940 std::unique_ptr
<MIRParser
>
941 llvm::createMIRParser(std::unique_ptr
<MemoryBuffer
> Contents
,
942 LLVMContext
&Context
) {
943 auto Filename
= Contents
->getBufferIdentifier();
944 if (Context
.shouldDiscardValueNames()) {
945 Context
.diagnose(DiagnosticInfoMIRParser(
948 Filename
, SourceMgr::DK_Error
,
949 "Can't read MIR with a Context that discards named Values")));
952 return std::make_unique
<MIRParser
>(
953 std::make_unique
<MIRParserImpl
>(std::move(Contents
), Filename
, Context
));