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