LLVM 20.0.0git
MIRParser.cpp
Go to the documentation of this file.
1//===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the class that parses the optional LLVM IR and machine
10// functions that are stored in MIR files.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
37#include "llvm/Support/SMLoc.h"
41#include <memory>
42
43using namespace llvm;
44
45namespace llvm {
46class MDNode;
47class RegisterBank;
48
49/// This class implements the parsing of LLVM IR that's embedded inside a MIR
50/// file.
52 SourceMgr SM;
53 LLVMContext &Context;
54 yaml::Input In;
55 StringRef Filename;
56 SlotMapping IRSlots;
57 std::unique_ptr<PerTargetMIParsingState> Target;
58
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
63 /// parts.
64 bool NoMIRDocuments = false;
65
66 std::function<void(Function &)> ProcessIRFunction;
67
68public:
69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
70 LLVMContext &Context,
71 std::function<void(Function &)> ProcessIRFunction);
72
73 void reportDiagnostic(const SMDiagnostic &Diag);
74
75 /// Report an error with the given message at unknown location.
76 ///
77 /// Always returns true.
78 bool error(const Twine &Message);
79
80 /// Report an error with the given message at the given location.
81 ///
82 /// Always returns true.
83 bool error(SMLoc Loc, const Twine &Message);
84
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.
87 ///
88 /// Always returns true.
89 bool error(const SMDiagnostic &Error, SMRange SourceRange);
90
91 /// Try to parse the optional LLVM module and the machine functions in the MIR
92 /// file.
93 ///
94 /// Return null if an error occurred.
95 std::unique_ptr<Module>
96 parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
97
98 /// Create an empty function with the given name.
100
102 ModuleAnalysisManager *FAM = nullptr);
103
104 /// Parse the machine function in the current YAML document.
105 ///
106 ///
107 /// Return true if an error occurred.
110
111 /// Initialize the machine function to the state that's described in the MIR
112 /// file.
113 ///
114 /// Return true if error occurred.
116 MachineFunction &MF);
117
119 const yaml::MachineFunction &YamlMF);
120
122 const yaml::MachineFunction &YamlMF);
123
125 const yaml::MachineFunction &YamlMF);
126
128 const yaml::MachineFunction &YamlMF);
129
131 std::vector<CalleeSavedInfo> &CSIInfo,
132 const yaml::StringValue &RegisterSource,
133 bool IsRestored, int FrameIdx);
134
135 struct VarExprLoc {
138 DILocation *DILoc = nullptr;
139 };
140
141 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
142 const yaml::StringValue &VarStr,
143 const yaml::StringValue &ExprStr,
144 const yaml::StringValue &LocStr);
145 template <typename T>
147 const T &Object,
148 int FrameIdx);
149
152 const yaml::MachineFunction &YamlMF);
153
155 const yaml::MachineJumpTable &YamlJTI);
156
158 MachineFunction &MF,
159 const yaml::MachineFunction &YMF);
160
161private:
162 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
163 const yaml::StringValue &Source);
164
165 bool parseMBBReference(PerFunctionMIParsingState &PFS,
167 const yaml::StringValue &Source);
168
169 bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
170 const yaml::StringValue &Source);
171
172 /// Return a MIR diagnostic converted from an MI string diagnostic.
173 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
174 SMRange SourceRange);
175
176 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
177 /// block scalar string.
178 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
179 SMRange SourceRange);
180
181 void computeFunctionProperties(MachineFunction &MF);
182
183 void setupDebugValueTracking(MachineFunction &MF,
185};
186
187} // end namespace llvm
188
189static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
190 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
191}
192
193MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
194 StringRef Filename, LLVMContext &Context,
195 std::function<void(Function &)> Callback)
196 : Context(Context),
197 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
198 ->getBuffer(),
199 nullptr, handleYAMLDiag, this),
200 Filename(Filename), ProcessIRFunction(Callback) {
201 In.setContext(&In);
202}
203
204bool MIRParserImpl::error(const Twine &Message) {
206 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
207 return true;
208}
209
210bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
212 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
213 return true;
214}
215
217 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
218 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
219 return true;
220}
221
224 switch (Diag.getKind()) {
226 Kind = DS_Error;
227 break;
229 Kind = DS_Warning;
230 break;
232 Kind = DS_Note;
233 break;
235 llvm_unreachable("remark unexpected");
236 break;
237 }
238 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
239}
240
241std::unique_ptr<Module>
243 if (!In.setCurrentDocument()) {
244 if (In.error())
245 return nullptr;
246 // Create an empty module when the MIR file is empty.
247 NoMIRDocuments = true;
248 auto M = std::make_unique<Module>(Filename, Context);
249 if (auto LayoutOverride =
250 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
251 M->setDataLayout(*LayoutOverride);
252 return M;
253 }
254
255 std::unique_ptr<Module> M;
256 // Parse the block scalar manually so that we can return unique pointer
257 // without having to go trough YAML traits.
258 if (const auto *BSN =
259 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
261 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
262 Context, &IRSlots, DataLayoutCallback);
263 if (!M) {
264 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
265 return nullptr;
266 }
267 In.nextDocument();
268 if (!In.setCurrentDocument())
269 NoMIRDocuments = true;
270 } else {
271 // Create an new, empty module.
272 M = std::make_unique<Module>(Filename, Context);
273 if (auto LayoutOverride =
274 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
275 M->setDataLayout(*LayoutOverride);
276 NoLLVMIR = true;
277 }
278 return M;
279}
280
283 if (NoMIRDocuments)
284 return false;
285
286 // Parse the machine functions.
287 do {
288 if (parseMachineFunction(M, MMI, MAM))
289 return true;
290 In.nextDocument();
291 } while (In.setCurrentDocument());
292
293 return false;
294}
295
297 auto &Context = M.getContext();
298 Function *F =
301 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
302 new UnreachableInst(Context, BB);
303
304 if (ProcessIRFunction)
305 ProcessIRFunction(*F);
306
307 return F;
308}
309
312 // Parse the yaml.
314 yaml::EmptyContext Ctx;
315
316 const LLVMTargetMachine &TM = MMI.getTarget();
317 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
318 TM.createDefaultFuncInfoYAML());
319
320 yaml::yamlize(In, YamlMF, false, Ctx);
321 if (In.error())
322 return true;
323
324 // Search for the corresponding IR function.
325 StringRef FunctionName = YamlMF.Name;
326 Function *F = M.getFunction(FunctionName);
327 if (!F) {
328 if (NoLLVMIR) {
329 F = createDummyFunction(FunctionName, M);
330 } else {
331 return error(Twine("function '") + FunctionName +
332 "' isn't defined in the provided LLVM IR");
333 }
334 }
335
336 if (!MAM) {
337 if (MMI.getMachineFunction(*F) != nullptr)
338 return error(Twine("redefinition of machine function '") + FunctionName +
339 "'");
340
341 // Create the MachineFunction.
343 if (initializeMachineFunction(YamlMF, MF))
344 return true;
345 } else {
346 auto &FAM =
349 return error(Twine("redefinition of machine function '") + FunctionName +
350 "'");
351
352 // Create the MachineFunction.
354 if (initializeMachineFunction(YamlMF, MF))
355 return true;
356 }
357
358 return false;
359}
360
361static bool isSSA(const MachineFunction &MF) {
362 const MachineRegisterInfo &MRI = MF.getRegInfo();
363 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
365 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
366 return false;
367
368 // Subregister defs are invalid in SSA.
369 const MachineOperand *RegDef = MRI.getOneDef(Reg);
370 if (RegDef && RegDef->getSubReg() != 0)
371 return false;
372 }
373 return true;
374}
375
376void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
377 MachineFunctionProperties &Properties = MF.getProperties();
378
379 bool HasPHI = false;
380 bool HasInlineAsm = false;
381 bool AllTiedOpsRewritten = true, HasTiedOps = false;
382 for (const MachineBasicBlock &MBB : MF) {
383 for (const MachineInstr &MI : MBB) {
384 if (MI.isPHI())
385 HasPHI = true;
386 if (MI.isInlineAsm())
387 HasInlineAsm = true;
388 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
389 const MachineOperand &MO = MI.getOperand(I);
390 if (!MO.isReg() || !MO.getReg())
391 continue;
392 unsigned DefIdx;
393 if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
394 HasTiedOps = true;
395 if (MO.getReg() != MI.getOperand(DefIdx).getReg())
396 AllTiedOpsRewritten = false;
397 }
398 }
399 }
400 }
401 if (!HasPHI)
403 MF.setHasInlineAsm(HasInlineAsm);
404
405 if (HasTiedOps && AllTiedOpsRewritten)
407
408 if (isSSA(MF))
410 else
412
413 const MachineRegisterInfo &MRI = MF.getRegInfo();
414 if (MRI.getNumVirtRegs() == 0)
416}
417
420 MachineFunction &MF = PFS.MF;
422 const LLVMTargetMachine &TM = MF.getTarget();
423 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
424 yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
425 if (MILoc.BlockNum >= MF.size())
426 return error(Twine(MF.getName()) +
427 Twine(" call instruction block out of range.") +
428 " Unable to reference bb:" + Twine(MILoc.BlockNum));
429 auto CallB = std::next(MF.begin(), MILoc.BlockNum);
430 if (MILoc.Offset >= CallB->size())
431 return error(Twine(MF.getName()) +
432 Twine(" call instruction offset out of range.") +
433 " Unable to reference instruction at bb: " +
434 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
435 auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
436 if (!CallI->isCall(MachineInstr::IgnoreBundle))
437 return error(Twine(MF.getName()) +
438 Twine(" call site info should reference call "
439 "instruction. Instruction at bb:") +
440 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
441 " is not a call instruction");
443 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
444 Register Reg;
445 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
446 return error(Error, ArgRegPair.Reg.SourceRange);
447 CSInfo.ArgRegPairs.emplace_back(Reg, ArgRegPair.ArgNo);
448 }
449
450 if (TM.Options.EmitCallSiteInfo)
451 MF.addCallSiteInfo(&*CallI, std::move(CSInfo));
452 }
453
454 if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
455 return error(Twine("Call site info provided but not used"));
456 return false;
457}
458
459void MIRParserImpl::setupDebugValueTracking(
461 const yaml::MachineFunction &YamlMF) {
462 // Compute the value of the "next instruction number" field.
463 unsigned MaxInstrNum = 0;
464 for (auto &MBB : MF)
465 for (auto &MI : MBB)
466 MaxInstrNum = std::max((unsigned)MI.peekDebugInstrNum(), MaxInstrNum);
467 MF.setDebugInstrNumberingCount(MaxInstrNum);
468
469 // Load any substitutions.
470 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
471 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
472 {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
473 }
474
475 // Flag for whether we're supposed to be using DBG_INSTR_REF.
476 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
477}
478
479bool
481 MachineFunction &MF) {
482 // TODO: Recreate the machine function.
483 if (Target) {
484 // Avoid clearing state if we're using the same subtarget again.
485 Target->setTarget(MF.getSubtarget());
486 } else {
488 }
489
490 MF.setAlignment(YamlMF.Alignment.valueOrOne());
492 MF.setHasWinCFI(YamlMF.HasWinCFI);
493
497 MF.setHasEHScopes(YamlMF.HasEHScopes);
499 MF.setIsOutlined(YamlMF.IsOutlined);
500
501 if (YamlMF.Legalized)
503 if (YamlMF.RegBankSelected)
504 MF.getProperties().set(
506 if (YamlMF.Selected)
508 if (YamlMF.FailedISel)
510 if (YamlMF.FailsVerification)
511 MF.getProperties().set(
513 if (YamlMF.TracksDebugUserValues)
514 MF.getProperties().set(
516
517 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
518 if (parseRegisterInfo(PFS, YamlMF))
519 return true;
520 if (!YamlMF.Constants.empty()) {
521 auto *ConstantPool = MF.getConstantPool();
522 assert(ConstantPool && "Constant pool must be created");
523 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
524 return true;
525 }
526 if (!YamlMF.MachineMetadataNodes.empty() &&
527 parseMachineMetadataNodes(PFS, MF, YamlMF))
528 return true;
529
530 StringRef BlockStr = YamlMF.Body.Value.Value;
532 SourceMgr BlockSM;
533 BlockSM.AddNewSourceBuffer(
534 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
535 SMLoc());
536 PFS.SM = &BlockSM;
537 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
539 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
540 return true;
541 }
542 // Check Basic Block Section Flags.
545 } else if (MF.hasBBSections()) {
547 }
548 PFS.SM = &SM;
549
550 // Initialize the frame information after creating all the MBBs so that the
551 // MBB references in the frame information can be resolved.
552 if (initializeFrameInfo(PFS, YamlMF))
553 return true;
554 // Initialize the jump table after creating all the MBBs so that the MBB
555 // references can be resolved.
556 if (!YamlMF.JumpTableInfo.Entries.empty() &&
558 return true;
559 // Parse the machine instructions after creating all of the MBBs so that the
560 // parser can resolve the MBB references.
561 StringRef InsnStr = YamlMF.Body.Value.Value;
562 SourceMgr InsnSM;
563 InsnSM.AddNewSourceBuffer(
564 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
565 SMLoc());
566 PFS.SM = &InsnSM;
567 if (parseMachineInstructions(PFS, InsnStr, Error)) {
569 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
570 return true;
571 }
572 PFS.SM = &SM;
573
574 if (setupRegisterInfo(PFS, YamlMF))
575 return true;
576
577 if (YamlMF.MachineFuncInfo) {
578 const LLVMTargetMachine &TM = MF.getTarget();
579 // Note this is called after the initial constructor of the
580 // MachineFunctionInfo based on the MachineFunction, which may depend on the
581 // IR.
582
583 SMRange SrcRange;
584 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
585 SrcRange)) {
586 return error(Error, SrcRange);
587 }
588 }
589
590 // Set the reserved registers after parsing MachineFuncInfo. The target may
591 // have been recording information used to select the reserved registers
592 // there.
593 // FIXME: This is a temporary workaround until the reserved registers can be
594 // serialized.
596 MRI.freezeReservedRegs();
597
598 computeFunctionProperties(MF);
599
600 if (initializeCallSiteInfo(PFS, YamlMF))
601 return false;
602
603 setupDebugValueTracking(MF, PFS, YamlMF);
604
606
607 MF.verify();
608 return false;
609}
610
612 const yaml::MachineFunction &YamlMF) {
613 MachineFunction &MF = PFS.MF;
614 MachineRegisterInfo &RegInfo = MF.getRegInfo();
615 assert(RegInfo.tracksLiveness());
616 if (!YamlMF.TracksRegLiveness)
617 RegInfo.invalidateLiveness();
618
620 // Parse the virtual register information.
621 for (const auto &VReg : YamlMF.VirtualRegisters) {
622 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
623 if (Info.Explicit)
624 return error(VReg.ID.SourceRange.Start,
625 Twine("redefinition of virtual register '%") +
626 Twine(VReg.ID.Value) + "'");
627 Info.Explicit = true;
628
629 if (VReg.Class.Value == "_") {
630 Info.Kind = VRegInfo::GENERIC;
631 Info.D.RegBank = nullptr;
632 } else {
633 const auto *RC = Target->getRegClass(VReg.Class.Value);
634 if (RC) {
635 Info.Kind = VRegInfo::NORMAL;
636 Info.D.RC = RC;
637 } else {
638 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
639 if (!RegBank)
640 return error(
641 VReg.Class.SourceRange.Start,
642 Twine("use of undefined register class or register bank '") +
643 VReg.Class.Value + "'");
644 Info.Kind = VRegInfo::REGBANK;
645 Info.D.RegBank = RegBank;
646 }
647 }
648
649 if (!VReg.PreferredRegister.Value.empty()) {
650 if (Info.Kind != VRegInfo::NORMAL)
651 return error(VReg.Class.SourceRange.Start,
652 Twine("preferred register can only be set for normal vregs"));
653
654 if (parseRegisterReference(PFS, Info.PreferredReg,
655 VReg.PreferredRegister.Value, Error))
656 return error(Error, VReg.PreferredRegister.SourceRange);
657 }
658 }
659
660 // Parse the liveins.
661 for (const auto &LiveIn : YamlMF.LiveIns) {
662 Register Reg;
663 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
664 return error(Error, LiveIn.Register.SourceRange);
665 Register VReg;
666 if (!LiveIn.VirtualRegister.Value.empty()) {
667 VRegInfo *Info;
668 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
669 Error))
670 return error(Error, LiveIn.VirtualRegister.SourceRange);
671 VReg = Info->VReg;
672 }
673 RegInfo.addLiveIn(Reg, VReg);
674 }
675
676 // Parse the callee saved registers (Registers that will
677 // be saved for the caller).
678 if (YamlMF.CalleeSavedRegisters) {
679 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
680 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
681 Register Reg;
682 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
683 return error(Error, RegSource.SourceRange);
684 CalleeSavedRegisters.push_back(Reg);
685 }
686 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
687 }
688
689 return false;
690}
691
693 const yaml::MachineFunction &YamlMF) {
694 MachineFunction &MF = PFS.MF;
697
698 bool Error = false;
699 // Create VRegs
700 auto populateVRegInfo = [&](const VRegInfo &Info, Twine Name) {
701 Register Reg = Info.VReg;
702 switch (Info.Kind) {
704 error(Twine("Cannot determine class/bank of virtual register ") +
705 Name + " in function '" + MF.getName() + "'");
706 Error = true;
707 break;
708 case VRegInfo::NORMAL:
709 if (!Info.D.RC->isAllocatable()) {
710 error(Twine("Cannot use non-allocatable class '") +
711 TRI->getRegClassName(Info.D.RC) + "' for virtual register " +
712 Name + " in function '" + MF.getName() + "'");
713 Error = true;
714 break;
715 }
716
717 MRI.setRegClass(Reg, Info.D.RC);
718 if (Info.PreferredReg != 0)
719 MRI.setSimpleHint(Reg, Info.PreferredReg);
720 break;
722 break;
724 MRI.setRegBank(Reg, *Info.D.RegBank);
725 break;
726 }
727 };
728
729 for (const auto &P : PFS.VRegInfosNamed) {
730 const VRegInfo &Info = *P.second;
731 populateVRegInfo(Info, Twine(P.first()));
732 }
733
734 for (auto P : PFS.VRegInfos) {
735 const VRegInfo &Info = *P.second;
736 populateVRegInfo(Info, Twine(P.first));
737 }
738
739 // Compute MachineRegisterInfo::UsedPhysRegMask
740 for (const MachineBasicBlock &MBB : MF) {
741 // Make sure MRI knows about registers clobbered by unwinder.
742 if (MBB.isEHPad())
743 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
744 MRI.addPhysRegsUsedFromRegMask(RegMask);
745
746 for (const MachineInstr &MI : MBB) {
747 for (const MachineOperand &MO : MI.operands()) {
748 if (!MO.isRegMask())
749 continue;
750 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
751 }
752 }
753 }
754
755 return Error;
756}
757
759 const yaml::MachineFunction &YamlMF) {
760 MachineFunction &MF = PFS.MF;
761 MachineFrameInfo &MFI = MF.getFrameInfo();
763 const Function &F = MF.getFunction();
764 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
767 MFI.setHasStackMap(YamlMFI.HasStackMap);
768 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
769 MFI.setStackSize(YamlMFI.StackSize);
771 if (YamlMFI.MaxAlignment)
773 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
774 MFI.setHasCalls(YamlMFI.HasCalls);
775 if (YamlMFI.MaxCallFrameSize != ~0u)
779 MFI.setHasVAStart(YamlMFI.HasVAStart);
781 MFI.setHasTailCall(YamlMFI.HasTailCall);
784 if (!YamlMFI.SavePoint.Value.empty()) {
785 MachineBasicBlock *MBB = nullptr;
786 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
787 return true;
788 MFI.setSavePoint(MBB);
789 }
790 if (!YamlMFI.RestorePoint.Value.empty()) {
791 MachineBasicBlock *MBB = nullptr;
792 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
793 return true;
794 MFI.setRestorePoint(MBB);
795 }
796
797 std::vector<CalleeSavedInfo> CSIInfo;
798 // Initialize the fixed frame objects.
799 for (const auto &Object : YamlMF.FixedStackObjects) {
800 int ObjectIdx;
802 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
803 Object.IsImmutable, Object.IsAliased);
804 else
805 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
806
807 if (!TFI->isSupportedStackID(Object.StackID))
808 return error(Object.ID.SourceRange.Start,
809 Twine("StackID is not supported by target"));
810 MFI.setStackID(ObjectIdx, Object.StackID);
811 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
812 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
813 ObjectIdx))
814 .second)
815 return error(Object.ID.SourceRange.Start,
816 Twine("redefinition of fixed stack object '%fixed-stack.") +
817 Twine(Object.ID.Value) + "'");
818 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
819 Object.CalleeSavedRestored, ObjectIdx))
820 return true;
821 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
822 return true;
823 }
824
825 for (const auto &Object : YamlMF.EntryValueObjects) {
827 Register Reg;
828 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
829 Error))
830 return error(Error, Object.EntryValueRegister.SourceRange);
831 if (!Reg.isPhysical())
832 return error(Object.EntryValueRegister.SourceRange.Start,
833 "Expected physical register for entry value field");
834 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
835 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
836 if (!MaybeInfo)
837 return true;
838 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
839 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
840 Reg.asMCReg(), MaybeInfo->DILoc);
841 }
842
843 // Initialize the ordinary frame objects.
844 for (const auto &Object : YamlMF.StackObjects) {
845 int ObjectIdx;
846 const AllocaInst *Alloca = nullptr;
847 const yaml::StringValue &Name = Object.Name;
848 if (!Name.Value.empty()) {
849 Alloca = dyn_cast_or_null<AllocaInst>(
850 F.getValueSymbolTable()->lookup(Name.Value));
851 if (!Alloca)
852 return error(Name.SourceRange.Start,
853 "alloca instruction named '" + Name.Value +
854 "' isn't defined in the function '" + F.getName() +
855 "'");
856 }
857 if (!TFI->isSupportedStackID(Object.StackID))
858 return error(Object.ID.SourceRange.Start,
859 Twine("StackID is not supported by target"));
861 ObjectIdx =
862 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
863 else
864 ObjectIdx = MFI.CreateStackObject(
865 Object.Size, Object.Alignment.valueOrOne(),
866 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
867 Object.StackID);
868 MFI.setObjectOffset(ObjectIdx, Object.Offset);
869
870 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
871 .second)
872 return error(Object.ID.SourceRange.Start,
873 Twine("redefinition of stack object '%stack.") +
874 Twine(Object.ID.Value) + "'");
875 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
876 Object.CalleeSavedRestored, ObjectIdx))
877 return true;
878 if (Object.LocalOffset)
879 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
880 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
881 return true;
882 }
883 MFI.setCalleeSavedInfo(CSIInfo);
884 if (!CSIInfo.empty())
885 MFI.setCalleeSavedInfoValid(true);
886
887 // Initialize the various stack object references after initializing the
888 // stack objects.
889 if (!YamlMFI.StackProtector.Value.empty()) {
891 int FI;
893 return error(Error, YamlMFI.StackProtector.SourceRange);
895 }
896
897 if (!YamlMFI.FunctionContext.Value.empty()) {
899 int FI;
901 return error(Error, YamlMFI.FunctionContext.SourceRange);
903 }
904
905 return false;
906}
907
909 std::vector<CalleeSavedInfo> &CSIInfo,
910 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
911 if (RegisterSource.Value.empty())
912 return false;
913 Register Reg;
915 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
916 return error(Error, RegisterSource.SourceRange);
917 CalleeSavedInfo CSI(Reg, FrameIdx);
918 CSI.setRestored(IsRestored);
919 CSIInfo.push_back(CSI);
920 return false;
921}
922
923/// Verify that given node is of a certain type. Return true on error.
924template <typename T>
925static bool typecheckMDNode(T *&Result, MDNode *Node,
926 const yaml::StringValue &Source,
927 StringRef TypeString, MIRParserImpl &Parser) {
928 if (!Node)
929 return false;
930 Result = dyn_cast<T>(Node);
931 if (!Result)
932 return Parser.error(Source.SourceRange.Start,
933 "expected a reference to a '" + TypeString +
934 "' metadata node");
935 return false;
936}
937
938std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
940 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
941 MDNode *Var = nullptr;
942 MDNode *Expr = nullptr;
943 MDNode *Loc = nullptr;
944 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
945 parseMDNode(PFS, Loc, LocStr))
946 return std::nullopt;
947 DILocalVariable *DIVar = nullptr;
948 DIExpression *DIExpr = nullptr;
949 DILocation *DILoc = nullptr;
950 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
951 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
952 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
953 return std::nullopt;
954 return VarExprLoc{DIVar, DIExpr, DILoc};
955}
956
957template <typename T>
959 const T &Object, int FrameIdx) {
960 std::optional<VarExprLoc> MaybeInfo =
961 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
962 if (!MaybeInfo)
963 return true;
964 // Debug information can only be attached to stack objects; Fixed stack
965 // objects aren't supported.
966 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
967 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
968 MaybeInfo->DILoc);
969 return false;
970}
971
972bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
973 MDNode *&Node, const yaml::StringValue &Source) {
974 if (Source.Value.empty())
975 return false;
977 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
978 return error(Error, Source.SourceRange);
979 return false;
980}
981
984 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
985 const MachineFunction &MF = PFS.MF;
986 const auto &M = *MF.getFunction().getParent();
988 for (const auto &YamlConstant : YamlMF.Constants) {
989 if (YamlConstant.IsTargetSpecific)
990 // FIXME: Support target-specific constant pools
991 return error(YamlConstant.Value.SourceRange.Start,
992 "Can't parse target-specific constant pool entries yet");
993 const Constant *Value = dyn_cast_or_null<Constant>(
994 parseConstantValue(YamlConstant.Value.Value, Error, M));
995 if (!Value)
996 return error(Error, YamlConstant.Value.SourceRange);
997 const Align PrefTypeAlign =
998 M.getDataLayout().getPrefTypeAlign(Value->getType());
999 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
1000 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
1001 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
1002 .second)
1003 return error(YamlConstant.ID.SourceRange.Start,
1004 Twine("redefinition of constant pool item '%const.") +
1005 Twine(YamlConstant.ID.Value) + "'");
1006 }
1007 return false;
1008}
1009
1011 const yaml::MachineJumpTable &YamlJTI) {
1013 for (const auto &Entry : YamlJTI.Entries) {
1014 std::vector<MachineBasicBlock *> Blocks;
1015 for (const auto &MBBSource : Entry.Blocks) {
1016 MachineBasicBlock *MBB = nullptr;
1017 if (parseMBBReference(PFS, MBB, MBBSource.Value))
1018 return true;
1019 Blocks.push_back(MBB);
1020 }
1021 unsigned Index = JTI->createJumpTableIndex(Blocks);
1022 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1023 .second)
1024 return error(Entry.ID.SourceRange.Start,
1025 Twine("redefinition of jump table entry '%jump-table.") +
1026 Twine(Entry.ID.Value) + "'");
1027 }
1028 return false;
1029}
1030
1031bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1033 const yaml::StringValue &Source) {
1035 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1036 return error(Error, Source.SourceRange);
1037 return false;
1038}
1039
1040bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1041 const yaml::StringValue &Source) {
1043 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1044 return error(Error, Source.SourceRange);
1045 return false;
1046}
1047
1050 const yaml::MachineFunction &YMF) {
1051 for (const auto &MDS : YMF.MachineMetadataNodes) {
1052 if (parseMachineMetadata(PFS, MDS))
1053 return true;
1054 }
1055 // Report missing definitions from forward referenced nodes.
1056 if (!PFS.MachineForwardRefMDNodes.empty())
1057 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1058 "use of undefined metadata '!" +
1059 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1060 return false;
1061}
1062
1063SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1064 SMRange SourceRange) {
1065 assert(SourceRange.isValid() && "Invalid source range");
1066 SMLoc Loc = SourceRange.Start;
1067 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1068 *Loc.getPointer() == '\'';
1069 // Translate the location of the error from the location in the MI string to
1070 // the corresponding location in the MIR file.
1071 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1072 (HasQuote ? 1 : 0));
1073
1074 // TODO: Translate any source ranges as well.
1075 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), std::nullopt,
1076 Error.getFixIts());
1077}
1078
1079SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1080 SMRange SourceRange) {
1081 assert(SourceRange.isValid());
1082
1083 // Translate the location of the error from the location in the llvm IR string
1084 // to the corresponding location in the MIR file.
1085 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1086 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1087 unsigned Column = Error.getColumnNo();
1088 StringRef LineStr = Error.getLineContents();
1089 SMLoc Loc = Error.getLoc();
1090
1091 // Get the full line and adjust the column number by taking the indentation of
1092 // LLVM IR into account.
1093 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1094 L != E; ++L) {
1095 if (L.line_number() == Line) {
1096 LineStr = *L;
1097 Loc = SMLoc::getFromPointer(LineStr.data());
1098 auto Indent = LineStr.find(Error.getLineContents());
1099 if (Indent != StringRef::npos)
1100 Column += Indent;
1101 break;
1102 }
1103 }
1104
1105 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1106 Error.getMessage(), LineStr, Error.getRanges(),
1107 Error.getFixIts());
1108}
1109
1110MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1111 : Impl(std::move(Impl)) {}
1112
1113MIRParser::~MIRParser() = default;
1114
1115std::unique_ptr<Module>
1117 return Impl->parseIRModule(DataLayoutCallback);
1118}
1119
1121 return Impl->parseMachineFunctions(M, MMI);
1122}
1123
1125 auto &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
1126 return Impl->parseMachineFunctions(M, MMI, &MAM);
1127}
1128
1129std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1130 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1131 std::function<void(Function &)> ProcessIRFunction) {
1132 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1133 if (std::error_code EC = FileOrErr.getError()) {
1135 "Could not open input file: " + EC.message());
1136 return nullptr;
1137 }
1138 return createMIRParser(std::move(FileOrErr.get()), Context,
1139 ProcessIRFunction);
1140}
1141
1142std::unique_ptr<MIRParser>
1143llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1144 LLVMContext &Context,
1145 std::function<void(Function &)> ProcessIRFunction) {
1146 auto Filename = Contents->getBufferIdentifier();
1147 if (Context.shouldDiscardValueNames()) {
1149 DS_Error,
1151 Filename, SourceMgr::DK_Error,
1152 "Can't read MIR with a Context that discards named Values")));
1153 return nullptr;
1154 }
1155 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1156 std::move(Contents), Filename, Context, ProcessIRFunction));
1157}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file defines the DenseMap class.
std::string Name
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static bool isSSA(const MachineFunction &MF)
Definition: MIRParser.cpp:361
static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context)
Definition: MIRParser.cpp:189
static bool typecheckMDNode(T *&Result, MDNode *Node, const yaml::StringValue &Source, StringRef TypeString, MIRParserImpl &Parser)
Verify that given node is of a certain type. Return true on error.
Definition: MIRParser.cpp:925
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
unsigned const TargetRegisterInfo * TRI
Module.h This file contains the declarations for the Module class.
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define error(X)
an instruction to allocate memory on the stack
Definition: Instructions.h:61
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:424
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
This is an important base class in LLVM.
Definition: Constant.h:42
DWARF expression.
Debug location.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Diagnostic information for machine IR parser.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:172
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
Metadata node.
Definition: Metadata.h:1069
This class implements the parsing of LLVM IR that's embedded inside a MIR file.
Definition: MIRParser.cpp:51
bool error(const Twine &Message)
Report an error with the given message at unknown location.
Definition: MIRParser.cpp:204
void reportDiagnostic(const SMDiagnostic &Diag)
Definition: MIRParser.cpp:222
bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:692
bool parseRegisterInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:611
bool initializeFrameInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:758
Function * createDummyFunction(StringRef Name, Module &M)
Create an empty function with the given name.
Definition: MIRParser.cpp:296
bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, const T &Object, int FrameIdx)
Definition: MIRParser.cpp:958
bool initializeMachineFunction(const yaml::MachineFunction &YamlMF, MachineFunction &MF)
Initialize the machine function to the state that's described in the MIR file.
Definition: MIRParser.cpp:480
std::unique_ptr< Module > parseIRModule(DataLayoutCallbackTy DataLayoutCallback)
Try to parse the optional LLVM module and the machine functions in the MIR file.
Definition: MIRParser.cpp:242
bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, const yaml::MachineJumpTable &YamlJTI)
Definition: MIRParser.cpp:1010
bool initializeConstantPool(PerFunctionMIParsingState &PFS, MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:982
MIRParserImpl(std::unique_ptr< MemoryBuffer > Contents, StringRef Filename, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction)
Definition: MIRParser.cpp:193
std::optional< VarExprLoc > parseVarExprLoc(PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr, const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr)
Definition: MIRParser.cpp:938
bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, std::vector< CalleeSavedInfo > &CSIInfo, const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx)
Definition: MIRParser.cpp:908
bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
Definition: MIRParser.cpp:1048
bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:418
bool parseMachineFunction(Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *FAM)
Parse the machine function in the current YAML document.
Definition: MIRParser.cpp:310
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *FAM=nullptr)
Definition: MIRParser.cpp:281
MIRParser(std::unique_ptr< MIRParserImpl > Impl)
Definition: MIRParser.cpp:1110
std::unique_ptr< Module > parseIRModule(DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Parses the optional LLVM IR module in the MIR file.
Definition: MIRParser.cpp:1116
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Parses MachineFunctions in the MIR file and add them to the given MachineModuleInfo MMI.
Definition: MIRParser.cpp:1120
bool isEHPad() const
Returns true if the block is a landing pad.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setRestorePoint(MachineBasicBlock *NewRestore)
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void ensureMaxAlignment(Align Alignment)
Make sure the function is at least Align bytes aligned.
void setHasPatchPoint(bool s=true)
void setLocalFrameSize(int64_t sz)
Set the size of the local object blob.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
void setFrameAddressIsTaken(bool T)
void setHasStackMap(bool s=true)
void setCVBytesOfCalleeSavedRegisters(unsigned S)
void setStackID(int ObjectIdx, uint8_t ID)
void setHasTailCall(bool V=true)
void setStackProtectorIndex(int I)
void setCalleeSavedInfoValid(bool v)
void setReturnAddressIsTaken(bool s)
void mapLocalFrameObject(int ObjectIndex, int64_t Offset)
Map a frame index into the local object block.
void setHasOpaqueSPAdjustment(bool B)
void setCalleeSavedInfo(std::vector< CalleeSavedInfo > CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
int CreateVariableSizedObject(Align Alignment, const AllocaInst *Alloca)
Notify the MachineFrameInfo object that a variable sized object has been created.
void setSavePoint(MachineBasicBlock *NewSave)
int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
void setStackSize(uint64_t Size)
Set the size of the stack.
void setHasMustTailInVarArgFunc(bool B)
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
void setFunctionContextIndex(int I)
This analysis create MachineFunction for given Function.
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
MachineFunctionProperties & reset(Property P)
void setBBSectionsType(BasicBlockSection V)
void setCallsUnwindInit(bool b)
void setHasEHFunclets(bool V)
void setExposesReturnsTwice(bool B)
setCallsSetJmp - Set a flag that indicates if there's a call to a "returns twice" function.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineJumpTableInfo * getOrCreateJumpTableInfo(unsigned JTEntryKind)
getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it does already exist,...
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void setHasEHCatchret(bool V)
void setCallsEHReturn(bool b)
void setAlignment(Align A)
setAlignment - Set the alignment of the function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
unsigned size() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
void addCallSiteInfo(const MachineInstr *CallI, CallSiteInfo &&CallInfo)
Start tracking the arguments passed to the call CallI.
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable in a stack slot.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
void assignBeginEndSections()
Assign IsBeginSection IsEndSection fields for basic blocks in this function.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned createJumpTableIndex(const std::vector< MachineBasicBlock * > &DestBBs)
createJumpTableIndex - Create a new jump table.
An analysis that produces MachineModuleInfo for a module.
This class contains meta information specific to a module.
MachineFunction & getOrCreateMachineFunction(Function &F)
Returns the MachineFunction constructed for the IR function F.
const LLVMTargetMachine & getTarget() const
MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
void setCalleeSavedRegs(ArrayRef< MCPhysReg > CSRs)
Sets the updated Callee Saved Registers list.
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
This class implements the register bank concept.
Definition: RegisterBank.h:28
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:281
SourceMgr::DiagKind getKind() const
Definition: SourceMgr.h:310
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
Represents a range in source code.
Definition: SMLoc.h:48
bool isValid() const
Definition: SMLoc.h:59
SMLoc Start
Definition: SMLoc.h:50
SMLoc End
Definition: SMLoc.h:50
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:31
unsigned getMainFileID() const
Definition: SourceMgr.h:132
std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file.
Definition: SourceMgr.cpp:192
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:125
SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
Definition: SourceMgr.cpp:274
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:144
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:282
static constexpr size_t npos
Definition: StringRef.h:52
Information about stack frame layout on the target.
virtual bool isSupportedStackID(TargetStackID::Value ID) const
llvm::BasicBlockSection getBBSectionsType() const
If basic blocks should be emitted into their own section, corresponding to -fbasic-block-sections.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual void mirFileLoaded(MachineFunction &MF) const
This is called after a .mir file was loaded.
virtual const TargetFrameLowering * getFrameLowering() const
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
static Type * getVoidTy(LLVMContext &C)
This function has undefined behavior.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:33
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3609
bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3615
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
Definition: MIParser.cpp:3574
bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3585
std::unique_ptr< MIRParser > createMIRParserFromFile(StringRef Filename, SMDiagnostic &Error, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction=nullptr)
This function is the main interface to the MIR serialization format parser.
Definition: MIRParser.cpp:1129
std::unique_ptr< MIRParser > createMIRParser(std::unique_ptr< MemoryBuffer > Contents, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction=nullptr)
This function is another interface to the MIR serialization format parser.
Definition: MIRParser.cpp:1143
std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition: Parser.cpp:47
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
Definition: MIParser.cpp:3580
bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3591
Constant * parseConstantValue(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type and a constant value in the given string.
Definition: Parser.cpp:188
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1856
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Warning
@ DS_Error
bool parseMachineMetadata(PerFunctionMIParsingState &PFS, StringRef Src, SMRange SourceRange, SMDiagnostic &Error)
Definition: MIParser.cpp:3620
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3603
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3597
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
SmallVector< ArgRegPair, 1 > ArgRegPairs
Vector of call argument and its forwarding register.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
DenseMap< unsigned, unsigned > JumpTableSlots
Definition: MIParser.h:180
VRegInfo & getVRegInfo(Register Num)
Definition: MIParser.cpp:320
DenseMap< unsigned, int > FixedStackObjectSlots
Definition: MIParser.h:177
DenseMap< unsigned, unsigned > ConstantPoolSlots
Definition: MIParser.h:179
StringMap< VRegInfo * > VRegInfosNamed
Definition: MIParser.h:176
DenseMap< unsigned, int > StackObjectSlots
Definition: MIParser.h:178
std::map< unsigned, std::pair< TempMDTuple, SMLoc > > MachineForwardRefMDNodes
Definition: MIParser.h:172
DenseMap< Register, VRegInfo * > VRegInfos
Definition: MIParser.h:175
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition: SlotMapping.h:33
Identifies call instruction location in machine function.
Serializable representation of MachineFrameInfo.
unsigned MaxCallFrameSize
~0u means: not computed yet.
std::vector< MachineStackObject > StackObjects
std::vector< StringValue > MachineMetadataNodes
std::optional< std::vector< FlowStringValue > > CalleeSavedRegisters
std::vector< EntryValueObject > EntryValueObjects
std::vector< MachineConstantPoolValue > Constants
std::vector< CallSiteInfo > CallSitesInfo
std::vector< MachineFunctionLiveIn > LiveIns
std::vector< VirtualRegisterDefinition > VirtualRegisters
std::vector< FixedMachineStackObject > FixedStackObjects
std::vector< DebugValueSubstitution > DebugValueSubstitutions
std::unique_ptr< MachineFunctionInfo > MachineFuncInfo
Constant pool.
MachineJumpTable JumpTableInfo
std::vector< Entry > Entries
MachineJumpTableInfo::JTEntryKind Kind
A wrapper around std::string which contains a source range that's being set during parsing.