LLVM 23.0.0git
MIRParser.cpp
Go to the documentation of this file.
1//===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the class that parses the optional LLVM IR and machine
10// functions that are stored in MIR files.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
37#include "llvm/Support/SMLoc.h"
41#include <memory>
42
43using namespace llvm;
44
45namespace llvm {
46class MDNode;
47class RegisterBank;
48
49/// This class implements the parsing of LLVM IR that's embedded inside a MIR
50/// file.
52 SourceMgr SM;
53 LLVMContext &Context;
54 yaml::Input In;
55 StringRef Filename;
56 SlotMapping IRSlots;
57 std::unique_ptr<PerTargetMIParsingState> Target;
58
59 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
60 /// created and inserted into the given module when this is true.
61 bool NoLLVMIR = false;
62 /// True when a well formed MIR file does not contain any MIR/machine function
63 /// parts.
64 bool NoMIRDocuments = false;
65
66 std::function<void(Function &)> ProcessIRFunction;
67
68public:
69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
70 LLVMContext &Context,
71 std::function<void(Function &)> ProcessIRFunction);
72
73 void reportDiagnostic(const SMDiagnostic &Diag);
74
75 /// Report an error with the given message at unknown location.
76 ///
77 /// Always returns true.
78 bool error(const Twine &Message);
79
80 /// Report an error with the given message at the given location.
81 ///
82 /// Always returns true.
83 bool error(SMLoc Loc, const Twine &Message);
84
85 /// Report a given error with the location translated from the location in an
86 /// embedded string literal to a location in the MIR file.
87 ///
88 /// Always returns true.
89 bool error(const SMDiagnostic &Error, SMRange SourceRange);
90
91 /// Try to parse the optional LLVM module and the machine functions in the MIR
92 /// file.
93 ///
94 /// Return null if an error occurred.
95 std::unique_ptr<Module>
96 parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
97
98 /// Create an empty function with the given name.
100
102 ModuleAnalysisManager *FAM = nullptr);
103
104 /// Parse the machine function in the current YAML document.
105 ///
106 ///
107 /// Return true if an error occurred.
110 Module::iterator &FirstUnvisitedFunction);
111
112 /// Initialize the machine function to the state that's described in the MIR
113 /// file.
114 ///
115 /// Return true if error occurred.
117 MachineFunction &MF);
118
120 const yaml::MachineFunction &YamlMF);
121
123 const yaml::MachineFunction &YamlMF);
124
126 const yaml::MachineFunction &YamlMF);
127
129 const yaml::MachineFunction &YamlMF);
130
132 const yaml::MachineFunction &YamlMF);
133
136 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
138
140 std::vector<CalleeSavedInfo> &CSIInfo,
141 const yaml::StringValue &RegisterSource,
142 bool IsRestored, int FrameIdx);
143
144 struct VarExprLoc {
147 DILocation *DILoc = nullptr;
148 };
149
150 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
151 const yaml::StringValue &VarStr,
152 const yaml::StringValue &ExprStr,
153 const yaml::StringValue &LocStr);
154 template <typename T>
156 const T &Object,
157 int FrameIdx);
158
161 const yaml::MachineFunction &YamlMF);
162
164 const yaml::MachineJumpTable &YamlJTI);
165
167 MachineFunction &MF,
168 const yaml::MachineFunction &YMF);
169
171 const yaml::MachineFunction &YMF);
172
173private:
174 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
175 const yaml::StringValue &Source);
176
177 bool parseMBBReference(PerFunctionMIParsingState &PFS,
179 const yaml::StringValue &Source);
180
181 bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
182 const yaml::StringValue &Source);
183
184 /// Return a MIR diagnostic converted from an MI string diagnostic.
185 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
186 SMRange SourceRange);
187
188 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
189 /// block scalar string.
190 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
191 SMRange SourceRange);
192
193 bool computeFunctionProperties(MachineFunction &MF,
194 const yaml::MachineFunction &YamlMF);
195
196 void setupDebugValueTracking(MachineFunction &MF,
198
199 bool parseMachineInst(MachineFunction &MF, yaml::MachineInstrLoc MILoc,
200 MachineInstr const *&MI);
201};
202
203} // end namespace llvm
204
205static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
206 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
207}
208
209MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
210 StringRef Filename, LLVMContext &Context,
211 std::function<void(Function &)> Callback)
212 : Context(Context),
213 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
214 ->getBuffer(),
215 nullptr, handleYAMLDiag, this),
216 Filename(Filename), ProcessIRFunction(Callback) {
217 In.setContext(&In);
218}
219
220bool MIRParserImpl::error(const Twine &Message) {
221 Context.diagnose(DiagnosticInfoMIRParser(
222 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
223 return true;
224}
225
226bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
227 Context.diagnose(DiagnosticInfoMIRParser(
228 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
229 return true;
230}
231
233 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
234 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
235 return true;
236}
237
240 switch (Diag.getKind()) {
242 Kind = DS_Error;
243 break;
245 Kind = DS_Warning;
246 break;
248 Kind = DS_Note;
249 break;
251 llvm_unreachable("remark unexpected");
252 break;
253 }
254 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
255}
256
257std::unique_ptr<Module>
259 if (!In.setCurrentDocument()) {
260 if (In.error())
261 return nullptr;
262 // Create an empty module when the MIR file is empty.
263 NoMIRDocuments = true;
264 auto M = std::make_unique<Module>(Filename, Context);
265 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
266 M->getDataLayoutStr()))
267 M->setDataLayout(*LayoutOverride);
268 return M;
269 }
270
271 std::unique_ptr<Module> M;
272 // Parse the block scalar manually so that we can return unique pointer
273 // without having to go trough YAML traits.
274 if (const auto *BSN =
275 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
277 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
278 Context, &IRSlots, DataLayoutCallback);
279 if (!M) {
280 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
281 return nullptr;
282 }
283 In.nextDocument();
284 if (!In.setCurrentDocument())
285 NoMIRDocuments = true;
286 } else {
287 // Create an new, empty module.
288 M = std::make_unique<Module>(Filename, Context);
289 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
290 M->getDataLayoutStr()))
291 M->setDataLayout(*LayoutOverride);
292 NoLLVMIR = true;
293 }
294 return M;
295}
296
299 if (NoMIRDocuments)
300 return false;
301
302 // Parse the machine functions.
303 auto FirstUnvisitedFunction = M.begin();
304 do {
305 if (parseMachineFunction(M, MMI, MAM, FirstUnvisitedFunction))
306 return true;
307 In.nextDocument();
308 } while (In.setCurrentDocument());
309
310 return false;
311}
312
314 auto &Context = M.getContext();
315 Function *F =
318 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
319 new UnreachableInst(Context, BB);
320
321 if (ProcessIRFunction)
322 ProcessIRFunction(*F);
323
324 return F;
325}
326
327static Function *
329 Module::iterator &FirstUnvisitedFunction) {
330 for (; FirstUnvisitedFunction != M.end(); ++FirstUnvisitedFunction)
331 if (!FirstUnvisitedFunction->hasName())
332 return &*FirstUnvisitedFunction++;
333
334 return nullptr;
335}
336
339 Module::iterator &FirstUnvisitedFunction) {
340 // Parse the yaml.
343
344 const TargetMachine &TM = MMI.getTarget();
345 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
347
348 yaml::yamlize(In, YamlMF, false, Ctx);
349 if (In.error())
350 return true;
351
352 // Search for the corresponding IR function.
353 StringRef FunctionName = YamlMF.Name;
354 Function *F = M.getFunction(FunctionName);
355 if (!F) {
356 if (NoLLVMIR) {
357 F = createDummyFunction(FunctionName, M);
358 } else if (!FunctionName.empty() ||
359 !(F = getNextUnusedUnnamedFunction(M, FirstUnvisitedFunction))) {
360 return error(Twine("function '") + FunctionName +
361 "' isn't defined in the provided LLVM IR");
362 }
363 }
364
365 if (!MAM) {
366 if (MMI.getMachineFunction(*F) != nullptr)
367 return error(Twine("redefinition of machine function '") + FunctionName +
368 "'");
369
370 // Create the MachineFunction.
372 if (initializeMachineFunction(YamlMF, MF))
373 return true;
374 } else {
375 auto &FAM =
376 MAM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
377 if (FAM.getCachedResult<MachineFunctionAnalysis>(*F))
378 return error(Twine("redefinition of machine function '") + FunctionName +
379 "'");
380
381 // Create the MachineFunction.
382 MachineFunction &MF = FAM.getResult<MachineFunctionAnalysis>(*F).getMF();
383 if (initializeMachineFunction(YamlMF, MF))
384 return true;
385 }
386
387 return false;
388}
389
390static bool isSSA(const MachineFunction &MF) {
391 const MachineRegisterInfo &MRI = MF.getRegInfo();
392 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
394 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
395 return false;
396
397 // Subregister defs are invalid in SSA.
398 const MachineOperand *RegDef = MRI.getOneDef(Reg);
399 if (RegDef && RegDef->getSubReg() != 0)
400 return false;
401 }
402 return true;
403}
404
405bool MIRParserImpl::computeFunctionProperties(
406 MachineFunction &MF, const yaml::MachineFunction &YamlMF) {
407 MachineFunctionProperties &Properties = MF.getProperties();
408
409 bool HasPHI = false;
410 bool HasInlineAsm = false;
411 bool HasFakeUses = false;
412 bool AllTiedOpsRewritten = true, HasTiedOps = false;
413 for (const MachineBasicBlock &MBB : MF) {
414 for (const MachineInstr &MI : MBB) {
415 if (MI.isPHI())
416 HasPHI = true;
417 if (MI.isInlineAsm())
418 HasInlineAsm = true;
419 if (MI.isFakeUse())
420 HasFakeUses = true;
421 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
422 const MachineOperand &MO = MI.getOperand(I);
423 if (!MO.isReg() || !MO.getReg())
424 continue;
425 unsigned DefIdx;
426 if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
427 HasTiedOps = true;
428 if (MO.getReg() != MI.getOperand(DefIdx).getReg())
429 AllTiedOpsRewritten = false;
430 }
431 }
432 }
433 }
434
435 // Helper function to sanity-check and set properties that are computed, but
436 // may be explicitly set from the input MIR
437 auto ComputedPropertyHelper =
438 [&Properties](std::optional<bool> ExplicitProp, bool ComputedProp,
440 // Prefer explicitly given values over the computed properties
441 if (ExplicitProp.value_or(ComputedProp))
442 Properties.set(P);
443 else
444 Properties.reset(P);
445
446 // Check for conflict between the explicit values and the computed ones
447 return ExplicitProp && *ExplicitProp && !ComputedProp;
448 };
449
450 if (ComputedPropertyHelper(YamlMF.NoPHIs, !HasPHI,
452 return error(MF.getName() +
453 " has explicit property NoPhi, but contains at least one PHI");
454 }
455
456 MF.setHasInlineAsm(HasInlineAsm);
457
458 if (HasTiedOps && AllTiedOpsRewritten)
459 Properties.setTiedOpsRewritten();
460
461 if (ComputedPropertyHelper(YamlMF.IsSSA, isSSA(MF),
463 return error(MF.getName() +
464 " has explicit property IsSSA, but is not valid SSA");
465 }
466
467 const MachineRegisterInfo &MRI = MF.getRegInfo();
468 if (ComputedPropertyHelper(YamlMF.NoVRegs, MRI.getNumVirtRegs() == 0,
470 return error(
471 MF.getName() +
472 " has explicit property NoVRegs, but contains virtual registers");
473 }
474
475 // For hasFakeUses we follow similar logic to the ComputedPropertyHelper,
476 // except for caring about the inverse case only, i.e. when the property is
477 // explicitly set to false and Fake Uses are present; having HasFakeUses=true
478 // on a function without fake uses is harmless.
479 if (YamlMF.HasFakeUses && !*YamlMF.HasFakeUses && HasFakeUses)
480 return error(
481 MF.getName() +
482 " has explicit property hasFakeUses=false, but contains fake uses");
483 MF.setHasFakeUses(YamlMF.HasFakeUses.value_or(HasFakeUses));
484
485 return false;
486}
487
488bool MIRParserImpl::parseMachineInst(MachineFunction &MF,
490 MachineInstr const *&MI) {
491 if (MILoc.BlockNum >= MF.size()) {
492 return error(Twine(MF.getName()) +
493 Twine(" instruction block out of range.") +
494 " Unable to reference bb:" + Twine(MILoc.BlockNum));
495 }
496 auto BB = std::next(MF.begin(), MILoc.BlockNum);
497 if (MILoc.Offset >= BB->size())
498 return error(
499 Twine(MF.getName()) + Twine(" instruction offset out of range.") +
500 " Unable to reference instruction at bb: " + Twine(MILoc.BlockNum) +
501 " at offset:" + Twine(MILoc.Offset));
502 MI = &*std::next(BB->instr_begin(), MILoc.Offset);
503 return false;
504}
505
508 MachineFunction &MF = PFS.MF;
510 const TargetMachine &TM = MF.getTarget();
511 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
512 yaml::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
513 const MachineInstr *CallI;
514 if (parseMachineInst(MF, MILoc, CallI))
515 return true;
517 return error(Twine(MF.getName()) +
518 Twine(" call site info should reference call "
519 "instruction. Instruction at bb:") +
520 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
521 " is not a call instruction");
523 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
524 Register Reg;
525 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
526 return error(Error, ArgRegPair.Reg.SourceRange);
527 CSInfo.ArgRegPairs.emplace_back(Reg, ArgRegPair.ArgNo);
528 }
529 if (!YamlCSInfo.CalleeTypeIds.empty()) {
530 for (auto CalleeTypeId : YamlCSInfo.CalleeTypeIds) {
531 IntegerType *Int64Ty = Type::getInt64Ty(Context);
532 CSInfo.CalleeTypeIds.push_back(ConstantInt::get(Int64Ty, CalleeTypeId,
533 /*isSigned=*/false));
534 }
535 }
536
538 MF.addCallSiteInfo(&*CallI, std::move(CSInfo));
539 }
540
541 if (!YamlMF.CallSitesInfo.empty() &&
543 return error("call site info provided but not used");
544 return false;
545}
546
547void MIRParserImpl::setupDebugValueTracking(
549 const yaml::MachineFunction &YamlMF) {
550 // Compute the value of the "next instruction number" field.
551 unsigned MaxInstrNum = 0;
552 for (auto &MBB : MF)
553 for (auto &MI : MBB)
554 MaxInstrNum = std::max(MI.peekDebugInstrNum(), MaxInstrNum);
555 MF.setDebugInstrNumberingCount(MaxInstrNum);
556
557 // Load any substitutions.
558 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
559 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
560 {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
561 }
562
563 // Flag for whether we're supposed to be using DBG_INSTR_REF.
564 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
565}
566
567bool
569 MachineFunction &MF) {
570 // TODO: Recreate the machine function.
571 if (Target) {
572 // Avoid clearing state if we're using the same subtarget again.
573 Target->setTarget(MF.getSubtarget());
574 } else {
575 Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
576 }
577
578 MF.setAlignment(YamlMF.Alignment.valueOrOne());
580 MF.setHasWinCFI(YamlMF.HasWinCFI);
581
585 MF.setHasEHScopes(YamlMF.HasEHScopes);
587 MF.setIsOutlined(YamlMF.IsOutlined);
588
590 if (YamlMF.Legalized)
591 Props.setLegalized();
592 if (YamlMF.RegBankSelected)
593 Props.setRegBankSelected();
594 if (YamlMF.Selected)
595 Props.setSelected();
596 if (YamlMF.FailedISel)
597 Props.setFailedISel();
598 if (YamlMF.FailsVerification)
599 Props.setFailsVerification();
600 if (YamlMF.TracksDebugUserValues)
601 Props.setTracksDebugUserValues();
602
603 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
604 if (parseRegisterInfo(PFS, YamlMF))
605 return true;
606 if (initializePrefetchTargets(PFS, YamlMF))
607 return true;
608 if (!YamlMF.Constants.empty()) {
609 auto *ConstantPool = MF.getConstantPool();
610 assert(ConstantPool && "Constant pool must be created");
611 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
612 return true;
613 }
614 if (!YamlMF.MachineMetadataNodes.empty() &&
615 parseMachineMetadataNodes(PFS, MF, YamlMF))
616 return true;
617
618 StringRef BlockStr = YamlMF.Body.Value.Value;
620 SourceMgr BlockSM;
621 BlockSM.AddNewSourceBuffer(
622 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
623 SMLoc());
624 PFS.SM = &BlockSM;
625 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
627 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
628 return true;
629 }
630 // Check Basic Block Section Flags.
631 if (MF.hasBBSections()) {
633 }
634 PFS.SM = &SM;
635
636 // Initialize the frame information after creating all the MBBs so that the
637 // MBB references in the frame information can be resolved.
638 if (initializeFrameInfo(PFS, YamlMF))
639 return true;
640 // Initialize the jump table after creating all the MBBs so that the MBB
641 // references can be resolved.
642 if (!YamlMF.JumpTableInfo.Entries.empty() &&
644 return true;
645 // Parse the machine instructions after creating all of the MBBs so that the
646 // parser can resolve the MBB references.
647 StringRef InsnStr = YamlMF.Body.Value.Value;
648 SourceMgr InsnSM;
649 InsnSM.AddNewSourceBuffer(
650 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
651 SMLoc());
652 PFS.SM = &InsnSM;
653 if (parseMachineInstructions(PFS, InsnStr, Error)) {
655 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
656 return true;
657 }
658 PFS.SM = &SM;
659
660 if (setupRegisterInfo(PFS, YamlMF))
661 return true;
662
663 if (YamlMF.MachineFuncInfo) {
664 const TargetMachine &TM = MF.getTarget();
665 // Note this is called after the initial constructor of the
666 // MachineFunctionInfo based on the MachineFunction, which may depend on the
667 // IR.
668
669 SMRange SrcRange;
671 SrcRange)) {
672 return error(Error, SrcRange);
673 }
674 }
675
676 // Set the reserved registers after parsing MachineFuncInfo. The target may
677 // have been recording information used to select the reserved registers
678 // there.
679 // FIXME: This is a temporary workaround until the reserved registers can be
680 // serialized.
682 MRI.freezeReservedRegs();
683
684 if (computeFunctionProperties(MF, YamlMF))
685 return true;
686
687 if (initializeCallSiteInfo(PFS, YamlMF))
688 return true;
689
690 if (parseCalledGlobals(PFS, MF, YamlMF))
691 return true;
692
693 if (initializePrefetchTargets(PFS, YamlMF))
694 return true;
695
696 setupDebugValueTracking(MF, PFS, YamlMF);
697
699
700 MF.verify(nullptr, nullptr, &errs());
701 return false;
702}
703
706 MachineFunction &MF = PFS.MF;
709 for (const auto &YamlTarget : YamlMF.PrefetchTargets) {
710 CallsiteID Target;
711 if (llvm::parsePrefetchTarget(PFS, Target, YamlTarget.Value, Error))
712 return error(Error, YamlTarget.SourceRange);
713 Targets[Target.BBID].push_back(Target.CallsiteIndex);
714 }
715 MF.setPrefetchTargets(Targets);
716 return false;
717}
718
720 const yaml::MachineFunction &YamlMF) {
721 MachineFunction &MF = PFS.MF;
722 MachineRegisterInfo &RegInfo = MF.getRegInfo();
723 assert(RegInfo.tracksLiveness());
724 if (!YamlMF.TracksRegLiveness)
725 RegInfo.invalidateLiveness();
726
728 // Parse the virtual register information.
729 for (const auto &VReg : YamlMF.VirtualRegisters) {
730 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
731 if (Info.Explicit)
732 return error(VReg.ID.SourceRange.Start,
733 Twine("redefinition of virtual register '%") +
734 Twine(VReg.ID.Value) + "'");
735 Info.Explicit = true;
736
737 if (VReg.Class.Value == "_") {
738 Info.Kind = VRegInfo::GENERIC;
739 Info.D.RegBank = nullptr;
740 } else {
741 const auto *RC = Target->getRegClass(VReg.Class.Value);
742 if (RC) {
743 Info.Kind = VRegInfo::NORMAL;
744 Info.D.RC = RC;
745 } else {
746 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
747 if (!RegBank)
748 return error(
749 VReg.Class.SourceRange.Start,
750 Twine("use of undefined register class or register bank '") +
751 VReg.Class.Value + "'");
752 Info.Kind = VRegInfo::REGBANK;
753 Info.D.RegBank = RegBank;
754 }
755 }
756
757 if (!VReg.PreferredRegister.Value.empty()) {
758 if (Info.Kind != VRegInfo::NORMAL)
759 return error(VReg.Class.SourceRange.Start,
760 Twine("preferred register can only be set for normal vregs"));
761
762 if (parseRegisterReference(PFS, Info.PreferredReg,
763 VReg.PreferredRegister.Value, Error))
764 return error(Error, VReg.PreferredRegister.SourceRange);
765 }
766
767 for (const auto &FlagStringValue : VReg.RegisterFlags) {
768 uint8_t FlagValue;
769 if (Target->getVRegFlagValue(FlagStringValue.Value, FlagValue))
770 return error(FlagStringValue.SourceRange.Start,
771 Twine("use of undefined register flag '") +
772 FlagStringValue.Value + "'");
773 Info.Flags |= FlagValue;
774 }
775 RegInfo.noteNewVirtualRegister(Info.VReg);
776 }
777
778 // Parse the liveins.
779 for (const auto &LiveIn : YamlMF.LiveIns) {
780 Register Reg;
781 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
782 return error(Error, LiveIn.Register.SourceRange);
783 Register VReg;
784 if (!LiveIn.VirtualRegister.Value.empty()) {
785 VRegInfo *Info;
786 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
787 Error))
788 return error(Error, LiveIn.VirtualRegister.SourceRange);
789 VReg = Info->VReg;
790 }
791 RegInfo.addLiveIn(Reg, VReg);
792 }
793
794 // Parse the callee saved registers (Registers that will
795 // be saved for the caller).
796 if (YamlMF.CalleeSavedRegisters) {
797 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
798 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
799 Register Reg;
800 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
801 return error(Error, RegSource.SourceRange);
802 CalleeSavedRegisters.push_back(Reg.id());
803 }
804 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
805 }
806
807 return false;
808}
809
811 const yaml::MachineFunction &YamlMF) {
812 MachineFunction &MF = PFS.MF;
815
817
818 // Create VRegs
819 auto populateVRegInfo = [&](const VRegInfo &Info, const Twine &Name) {
820 Register Reg = Info.VReg;
821 switch (Info.Kind) {
823 Errors.push_back(
824 (Twine("Cannot determine class/bank of virtual register ") + Name +
825 " in function '" + MF.getName() + "'")
826 .str());
827 break;
828 case VRegInfo::NORMAL:
829 if (!Info.D.RC->isAllocatable()) {
830 Errors.push_back((Twine("Cannot use non-allocatable class '") +
831 TRI->getRegClassName(Info.D.RC) +
832 "' for virtual register " + Name + " in function '" +
833 MF.getName() + "'")
834 .str());
835 break;
836 }
837
838 MRI.setRegClass(Reg, Info.D.RC);
839 if (Info.PreferredReg != 0)
840 MRI.setSimpleHint(Reg, Info.PreferredReg);
841 break;
843 break;
845 MRI.setRegBank(Reg, *Info.D.RegBank);
846 break;
847 }
848 };
849
850 for (const auto &P : PFS.VRegInfosNamed) {
851 const VRegInfo &Info = *P.second;
852 populateVRegInfo(Info, Twine(P.first()));
853 }
854
855 for (auto P : PFS.VRegInfos) {
856 const VRegInfo &Info = *P.second;
857 populateVRegInfo(Info, Twine(P.first.id()));
858 }
859
860 // Compute MachineRegisterInfo::UsedPhysRegMask
861 for (const MachineBasicBlock &MBB : MF) {
862 // Make sure MRI knows about registers clobbered by unwinder.
863 if (MBB.isEHPad())
864 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
865 MRI.addPhysRegsUsedFromRegMask(RegMask);
866
867 for (const MachineInstr &MI : MBB) {
868 for (const MachineOperand &MO : MI.operands()) {
869 if (!MO.isRegMask())
870 continue;
872 }
873 }
874 }
875
876 if (Errors.empty())
877 return false;
878
879 // Report errors in a deterministic order.
880 sort(Errors);
881 for (auto &E : Errors)
882 error(E);
883 return true;
884}
885
887 const yaml::MachineFunction &YamlMF) {
888 MachineFunction &MF = PFS.MF;
889 MachineFrameInfo &MFI = MF.getFrameInfo();
891 const Function &F = MF.getFunction();
892 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
895 MFI.setHasStackMap(YamlMFI.HasStackMap);
896 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
897 MFI.setStackSize(YamlMFI.StackSize);
899 if (YamlMFI.MaxAlignment)
901 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
902 MFI.setHasCalls(YamlMFI.HasCalls);
903 if (YamlMFI.MaxCallFrameSize != ~0u)
907 MFI.setHasVAStart(YamlMFI.HasVAStart);
909 MFI.setHasTailCall(YamlMFI.HasTailCall);
912 llvm::SaveRestorePoints SavePoints;
913 if (initializeSaveRestorePoints(PFS, YamlMFI.SavePoints, SavePoints))
914 return true;
915 MFI.setSavePoints(SavePoints);
916 llvm::SaveRestorePoints RestorePoints;
917 if (initializeSaveRestorePoints(PFS, YamlMFI.RestorePoints, RestorePoints))
918 return true;
919 MFI.setRestorePoints(RestorePoints);
920
921 std::vector<CalleeSavedInfo> CSIInfo;
922 // Initialize the fixed frame objects.
923 for (const auto &Object : YamlMF.FixedStackObjects) {
924 int ObjectIdx;
926 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
927 Object.IsImmutable, Object.IsAliased);
928 else
929 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
930
931 if (!TFI->isSupportedStackID(Object.StackID))
932 return error(Object.ID.SourceRange.Start,
933 Twine("StackID is not supported by target"));
934 MFI.setStackID(ObjectIdx, Object.StackID);
935 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
936 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
937 ObjectIdx))
938 .second)
939 return error(Object.ID.SourceRange.Start,
940 Twine("redefinition of fixed stack object '%fixed-stack.") +
941 Twine(Object.ID.Value) + "'");
942 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
943 Object.CalleeSavedRestored, ObjectIdx))
944 return true;
945 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
946 return true;
947 }
948
949 for (const auto &Object : YamlMF.EntryValueObjects) {
951 Register Reg;
952 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
953 Error))
954 return error(Error, Object.EntryValueRegister.SourceRange);
955 if (!Reg.isPhysical())
956 return error(Object.EntryValueRegister.SourceRange.Start,
957 "Expected physical register for entry value field");
958 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
959 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
960 if (!MaybeInfo)
961 return true;
962 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
963 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
964 Reg.asMCReg(), MaybeInfo->DILoc);
965 }
966
967 // Initialize the ordinary frame objects.
968 for (const auto &Object : YamlMF.StackObjects) {
969 int ObjectIdx;
970 const AllocaInst *Alloca = nullptr;
971 const yaml::StringValue &Name = Object.Name;
972 if (!Name.Value.empty()) {
974 F.getValueSymbolTable()->lookup(Name.Value));
975 if (!Alloca)
976 return error(Name.SourceRange.Start,
977 "alloca instruction named '" + Name.Value +
978 "' isn't defined in the function '" + F.getName() +
979 "'");
980 }
981 if (!TFI->isSupportedStackID(Object.StackID))
982 return error(Object.ID.SourceRange.Start,
983 Twine("StackID is not supported by target"));
985 ObjectIdx =
986 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
987 else
988 ObjectIdx = MFI.CreateStackObject(
989 Object.Size, Object.Alignment.valueOrOne(),
990 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
991 Object.StackID);
992 MFI.setObjectOffset(ObjectIdx, Object.Offset);
993
994 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
995 .second)
996 return error(Object.ID.SourceRange.Start,
997 Twine("redefinition of stack object '%stack.") +
998 Twine(Object.ID.Value) + "'");
999 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
1000 Object.CalleeSavedRestored, ObjectIdx))
1001 return true;
1002 if (Object.LocalOffset)
1003 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
1004 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
1005 return true;
1006 }
1007 MFI.setCalleeSavedInfo(CSIInfo);
1008 if (!CSIInfo.empty())
1009 MFI.setCalleeSavedInfoValid(true);
1010
1011 // Initialize the various stack object references after initializing the
1012 // stack objects.
1013 if (!YamlMFI.StackProtector.Value.empty()) {
1015 int FI;
1016 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
1017 return error(Error, YamlMFI.StackProtector.SourceRange);
1018 MFI.setStackProtectorIndex(FI);
1019 }
1020
1021 if (!YamlMFI.FunctionContext.Value.empty()) {
1023 int FI;
1025 return error(Error, YamlMFI.FunctionContext.SourceRange);
1027 }
1028
1029 return false;
1030}
1031
1033 std::vector<CalleeSavedInfo> &CSIInfo,
1034 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
1035 if (RegisterSource.Value.empty())
1036 return false;
1037 Register Reg;
1039 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
1040 return error(Error, RegisterSource.SourceRange);
1041 CalleeSavedInfo CSI(Reg, FrameIdx);
1042 CSI.setRestored(IsRestored);
1043 CSIInfo.push_back(CSI);
1044 return false;
1045}
1046
1047/// Verify that given node is of a certain type. Return true on error.
1048template <typename T>
1049static bool typecheckMDNode(T *&Result, MDNode *Node,
1050 const yaml::StringValue &Source,
1051 StringRef TypeString, MIRParserImpl &Parser) {
1052 if (!Node)
1053 return false;
1054 Result = dyn_cast<T>(Node);
1055 if (!Result)
1056 return Parser.error(Source.SourceRange.Start,
1057 "expected a reference to a '" + TypeString +
1058 "' metadata node");
1059 return false;
1060}
1061
1062std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
1063 PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr,
1064 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
1065 MDNode *Var = nullptr;
1066 MDNode *Expr = nullptr;
1067 MDNode *Loc = nullptr;
1068 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
1069 parseMDNode(PFS, Loc, LocStr))
1070 return std::nullopt;
1071 DILocalVariable *DIVar = nullptr;
1072 DIExpression *DIExpr = nullptr;
1073 DILocation *DILoc = nullptr;
1074 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
1075 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
1076 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
1077 return std::nullopt;
1078 return VarExprLoc{DIVar, DIExpr, DILoc};
1079}
1080
1081template <typename T>
1083 const T &Object, int FrameIdx) {
1084 std::optional<VarExprLoc> MaybeInfo =
1085 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
1086 if (!MaybeInfo)
1087 return true;
1088 // Debug information can only be attached to stack objects; Fixed stack
1089 // objects aren't supported.
1090 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1091 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
1092 MaybeInfo->DILoc);
1093 return false;
1094}
1095
1096bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
1097 MDNode *&Node, const yaml::StringValue &Source) {
1098 if (Source.Value.empty())
1099 return false;
1101 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
1102 return error(Error, Source.SourceRange);
1103 return false;
1104}
1105
1108 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
1109 const MachineFunction &MF = PFS.MF;
1110 const auto &M = *MF.getFunction().getParent();
1112 for (const auto &YamlConstant : YamlMF.Constants) {
1113 if (YamlConstant.IsTargetSpecific)
1114 // FIXME: Support target-specific constant pools
1115 return error(YamlConstant.Value.SourceRange.Start,
1116 "Can't parse target-specific constant pool entries yet");
1118 parseConstantValue(YamlConstant.Value.Value, Error, M));
1119 if (!Value)
1120 return error(Error, YamlConstant.Value.SourceRange);
1121 const Align PrefTypeAlign =
1122 M.getDataLayout().getPrefTypeAlign(Value->getType());
1123 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
1124 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
1125 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
1126 .second)
1127 return error(YamlConstant.ID.SourceRange.Start,
1128 Twine("redefinition of constant pool item '%const.") +
1129 Twine(YamlConstant.ID.Value) + "'");
1130 }
1131 return false;
1132}
1133
1134// Return true if basic block was incorrectly specified in MIR
1137 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
1140 MachineBasicBlock *MBB = nullptr;
1141 for (const yaml::SaveRestorePointEntry &Entry : YamlSRPoints) {
1142 if (parseMBBReference(PFS, MBB, Entry.Point.Value))
1143 return true;
1144
1145 std::vector<CalleeSavedInfo> Registers;
1146 for (auto &RegStr : Entry.Registers) {
1147 Register Reg;
1148 if (parseNamedRegisterReference(PFS, Reg, RegStr.Value, Error))
1149 return error(Error, RegStr.SourceRange);
1150 Registers.push_back(CalleeSavedInfo(Reg));
1151 }
1152 SaveRestorePoints.try_emplace(MBB, std::move(Registers));
1153 }
1154 return false;
1155}
1156
1158 const yaml::MachineJumpTable &YamlJTI) {
1160 for (const auto &Entry : YamlJTI.Entries) {
1161 std::vector<MachineBasicBlock *> Blocks;
1162 for (const auto &MBBSource : Entry.Blocks) {
1163 MachineBasicBlock *MBB = nullptr;
1164 if (parseMBBReference(PFS, MBB, MBBSource.Value))
1165 return true;
1166 Blocks.push_back(MBB);
1167 }
1168 unsigned Index = JTI->createJumpTableIndex(Blocks);
1169 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1170 .second)
1171 return error(Entry.ID.SourceRange.Start,
1172 Twine("redefinition of jump table entry '%jump-table.") +
1173 Twine(Entry.ID.Value) + "'");
1174 }
1175 return false;
1176}
1177
1178bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1180 const yaml::StringValue &Source) {
1182 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1183 return error(Error, Source.SourceRange);
1184 return false;
1185}
1186
1187bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1188 const yaml::StringValue &Source) {
1190 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1191 return error(Error, Source.SourceRange);
1192 return false;
1193}
1194
1197 const yaml::MachineFunction &YMF) {
1198 for (const auto &MDS : YMF.MachineMetadataNodes) {
1199 if (parseMachineMetadata(PFS, MDS))
1200 return true;
1201 }
1202 // Report missing definitions from forward referenced nodes.
1203 if (!PFS.MachineForwardRefMDNodes.empty())
1204 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1205 "use of undefined metadata '!" +
1206 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1207 return false;
1208}
1209
1211 MachineFunction &MF,
1212 const yaml::MachineFunction &YMF) {
1213 Function &F = MF.getFunction();
1214 for (const auto &YamlCG : YMF.CalledGlobals) {
1215 yaml::MachineInstrLoc MILoc = YamlCG.CallSite;
1216 const MachineInstr *CallI;
1217 if (parseMachineInst(MF, MILoc, CallI))
1218 return true;
1220 return error(Twine(MF.getName()) +
1221 Twine(" called global should reference call "
1222 "instruction. Instruction at bb:") +
1223 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
1224 " is not a call instruction");
1225
1226 auto Callee =
1227 F.getParent()->getValueSymbolTable().lookup(YamlCG.Callee.Value);
1228 if (!Callee)
1229 return error(YamlCG.Callee.SourceRange.Start,
1230 "use of undefined global '" + YamlCG.Callee.Value + "'");
1231 if (!isa<GlobalValue>(Callee))
1232 return error(YamlCG.Callee.SourceRange.Start,
1233 "use of non-global value '" + YamlCG.Callee.Value + "'");
1234
1235 MF.addCalledGlobal(CallI, {cast<GlobalValue>(Callee), YamlCG.Flags});
1236 }
1237
1238 return false;
1239}
1240
1241SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1242 SMRange SourceRange) {
1243 assert(SourceRange.isValid() && "Invalid source range");
1244 SMLoc Loc = SourceRange.Start;
1245 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1246 *Loc.getPointer() == '\'';
1247 // Translate the location of the error from the location in the MI string to
1248 // the corresponding location in the MIR file.
1249 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1250 (HasQuote ? 1 : 0));
1251
1252 // TODO: Translate any source ranges as well.
1253 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), {},
1254 Error.getFixIts());
1255}
1256
1257SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1258 SMRange SourceRange) {
1259 assert(SourceRange.isValid());
1260
1261 // Translate the location of the error from the location in the llvm IR string
1262 // to the corresponding location in the MIR file.
1263 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1264 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1265 unsigned Column = Error.getColumnNo();
1266 StringRef LineStr = Error.getLineContents();
1267 SMLoc Loc = Error.getLoc();
1268
1269 // Get the full line and adjust the column number by taking the indentation of
1270 // LLVM IR into account.
1271 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1272 L != E; ++L) {
1273 if (L.line_number() == Line) {
1274 LineStr = *L;
1275 Loc = SMLoc::getFromPointer(LineStr.data());
1276 auto Indent = LineStr.find(Error.getLineContents());
1277 if (Indent != StringRef::npos)
1278 Column += Indent;
1279 break;
1280 }
1281 }
1282
1283 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1284 Error.getMessage(), LineStr, Error.getRanges(),
1285 Error.getFixIts());
1286}
1287
1288MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1289 : Impl(std::move(Impl)) {}
1290
1291MIRParser::~MIRParser() = default;
1292
1293std::unique_ptr<Module>
1295 return Impl->parseIRModule(DataLayoutCallback);
1296}
1297
1299 return Impl->parseMachineFunctions(M, MMI);
1300}
1301
1303 auto &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
1304 return Impl->parseMachineFunctions(M, MMI, &MAM);
1305}
1306
1307std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1309 std::function<void(Function &)> ProcessIRFunction) {
1310 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1311 if (std::error_code EC = FileOrErr.getError()) {
1313 "could not open input file: " + EC.message());
1314 return nullptr;
1315 }
1316 return createMIRParser(std::move(FileOrErr.get()), Context,
1317 ProcessIRFunction);
1318}
1319
1320std::unique_ptr<MIRParser>
1321llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1322 LLVMContext &Context,
1323 std::function<void(Function &)> ProcessIRFunction) {
1324 auto Filename = Contents->getBufferIdentifier();
1325 if (Context.shouldDiscardValueNames()) {
1326 Context.diagnose(DiagnosticInfoMIRParser(
1327 DS_Error,
1330 "cannot read MIR with a Context that discards named Values")));
1331 return nullptr;
1332 }
1333 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1334 std::move(Contents), Filename, Context, ProcessIRFunction));
1335}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isSSA(const MachineFunction &MF)
static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context)
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.
static Function * getNextUnusedUnnamedFunction(const Module &M, Module::iterator &FirstUnvisitedFunction)
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
#define T
static constexpr unsigned SM(unsigned Version)
static constexpr StringLiteral Filename
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
SI Pre allocate WWM Registers
#define error(X)
an instruction to allocate memory on the stack
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
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:168
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
Module * getParent()
Get the module that this global value is contained inside of...
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1080
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.
void reportDiagnostic(const SMDiagnostic &Diag)
bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
bool parseRegisterInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
bool initializeFrameInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
bool parseMachineFunction(Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *FAM, Module::iterator &FirstUnvisitedFunction)
Parse the machine function in the current YAML document.
Function * createDummyFunction(StringRef Name, Module &M)
Create an empty function with the given name.
bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, const T &Object, int FrameIdx)
bool initializeMachineFunction(const yaml::MachineFunction &YamlMF, MachineFunction &MF)
Initialize the machine function to the state that's described in the MIR file.
std::unique_ptr< Module > parseIRModule(DataLayoutCallbackTy DataLayoutCallback)
Try to parse the optional LLVM module and the machine functions in the MIR file.
bool initializePrefetchTargets(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, const yaml::MachineJumpTable &YamlJTI)
bool initializeConstantPool(PerFunctionMIParsingState &PFS, MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF)
MIRParserImpl(std::unique_ptr< MemoryBuffer > Contents, StringRef Filename, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction)
std::optional< VarExprLoc > parseVarExprLoc(PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr, const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr)
bool parseCalledGlobals(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, std::vector< CalleeSavedInfo > &CSIInfo, const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx)
bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
bool initializeSaveRestorePoints(PerFunctionMIParsingState &PFS, const std::vector< yaml::SaveRestorePointEntry > &YamlSRPoints, llvm::SaveRestorePoints &SaveRestorePoints)
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *FAM=nullptr)
LLVM_ABI MIRParser(std::unique_ptr< MIRParserImpl > Impl)
LLVM_ABI std::unique_ptr< Module > parseIRModule(DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Parses the optional LLVM IR module in the MIR file.
LLVM_ABI bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Parses MachineFunctions in the MIR file and add them to the given MachineModuleInfo MMI.
LLVM_ABI ~MIRParser()
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 setSavePoints(SaveRestorePoints NewSavePoints)
void setCVBytesOfCalleeSavedRegisters(unsigned S)
void setStackID(int ObjectIdx, uint8_t ID)
void setHasTailCall(bool V=true)
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 setRestorePoints(SaveRestorePoints NewRestorePoints)
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 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 setAlignment(Align A)
setAlignment - Set the alignment of the function.
void setPrefetchTargets(const DenseMap< UniqueBBID, SmallVector< unsigned > > &V)
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.
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.
bool isCall(QueryType Type=AnyInBundle) const
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,...
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
MachineOperand * getOneDef(Register Reg) const
Returns the defining operand if there is exactly one operand defining the specified register,...
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
LLVM_ABI void setRegBank(Register Reg, const RegisterBank &RegBank)
Set the register bank to RegBank for Reg.
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
void setSimpleHint(Register VReg, Register PrefReg)
Specify the preferred (target independent) register allocation hint for the specified virtual registe...
void addPhysRegsUsedFromRegMask(const uint32_t *RegMask)
addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
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
FunctionListType::iterator iterator
The Function iterators.
Definition Module.h:92
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:297
SourceMgr::DiagKind getKind() const
Definition SourceMgr.h:327
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
constexpr const char * getPointer() const
Definition SMLoc.h:33
Represents a range in source code.
Definition SMLoc.h:47
bool isValid() const
Definition SMLoc.h:57
SMLoc Start
Definition SMLoc.h:49
SMLoc End
Definition SMLoc.h:49
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition SourceMgr.h:160
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
static constexpr size_t npos
Definition StringRef.h:57
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:137
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
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.
TargetOptions Options
virtual yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const
Parse out the target's MachineFunctionInfo from the YAML reprsentation.
unsigned EmitCallSiteInfo
The flag enables call site info production.
unsigned EmitCallGraphSection
Emit section containing call graph metadata.
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.
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)
Definition Type.cpp:297
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
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
A forward iterator which reads text lines from a buffer.
The Input class is used to parse a yaml document into in-memory structs and vectors.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::enable_if_t< has_ScalarEnumerationTraits< T >::value, void > yamlize(IO &io, T &Val, bool, EmptyContext &Ctx)
Definition YAMLTraits.h:887
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;}, AsmParserContext *ParserContext=nullptr)
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition Parser.cpp:51
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
bool parsePrefetchTarget(PerFunctionMIParsingState &PFS, CallsiteID &Target, StringRef Src, SMDiagnostic &Error)
bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
DenseMap< MachineBasicBlock *, std::vector< CalleeSavedInfo > > SaveRestorePoints
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
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.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
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.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:36
@ Sub
Subtraction of integers.
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
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:195
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:1917
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool parseMachineMetadata(PerFunctionMIParsingState &PFS, StringRef Src, SMRange SourceRange, SMDiagnostic &Error)
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
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:130
DenseMap< unsigned, unsigned > JumpTableSlots
Definition MIParser.h:182
VRegInfo & getVRegInfo(Register Num)
Definition MIParser.cpp:328
DenseMap< unsigned, int > FixedStackObjectSlots
Definition MIParser.h:179
DenseMap< unsigned, unsigned > ConstantPoolSlots
Definition MIParser.h:181
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:178
DenseMap< unsigned, int > StackObjectSlots
Definition MIParser.h:180
std::map< unsigned, std::pair< TempMDTuple, SMLoc > > MachineForwardRefMDNodes
Definition MIParser.h:174
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:177
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
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< FlowStringValue > PrefetchTargets
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.
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.