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"
27#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Module.h"
36#include "llvm/Support/SMLoc.h"
40#include <memory>
41
42using namespace llvm;
43
44namespace llvm {
45class MDNode;
46class RegisterBank;
47
48/// This class implements the parsing of LLVM IR that's embedded inside a MIR
49/// file.
51 SourceMgr SM;
52 LLVMContext &Context;
53 yaml::Input In;
54 StringRef Filename;
55 SlotMapping IRSlots;
56 std::unique_ptr<PerTargetMIParsingState> Target;
57
58 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
59 /// created and inserted into the given module when this is true.
60 bool NoLLVMIR = false;
61 /// True when a well formed MIR file does not contain any MIR/machine function
62 /// parts.
63 bool NoMIRDocuments = false;
64
65 std::function<void(Function &)> ProcessIRFunction;
66
67public:
68 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
70 std::function<void(Function &)> ProcessIRFunction);
71
72 void reportDiagnostic(const SMDiagnostic &Diag);
73
74 /// Report an error with the given message at unknown location.
75 ///
76 /// Always returns true.
77 bool error(const Twine &Message);
78
79 /// Report an error with the given message at the given location.
80 ///
81 /// Always returns true.
82 bool error(SMLoc Loc, const Twine &Message);
83
84 /// Report a given error with the location translated from the location in an
85 /// embedded string literal to a location in the MIR file.
86 ///
87 /// Always returns true.
88 bool error(const SMDiagnostic &Error, SMRange SourceRange);
89
90 /// Try to parse the optional LLVM module and the machine functions in the MIR
91 /// file.
92 ///
93 /// Return null if an error occurred.
94 std::unique_ptr<Module>
95 parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
96
97 /// Create an empty function with the given name.
99
101
102 /// Parse the machine function in the current YAML document.
103 ///
104 ///
105 /// Return true if an error occurred.
107
108 /// Initialize the machine function to the state that's described in the MIR
109 /// file.
110 ///
111 /// Return true if error occurred.
113 MachineFunction &MF);
114
116 const yaml::MachineFunction &YamlMF);
117
119 const yaml::MachineFunction &YamlMF);
120
122 const yaml::MachineFunction &YamlMF);
123
125 const yaml::MachineFunction &YamlMF);
126
128 std::vector<CalleeSavedInfo> &CSIInfo,
129 const yaml::StringValue &RegisterSource,
130 bool IsRestored, int FrameIdx);
131
132 struct VarExprLoc {
135 DILocation *DILoc = nullptr;
136 };
137
138 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
139 const yaml::StringValue &VarStr,
140 const yaml::StringValue &ExprStr,
141 const yaml::StringValue &LocStr);
142 template <typename T>
144 const T &Object,
145 int FrameIdx);
146
149 const yaml::MachineFunction &YamlMF);
150
152 const yaml::MachineJumpTable &YamlJTI);
153
155 MachineFunction &MF,
156 const yaml::MachineFunction &YMF);
157
158private:
159 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
160 const yaml::StringValue &Source);
161
162 bool parseMBBReference(PerFunctionMIParsingState &PFS,
164 const yaml::StringValue &Source);
165
166 bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
167 const yaml::StringValue &Source);
168
169 /// Return a MIR diagnostic converted from an MI string diagnostic.
170 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
171 SMRange SourceRange);
172
173 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
174 /// block scalar string.
175 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
176 SMRange SourceRange);
177
178 void computeFunctionProperties(MachineFunction &MF);
179
180 void setupDebugValueTracking(MachineFunction &MF,
182};
183
184} // end namespace llvm
185
186static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
187 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
188}
189
190MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
191 StringRef Filename, LLVMContext &Context,
192 std::function<void(Function &)> Callback)
193 : Context(Context),
194 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
195 ->getBuffer(),
196 nullptr, handleYAMLDiag, this),
197 Filename(Filename), ProcessIRFunction(Callback) {
198 In.setContext(&In);
199}
200
201bool MIRParserImpl::error(const Twine &Message) {
203 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
204 return true;
205}
206
207bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
209 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
210 return true;
211}
212
214 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
215 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
216 return true;
217}
218
221 switch (Diag.getKind()) {
223 Kind = DS_Error;
224 break;
226 Kind = DS_Warning;
227 break;
229 Kind = DS_Note;
230 break;
232 llvm_unreachable("remark unexpected");
233 break;
234 }
236}
237
238std::unique_ptr<Module>
240 if (!In.setCurrentDocument()) {
241 if (In.error())
242 return nullptr;
243 // Create an empty module when the MIR file is empty.
244 NoMIRDocuments = true;
245 auto M = std::make_unique<Module>(Filename, Context);
246 if (auto LayoutOverride =
247 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
248 M->setDataLayout(*LayoutOverride);
249 return M;
250 }
251
252 std::unique_ptr<Module> M;
253 // Parse the block scalar manually so that we can return unique pointer
254 // without having to go trough YAML traits.
255 if (const auto *BSN =
256 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
258 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
259 Context, &IRSlots, DataLayoutCallback);
260 if (!M) {
261 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
262 return nullptr;
263 }
264 In.nextDocument();
265 if (!In.setCurrentDocument())
266 NoMIRDocuments = true;
267 } else {
268 // Create an new, empty module.
269 M = std::make_unique<Module>(Filename, Context);
270 if (auto LayoutOverride =
271 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
272 M->setDataLayout(*LayoutOverride);
273 NoLLVMIR = true;
274 }
275 return M;
276}
277
279 if (NoMIRDocuments)
280 return false;
281
282 // Parse the machine functions.
283 do {
284 if (parseMachineFunction(M, MMI))
285 return true;
286 In.nextDocument();
287 } while (In.setCurrentDocument());
288
289 return false;
290}
291
293 auto &Context = M.getContext();
294 Function *F =
297 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
298 new UnreachableInst(Context, BB);
299
300 if (ProcessIRFunction)
301 ProcessIRFunction(*F);
302
303 return F;
304}
305
307 // Parse the yaml.
309 yaml::EmptyContext Ctx;
310
311 const LLVMTargetMachine &TM = MMI.getTarget();
312 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
313 TM.createDefaultFuncInfoYAML());
314
315 yaml::yamlize(In, YamlMF, false, Ctx);
316 if (In.error())
317 return true;
318
319 // Search for the corresponding IR function.
320 StringRef FunctionName = YamlMF.Name;
321 Function *F = M.getFunction(FunctionName);
322 if (!F) {
323 if (NoLLVMIR) {
324 F = createDummyFunction(FunctionName, M);
325 } else {
326 return error(Twine("function '") + FunctionName +
327 "' isn't defined in the provided LLVM IR");
328 }
329 }
330 if (MMI.getMachineFunction(*F) != nullptr)
331 return error(Twine("redefinition of machine function '") + FunctionName +
332 "'");
333
334 // Create the MachineFunction.
336 if (initializeMachineFunction(YamlMF, MF))
337 return true;
338
339 return false;
340}
341
342static bool isSSA(const MachineFunction &MF) {
343 const MachineRegisterInfo &MRI = MF.getRegInfo();
344 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
346 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
347 return false;
348
349 // Subregister defs are invalid in SSA.
350 const MachineOperand *RegDef = MRI.getOneDef(Reg);
351 if (RegDef && RegDef->getSubReg() != 0)
352 return false;
353 }
354 return true;
355}
356
357void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
358 MachineFunctionProperties &Properties = MF.getProperties();
359
360 bool HasPHI = false;
361 bool HasInlineAsm = false;
362 bool AllTiedOpsRewritten = true, HasTiedOps = false;
363 for (const MachineBasicBlock &MBB : MF) {
364 for (const MachineInstr &MI : MBB) {
365 if (MI.isPHI())
366 HasPHI = true;
367 if (MI.isInlineAsm())
368 HasInlineAsm = true;
369 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
370 const MachineOperand &MO = MI.getOperand(I);
371 if (!MO.isReg() || !MO.getReg())
372 continue;
373 unsigned DefIdx;
374 if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
375 HasTiedOps = true;
376 if (MO.getReg() != MI.getOperand(DefIdx).getReg())
377 AllTiedOpsRewritten = false;
378 }
379 }
380 }
381 }
382 if (!HasPHI)
384 MF.setHasInlineAsm(HasInlineAsm);
385
386 if (HasTiedOps && AllTiedOpsRewritten)
388
389 if (isSSA(MF))
391 else
393
394 const MachineRegisterInfo &MRI = MF.getRegInfo();
395 if (MRI.getNumVirtRegs() == 0)
397}
398
401 MachineFunction &MF = PFS.MF;
403 const LLVMTargetMachine &TM = MF.getTarget();
404 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
405 yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
406 if (MILoc.BlockNum >= MF.size())
407 return error(Twine(MF.getName()) +
408 Twine(" call instruction block out of range.") +
409 " Unable to reference bb:" + Twine(MILoc.BlockNum));
410 auto CallB = std::next(MF.begin(), MILoc.BlockNum);
411 if (MILoc.Offset >= CallB->size())
412 return error(Twine(MF.getName()) +
413 Twine(" call instruction offset out of range.") +
414 " Unable to reference instruction at bb: " +
415 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
416 auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
417 if (!CallI->isCall(MachineInstr::IgnoreBundle))
418 return error(Twine(MF.getName()) +
419 Twine(" call site info should reference call "
420 "instruction. Instruction at bb:") +
421 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
422 " is not a call instruction");
424 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
425 Register Reg;
426 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
427 return error(Error, ArgRegPair.Reg.SourceRange);
428 CSInfo.emplace_back(Reg, ArgRegPair.ArgNo);
429 }
430
431 if (TM.Options.EmitCallSiteInfo)
432 MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo));
433 }
434
435 if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
436 return error(Twine("Call site info provided but not used"));
437 return false;
438}
439
440void MIRParserImpl::setupDebugValueTracking(
442 const yaml::MachineFunction &YamlMF) {
443 // Compute the value of the "next instruction number" field.
444 unsigned MaxInstrNum = 0;
445 for (auto &MBB : MF)
446 for (auto &MI : MBB)
447 MaxInstrNum = std::max((unsigned)MI.peekDebugInstrNum(), MaxInstrNum);
448 MF.setDebugInstrNumberingCount(MaxInstrNum);
449
450 // Load any substitutions.
451 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
452 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
453 {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
454 }
455
456 // Flag for whether we're supposed to be using DBG_INSTR_REF.
457 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
458}
459
460bool
462 MachineFunction &MF) {
463 // TODO: Recreate the machine function.
464 if (Target) {
465 // Avoid clearing state if we're using the same subtarget again.
466 Target->setTarget(MF.getSubtarget());
467 } else {
469 }
470
471 MF.setAlignment(YamlMF.Alignment.valueOrOne());
473 MF.setHasWinCFI(YamlMF.HasWinCFI);
474
478 MF.setHasEHScopes(YamlMF.HasEHScopes);
480 MF.setIsOutlined(YamlMF.IsOutlined);
481
482 if (YamlMF.Legalized)
484 if (YamlMF.RegBankSelected)
485 MF.getProperties().set(
487 if (YamlMF.Selected)
489 if (YamlMF.FailedISel)
491 if (YamlMF.FailsVerification)
492 MF.getProperties().set(
494 if (YamlMF.TracksDebugUserValues)
495 MF.getProperties().set(
497
498 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
499 if (parseRegisterInfo(PFS, YamlMF))
500 return true;
501 if (!YamlMF.Constants.empty()) {
502 auto *ConstantPool = MF.getConstantPool();
503 assert(ConstantPool && "Constant pool must be created");
504 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
505 return true;
506 }
507 if (!YamlMF.MachineMetadataNodes.empty() &&
508 parseMachineMetadataNodes(PFS, MF, YamlMF))
509 return true;
510
511 StringRef BlockStr = YamlMF.Body.Value.Value;
513 SourceMgr BlockSM;
514 BlockSM.AddNewSourceBuffer(
515 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
516 SMLoc());
517 PFS.SM = &BlockSM;
518 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
520 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
521 return true;
522 }
523 // Check Basic Block Section Flags.
526 } else if (MF.hasBBSections()) {
528 }
529 PFS.SM = &SM;
530
531 // Initialize the frame information after creating all the MBBs so that the
532 // MBB references in the frame information can be resolved.
533 if (initializeFrameInfo(PFS, YamlMF))
534 return true;
535 // Initialize the jump table after creating all the MBBs so that the MBB
536 // references can be resolved.
537 if (!YamlMF.JumpTableInfo.Entries.empty() &&
539 return true;
540 // Parse the machine instructions after creating all of the MBBs so that the
541 // parser can resolve the MBB references.
542 StringRef InsnStr = YamlMF.Body.Value.Value;
543 SourceMgr InsnSM;
544 InsnSM.AddNewSourceBuffer(
545 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
546 SMLoc());
547 PFS.SM = &InsnSM;
548 if (parseMachineInstructions(PFS, InsnStr, Error)) {
550 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
551 return true;
552 }
553 PFS.SM = &SM;
554
555 if (setupRegisterInfo(PFS, YamlMF))
556 return true;
557
558 if (YamlMF.MachineFuncInfo) {
559 const LLVMTargetMachine &TM = MF.getTarget();
560 // Note this is called after the initial constructor of the
561 // MachineFunctionInfo based on the MachineFunction, which may depend on the
562 // IR.
563
564 SMRange SrcRange;
565 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
566 SrcRange)) {
567 return error(Error, SrcRange);
568 }
569 }
570
571 // Set the reserved registers after parsing MachineFuncInfo. The target may
572 // have been recording information used to select the reserved registers
573 // there.
574 // FIXME: This is a temporary workaround until the reserved registers can be
575 // serialized.
577 MRI.freezeReservedRegs();
578
579 computeFunctionProperties(MF);
580
581 if (initializeCallSiteInfo(PFS, YamlMF))
582 return false;
583
584 setupDebugValueTracking(MF, PFS, YamlMF);
585
587
588 MF.verify();
589 return false;
590}
591
593 const yaml::MachineFunction &YamlMF) {
594 MachineFunction &MF = PFS.MF;
595 MachineRegisterInfo &RegInfo = MF.getRegInfo();
596 assert(RegInfo.tracksLiveness());
597 if (!YamlMF.TracksRegLiveness)
598 RegInfo.invalidateLiveness();
599
601 // Parse the virtual register information.
602 for (const auto &VReg : YamlMF.VirtualRegisters) {
603 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
604 if (Info.Explicit)
605 return error(VReg.ID.SourceRange.Start,
606 Twine("redefinition of virtual register '%") +
607 Twine(VReg.ID.Value) + "'");
608 Info.Explicit = true;
609
610 if (VReg.Class.Value == "_") {
611 Info.Kind = VRegInfo::GENERIC;
612 Info.D.RegBank = nullptr;
613 } else {
614 const auto *RC = Target->getRegClass(VReg.Class.Value);
615 if (RC) {
616 Info.Kind = VRegInfo::NORMAL;
617 Info.D.RC = RC;
618 } else {
619 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
620 if (!RegBank)
621 return error(
622 VReg.Class.SourceRange.Start,
623 Twine("use of undefined register class or register bank '") +
624 VReg.Class.Value + "'");
625 Info.Kind = VRegInfo::REGBANK;
626 Info.D.RegBank = RegBank;
627 }
628 }
629
630 if (!VReg.PreferredRegister.Value.empty()) {
631 if (Info.Kind != VRegInfo::NORMAL)
632 return error(VReg.Class.SourceRange.Start,
633 Twine("preferred register can only be set for normal vregs"));
634
635 if (parseRegisterReference(PFS, Info.PreferredReg,
636 VReg.PreferredRegister.Value, Error))
637 return error(Error, VReg.PreferredRegister.SourceRange);
638 }
639 }
640
641 // Parse the liveins.
642 for (const auto &LiveIn : YamlMF.LiveIns) {
643 Register Reg;
644 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
645 return error(Error, LiveIn.Register.SourceRange);
646 Register VReg;
647 if (!LiveIn.VirtualRegister.Value.empty()) {
648 VRegInfo *Info;
649 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
650 Error))
651 return error(Error, LiveIn.VirtualRegister.SourceRange);
652 VReg = Info->VReg;
653 }
654 RegInfo.addLiveIn(Reg, VReg);
655 }
656
657 // Parse the callee saved registers (Registers that will
658 // be saved for the caller).
659 if (YamlMF.CalleeSavedRegisters) {
660 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
661 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
662 Register Reg;
663 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
664 return error(Error, RegSource.SourceRange);
665 CalleeSavedRegisters.push_back(Reg);
666 }
667 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
668 }
669
670 return false;
671}
672
674 const yaml::MachineFunction &YamlMF) {
675 MachineFunction &MF = PFS.MF;
678
679 bool Error = false;
680 // Create VRegs
681 auto populateVRegInfo = [&](const VRegInfo &Info, Twine Name) {
682 Register Reg = Info.VReg;
683 switch (Info.Kind) {
685 error(Twine("Cannot determine class/bank of virtual register ") +
686 Name + " in function '" + MF.getName() + "'");
687 Error = true;
688 break;
689 case VRegInfo::NORMAL:
690 if (!Info.D.RC->isAllocatable()) {
691 error(Twine("Cannot use non-allocatable class '") +
692 TRI->getRegClassName(Info.D.RC) + "' for virtual register " +
693 Name + " in function '" + MF.getName() + "'");
694 Error = true;
695 break;
696 }
697
698 MRI.setRegClass(Reg, Info.D.RC);
699 if (Info.PreferredReg != 0)
700 MRI.setSimpleHint(Reg, Info.PreferredReg);
701 break;
703 break;
705 MRI.setRegBank(Reg, *Info.D.RegBank);
706 break;
707 }
708 };
709
710 for (const auto &P : PFS.VRegInfosNamed) {
711 const VRegInfo &Info = *P.second;
712 populateVRegInfo(Info, Twine(P.first()));
713 }
714
715 for (auto P : PFS.VRegInfos) {
716 const VRegInfo &Info = *P.second;
717 populateVRegInfo(Info, Twine(P.first));
718 }
719
720 // Compute MachineRegisterInfo::UsedPhysRegMask
721 for (const MachineBasicBlock &MBB : MF) {
722 // Make sure MRI knows about registers clobbered by unwinder.
723 if (MBB.isEHPad())
724 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
725 MRI.addPhysRegsUsedFromRegMask(RegMask);
726
727 for (const MachineInstr &MI : MBB) {
728 for (const MachineOperand &MO : MI.operands()) {
729 if (!MO.isRegMask())
730 continue;
731 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
732 }
733 }
734 }
735
736 return Error;
737}
738
740 const yaml::MachineFunction &YamlMF) {
741 MachineFunction &MF = PFS.MF;
742 MachineFrameInfo &MFI = MF.getFrameInfo();
744 const Function &F = MF.getFunction();
745 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
748 MFI.setHasStackMap(YamlMFI.HasStackMap);
749 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
750 MFI.setStackSize(YamlMFI.StackSize);
752 if (YamlMFI.MaxAlignment)
754 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
755 MFI.setHasCalls(YamlMFI.HasCalls);
756 if (YamlMFI.MaxCallFrameSize != ~0u)
760 MFI.setHasVAStart(YamlMFI.HasVAStart);
762 MFI.setHasTailCall(YamlMFI.HasTailCall);
764 if (!YamlMFI.SavePoint.Value.empty()) {
765 MachineBasicBlock *MBB = nullptr;
766 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
767 return true;
768 MFI.setSavePoint(MBB);
769 }
770 if (!YamlMFI.RestorePoint.Value.empty()) {
771 MachineBasicBlock *MBB = nullptr;
772 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
773 return true;
774 MFI.setRestorePoint(MBB);
775 }
776
777 std::vector<CalleeSavedInfo> CSIInfo;
778 // Initialize the fixed frame objects.
779 for (const auto &Object : YamlMF.FixedStackObjects) {
780 int ObjectIdx;
782 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
783 Object.IsImmutable, Object.IsAliased);
784 else
785 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
786
787 if (!TFI->isSupportedStackID(Object.StackID))
788 return error(Object.ID.SourceRange.Start,
789 Twine("StackID is not supported by target"));
790 MFI.setStackID(ObjectIdx, Object.StackID);
791 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
792 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
793 ObjectIdx))
794 .second)
795 return error(Object.ID.SourceRange.Start,
796 Twine("redefinition of fixed stack object '%fixed-stack.") +
797 Twine(Object.ID.Value) + "'");
798 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
799 Object.CalleeSavedRestored, ObjectIdx))
800 return true;
801 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
802 return true;
803 }
804
805 for (const auto &Object : YamlMF.EntryValueObjects) {
807 Register Reg;
808 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
809 Error))
810 return error(Error, Object.EntryValueRegister.SourceRange);
811 if (!Reg.isPhysical())
812 return error(Object.EntryValueRegister.SourceRange.Start,
813 "Expected physical register for entry value field");
814 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
815 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
816 if (!MaybeInfo)
817 return true;
818 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
819 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
820 Reg.asMCReg(), MaybeInfo->DILoc);
821 }
822
823 // Initialize the ordinary frame objects.
824 for (const auto &Object : YamlMF.StackObjects) {
825 int ObjectIdx;
826 const AllocaInst *Alloca = nullptr;
827 const yaml::StringValue &Name = Object.Name;
828 if (!Name.Value.empty()) {
829 Alloca = dyn_cast_or_null<AllocaInst>(
830 F.getValueSymbolTable()->lookup(Name.Value));
831 if (!Alloca)
832 return error(Name.SourceRange.Start,
833 "alloca instruction named '" + Name.Value +
834 "' isn't defined in the function '" + F.getName() +
835 "'");
836 }
837 if (!TFI->isSupportedStackID(Object.StackID))
838 return error(Object.ID.SourceRange.Start,
839 Twine("StackID is not supported by target"));
841 ObjectIdx =
842 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
843 else
844 ObjectIdx = MFI.CreateStackObject(
845 Object.Size, Object.Alignment.valueOrOne(),
846 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
847 Object.StackID);
848 MFI.setObjectOffset(ObjectIdx, Object.Offset);
849
850 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
851 .second)
852 return error(Object.ID.SourceRange.Start,
853 Twine("redefinition of stack object '%stack.") +
854 Twine(Object.ID.Value) + "'");
855 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
856 Object.CalleeSavedRestored, ObjectIdx))
857 return true;
858 if (Object.LocalOffset)
859 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
860 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
861 return true;
862 }
863 MFI.setCalleeSavedInfo(CSIInfo);
864 if (!CSIInfo.empty())
865 MFI.setCalleeSavedInfoValid(true);
866
867 // Initialize the various stack object references after initializing the
868 // stack objects.
869 if (!YamlMFI.StackProtector.Value.empty()) {
871 int FI;
873 return error(Error, YamlMFI.StackProtector.SourceRange);
875 }
876
877 if (!YamlMFI.FunctionContext.Value.empty()) {
879 int FI;
881 return error(Error, YamlMFI.FunctionContext.SourceRange);
883 }
884
885 return false;
886}
887
889 std::vector<CalleeSavedInfo> &CSIInfo,
890 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
891 if (RegisterSource.Value.empty())
892 return false;
893 Register Reg;
895 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
896 return error(Error, RegisterSource.SourceRange);
897 CalleeSavedInfo CSI(Reg, FrameIdx);
898 CSI.setRestored(IsRestored);
899 CSIInfo.push_back(CSI);
900 return false;
901}
902
903/// Verify that given node is of a certain type. Return true on error.
904template <typename T>
905static bool typecheckMDNode(T *&Result, MDNode *Node,
906 const yaml::StringValue &Source,
907 StringRef TypeString, MIRParserImpl &Parser) {
908 if (!Node)
909 return false;
910 Result = dyn_cast<T>(Node);
911 if (!Result)
912 return Parser.error(Source.SourceRange.Start,
913 "expected a reference to a '" + TypeString +
914 "' metadata node");
915 return false;
916}
917
918std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
920 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
921 MDNode *Var = nullptr;
922 MDNode *Expr = nullptr;
923 MDNode *Loc = nullptr;
924 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
925 parseMDNode(PFS, Loc, LocStr))
926 return std::nullopt;
927 DILocalVariable *DIVar = nullptr;
928 DIExpression *DIExpr = nullptr;
929 DILocation *DILoc = nullptr;
930 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
931 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
932 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
933 return std::nullopt;
934 return VarExprLoc{DIVar, DIExpr, DILoc};
935}
936
937template <typename T>
939 const T &Object, int FrameIdx) {
940 std::optional<VarExprLoc> MaybeInfo =
941 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
942 if (!MaybeInfo)
943 return true;
944 // Debug information can only be attached to stack objects; Fixed stack
945 // objects aren't supported.
946 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
947 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
948 MaybeInfo->DILoc);
949 return false;
950}
951
952bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
953 MDNode *&Node, const yaml::StringValue &Source) {
954 if (Source.Value.empty())
955 return false;
957 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
958 return error(Error, Source.SourceRange);
959 return false;
960}
961
964 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
965 const MachineFunction &MF = PFS.MF;
966 const auto &M = *MF.getFunction().getParent();
968 for (const auto &YamlConstant : YamlMF.Constants) {
969 if (YamlConstant.IsTargetSpecific)
970 // FIXME: Support target-specific constant pools
971 return error(YamlConstant.Value.SourceRange.Start,
972 "Can't parse target-specific constant pool entries yet");
973 const Constant *Value = dyn_cast_or_null<Constant>(
974 parseConstantValue(YamlConstant.Value.Value, Error, M));
975 if (!Value)
976 return error(Error, YamlConstant.Value.SourceRange);
977 const Align PrefTypeAlign =
978 M.getDataLayout().getPrefTypeAlign(Value->getType());
979 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
980 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
981 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
982 .second)
983 return error(YamlConstant.ID.SourceRange.Start,
984 Twine("redefinition of constant pool item '%const.") +
985 Twine(YamlConstant.ID.Value) + "'");
986 }
987 return false;
988}
989
991 const yaml::MachineJumpTable &YamlJTI) {
993 for (const auto &Entry : YamlJTI.Entries) {
994 std::vector<MachineBasicBlock *> Blocks;
995 for (const auto &MBBSource : Entry.Blocks) {
996 MachineBasicBlock *MBB = nullptr;
997 if (parseMBBReference(PFS, MBB, MBBSource.Value))
998 return true;
999 Blocks.push_back(MBB);
1000 }
1001 unsigned Index = JTI->createJumpTableIndex(Blocks);
1002 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1003 .second)
1004 return error(Entry.ID.SourceRange.Start,
1005 Twine("redefinition of jump table entry '%jump-table.") +
1006 Twine(Entry.ID.Value) + "'");
1007 }
1008 return false;
1009}
1010
1011bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1013 const yaml::StringValue &Source) {
1015 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1016 return error(Error, Source.SourceRange);
1017 return false;
1018}
1019
1020bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1021 const yaml::StringValue &Source) {
1023 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1024 return error(Error, Source.SourceRange);
1025 return false;
1026}
1027
1030 const yaml::MachineFunction &YMF) {
1031 for (const auto &MDS : YMF.MachineMetadataNodes) {
1032 if (parseMachineMetadata(PFS, MDS))
1033 return true;
1034 }
1035 // Report missing definitions from forward referenced nodes.
1036 if (!PFS.MachineForwardRefMDNodes.empty())
1037 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1038 "use of undefined metadata '!" +
1039 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1040 return false;
1041}
1042
1043SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1044 SMRange SourceRange) {
1045 assert(SourceRange.isValid() && "Invalid source range");
1046 SMLoc Loc = SourceRange.Start;
1047 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1048 *Loc.getPointer() == '\'';
1049 // Translate the location of the error from the location in the MI string to
1050 // the corresponding location in the MIR file.
1051 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1052 (HasQuote ? 1 : 0));
1053
1054 // TODO: Translate any source ranges as well.
1055 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), std::nullopt,
1056 Error.getFixIts());
1057}
1058
1059SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1060 SMRange SourceRange) {
1061 assert(SourceRange.isValid());
1062
1063 // Translate the location of the error from the location in the llvm IR string
1064 // to the corresponding location in the MIR file.
1065 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1066 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1067 unsigned Column = Error.getColumnNo();
1068 StringRef LineStr = Error.getLineContents();
1069 SMLoc Loc = Error.getLoc();
1070
1071 // Get the full line and adjust the column number by taking the indentation of
1072 // LLVM IR into account.
1073 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1074 L != E; ++L) {
1075 if (L.line_number() == Line) {
1076 LineStr = *L;
1077 Loc = SMLoc::getFromPointer(LineStr.data());
1078 auto Indent = LineStr.find(Error.getLineContents());
1079 if (Indent != StringRef::npos)
1080 Column += Indent;
1081 break;
1082 }
1083 }
1084
1085 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1086 Error.getMessage(), LineStr, Error.getRanges(),
1087 Error.getFixIts());
1088}
1089
1090MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1091 : Impl(std::move(Impl)) {}
1092
1093MIRParser::~MIRParser() = default;
1094
1095std::unique_ptr<Module>
1097 return Impl->parseIRModule(DataLayoutCallback);
1098}
1099
1101 return Impl->parseMachineFunctions(M, MMI);
1102}
1103
1104std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1105 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1106 std::function<void(Function &)> ProcessIRFunction) {
1107 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1108 if (std::error_code EC = FileOrErr.getError()) {
1110 "Could not open input file: " + EC.message());
1111 return nullptr;
1112 }
1113 return createMIRParser(std::move(FileOrErr.get()), Context,
1114 ProcessIRFunction);
1115}
1116
1117std::unique_ptr<MIRParser>
1118llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1119 LLVMContext &Context,
1120 std::function<void(Function &)> ProcessIRFunction) {
1121 auto Filename = Contents->getBufferIdentifier();
1124 DS_Error,
1126 Filename, SourceMgr::DK_Error,
1127 "Can't read MIR with a Context that discards named Values")));
1128 return nullptr;
1129 }
1130 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1131 std::move(Contents), Filename, Context, ProcessIRFunction));
1132}
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:342
static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context)
Definition: MIRParser.cpp:186
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:905
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)
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
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:198
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:162
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
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:50
bool error(const Twine &Message)
Report an error with the given message at unknown location.
Definition: MIRParser.cpp:201
void reportDiagnostic(const SMDiagnostic &Diag)
Definition: MIRParser.cpp:219
bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:673
bool parseRegisterInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:592
bool initializeFrameInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:739
Function * createDummyFunction(StringRef Name, Module &M)
Create an empty function with the given name.
Definition: MIRParser.cpp:292
bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, const T &Object, int FrameIdx)
Definition: MIRParser.cpp:938
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:461
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:239
bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, const yaml::MachineJumpTable &YamlJTI)
Definition: MIRParser.cpp:990
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Definition: MIRParser.cpp:278
bool initializeConstantPool(PerFunctionMIParsingState &PFS, MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:962
MIRParserImpl(std::unique_ptr< MemoryBuffer > Contents, StringRef Filename, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction)
Definition: MIRParser.cpp:190
std::optional< VarExprLoc > parseVarExprLoc(PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr, const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr)
Definition: MIRParser.cpp:918
bool parseMachineFunction(Module &M, MachineModuleInfo &MMI)
Parse the machine function in the current YAML document.
Definition: MIRParser.cpp:306
bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, std::vector< CalleeSavedInfo > &CSIInfo, const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx)
Definition: MIRParser.cpp:888
bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
Definition: MIRParser.cpp:1028
bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:399
MIRParser(std::unique_ptr< MIRParserImpl > Impl)
Definition: MIRParser.cpp:1090
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:1096
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Parses MachineFunctions in the MIR file and add them to the given MachineModuleInfo MMI.
Definition: MIRParser.cpp:1100
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)
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.
void addCallArgsForwardingRegs(const MachineInstr *CallI, CallSiteInfoImpl &&CallInfo)
Start tracking the arguments passed to the call CallI.
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.
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.
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
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
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:293
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:1104
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:1118
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:1858
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
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.