LLVM 22.0.0git
MIRParser.cpp
Go to the documentation of this file.
1//===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the class that parses the optional LLVM IR and machine
10// functions that are stored in MIR files.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
37#include "llvm/Support/SMLoc.h"
41#include <memory>
42
43using namespace llvm;
44
45namespace llvm {
46class MDNode;
47class RegisterBank;
48
49/// This class implements the parsing of LLVM IR that's embedded inside a MIR
50/// file.
52 SourceMgr SM;
53 LLVMContext &Context;
54 yaml::Input In;
55 StringRef Filename;
56 SlotMapping IRSlots;
57 std::unique_ptr<PerTargetMIParsingState> Target;
58
59 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
60 /// created and inserted into the given module when this is true.
61 bool NoLLVMIR = false;
62 /// True when a well formed MIR file does not contain any MIR/machine function
63 /// parts.
64 bool NoMIRDocuments = false;
65
66 std::function<void(Function &)> ProcessIRFunction;
67
68public:
69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
71 std::function<void(Function &)> ProcessIRFunction);
72
73 void reportDiagnostic(const SMDiagnostic &Diag);
74
75 /// Report an error with the given message at unknown location.
76 ///
77 /// Always returns true.
78 bool error(const Twine &Message);
79
80 /// Report an error with the given message at the given location.
81 ///
82 /// Always returns true.
83 bool error(SMLoc Loc, const Twine &Message);
84
85 /// Report a given error with the location translated from the location in an
86 /// embedded string literal to a location in the MIR file.
87 ///
88 /// Always returns true.
89 bool error(const SMDiagnostic &Error, SMRange SourceRange);
90
91 /// Try to parse the optional LLVM module and the machine functions in the MIR
92 /// file.
93 ///
94 /// Return null if an error occurred.
95 std::unique_ptr<Module>
96 parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
97
98 /// Create an empty function with the given name.
100
102 ModuleAnalysisManager *FAM = nullptr);
103
104 /// Parse the machine function in the current YAML document.
105 ///
106 ///
107 /// Return true if an error occurred.
110
111 /// Initialize the machine function to the state that's described in the MIR
112 /// file.
113 ///
114 /// Return true if error occurred.
116 MachineFunction &MF);
117
119 const yaml::MachineFunction &YamlMF);
120
122 const yaml::MachineFunction &YamlMF);
123
125 const yaml::MachineFunction &YamlMF);
126
129 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
130 SmallVectorImpl<MachineBasicBlock *> &SaveRestorePoints);
131
133 const yaml::MachineFunction &YamlMF);
134
136 std::vector<CalleeSavedInfo> &CSIInfo,
137 const yaml::StringValue &RegisterSource,
138 bool IsRestored, int FrameIdx);
139
140 struct VarExprLoc {
143 DILocation *DILoc = nullptr;
144 };
145
146 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
147 const yaml::StringValue &VarStr,
148 const yaml::StringValue &ExprStr,
149 const yaml::StringValue &LocStr);
150 template <typename T>
152 const T &Object,
153 int FrameIdx);
154
157 const yaml::MachineFunction &YamlMF);
158
160 const yaml::MachineJumpTable &YamlJTI);
161
163 MachineFunction &MF,
164 const yaml::MachineFunction &YMF);
165
167 const yaml::MachineFunction &YMF);
168
169private:
170 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
171 const yaml::StringValue &Source);
172
173 bool parseMBBReference(PerFunctionMIParsingState &PFS,
175 const yaml::StringValue &Source);
176
177 bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
178 const yaml::StringValue &Source);
179
180 /// Return a MIR diagnostic converted from an MI string diagnostic.
181 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
182 SMRange SourceRange);
183
184 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
185 /// block scalar string.
186 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
187 SMRange SourceRange);
188
189 bool computeFunctionProperties(MachineFunction &MF,
190 const yaml::MachineFunction &YamlMF);
191
192 void setupDebugValueTracking(MachineFunction &MF,
194
195 bool parseMachineInst(MachineFunction &MF, yaml::MachineInstrLoc MILoc,
196 MachineInstr const *&MI);
197};
198
199} // end namespace llvm
200
201static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
202 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
203}
204
205MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
206 StringRef Filename, LLVMContext &Context,
207 std::function<void(Function &)> Callback)
208 : Context(Context),
209 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
210 ->getBuffer(),
211 nullptr, handleYAMLDiag, this),
212 Filename(Filename), ProcessIRFunction(Callback) {
213 In.setContext(&In);
214}
215
216bool MIRParserImpl::error(const Twine &Message) {
218 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
219 return true;
220}
221
222bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
224 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
225 return true;
226}
227
229 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
230 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
231 return true;
232}
233
236 switch (Diag.getKind()) {
238 Kind = DS_Error;
239 break;
241 Kind = DS_Warning;
242 break;
244 Kind = DS_Note;
245 break;
247 llvm_unreachable("remark unexpected");
248 break;
249 }
250 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
251}
252
253std::unique_ptr<Module>
255 if (!In.setCurrentDocument()) {
256 if (In.error())
257 return nullptr;
258 // Create an empty module when the MIR file is empty.
259 NoMIRDocuments = true;
260 auto M = std::make_unique<Module>(Filename, Context);
261 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
262 M->getDataLayoutStr()))
263 M->setDataLayout(*LayoutOverride);
264 return M;
265 }
266
267 std::unique_ptr<Module> M;
268 // Parse the block scalar manually so that we can return unique pointer
269 // without having to go trough YAML traits.
270 if (const auto *BSN =
271 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
273 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
274 Context, &IRSlots, DataLayoutCallback);
275 if (!M) {
276 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
277 return nullptr;
278 }
279 In.nextDocument();
280 if (!In.setCurrentDocument())
281 NoMIRDocuments = true;
282 } else {
283 // Create an new, empty module.
284 M = std::make_unique<Module>(Filename, Context);
285 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
286 M->getDataLayoutStr()))
287 M->setDataLayout(*LayoutOverride);
288 NoLLVMIR = true;
289 }
290 return M;
291}
292
295 if (NoMIRDocuments)
296 return false;
297
298 // Parse the machine functions.
299 do {
300 if (parseMachineFunction(M, MMI, MAM))
301 return true;
302 In.nextDocument();
303 } while (In.setCurrentDocument());
304
305 return false;
306}
307
309 auto &Context = M.getContext();
310 Function *F =
313 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
314 new UnreachableInst(Context, BB);
315
316 if (ProcessIRFunction)
317 ProcessIRFunction(*F);
318
319 return F;
320}
321
324 // Parse the yaml.
326 yaml::EmptyContext Ctx;
327
328 const TargetMachine &TM = MMI.getTarget();
329 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
330 TM.createDefaultFuncInfoYAML());
331
332 yaml::yamlize(In, YamlMF, false, Ctx);
333 if (In.error())
334 return true;
335
336 // Search for the corresponding IR function.
337 StringRef FunctionName = YamlMF.Name;
338 Function *F = M.getFunction(FunctionName);
339 if (!F) {
340 if (NoLLVMIR) {
341 F = createDummyFunction(FunctionName, M);
342 } else {
343 return error(Twine("function '") + FunctionName +
344 "' isn't defined in the provided LLVM IR");
345 }
346 }
347
348 if (!MAM) {
349 if (MMI.getMachineFunction(*F) != nullptr)
350 return error(Twine("redefinition of machine function '") + FunctionName +
351 "'");
352
353 // Create the MachineFunction.
355 if (initializeMachineFunction(YamlMF, MF))
356 return true;
357 } else {
358 auto &FAM =
361 return error(Twine("redefinition of machine function '") + FunctionName +
362 "'");
363
364 // Create the MachineFunction.
366 if (initializeMachineFunction(YamlMF, MF))
367 return true;
368 }
369
370 return false;
371}
372
373static bool isSSA(const MachineFunction &MF) {
374 const MachineRegisterInfo &MRI = MF.getRegInfo();
375 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
377 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
378 return false;
379
380 // Subregister defs are invalid in SSA.
381 const MachineOperand *RegDef = MRI.getOneDef(Reg);
382 if (RegDef && RegDef->getSubReg() != 0)
383 return false;
384 }
385 return true;
386}
387
388bool MIRParserImpl::computeFunctionProperties(
389 MachineFunction &MF, const yaml::MachineFunction &YamlMF) {
390 MachineFunctionProperties &Properties = MF.getProperties();
391
392 bool HasPHI = false;
393 bool HasInlineAsm = false;
394 bool HasFakeUses = false;
395 bool AllTiedOpsRewritten = true, HasTiedOps = false;
396 for (const MachineBasicBlock &MBB : MF) {
397 for (const MachineInstr &MI : MBB) {
398 if (MI.isPHI())
399 HasPHI = true;
400 if (MI.isInlineAsm())
401 HasInlineAsm = true;
402 if (MI.isFakeUse())
403 HasFakeUses = true;
404 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
405 const MachineOperand &MO = MI.getOperand(I);
406 if (!MO.isReg() || !MO.getReg())
407 continue;
408 unsigned DefIdx;
409 if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
410 HasTiedOps = true;
411 if (MO.getReg() != MI.getOperand(DefIdx).getReg())
412 AllTiedOpsRewritten = false;
413 }
414 }
415 }
416 }
417
418 // Helper function to sanity-check and set properties that are computed, but
419 // may be explicitly set from the input MIR
420 auto ComputedPropertyHelper =
421 [&Properties](std::optional<bool> ExplicitProp, bool ComputedProp,
423 // Prefer explicitly given values over the computed properties
424 if (ExplicitProp.value_or(ComputedProp))
425 Properties.set(P);
426 else
427 Properties.reset(P);
428
429 // Check for conflict between the explicit values and the computed ones
430 return ExplicitProp && *ExplicitProp && !ComputedProp;
431 };
432
433 if (ComputedPropertyHelper(YamlMF.NoPHIs, !HasPHI,
435 return error(MF.getName() +
436 " has explicit property NoPhi, but contains at least one PHI");
437 }
438
439 MF.setHasInlineAsm(HasInlineAsm);
440
441 if (HasTiedOps && AllTiedOpsRewritten)
442 Properties.setTiedOpsRewritten();
443
444 if (ComputedPropertyHelper(YamlMF.IsSSA, isSSA(MF),
446 return error(MF.getName() +
447 " has explicit property IsSSA, but is not valid SSA");
448 }
449
450 const MachineRegisterInfo &MRI = MF.getRegInfo();
451 if (ComputedPropertyHelper(YamlMF.NoVRegs, MRI.getNumVirtRegs() == 0,
453 return error(
454 MF.getName() +
455 " has explicit property NoVRegs, but contains virtual registers");
456 }
457
458 // For hasFakeUses we follow similar logic to the ComputedPropertyHelper,
459 // except for caring about the inverse case only, i.e. when the property is
460 // explicitly set to false and Fake Uses are present; having HasFakeUses=true
461 // on a function without fake uses is harmless.
462 if (YamlMF.HasFakeUses && !*YamlMF.HasFakeUses && HasFakeUses)
463 return error(
464 MF.getName() +
465 " has explicit property hasFakeUses=false, but contains fake uses");
466 MF.setHasFakeUses(YamlMF.HasFakeUses.value_or(HasFakeUses));
467
468 return false;
469}
470
471bool MIRParserImpl::parseMachineInst(MachineFunction &MF,
473 MachineInstr const *&MI) {
474 if (MILoc.BlockNum >= MF.size()) {
475 return error(Twine(MF.getName()) +
476 Twine(" instruction block out of range.") +
477 " Unable to reference bb:" + Twine(MILoc.BlockNum));
478 }
479 auto BB = std::next(MF.begin(), MILoc.BlockNum);
480 if (MILoc.Offset >= BB->size())
481 return error(
482 Twine(MF.getName()) + Twine(" instruction offset out of range.") +
483 " Unable to reference instruction at bb: " + Twine(MILoc.BlockNum) +
484 " at offset:" + Twine(MILoc.Offset));
485 MI = &*std::next(BB->instr_begin(), MILoc.Offset);
486 return false;
487}
488
491 MachineFunction &MF = PFS.MF;
493 const TargetMachine &TM = MF.getTarget();
494 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
495 yaml::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
496 const MachineInstr *CallI;
497 if (parseMachineInst(MF, MILoc, CallI))
498 return true;
500 return error(Twine(MF.getName()) +
501 Twine(" call site info should reference call "
502 "instruction. Instruction at bb:") +
503 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
504 " is not a call instruction");
506 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
507 Register Reg;
508 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
509 return error(Error, ArgRegPair.Reg.SourceRange);
510 CSInfo.ArgRegPairs.emplace_back(Reg, ArgRegPair.ArgNo);
511 }
512 if (!YamlCSInfo.CalleeTypeIds.empty()) {
513 for (auto CalleeTypeId : YamlCSInfo.CalleeTypeIds) {
515 CSInfo.CalleeTypeIds.push_back(ConstantInt::get(Int64Ty, CalleeTypeId,
516 /*isSigned=*/false));
517 }
518 }
519
520 if (TM.Options.EmitCallSiteInfo || TM.Options.EmitCallGraphSection)
521 MF.addCallSiteInfo(&*CallI, std::move(CSInfo));
522 }
523
524 if (!YamlMF.CallSitesInfo.empty() &&
525 !(TM.Options.EmitCallSiteInfo || TM.Options.EmitCallGraphSection))
526 return error("call site info provided but not used");
527 return false;
528}
529
530void MIRParserImpl::setupDebugValueTracking(
532 const yaml::MachineFunction &YamlMF) {
533 // Compute the value of the "next instruction number" field.
534 unsigned MaxInstrNum = 0;
535 for (auto &MBB : MF)
536 for (auto &MI : MBB)
537 MaxInstrNum = std::max(MI.peekDebugInstrNum(), MaxInstrNum);
538 MF.setDebugInstrNumberingCount(MaxInstrNum);
539
540 // Load any substitutions.
541 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
542 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
543 {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
544 }
545
546 // Flag for whether we're supposed to be using DBG_INSTR_REF.
547 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
548}
549
550bool
552 MachineFunction &MF) {
553 // TODO: Recreate the machine function.
554 if (Target) {
555 // Avoid clearing state if we're using the same subtarget again.
556 Target->setTarget(MF.getSubtarget());
557 } else {
559 }
560
561 MF.setAlignment(YamlMF.Alignment.valueOrOne());
563 MF.setHasWinCFI(YamlMF.HasWinCFI);
564
568 MF.setHasEHScopes(YamlMF.HasEHScopes);
570 MF.setIsOutlined(YamlMF.IsOutlined);
571
573 if (YamlMF.Legalized)
574 Props.setLegalized();
575 if (YamlMF.RegBankSelected)
576 Props.setRegBankSelected();
577 if (YamlMF.Selected)
578 Props.setSelected();
579 if (YamlMF.FailedISel)
580 Props.setFailedISel();
581 if (YamlMF.FailsVerification)
582 Props.setFailsVerification();
583 if (YamlMF.TracksDebugUserValues)
584 Props.setTracksDebugUserValues();
585
586 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
587 if (parseRegisterInfo(PFS, YamlMF))
588 return true;
589 if (!YamlMF.Constants.empty()) {
590 auto *ConstantPool = MF.getConstantPool();
591 assert(ConstantPool && "Constant pool must be created");
592 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
593 return true;
594 }
595 if (!YamlMF.MachineMetadataNodes.empty() &&
596 parseMachineMetadataNodes(PFS, MF, YamlMF))
597 return true;
598
599 StringRef BlockStr = YamlMF.Body.Value.Value;
601 SourceMgr BlockSM;
602 BlockSM.AddNewSourceBuffer(
603 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
604 SMLoc());
605 PFS.SM = &BlockSM;
606 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
608 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
609 return true;
610 }
611 // Check Basic Block Section Flags.
612 if (MF.hasBBSections()) {
614 }
615 PFS.SM = &SM;
616
617 // Initialize the frame information after creating all the MBBs so that the
618 // MBB references in the frame information can be resolved.
619 if (initializeFrameInfo(PFS, YamlMF))
620 return true;
621 // Initialize the jump table after creating all the MBBs so that the MBB
622 // references can be resolved.
623 if (!YamlMF.JumpTableInfo.Entries.empty() &&
625 return true;
626 // Parse the machine instructions after creating all of the MBBs so that the
627 // parser can resolve the MBB references.
628 StringRef InsnStr = YamlMF.Body.Value.Value;
629 SourceMgr InsnSM;
630 InsnSM.AddNewSourceBuffer(
631 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
632 SMLoc());
633 PFS.SM = &InsnSM;
634 if (parseMachineInstructions(PFS, InsnStr, Error)) {
636 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
637 return true;
638 }
639 PFS.SM = &SM;
640
641 if (setupRegisterInfo(PFS, YamlMF))
642 return true;
643
644 if (YamlMF.MachineFuncInfo) {
645 const TargetMachine &TM = MF.getTarget();
646 // Note this is called after the initial constructor of the
647 // MachineFunctionInfo based on the MachineFunction, which may depend on the
648 // IR.
649
650 SMRange SrcRange;
651 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
652 SrcRange)) {
653 return error(Error, SrcRange);
654 }
655 }
656
657 // Set the reserved registers after parsing MachineFuncInfo. The target may
658 // have been recording information used to select the reserved registers
659 // there.
660 // FIXME: This is a temporary workaround until the reserved registers can be
661 // serialized.
663 MRI.freezeReservedRegs();
664
665 if (computeFunctionProperties(MF, YamlMF))
666 return true;
667
668 if (initializeCallSiteInfo(PFS, YamlMF))
669 return true;
670
671 if (parseCalledGlobals(PFS, MF, YamlMF))
672 return true;
673
674 setupDebugValueTracking(MF, PFS, YamlMF);
675
677
678 MF.verify(nullptr, nullptr, &errs());
679 return false;
680}
681
683 const yaml::MachineFunction &YamlMF) {
684 MachineFunction &MF = PFS.MF;
685 MachineRegisterInfo &RegInfo = MF.getRegInfo();
686 assert(RegInfo.tracksLiveness());
687 if (!YamlMF.TracksRegLiveness)
688 RegInfo.invalidateLiveness();
689
691 // Parse the virtual register information.
692 for (const auto &VReg : YamlMF.VirtualRegisters) {
693 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
694 if (Info.Explicit)
695 return error(VReg.ID.SourceRange.Start,
696 Twine("redefinition of virtual register '%") +
697 Twine(VReg.ID.Value) + "'");
698 Info.Explicit = true;
699
700 if (VReg.Class.Value == "_") {
701 Info.Kind = VRegInfo::GENERIC;
702 Info.D.RegBank = nullptr;
703 } else {
704 const auto *RC = Target->getRegClass(VReg.Class.Value);
705 if (RC) {
706 Info.Kind = VRegInfo::NORMAL;
707 Info.D.RC = RC;
708 } else {
709 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
710 if (!RegBank)
711 return error(
712 VReg.Class.SourceRange.Start,
713 Twine("use of undefined register class or register bank '") +
714 VReg.Class.Value + "'");
715 Info.Kind = VRegInfo::REGBANK;
716 Info.D.RegBank = RegBank;
717 }
718 }
719
720 if (!VReg.PreferredRegister.Value.empty()) {
721 if (Info.Kind != VRegInfo::NORMAL)
722 return error(VReg.Class.SourceRange.Start,
723 Twine("preferred register can only be set for normal vregs"));
724
725 if (parseRegisterReference(PFS, Info.PreferredReg,
726 VReg.PreferredRegister.Value, Error))
727 return error(Error, VReg.PreferredRegister.SourceRange);
728 }
729
730 for (const auto &FlagStringValue : VReg.RegisterFlags) {
731 uint8_t FlagValue;
732 if (Target->getVRegFlagValue(FlagStringValue.Value, FlagValue))
733 return error(FlagStringValue.SourceRange.Start,
734 Twine("use of undefined register flag '") +
735 FlagStringValue.Value + "'");
736 Info.Flags |= FlagValue;
737 }
738 RegInfo.noteNewVirtualRegister(Info.VReg);
739 }
740
741 // Parse the liveins.
742 for (const auto &LiveIn : YamlMF.LiveIns) {
743 Register Reg;
744 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
745 return error(Error, LiveIn.Register.SourceRange);
746 Register VReg;
747 if (!LiveIn.VirtualRegister.Value.empty()) {
748 VRegInfo *Info;
749 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
750 Error))
751 return error(Error, LiveIn.VirtualRegister.SourceRange);
752 VReg = Info->VReg;
753 }
754 RegInfo.addLiveIn(Reg, VReg);
755 }
756
757 // Parse the callee saved registers (Registers that will
758 // be saved for the caller).
759 if (YamlMF.CalleeSavedRegisters) {
760 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
761 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
762 Register Reg;
763 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
764 return error(Error, RegSource.SourceRange);
765 CalleeSavedRegisters.push_back(Reg.id());
766 }
767 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
768 }
769
770 return false;
771}
772
774 const yaml::MachineFunction &YamlMF) {
775 MachineFunction &MF = PFS.MF;
778
780
781 // Create VRegs
782 auto populateVRegInfo = [&](const VRegInfo &Info, const Twine &Name) {
783 Register Reg = Info.VReg;
784 switch (Info.Kind) {
786 Errors.push_back(
787 (Twine("Cannot determine class/bank of virtual register ") + Name +
788 " in function '" + MF.getName() + "'")
789 .str());
790 break;
791 case VRegInfo::NORMAL:
792 if (!Info.D.RC->isAllocatable()) {
793 Errors.push_back((Twine("Cannot use non-allocatable class '") +
794 TRI->getRegClassName(Info.D.RC) +
795 "' for virtual register " + Name + " in function '" +
796 MF.getName() + "'")
797 .str());
798 break;
799 }
800
801 MRI.setRegClass(Reg, Info.D.RC);
802 if (Info.PreferredReg != 0)
803 MRI.setSimpleHint(Reg, Info.PreferredReg);
804 break;
806 break;
808 MRI.setRegBank(Reg, *Info.D.RegBank);
809 break;
810 }
811 };
812
813 for (const auto &P : PFS.VRegInfosNamed) {
814 const VRegInfo &Info = *P.second;
815 populateVRegInfo(Info, Twine(P.first()));
816 }
817
818 for (auto P : PFS.VRegInfos) {
819 const VRegInfo &Info = *P.second;
820 populateVRegInfo(Info, Twine(P.first.id()));
821 }
822
823 // Compute MachineRegisterInfo::UsedPhysRegMask
824 for (const MachineBasicBlock &MBB : MF) {
825 // Make sure MRI knows about registers clobbered by unwinder.
826 if (MBB.isEHPad())
827 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
828 MRI.addPhysRegsUsedFromRegMask(RegMask);
829
830 for (const MachineInstr &MI : MBB) {
831 for (const MachineOperand &MO : MI.operands()) {
832 if (!MO.isRegMask())
833 continue;
834 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
835 }
836 }
837 }
838
839 if (Errors.empty())
840 return false;
841
842 // Report errors in a deterministic order.
843 sort(Errors);
844 for (auto &E : Errors)
845 error(E);
846 return true;
847}
848
850 const yaml::MachineFunction &YamlMF) {
851 MachineFunction &MF = PFS.MF;
852 MachineFrameInfo &MFI = MF.getFrameInfo();
854 const Function &F = MF.getFunction();
855 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
858 MFI.setHasStackMap(YamlMFI.HasStackMap);
859 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
860 MFI.setStackSize(YamlMFI.StackSize);
862 if (YamlMFI.MaxAlignment)
864 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
865 MFI.setHasCalls(YamlMFI.HasCalls);
866 if (YamlMFI.MaxCallFrameSize != ~0u)
870 MFI.setHasVAStart(YamlMFI.HasVAStart);
872 MFI.setHasTailCall(YamlMFI.HasTailCall);
876 if (initializeSaveRestorePoints(PFS, YamlMFI.SavePoints, SavePoints))
877 return true;
878 MFI.setSavePoints(SavePoints);
880 if (initializeSaveRestorePoints(PFS, YamlMFI.RestorePoints, RestorePoints))
881 return true;
882 MFI.setRestorePoints(RestorePoints);
883
884 std::vector<CalleeSavedInfo> CSIInfo;
885 // Initialize the fixed frame objects.
886 for (const auto &Object : YamlMF.FixedStackObjects) {
887 int ObjectIdx;
889 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
890 Object.IsImmutable, Object.IsAliased);
891 else
892 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
893
894 if (!TFI->isSupportedStackID(Object.StackID))
895 return error(Object.ID.SourceRange.Start,
896 Twine("StackID is not supported by target"));
897 MFI.setStackID(ObjectIdx, Object.StackID);
898 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
899 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
900 ObjectIdx))
901 .second)
902 return error(Object.ID.SourceRange.Start,
903 Twine("redefinition of fixed stack object '%fixed-stack.") +
904 Twine(Object.ID.Value) + "'");
905 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
906 Object.CalleeSavedRestored, ObjectIdx))
907 return true;
908 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
909 return true;
910 }
911
912 for (const auto &Object : YamlMF.EntryValueObjects) {
914 Register Reg;
915 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
916 Error))
917 return error(Error, Object.EntryValueRegister.SourceRange);
918 if (!Reg.isPhysical())
919 return error(Object.EntryValueRegister.SourceRange.Start,
920 "Expected physical register for entry value field");
921 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
922 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
923 if (!MaybeInfo)
924 return true;
925 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
926 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
927 Reg.asMCReg(), MaybeInfo->DILoc);
928 }
929
930 // Initialize the ordinary frame objects.
931 for (const auto &Object : YamlMF.StackObjects) {
932 int ObjectIdx;
933 const AllocaInst *Alloca = nullptr;
934 const yaml::StringValue &Name = Object.Name;
935 if (!Name.Value.empty()) {
936 Alloca = dyn_cast_or_null<AllocaInst>(
937 F.getValueSymbolTable()->lookup(Name.Value));
938 if (!Alloca)
939 return error(Name.SourceRange.Start,
940 "alloca instruction named '" + Name.Value +
941 "' isn't defined in the function '" + F.getName() +
942 "'");
943 }
944 if (!TFI->isSupportedStackID(Object.StackID))
945 return error(Object.ID.SourceRange.Start,
946 Twine("StackID is not supported by target"));
948 ObjectIdx =
949 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
950 else
951 ObjectIdx = MFI.CreateStackObject(
952 Object.Size, Object.Alignment.valueOrOne(),
953 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
954 Object.StackID);
955 MFI.setObjectOffset(ObjectIdx, Object.Offset);
956
957 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
958 .second)
959 return error(Object.ID.SourceRange.Start,
960 Twine("redefinition of stack object '%stack.") +
961 Twine(Object.ID.Value) + "'");
962 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
963 Object.CalleeSavedRestored, ObjectIdx))
964 return true;
965 if (Object.LocalOffset)
966 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
967 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
968 return true;
969 }
970 MFI.setCalleeSavedInfo(CSIInfo);
971 if (!CSIInfo.empty())
972 MFI.setCalleeSavedInfoValid(true);
973
974 // Initialize the various stack object references after initializing the
975 // stack objects.
976 if (!YamlMFI.StackProtector.Value.empty()) {
978 int FI;
980 return error(Error, YamlMFI.StackProtector.SourceRange);
982 }
983
984 if (!YamlMFI.FunctionContext.Value.empty()) {
986 int FI;
988 return error(Error, YamlMFI.FunctionContext.SourceRange);
990 }
991
992 return false;
993}
994
996 std::vector<CalleeSavedInfo> &CSIInfo,
997 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
998 if (RegisterSource.Value.empty())
999 return false;
1000 Register Reg;
1002 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
1003 return error(Error, RegisterSource.SourceRange);
1004 CalleeSavedInfo CSI(Reg, FrameIdx);
1005 CSI.setRestored(IsRestored);
1006 CSIInfo.push_back(CSI);
1007 return false;
1008}
1009
1010/// Verify that given node is of a certain type. Return true on error.
1011template <typename T>
1012static bool typecheckMDNode(T *&Result, MDNode *Node,
1013 const yaml::StringValue &Source,
1014 StringRef TypeString, MIRParserImpl &Parser) {
1015 if (!Node)
1016 return false;
1017 Result = dyn_cast<T>(Node);
1018 if (!Result)
1019 return Parser.error(Source.SourceRange.Start,
1020 "expected a reference to a '" + TypeString +
1021 "' metadata node");
1022 return false;
1023}
1024
1025std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
1026 PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr,
1027 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
1028 MDNode *Var = nullptr;
1029 MDNode *Expr = nullptr;
1030 MDNode *Loc = nullptr;
1031 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
1032 parseMDNode(PFS, Loc, LocStr))
1033 return std::nullopt;
1034 DILocalVariable *DIVar = nullptr;
1035 DIExpression *DIExpr = nullptr;
1036 DILocation *DILoc = nullptr;
1037 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
1038 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
1039 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
1040 return std::nullopt;
1041 return VarExprLoc{DIVar, DIExpr, DILoc};
1042}
1043
1044template <typename T>
1046 const T &Object, int FrameIdx) {
1047 std::optional<VarExprLoc> MaybeInfo =
1048 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
1049 if (!MaybeInfo)
1050 return true;
1051 // Debug information can only be attached to stack objects; Fixed stack
1052 // objects aren't supported.
1053 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1054 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
1055 MaybeInfo->DILoc);
1056 return false;
1057}
1058
1059bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
1060 MDNode *&Node, const yaml::StringValue &Source) {
1061 if (Source.Value.empty())
1062 return false;
1064 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
1065 return error(Error, Source.SourceRange);
1066 return false;
1067}
1068
1071 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
1072 const MachineFunction &MF = PFS.MF;
1073 const auto &M = *MF.getFunction().getParent();
1075 for (const auto &YamlConstant : YamlMF.Constants) {
1076 if (YamlConstant.IsTargetSpecific)
1077 // FIXME: Support target-specific constant pools
1078 return error(YamlConstant.Value.SourceRange.Start,
1079 "Can't parse target-specific constant pool entries yet");
1080 const Constant *Value = dyn_cast_or_null<Constant>(
1081 parseConstantValue(YamlConstant.Value.Value, Error, M));
1082 if (!Value)
1083 return error(Error, YamlConstant.Value.SourceRange);
1084 const Align PrefTypeAlign =
1085 M.getDataLayout().getPrefTypeAlign(Value->getType());
1086 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
1087 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
1088 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
1089 .second)
1090 return error(YamlConstant.ID.SourceRange.Start,
1091 Twine("redefinition of constant pool item '%const.") +
1092 Twine(YamlConstant.ID.Value) + "'");
1093 }
1094 return false;
1095}
1096
1097// Return true if basic block was incorrectly specified in MIR
1100 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
1101 SmallVectorImpl<MachineBasicBlock *> &SaveRestorePoints) {
1102 MachineBasicBlock *MBB = nullptr;
1103 for (const yaml::SaveRestorePointEntry &Entry : YamlSRPoints) {
1104 if (parseMBBReference(PFS, MBB, Entry.Point.Value))
1105 return true;
1106 SaveRestorePoints.push_back(MBB);
1107 }
1108
1109 return false;
1110}
1111
1113 const yaml::MachineJumpTable &YamlJTI) {
1115 for (const auto &Entry : YamlJTI.Entries) {
1116 std::vector<MachineBasicBlock *> Blocks;
1117 for (const auto &MBBSource : Entry.Blocks) {
1118 MachineBasicBlock *MBB = nullptr;
1119 if (parseMBBReference(PFS, MBB, MBBSource.Value))
1120 return true;
1121 Blocks.push_back(MBB);
1122 }
1123 unsigned Index = JTI->createJumpTableIndex(Blocks);
1124 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1125 .second)
1126 return error(Entry.ID.SourceRange.Start,
1127 Twine("redefinition of jump table entry '%jump-table.") +
1128 Twine(Entry.ID.Value) + "'");
1129 }
1130 return false;
1131}
1132
1133bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1135 const yaml::StringValue &Source) {
1137 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1138 return error(Error, Source.SourceRange);
1139 return false;
1140}
1141
1142bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1143 const yaml::StringValue &Source) {
1145 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1146 return error(Error, Source.SourceRange);
1147 return false;
1148}
1149
1152 const yaml::MachineFunction &YMF) {
1153 for (const auto &MDS : YMF.MachineMetadataNodes) {
1154 if (parseMachineMetadata(PFS, MDS))
1155 return true;
1156 }
1157 // Report missing definitions from forward referenced nodes.
1158 if (!PFS.MachineForwardRefMDNodes.empty())
1159 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1160 "use of undefined metadata '!" +
1161 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1162 return false;
1163}
1164
1166 MachineFunction &MF,
1167 const yaml::MachineFunction &YMF) {
1168 Function &F = MF.getFunction();
1169 for (const auto &YamlCG : YMF.CalledGlobals) {
1170 yaml::MachineInstrLoc MILoc = YamlCG.CallSite;
1171 const MachineInstr *CallI;
1172 if (parseMachineInst(MF, MILoc, CallI))
1173 return true;
1175 return error(Twine(MF.getName()) +
1176 Twine(" called global should reference call "
1177 "instruction. Instruction at bb:") +
1178 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
1179 " is not a call instruction");
1180
1181 auto Callee =
1182 F.getParent()->getValueSymbolTable().lookup(YamlCG.Callee.Value);
1183 if (!Callee)
1184 return error(YamlCG.Callee.SourceRange.Start,
1185 "use of undefined global '" + YamlCG.Callee.Value + "'");
1186 if (!isa<GlobalValue>(Callee))
1187 return error(YamlCG.Callee.SourceRange.Start,
1188 "use of non-global value '" + YamlCG.Callee.Value + "'");
1189
1190 MF.addCalledGlobal(CallI, {cast<GlobalValue>(Callee), YamlCG.Flags});
1191 }
1192
1193 return false;
1194}
1195
1196SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1197 SMRange SourceRange) {
1198 assert(SourceRange.isValid() && "Invalid source range");
1199 SMLoc Loc = SourceRange.Start;
1200 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1201 *Loc.getPointer() == '\'';
1202 // Translate the location of the error from the location in the MI string to
1203 // the corresponding location in the MIR file.
1204 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1205 (HasQuote ? 1 : 0));
1206
1207 // TODO: Translate any source ranges as well.
1208 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), {},
1209 Error.getFixIts());
1210}
1211
1212SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1213 SMRange SourceRange) {
1214 assert(SourceRange.isValid());
1215
1216 // Translate the location of the error from the location in the llvm IR string
1217 // to the corresponding location in the MIR file.
1218 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1219 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1220 unsigned Column = Error.getColumnNo();
1221 StringRef LineStr = Error.getLineContents();
1222 SMLoc Loc = Error.getLoc();
1223
1224 // Get the full line and adjust the column number by taking the indentation of
1225 // LLVM IR into account.
1226 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1227 L != E; ++L) {
1228 if (L.line_number() == Line) {
1229 LineStr = *L;
1230 Loc = SMLoc::getFromPointer(LineStr.data());
1231 auto Indent = LineStr.find(Error.getLineContents());
1232 if (Indent != StringRef::npos)
1233 Column += Indent;
1234 break;
1235 }
1236 }
1237
1238 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1239 Error.getMessage(), LineStr, Error.getRanges(),
1240 Error.getFixIts());
1241}
1242
1243MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1244 : Impl(std::move(Impl)) {}
1245
1246MIRParser::~MIRParser() = default;
1247
1248std::unique_ptr<Module>
1250 return Impl->parseIRModule(DataLayoutCallback);
1251}
1252
1254 return Impl->parseMachineFunctions(M, MMI);
1255}
1256
1258 auto &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
1259 return Impl->parseMachineFunctions(M, MMI, &MAM);
1260}
1261
1262std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1263 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1264 std::function<void(Function &)> ProcessIRFunction) {
1265 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1266 if (std::error_code EC = FileOrErr.getError()) {
1268 "Could not open input file: " + EC.message());
1269 return nullptr;
1270 }
1271 return createMIRParser(std::move(FileOrErr.get()), Context,
1272 ProcessIRFunction);
1273}
1274
1275std::unique_ptr<MIRParser>
1276llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1277 LLVMContext &Context,
1278 std::function<void(Function &)> ProcessIRFunction) {
1279 auto Filename = Contents->getBufferIdentifier();
1280 if (Context.shouldDiscardValueNames()) {
1282 DS_Error,
1284 Filename, SourceMgr::DK_Error,
1285 "Can't read MIR with a Context that discards named Values")));
1286 return nullptr;
1287 }
1288 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1289 std::move(Contents), Filename, Context, ProcessIRFunction));
1290}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
Module.h This file contains the declarations for the Module class.
#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:373
static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context)
Definition: MIRParser.cpp:201
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:1012
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register const TargetRegisterInfo * TRI
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
#define error(X)
an instruction to allocate memory on the stack
Definition: Instructions.h:64
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:431
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:206
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:43
DWARF expression.
Debug location.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
Diagnostic information for machine IR parser.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static LLVM_ABI 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:166
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:663
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:53
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:585
Class to represent integer types.
Definition: DerivedTypes.h:42
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Metadata node.
Definition: Metadata.h:1077
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:216
bool initializeSaveRestorePoints(PerFunctionMIParsingState &PFS, const std::vector< yaml::SaveRestorePointEntry > &YamlSRPoints, SmallVectorImpl< MachineBasicBlock * > &SaveRestorePoints)
Definition: MIRParser.cpp:1098
void reportDiagnostic(const SMDiagnostic &Diag)
Definition: MIRParser.cpp:234
bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:773
bool parseRegisterInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:682
bool initializeFrameInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:849
Function * createDummyFunction(StringRef Name, Module &M)
Create an empty function with the given name.
Definition: MIRParser.cpp:308
bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, const T &Object, int FrameIdx)
Definition: MIRParser.cpp:1045
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:551
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:254
bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, const yaml::MachineJumpTable &YamlJTI)
Definition: MIRParser.cpp:1112
bool initializeConstantPool(PerFunctionMIParsingState &PFS, MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:1069
MIRParserImpl(std::unique_ptr< MemoryBuffer > Contents, StringRef Filename, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction)
Definition: MIRParser.cpp:205
std::optional< VarExprLoc > parseVarExprLoc(PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr, const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr)
Definition: MIRParser.cpp:1025
bool parseCalledGlobals(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
Definition: MIRParser.cpp:1165
bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, std::vector< CalleeSavedInfo > &CSIInfo, const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx)
Definition: MIRParser.cpp:995
bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
Definition: MIRParser.cpp:1150
bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:489
bool parseMachineFunction(Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *FAM)
Parse the machine function in the current YAML document.
Definition: MIRParser.cpp:322
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *FAM=nullptr)
Definition: MIRParser.cpp:293
LLVM_ABI MIRParser(std::unique_ptr< MIRParserImpl > Impl)
Definition: MIRParser.cpp:1243
LLVM_ABI 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:1249
LLVM_ABI bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Parses MachineFunctions in the MIR file and add them to the given MachineModuleInfo MMI.
Definition: MIRParser.cpp:1253
LLVM_ABI ~MIRParser()
bool isEHPad() const
Returns true if the block is a landing pad.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI 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.
LLVM_ABI 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 setRestorePoints(ArrayRef< MachineBasicBlock * > NewRestorePoints)
void setStackID(int ObjectIdx, uint8_t ID)
void setHasTailCall(bool V=true)
void setStackProtectorIndex(int I)
void setCalleeSavedInfoValid(bool v)
void setReturnAddressIsTaken(bool s)
void mapLocalFrameObject(int ObjectIndex, int64_t Offset)
Map a frame index into the local object block.
void setHasOpaqueSPAdjustment(bool B)
void setCalleeSavedInfo(std::vector< CalleeSavedInfo > CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
LLVM_ABI int CreateVariableSizedObject(Align Alignment, const AllocaInst *Alloca)
Notify the MachineFrameInfo object that a variable sized object has been created.
void setSavePoints(ArrayRef< MachineBasicBlock * > NewSavePoints)
LLVM_ABI int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
void setStackSize(uint64_t Size)
Set the size of the stack.
void setHasMustTailInVarArgFunc(bool B)
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
void setFunctionContextIndex(int I)
This analysis create MachineFunction for given Function.
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
MachineFunctionProperties & reset(Property P)
void 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 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.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
void addCallSiteInfo(const MachineInstr *CallI, CallSiteInfo &&CallInfo)
Start tracking the arguments passed to the call CallI.
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable in a stack slot.
void setHasEHContTarget(bool V)
void addCalledGlobal(const MachineInstr *MI, CalledGlobalInfo Details)
Notes the global and target flags for a call site.
void assignBeginEndSections()
Assign IsBeginSection IsEndSection fields for basic blocks in this function.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
Definition: MachineInstr.h:72
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:948
LLVM_ABI unsigned createJumpTableIndex(const std::vector< MachineBasicBlock * > &DestBBs)
createJumpTableIndex - Create a new jump table.
An analysis that produces MachineModuleInfo for a module.
This class contains meta information specific to a module.
LLVM_ABI MachineFunction & getOrCreateMachineFunction(Function &F)
Returns the MachineFunction constructed for the IR function F.
const TargetMachine & getTarget() const
LLVM_ABI 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 noteNewVirtualRegister(Register Reg)
LLVM_ABI 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:67
This class implements the register bank concept.
Definition: RegisterBank.h:29
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:67
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:282
SourceMgr::DiagKind getKind() const
Definition: SourceMgr.h:312
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
bool empty() const
Definition: SmallVector.h:82
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:32
unsigned getMainFileID() const
Definition: SourceMgr.h:133
LLVM_ABI 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:126
LLVM_ABI 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:145
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:148
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:301
static constexpr size_t npos
Definition: StringRef.h:57
Information about stack frame layout on the target.
virtual bool isSupportedStackID(TargetStackID::Value ID) const
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:83
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual void mirFileLoaded(MachineFunction &MF) const
This is called after a .mir file was loaded.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
This function has undefined behavior.
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
An efficient, type-erasing, non-owning reference to a callable.
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:34
#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:3650
bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3656
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
Definition: MIParser.cpp:3615
bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3626
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
LLVM_ABI 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:1262
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI 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:1276
@ Sub
Subtraction of integers.
LLVM_ABI std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition: Parser.cpp:47
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
Definition: MIParser.cpp:3621
bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3632
LLVM_ABI Constant * parseConstantValue(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type and a constant value in the given string.
Definition: Parser.cpp:188
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
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:3661
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3644
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3638
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
SmallVector< ConstantInt *, 4 > CalleeTypeIds
Callee type ids.
SmallVector< ArgRegPair, 1 > ArgRegPairs
Vector of call argument and its forwarding register.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
DenseMap< unsigned, unsigned > JumpTableSlots
Definition: MIParser.h:181
VRegInfo & getVRegInfo(Register Num)
Definition: MIParser.cpp:328
DenseMap< unsigned, int > FixedStackObjectSlots
Definition: MIParser.h:178
DenseMap< unsigned, unsigned > ConstantPoolSlots
Definition: MIParser.h:180
StringMap< VRegInfo * > VRegInfosNamed
Definition: MIParser.h:177
DenseMap< unsigned, int > StackObjectSlots
Definition: MIParser.h:179
std::map< unsigned, std::pair< TempMDTuple, SMLoc > > MachineForwardRefMDNodes
Definition: MIParser.h:173
DenseMap< Register, VRegInfo * > VRegInfos
Definition: MIParser.h:176
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition: SlotMapping.h:33
Serializable representation of MachineFrameInfo.
std::vector< SaveRestorePointEntry > RestorePoints
unsigned MaxCallFrameSize
~0u means: not computed yet.
std::vector< SaveRestorePointEntry > SavePoints
std::vector< MachineStackObject > StackObjects
std::vector< StringValue > MachineMetadataNodes
std::optional< std::vector< FlowStringValue > > CalleeSavedRegisters
std::vector< CalledGlobal > CalledGlobals
std::optional< bool > HasFakeUses
std::vector< EntryValueObject > EntryValueObjects
std::optional< bool > NoPHIs
std::vector< MachineConstantPoolValue > Constants
std::optional< bool > NoVRegs
std::vector< CallSiteInfo > CallSitesInfo
std::vector< MachineFunctionLiveIn > LiveIns
std::vector< VirtualRegisterDefinition > VirtualRegisters
std::vector< FixedMachineStackObject > FixedStackObjects
std::optional< bool > IsSSA
std::vector< DebugValueSubstitution > DebugValueSubstitutions
std::unique_ptr< MachineFunctionInfo > MachineFuncInfo
Constant pool.
MachineJumpTable JumpTableInfo
Identifies call instruction location in machine function.
std::vector< Entry > Entries
MachineJumpTableInfo::JTEntryKind Kind
A wrapper around std::string which contains a source range that's being set during parsing.