LLVM 19.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,
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 }
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);
783 if (!YamlMFI.SavePoint.Value.empty()) {
784 MachineBasicBlock *MBB = nullptr;
785 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
786 return true;
787 MFI.setSavePoint(MBB);
788 }
789 if (!YamlMFI.RestorePoint.Value.empty()) {
790 MachineBasicBlock *MBB = nullptr;
791 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
792 return true;
793 MFI.setRestorePoint(MBB);
794 }
795
796 std::vector<CalleeSavedInfo> CSIInfo;
797 // Initialize the fixed frame objects.
798 for (const auto &Object : YamlMF.FixedStackObjects) {
799 int ObjectIdx;
801 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
802 Object.IsImmutable, Object.IsAliased);
803 else
804 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
805
806 if (!TFI->isSupportedStackID(Object.StackID))
807 return error(Object.ID.SourceRange.Start,
808 Twine("StackID is not supported by target"));
809 MFI.setStackID(ObjectIdx, Object.StackID);
810 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
811 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
812 ObjectIdx))
813 .second)
814 return error(Object.ID.SourceRange.Start,
815 Twine("redefinition of fixed stack object '%fixed-stack.") +
816 Twine(Object.ID.Value) + "'");
817 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
818 Object.CalleeSavedRestored, ObjectIdx))
819 return true;
820 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
821 return true;
822 }
823
824 for (const auto &Object : YamlMF.EntryValueObjects) {
826 Register Reg;
827 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
828 Error))
829 return error(Error, Object.EntryValueRegister.SourceRange);
830 if (!Reg.isPhysical())
831 return error(Object.EntryValueRegister.SourceRange.Start,
832 "Expected physical register for entry value field");
833 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
834 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
835 if (!MaybeInfo)
836 return true;
837 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
838 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
839 Reg.asMCReg(), MaybeInfo->DILoc);
840 }
841
842 // Initialize the ordinary frame objects.
843 for (const auto &Object : YamlMF.StackObjects) {
844 int ObjectIdx;
845 const AllocaInst *Alloca = nullptr;
846 const yaml::StringValue &Name = Object.Name;
847 if (!Name.Value.empty()) {
848 Alloca = dyn_cast_or_null<AllocaInst>(
849 F.getValueSymbolTable()->lookup(Name.Value));
850 if (!Alloca)
851 return error(Name.SourceRange.Start,
852 "alloca instruction named '" + Name.Value +
853 "' isn't defined in the function '" + F.getName() +
854 "'");
855 }
856 if (!TFI->isSupportedStackID(Object.StackID))
857 return error(Object.ID.SourceRange.Start,
858 Twine("StackID is not supported by target"));
860 ObjectIdx =
861 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
862 else
863 ObjectIdx = MFI.CreateStackObject(
864 Object.Size, Object.Alignment.valueOrOne(),
865 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
866 Object.StackID);
867 MFI.setObjectOffset(ObjectIdx, Object.Offset);
868
869 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
870 .second)
871 return error(Object.ID.SourceRange.Start,
872 Twine("redefinition of stack object '%stack.") +
873 Twine(Object.ID.Value) + "'");
874 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
875 Object.CalleeSavedRestored, ObjectIdx))
876 return true;
877 if (Object.LocalOffset)
878 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
879 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
880 return true;
881 }
882 MFI.setCalleeSavedInfo(CSIInfo);
883 if (!CSIInfo.empty())
884 MFI.setCalleeSavedInfoValid(true);
885
886 // Initialize the various stack object references after initializing the
887 // stack objects.
888 if (!YamlMFI.StackProtector.Value.empty()) {
890 int FI;
892 return error(Error, YamlMFI.StackProtector.SourceRange);
894 }
895
896 if (!YamlMFI.FunctionContext.Value.empty()) {
898 int FI;
900 return error(Error, YamlMFI.FunctionContext.SourceRange);
902 }
903
904 return false;
905}
906
908 std::vector<CalleeSavedInfo> &CSIInfo,
909 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
910 if (RegisterSource.Value.empty())
911 return false;
912 Register Reg;
914 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
915 return error(Error, RegisterSource.SourceRange);
916 CalleeSavedInfo CSI(Reg, FrameIdx);
917 CSI.setRestored(IsRestored);
918 CSIInfo.push_back(CSI);
919 return false;
920}
921
922/// Verify that given node is of a certain type. Return true on error.
923template <typename T>
924static bool typecheckMDNode(T *&Result, MDNode *Node,
925 const yaml::StringValue &Source,
926 StringRef TypeString, MIRParserImpl &Parser) {
927 if (!Node)
928 return false;
929 Result = dyn_cast<T>(Node);
930 if (!Result)
931 return Parser.error(Source.SourceRange.Start,
932 "expected a reference to a '" + TypeString +
933 "' metadata node");
934 return false;
935}
936
937std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
939 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
940 MDNode *Var = nullptr;
941 MDNode *Expr = nullptr;
942 MDNode *Loc = nullptr;
943 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
944 parseMDNode(PFS, Loc, LocStr))
945 return std::nullopt;
946 DILocalVariable *DIVar = nullptr;
947 DIExpression *DIExpr = nullptr;
948 DILocation *DILoc = nullptr;
949 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
950 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
951 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
952 return std::nullopt;
953 return VarExprLoc{DIVar, DIExpr, DILoc};
954}
955
956template <typename T>
958 const T &Object, int FrameIdx) {
959 std::optional<VarExprLoc> MaybeInfo =
960 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
961 if (!MaybeInfo)
962 return true;
963 // Debug information can only be attached to stack objects; Fixed stack
964 // objects aren't supported.
965 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
966 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
967 MaybeInfo->DILoc);
968 return false;
969}
970
971bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
972 MDNode *&Node, const yaml::StringValue &Source) {
973 if (Source.Value.empty())
974 return false;
976 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
977 return error(Error, Source.SourceRange);
978 return false;
979}
980
983 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
984 const MachineFunction &MF = PFS.MF;
985 const auto &M = *MF.getFunction().getParent();
987 for (const auto &YamlConstant : YamlMF.Constants) {
988 if (YamlConstant.IsTargetSpecific)
989 // FIXME: Support target-specific constant pools
990 return error(YamlConstant.Value.SourceRange.Start,
991 "Can't parse target-specific constant pool entries yet");
992 const Constant *Value = dyn_cast_or_null<Constant>(
993 parseConstantValue(YamlConstant.Value.Value, Error, M));
994 if (!Value)
995 return error(Error, YamlConstant.Value.SourceRange);
996 const Align PrefTypeAlign =
997 M.getDataLayout().getPrefTypeAlign(Value->getType());
998 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
999 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
1000 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
1001 .second)
1002 return error(YamlConstant.ID.SourceRange.Start,
1003 Twine("redefinition of constant pool item '%const.") +
1004 Twine(YamlConstant.ID.Value) + "'");
1005 }
1006 return false;
1007}
1008
1010 const yaml::MachineJumpTable &YamlJTI) {
1012 for (const auto &Entry : YamlJTI.Entries) {
1013 std::vector<MachineBasicBlock *> Blocks;
1014 for (const auto &MBBSource : Entry.Blocks) {
1015 MachineBasicBlock *MBB = nullptr;
1016 if (parseMBBReference(PFS, MBB, MBBSource.Value))
1017 return true;
1018 Blocks.push_back(MBB);
1019 }
1020 unsigned Index = JTI->createJumpTableIndex(Blocks);
1021 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1022 .second)
1023 return error(Entry.ID.SourceRange.Start,
1024 Twine("redefinition of jump table entry '%jump-table.") +
1025 Twine(Entry.ID.Value) + "'");
1026 }
1027 return false;
1028}
1029
1030bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1032 const yaml::StringValue &Source) {
1034 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1035 return error(Error, Source.SourceRange);
1036 return false;
1037}
1038
1039bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1040 const yaml::StringValue &Source) {
1042 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1043 return error(Error, Source.SourceRange);
1044 return false;
1045}
1046
1049 const yaml::MachineFunction &YMF) {
1050 for (const auto &MDS : YMF.MachineMetadataNodes) {
1051 if (parseMachineMetadata(PFS, MDS))
1052 return true;
1053 }
1054 // Report missing definitions from forward referenced nodes.
1055 if (!PFS.MachineForwardRefMDNodes.empty())
1056 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1057 "use of undefined metadata '!" +
1058 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1059 return false;
1060}
1061
1062SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1063 SMRange SourceRange) {
1064 assert(SourceRange.isValid() && "Invalid source range");
1065 SMLoc Loc = SourceRange.Start;
1066 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1067 *Loc.getPointer() == '\'';
1068 // Translate the location of the error from the location in the MI string to
1069 // the corresponding location in the MIR file.
1070 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1071 (HasQuote ? 1 : 0));
1072
1073 // TODO: Translate any source ranges as well.
1074 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), std::nullopt,
1075 Error.getFixIts());
1076}
1077
1078SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1079 SMRange SourceRange) {
1080 assert(SourceRange.isValid());
1081
1082 // Translate the location of the error from the location in the llvm IR string
1083 // to the corresponding location in the MIR file.
1084 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1085 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1086 unsigned Column = Error.getColumnNo();
1087 StringRef LineStr = Error.getLineContents();
1088 SMLoc Loc = Error.getLoc();
1089
1090 // Get the full line and adjust the column number by taking the indentation of
1091 // LLVM IR into account.
1092 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1093 L != E; ++L) {
1094 if (L.line_number() == Line) {
1095 LineStr = *L;
1096 Loc = SMLoc::getFromPointer(LineStr.data());
1097 auto Indent = LineStr.find(Error.getLineContents());
1098 if (Indent != StringRef::npos)
1099 Column += Indent;
1100 break;
1101 }
1102 }
1103
1104 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1105 Error.getMessage(), LineStr, Error.getRanges(),
1106 Error.getFixIts());
1107}
1108
1109MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1110 : Impl(std::move(Impl)) {}
1111
1112MIRParser::~MIRParser() = default;
1113
1114std::unique_ptr<Module>
1116 return Impl->parseIRModule(DataLayoutCallback);
1117}
1118
1120 return Impl->parseMachineFunctions(M, MMI);
1121}
1122
1124 auto &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
1125 return Impl->parseMachineFunctions(M, MMI, &MAM);
1126}
1127
1128std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1129 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1130 std::function<void(Function &)> ProcessIRFunction) {
1131 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1132 if (std::error_code EC = FileOrErr.getError()) {
1134 "Could not open input file: " + EC.message());
1135 return nullptr;
1136 }
1137 return createMIRParser(std::move(FileOrErr.get()), Context,
1138 ProcessIRFunction);
1139}
1140
1141std::unique_ptr<MIRParser>
1142llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1143 LLVMContext &Context,
1144 std::function<void(Function &)> ProcessIRFunction) {
1145 auto Filename = Contents->getBufferIdentifier();
1148 DS_Error,
1150 Filename, SourceMgr::DK_Error,
1151 "Can't read MIR with a Context that discards named Values")));
1152 return nullptr;
1153 }
1154 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1155 std::move(Contents), Filename, Context, ProcessIRFunction));
1156}
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:924
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.
LLVMContext & Context
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
const char LLVMTargetMachineRef TM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define error(X)
an instruction to allocate memory on the stack
Definition: Instructions.h:59
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:492
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:199
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:41
DWARF expression.
Debug location.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
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:164
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:631
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:1067
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:957
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:1009
bool initializeConstantPool(PerFunctionMIParsingState &PFS, MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:981
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:937
bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, std::vector< CalleeSavedInfo > &CSIInfo, const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx)
Definition: MIRParser.cpp:907
bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
Definition: MIRParser.cpp:1047
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:1109
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:1115
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Parses MachineFunctions in the MIR file and add them to the given MachineModuleInfo MMI.
Definition: MIRParser.cpp:1119
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.
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 setOffsetAdjustment(int Adj)
Set the correction for frame offsets.
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)
void setMaxCallFrameSize(unsigned S)
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 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:289
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:3643
bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3649
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
Definition: MIParser.cpp:3608
bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3619
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:1128
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:1142
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:46
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
Definition: MIParser.cpp:3614
bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3625
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:187
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:1849
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:3654
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3637
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3631
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.