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
14#include "llvm/CodeGen/MIRParser/MIRParser.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/AsmParser/Parser.h"
18#include "llvm/AsmParser/SlotMapping.h"
19#include "llvm/CodeGen/MIRParser/MIParser.h"
20#include "llvm/CodeGen/MIRYamlMapping.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionAnalysis.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/CodeGen/TargetFrameLowering.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/DebugInfoMetadata.h"
30#include "llvm/IR/DiagnosticInfo.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/ValueSymbolTable.h"
35#include "llvm/Support/LineIterator.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/SMLoc.h"
38#include "llvm/Support/SourceMgr.h"
39#include "llvm/Support/YAMLTraits.h"
40#include "llvm/Target/TargetMachine.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.
51class MIRParserImpl {
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.
99 Function *createDummyFunction(StringRef Name, Module &M);
100
101 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI,
102 ModuleAnalysisManager *FAM = nullptr);
103
104 /// Parse the machine function in the current YAML document.
105 ///
106 ///
107 /// Return true if an error occurred.
108 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI,
109 ModuleAnalysisManager *FAM,
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.
116 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
117 MachineFunction &MF);
118
119 bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS,
120 const yaml::MachineFunction &YamlMF);
121
122 bool initializePrefetchTargets(PerFunctionMIParsingState &PFS,
123 const yaml::MachineFunction &YamlMF);
124
125 bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
126 const yaml::MachineFunction &YamlMF);
127
128 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
129 const yaml::MachineFunction &YamlMF);
130
131 bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
132 const yaml::MachineFunction &YamlMF);
133
134 bool initializeSaveRestorePoints(
135 PerFunctionMIParsingState &PFS,
136 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
137 llvm::SaveRestorePoints &SaveRestorePoints);
138
139 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
140 std::vector<CalleeSavedInfo> &CSIInfo,
141 const yaml::StringValue &RegisterSource,
142 bool IsRestored, int FrameIdx);
143
144 struct VarExprLoc {
145 DILocalVariable *DIVar = nullptr;
146 DIExpression *DIExpr = nullptr;
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>
155 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
156 const T &Object,
157 int FrameIdx);
158
159 bool initializeConstantPool(PerFunctionMIParsingState &PFS,
160 MachineConstantPool &ConstantPool,
161 const yaml::MachineFunction &YamlMF);
162
163 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
164 const yaml::MachineJumpTable &YamlJTI);
165
166 bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS,
167 MachineFunction &MF,
168 const yaml::MachineFunction &YMF);
169
170 bool parseCalledGlobals(PerFunctionMIParsingState &PFS, MachineFunction &MF,
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,
178 MachineBasicBlock *&MBB,
179 const yaml::StringValue &Source);
180
181 /// Return a MIR diagnostic converted from an MI string diagnostic.
182 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
183 SMRange SourceRange);
184
185 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
186 /// block scalar string.
187 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
188 SMRange SourceRange);
189
190 bool computeFunctionProperties(MachineFunction &MF,
191 const yaml::MachineFunction &YamlMF);
192
193 void setupDebugValueTracking(MachineFunction &MF,
194 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF);
195
196 bool parseMachineInst(MachineFunction &MF, yaml::MachineInstrLoc MILoc,
197 MachineInstr const *&MI);
198};
199
200} // end namespace llvm
201
202static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
203 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
204}
205
206MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
207 StringRef Filename, LLVMContext &Context,
208 std::function<void(Function &)> Callback)
209 : Context(Context),
210 In(SM.getMemoryBuffer(i: SM.AddNewSourceBuffer(F: std::move(Contents), IncludeLoc: SMLoc()))
211 ->getBuffer(),
212 nullptr, handleYAMLDiag, this),
213 Filename(Filename), ProcessIRFunction(Callback) {
214 In.setContext(&In);
215}
216
217bool MIRParserImpl::error(const Twine &Message) {
218 Context.diagnose(DI: DiagnosticInfoMIRParser(
219 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
220 return true;
221}
222
223bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
224 Context.diagnose(DI: DiagnosticInfoMIRParser(
225 DS_Error, SM.GetMessage(Loc, Kind: SourceMgr::DK_Error, Msg: Message)));
226 return true;
227}
228
229bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
230 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
231 reportDiagnostic(Diag: diagFromMIStringDiag(Error, SourceRange));
232 return true;
233}
234
235void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
236 DiagnosticSeverity Kind;
237 switch (Diag.getKind()) {
238 case SourceMgr::DK_Error:
239 Kind = DS_Error;
240 break;
241 case SourceMgr::DK_Warning:
242 Kind = DS_Warning;
243 break;
244 case SourceMgr::DK_Note:
245 Kind = DS_Note;
246 break;
247 case SourceMgr::DK_Remark:
248 llvm_unreachable("remark unexpected");
249 break;
250 }
251 Context.diagnose(DI: DiagnosticInfoMIRParser(Kind, Diag));
252}
253
254std::unique_ptr<Module>
255MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
256 if (!In.setCurrentDocument()) {
257 if (In.error())
258 return nullptr;
259 // Create an empty module when the MIR file is empty.
260 NoMIRDocuments = true;
261 auto M = std::make_unique<Module>(args&: Filename, args&: Context);
262 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
263 M->getDataLayoutStr()))
264 M->setDataLayout(*LayoutOverride);
265 return M;
266 }
267
268 std::unique_ptr<Module> M;
269 // Parse the block scalar manually so that we can return unique pointer
270 // without having to go trough YAML traits.
271 if (const auto *BSN =
272 dyn_cast_or_null<yaml::BlockScalarNode>(Val: In.getCurrentNode())) {
273 SMDiagnostic Error;
274 M = parseAssembly(F: MemoryBufferRef(BSN->getValue(), Filename), Err&: Error,
275 Context, Slots: &IRSlots, DataLayoutCallback);
276 if (!M) {
277 reportDiagnostic(Diag: diagFromBlockStringDiag(Error, SourceRange: BSN->getSourceRange()));
278 return nullptr;
279 }
280 In.nextDocument();
281 if (!In.setCurrentDocument())
282 NoMIRDocuments = true;
283 } else {
284 // Create an new, empty module.
285 M = std::make_unique<Module>(args&: Filename, args&: Context);
286 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
287 M->getDataLayoutStr()))
288 M->setDataLayout(*LayoutOverride);
289 NoLLVMIR = true;
290 }
291 return M;
292}
293
294bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI,
295 ModuleAnalysisManager *MAM) {
296 if (NoMIRDocuments)
297 return false;
298
299 // Parse the machine functions.
300 auto FirstUnvisitedFunction = M.begin();
301 do {
302 if (parseMachineFunction(M, MMI, FAM: MAM, FirstUnvisitedFunction))
303 return true;
304 In.nextDocument();
305 } while (In.setCurrentDocument());
306
307 return false;
308}
309
310Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
311 auto &Context = M.getContext();
312 Function *F =
313 Function::Create(Ty: FunctionType::get(Result: Type::getVoidTy(C&: Context), isVarArg: false),
314 Linkage: Function::ExternalLinkage, N: Name, M);
315 BasicBlock *BB = BasicBlock::Create(Context, Name: "entry", Parent: F);
316 new UnreachableInst(Context, BB);
317
318 if (ProcessIRFunction)
319 ProcessIRFunction(*F);
320
321 return F;
322}
323
324static Function *
325getNextUnusedUnnamedFunction(const Module &M,
326 Module::iterator &FirstUnvisitedFunction) {
327 for (; FirstUnvisitedFunction != M.end(); ++FirstUnvisitedFunction)
328 if (!FirstUnvisitedFunction->hasName())
329 return &*FirstUnvisitedFunction++;
330
331 return nullptr;
332}
333
334bool MIRParserImpl::parseMachineFunction(
335 Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *MAM,
336 Module::iterator &FirstUnvisitedFunction) {
337 // Parse the yaml.
338 yaml::MachineFunction YamlMF;
339 yaml::EmptyContext Ctx;
340
341 const TargetMachine &TM = MMI.getTarget();
342 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
343 TM.createDefaultFuncInfoYAML());
344
345 yaml::yamlize(io&: In, Val&: YamlMF, false, Ctx);
346 if (In.error())
347 return true;
348
349 // Search for the corresponding IR function.
350 StringRef FunctionName = YamlMF.Name;
351 Function *F = M.getFunction(Name: FunctionName);
352 if (!F) {
353 if (NoLLVMIR) {
354 F = createDummyFunction(Name: FunctionName, M);
355 } else if (!FunctionName.empty() ||
356 !(F = getNextUnusedUnnamedFunction(M, FirstUnvisitedFunction))) {
357 return error(Message: Twine("function '") + FunctionName +
358 "' isn't defined in the provided LLVM IR");
359 }
360 }
361
362 if (!MAM) {
363 if (MMI.getMachineFunction(F: *F) != nullptr)
364 return error(Message: Twine("redefinition of machine function '") + FunctionName +
365 "'");
366
367 // Create the MachineFunction.
368 MachineFunction &MF = MMI.getOrCreateMachineFunction(F&: *F);
369 if (initializeMachineFunction(YamlMF, MF))
370 return true;
371 } else {
372 auto &FAM =
373 MAM->getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
374 if (FAM.getCachedResult<MachineFunctionAnalysis>(IR&: *F))
375 return error(Message: Twine("redefinition of machine function '") + FunctionName +
376 "'");
377
378 // Create the MachineFunction.
379 MachineFunction &MF = FAM.getResult<MachineFunctionAnalysis>(IR&: *F).getMF();
380 if (initializeMachineFunction(YamlMF, MF))
381 return true;
382 }
383
384 return false;
385}
386
387static bool isSSA(const MachineFunction &MF) {
388 const MachineRegisterInfo &MRI = MF.getRegInfo();
389 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
390 Register Reg = Register::index2VirtReg(Index: I);
391 if (!MRI.hasOneDef(RegNo: Reg) && !MRI.def_empty(RegNo: Reg))
392 return false;
393
394 // Subregister defs are invalid in SSA.
395 const MachineOperand *RegDef = MRI.getOneDef(Reg);
396 if (RegDef && RegDef->getSubReg() != 0)
397 return false;
398 }
399 return true;
400}
401
402bool MIRParserImpl::computeFunctionProperties(
403 MachineFunction &MF, const yaml::MachineFunction &YamlMF) {
404 MachineFunctionProperties &Properties = MF.getProperties();
405
406 bool HasPHI = false;
407 bool HasInlineAsm = false;
408 bool HasFakeUses = false;
409 bool AllTiedOpsRewritten = true, HasTiedOps = false;
410 for (const MachineBasicBlock &MBB : MF) {
411 for (const MachineInstr &MI : MBB) {
412 if (MI.isPHI())
413 HasPHI = true;
414 if (MI.isInlineAsm())
415 HasInlineAsm = true;
416 if (MI.isFakeUse())
417 HasFakeUses = true;
418 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
419 const MachineOperand &MO = MI.getOperand(i: I);
420 if (!MO.isReg() || !MO.getReg())
421 continue;
422 unsigned DefIdx;
423 if (MO.isUse() && MI.isRegTiedToDefOperand(UseOpIdx: I, DefOpIdx: &DefIdx)) {
424 HasTiedOps = true;
425 if (MO.getReg() != MI.getOperand(i: DefIdx).getReg())
426 AllTiedOpsRewritten = false;
427 }
428 }
429 }
430 }
431
432 // Helper function to sanity-check and set properties that are computed, but
433 // may be explicitly set from the input MIR
434 auto ComputedPropertyHelper =
435 [&Properties](std::optional<bool> ExplicitProp, bool ComputedProp,
436 MachineFunctionProperties::Property P) -> bool {
437 // Prefer explicitly given values over the computed properties
438 if (ExplicitProp.value_or(u&: ComputedProp))
439 Properties.set(P);
440 else
441 Properties.reset(P);
442
443 // Check for conflict between the explicit values and the computed ones
444 return ExplicitProp && *ExplicitProp && !ComputedProp;
445 };
446
447 if (ComputedPropertyHelper(YamlMF.NoPHIs, !HasPHI,
448 MachineFunctionProperties::Property::NoPHIs)) {
449 return error(Message: MF.getName() +
450 " has explicit property NoPhi, but contains at least one PHI");
451 }
452
453 MF.setHasInlineAsm(HasInlineAsm);
454
455 if (HasTiedOps && AllTiedOpsRewritten)
456 Properties.setTiedOpsRewritten();
457
458 if (ComputedPropertyHelper(YamlMF.IsSSA, isSSA(MF),
459 MachineFunctionProperties::Property::IsSSA)) {
460 return error(Message: MF.getName() +
461 " has explicit property IsSSA, but is not valid SSA");
462 }
463
464 const MachineRegisterInfo &MRI = MF.getRegInfo();
465 if (ComputedPropertyHelper(YamlMF.NoVRegs, MRI.getNumVirtRegs() == 0,
466 MachineFunctionProperties::Property::NoVRegs)) {
467 return error(
468 Message: MF.getName() +
469 " has explicit property NoVRegs, but contains virtual registers");
470 }
471
472 // For hasFakeUses we follow similar logic to the ComputedPropertyHelper,
473 // except for caring about the inverse case only, i.e. when the property is
474 // explicitly set to false and Fake Uses are present; having HasFakeUses=true
475 // on a function without fake uses is harmless.
476 if (YamlMF.HasFakeUses && !*YamlMF.HasFakeUses && HasFakeUses)
477 return error(
478 Message: MF.getName() +
479 " has explicit property hasFakeUses=false, but contains fake uses");
480 MF.setHasFakeUses(YamlMF.HasFakeUses.value_or(u&: HasFakeUses));
481
482 return false;
483}
484
485bool MIRParserImpl::parseMachineInst(MachineFunction &MF,
486 yaml::MachineInstrLoc MILoc,
487 MachineInstr const *&MI) {
488 if (MILoc.BlockNum >= MF.size()) {
489 return error(Message: Twine(MF.getName()) +
490 Twine(" instruction block out of range.") +
491 " Unable to reference bb:" + Twine(MILoc.BlockNum));
492 }
493 auto BB = std::next(x: MF.begin(), n: MILoc.BlockNum);
494 if (MILoc.Offset >= BB->size())
495 return error(
496 Message: Twine(MF.getName()) + Twine(" instruction offset out of range.") +
497 " Unable to reference instruction at bb: " + Twine(MILoc.BlockNum) +
498 " at offset:" + Twine(MILoc.Offset));
499 MI = &*std::next(x: BB->instr_begin(), n: MILoc.Offset);
500 return false;
501}
502
503bool MIRParserImpl::initializeCallSiteInfo(
504 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
505 MachineFunction &MF = PFS.MF;
506 SMDiagnostic Error;
507 const TargetMachine &TM = MF.getTarget();
508 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
509 yaml::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
510 const MachineInstr *CallI;
511 if (parseMachineInst(MF, MILoc, MI&: CallI))
512 return true;
513 if (!CallI->isCall(Type: MachineInstr::IgnoreBundle))
514 return error(Message: Twine(MF.getName()) +
515 Twine(" call site info should reference call "
516 "instruction. Instruction at bb:") +
517 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
518 " is not a call instruction");
519 MachineFunction::CallSiteInfo CSInfo;
520 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
521 Register Reg;
522 if (parseNamedRegisterReference(PFS, Reg, Src: ArgRegPair.Reg.Value, Error))
523 return error(Error, SourceRange: ArgRegPair.Reg.SourceRange);
524 CSInfo.ArgRegPairs.emplace_back(Args&: Reg, Args&: ArgRegPair.ArgNo);
525 }
526 if (!YamlCSInfo.CalleeTypeIds.empty()) {
527 for (auto CalleeTypeId : YamlCSInfo.CalleeTypeIds) {
528 IntegerType *Int64Ty = Type::getInt64Ty(C&: Context);
529 CSInfo.CalleeTypeIds.push_back(Elt: ConstantInt::get(Ty: Int64Ty, V: CalleeTypeId,
530 /*isSigned=*/IsSigned: false));
531 }
532 }
533
534 if (TM.Options.EmitCallSiteInfo || TM.Options.EmitCallGraphSection)
535 MF.addCallSiteInfo(CallI: &*CallI, CallInfo: std::move(CSInfo));
536 }
537
538 if (!YamlMF.CallSitesInfo.empty() &&
539 !(TM.Options.EmitCallSiteInfo || TM.Options.EmitCallGraphSection))
540 return error(Message: "call site info provided but not used");
541 return false;
542}
543
544void MIRParserImpl::setupDebugValueTracking(
545 MachineFunction &MF, PerFunctionMIParsingState &PFS,
546 const yaml::MachineFunction &YamlMF) {
547 // Compute the value of the "next instruction number" field.
548 unsigned MaxInstrNum = 0;
549 for (auto &MBB : MF)
550 for (auto &MI : MBB)
551 MaxInstrNum = std::max(a: MI.peekDebugInstrNum(), b: MaxInstrNum);
552 MF.setDebugInstrNumberingCount(MaxInstrNum);
553
554 // Load any substitutions.
555 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
556 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
557 {Sub.DstInst, Sub.DstOp}, SubReg: Sub.Subreg);
558 }
559
560 // Flag for whether we're supposed to be using DBG_INSTR_REF.
561 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
562}
563
564bool
565MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
566 MachineFunction &MF) {
567 // TODO: Recreate the machine function.
568 if (Target) {
569 // Avoid clearing state if we're using the same subtarget again.
570 Target->setTarget(MF.getSubtarget());
571 } else {
572 Target.reset(p: new PerTargetMIParsingState(MF.getSubtarget()));
573 }
574
575 MF.setAlignment(YamlMF.Alignment.valueOrOne());
576 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
577 MF.setHasWinCFI(YamlMF.HasWinCFI);
578
579 MF.setCallsEHReturn(YamlMF.CallsEHReturn);
580 MF.setCallsUnwindInit(YamlMF.CallsUnwindInit);
581 MF.setHasEHContTarget(YamlMF.HasEHContTarget);
582 MF.setHasEHScopes(YamlMF.HasEHScopes);
583 MF.setHasEHFunclets(YamlMF.HasEHFunclets);
584 MF.setIsOutlined(YamlMF.IsOutlined);
585
586 MachineFunctionProperties &Props = MF.getProperties();
587 if (YamlMF.Legalized)
588 Props.setLegalized();
589 if (YamlMF.RegBankSelected)
590 Props.setRegBankSelected();
591 if (YamlMF.Selected)
592 Props.setSelected();
593 if (YamlMF.FailedISel)
594 Props.setFailedISel();
595 if (YamlMF.FailsVerification)
596 Props.setFailsVerification();
597 if (YamlMF.TracksDebugUserValues)
598 Props.setTracksDebugUserValues();
599
600 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
601 if (parseRegisterInfo(PFS, YamlMF))
602 return true;
603 if (initializePrefetchTargets(PFS, YamlMF))
604 return true;
605 if (!YamlMF.Constants.empty()) {
606 auto *ConstantPool = MF.getConstantPool();
607 assert(ConstantPool && "Constant pool must be created");
608 if (initializeConstantPool(PFS, ConstantPool&: *ConstantPool, YamlMF))
609 return true;
610 }
611 if (!YamlMF.MachineMetadataNodes.empty() &&
612 parseMachineMetadataNodes(PFS, MF, YMF: YamlMF))
613 return true;
614
615 StringRef BlockStr = YamlMF.Body.Value.Value;
616 SMDiagnostic Error;
617 SourceMgr BlockSM;
618 BlockSM.AddNewSourceBuffer(
619 F: MemoryBuffer::getMemBuffer(InputData: BlockStr, BufferName: "",/*RequiresNullTerminator=*/false),
620 IncludeLoc: SMLoc());
621 PFS.SM = &BlockSM;
622 if (parseMachineBasicBlockDefinitions(PFS, Src: BlockStr, Error)) {
623 reportDiagnostic(
624 Diag: diagFromBlockStringDiag(Error, SourceRange: YamlMF.Body.Value.SourceRange));
625 return true;
626 }
627 // Check Basic Block Section Flags.
628 if (MF.hasBBSections()) {
629 MF.assignBeginEndSections();
630 }
631 PFS.SM = &SM;
632
633 // Initialize the frame information after creating all the MBBs so that the
634 // MBB references in the frame information can be resolved.
635 if (initializeFrameInfo(PFS, YamlMF))
636 return true;
637 // Initialize the jump table after creating all the MBBs so that the MBB
638 // references can be resolved.
639 if (!YamlMF.JumpTableInfo.Entries.empty() &&
640 initializeJumpTableInfo(PFS, YamlJTI: YamlMF.JumpTableInfo))
641 return true;
642 // Parse the machine instructions after creating all of the MBBs so that the
643 // parser can resolve the MBB references.
644 StringRef InsnStr = YamlMF.Body.Value.Value;
645 SourceMgr InsnSM;
646 InsnSM.AddNewSourceBuffer(
647 F: MemoryBuffer::getMemBuffer(InputData: InsnStr, BufferName: "", /*RequiresNullTerminator=*/false),
648 IncludeLoc: SMLoc());
649 PFS.SM = &InsnSM;
650 if (parseMachineInstructions(PFS, Src: InsnStr, Error)) {
651 reportDiagnostic(
652 Diag: diagFromBlockStringDiag(Error, SourceRange: YamlMF.Body.Value.SourceRange));
653 return true;
654 }
655 PFS.SM = &SM;
656
657 if (setupRegisterInfo(PFS, YamlMF))
658 return true;
659
660 if (YamlMF.MachineFuncInfo) {
661 const TargetMachine &TM = MF.getTarget();
662 // Note this is called after the initial constructor of the
663 // MachineFunctionInfo based on the MachineFunction, which may depend on the
664 // IR.
665
666 SMRange SrcRange;
667 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
668 SourceRange&: SrcRange)) {
669 return error(Error, SourceRange: SrcRange);
670 }
671 }
672
673 // Set the reserved registers after parsing MachineFuncInfo. The target may
674 // have been recording information used to select the reserved registers
675 // there.
676 // FIXME: This is a temporary workaround until the reserved registers can be
677 // serialized.
678 MachineRegisterInfo &MRI = MF.getRegInfo();
679 MRI.freezeReservedRegs();
680
681 if (computeFunctionProperties(MF, YamlMF))
682 return true;
683
684 if (initializeCallSiteInfo(PFS, YamlMF))
685 return true;
686
687 if (parseCalledGlobals(PFS, MF, YMF: YamlMF))
688 return true;
689
690 if (initializePrefetchTargets(PFS, YamlMF))
691 return true;
692
693 setupDebugValueTracking(MF, PFS, YamlMF);
694
695 MF.getSubtarget().mirFileLoaded(MF);
696
697 MF.verify(p: nullptr, Banner: nullptr, OS: &errs());
698 return false;
699}
700
701bool MIRParserImpl::initializePrefetchTargets(
702 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
703 MachineFunction &MF = PFS.MF;
704 SMDiagnostic Error;
705 DenseMap<UniqueBBID, SmallVector<unsigned>> Targets;
706 for (const auto &YamlTarget : YamlMF.PrefetchTargets) {
707 CallsiteID Target;
708 if (llvm::parsePrefetchTarget(PFS, Target, Src: YamlTarget.Value, Error))
709 return error(Error, SourceRange: YamlTarget.SourceRange);
710 Targets[Target.BBID].push_back(Elt: Target.CallsiteIndex);
711 }
712 MF.setPrefetchTargets(Targets);
713 return false;
714}
715
716bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
717 const yaml::MachineFunction &YamlMF) {
718 MachineFunction &MF = PFS.MF;
719 MachineRegisterInfo &RegInfo = MF.getRegInfo();
720 assert(RegInfo.tracksLiveness());
721 if (!YamlMF.TracksRegLiveness)
722 RegInfo.invalidateLiveness();
723
724 SMDiagnostic Error;
725 // Parse the virtual register information.
726 for (const auto &VReg : YamlMF.VirtualRegisters) {
727 VRegInfo &Info = PFS.getVRegInfo(Num: VReg.ID.Value);
728 if (Info.Explicit)
729 return error(Loc: VReg.ID.SourceRange.Start,
730 Message: Twine("redefinition of virtual register '%") +
731 Twine(VReg.ID.Value) + "'");
732 Info.Explicit = true;
733
734 if (VReg.Class.Value == "_") {
735 Info.Kind = VRegInfo::GENERIC;
736 Info.D.RegBank = nullptr;
737 } else {
738 const auto *RC = Target->getRegClass(Name: VReg.Class.Value);
739 if (RC) {
740 Info.Kind = VRegInfo::NORMAL;
741 Info.D.RC = RC;
742 } else {
743 const RegisterBank *RegBank = Target->getRegBank(Name: VReg.Class.Value);
744 if (!RegBank)
745 return error(
746 Loc: VReg.Class.SourceRange.Start,
747 Message: Twine("use of undefined register class or register bank '") +
748 VReg.Class.Value + "'");
749 Info.Kind = VRegInfo::REGBANK;
750 Info.D.RegBank = RegBank;
751 }
752 }
753
754 if (!VReg.PreferredRegister.Value.empty()) {
755 if (Info.Kind != VRegInfo::NORMAL)
756 return error(Loc: VReg.Class.SourceRange.Start,
757 Message: Twine("preferred register can only be set for normal vregs"));
758
759 if (parseRegisterReference(PFS, Reg&: Info.PreferredReg,
760 Src: VReg.PreferredRegister.Value, Error))
761 return error(Error, SourceRange: VReg.PreferredRegister.SourceRange);
762 }
763
764 for (const auto &FlagStringValue : VReg.RegisterFlags) {
765 uint8_t FlagValue;
766 if (Target->getVRegFlagValue(FlagName: FlagStringValue.Value, FlagValue))
767 return error(Loc: FlagStringValue.SourceRange.Start,
768 Message: Twine("use of undefined register flag '") +
769 FlagStringValue.Value + "'");
770 Info.Flags |= FlagValue;
771 }
772 RegInfo.noteNewVirtualRegister(Reg: Info.VReg);
773 }
774
775 // Parse the liveins.
776 for (const auto &LiveIn : YamlMF.LiveIns) {
777 Register Reg;
778 if (parseNamedRegisterReference(PFS, Reg, Src: LiveIn.Register.Value, Error))
779 return error(Error, SourceRange: LiveIn.Register.SourceRange);
780 Register VReg;
781 if (!LiveIn.VirtualRegister.Value.empty()) {
782 VRegInfo *Info;
783 if (parseVirtualRegisterReference(PFS, Info, Src: LiveIn.VirtualRegister.Value,
784 Error))
785 return error(Error, SourceRange: LiveIn.VirtualRegister.SourceRange);
786 VReg = Info->VReg;
787 }
788 RegInfo.addLiveIn(Reg, vreg: VReg);
789 }
790
791 // Parse the callee saved registers (Registers that will
792 // be saved for the caller).
793 if (YamlMF.CalleeSavedRegisters) {
794 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
795 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
796 Register Reg;
797 if (parseNamedRegisterReference(PFS, Reg, Src: RegSource.Value, Error))
798 return error(Error, SourceRange: RegSource.SourceRange);
799 CalleeSavedRegisters.push_back(Elt: Reg.id());
800 }
801 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
802 }
803
804 // Stash any VirtRegMap state on MRI.
805 // VirtRegMap::init() will use that information to get pre-populated
806 // on the first analysis run.
807 for (const auto &VReg : YamlMF.VirtualRegisters) {
808 if (VReg.SplitFrom.Value.empty() && VReg.AssignedPhys.Value.empty())
809 continue;
810
811 auto It = PFS.VRegInfos.find(Val: VReg.ID.Value);
812 if (It == PFS.VRegInfos.end())
813 continue;
814 Register ChildReg = It->second->VReg;
815
816 MachineRegisterInfo::PendingVirtRegMapEntry Pending;
817 Pending.VReg = ChildReg;
818
819 if (!VReg.SplitFrom.Value.empty()) {
820 VRegInfo *Parent = nullptr;
821 if (parseVirtualRegisterReference(PFS, Info&: Parent, Src: VReg.SplitFrom.Value,
822 Error))
823 return error(Error, SourceRange: VReg.SplitFrom.SourceRange);
824 if (Parent->VReg == ChildReg)
825 return error(Loc: VReg.SplitFrom.SourceRange.Start,
826 Message: Twine("'split-from' references the same vreg as 'id' (%") +
827 Twine(VReg.ID.Value) + ")");
828 Pending.SplitFrom = Parent->VReg;
829 }
830 if (!VReg.AssignedPhys.Value.empty()) {
831 Register Phys;
832 if (parseRegisterReference(PFS, Reg&: Phys, Src: VReg.AssignedPhys.Value, Error))
833 return error(Error, SourceRange: VReg.AssignedPhys.SourceRange);
834 if (!Phys.isPhysical())
835 return error(
836 Loc: VReg.AssignedPhys.SourceRange.Start,
837 Message: Twine("'assigned-phys' must be a physical register, got '") +
838 VReg.AssignedPhys.Value + "'");
839 Pending.AssignedPhys = Phys.asMCReg();
840 }
841 RegInfo.addPendingVirtRegMapEntry(Entry: Pending);
842 }
843
844 return false;
845}
846
847bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
848 const yaml::MachineFunction &YamlMF) {
849 MachineFunction &MF = PFS.MF;
850 MachineRegisterInfo &MRI = MF.getRegInfo();
851 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
852
853 SmallVector<std::string> Errors;
854
855 // Create VRegs
856 auto populateVRegInfo = [&](const VRegInfo &Info, const Twine &Name) {
857 Register Reg = Info.VReg;
858 switch (Info.Kind) {
859 case VRegInfo::UNKNOWN:
860 Errors.push_back(
861 Elt: (Twine("Cannot determine class/bank of virtual register ") + Name +
862 " in function '" + MF.getName() + "'")
863 .str());
864 break;
865 case VRegInfo::NORMAL:
866 if (!Info.D.RC->isAllocatable()) {
867 Errors.push_back(Elt: (Twine("Cannot use non-allocatable class '") +
868 TRI->getRegClassName(Class: Info.D.RC) +
869 "' for virtual register " + Name + " in function '" +
870 MF.getName() + "'")
871 .str());
872 break;
873 }
874
875 MRI.setRegClass(Reg, RC: Info.D.RC);
876 if (Info.PreferredReg != 0)
877 MRI.setSimpleHint(VReg: Reg, PrefReg: Info.PreferredReg);
878 break;
879 case VRegInfo::GENERIC:
880 break;
881 case VRegInfo::REGBANK:
882 MRI.setRegBank(Reg, RegBank: *Info.D.RegBank);
883 break;
884 }
885 };
886
887 for (const auto &P : PFS.VRegInfosNamed) {
888 const VRegInfo &Info = *P.second;
889 populateVRegInfo(Info, Twine(P.first()));
890 }
891
892 for (auto P : PFS.VRegInfos) {
893 const VRegInfo &Info = *P.second;
894 populateVRegInfo(Info, Twine(P.first.id()));
895 }
896
897 // Compute MachineRegisterInfo::UsedPhysRegMask
898 for (const MachineBasicBlock &MBB : MF) {
899 // Make sure MRI knows about registers clobbered by unwinder.
900 if (MBB.isEHPad())
901 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
902 MRI.addPhysRegsUsedFromRegMask(RegMask);
903
904 for (const MachineInstr &MI : MBB) {
905 for (const MachineOperand &MO : MI.operands()) {
906 if (!MO.isRegMask())
907 continue;
908 MRI.addPhysRegsUsedFromRegMask(RegMask: MO.getRegMask());
909 }
910 }
911 }
912
913 if (Errors.empty())
914 return false;
915
916 // Report errors in a deterministic order.
917 sort(C&: Errors);
918 for (auto &E : Errors)
919 error(Message: E);
920 return true;
921}
922
923bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
924 const yaml::MachineFunction &YamlMF) {
925 MachineFunction &MF = PFS.MF;
926 MachineFrameInfo &MFI = MF.getFrameInfo();
927 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
928 const Function &F = MF.getFunction();
929 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
930 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
931 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
932 MFI.setHasStackMap(YamlMFI.HasStackMap);
933 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
934 MFI.setStackSize(YamlMFI.StackSize);
935 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
936 if (YamlMFI.MaxAlignment)
937 MFI.ensureMaxAlignment(Alignment: Align(YamlMFI.MaxAlignment));
938 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
939 MFI.setHasCalls(YamlMFI.HasCalls);
940 if (YamlMFI.FramePointerPolicy != FramePointerKind::None)
941 MFI.setFramePointerPolicy(YamlMFI.FramePointerPolicy);
942 if (YamlMFI.MaxCallFrameSize != ~0u)
943 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
944 MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
945 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
946 MFI.setHasVAStart(YamlMFI.HasVAStart);
947 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
948 MFI.setHasTailCall(YamlMFI.HasTailCall);
949 MFI.setCalleeSavedInfoValid(YamlMFI.IsCalleeSavedInfoValid);
950 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
951 llvm::SaveRestorePoints SavePoints;
952 if (initializeSaveRestorePoints(PFS, YamlSRPoints: YamlMFI.SavePoints, SaveRestorePoints&: SavePoints))
953 return true;
954 MFI.setSavePoints(SavePoints);
955 llvm::SaveRestorePoints RestorePoints;
956 if (initializeSaveRestorePoints(PFS, YamlSRPoints: YamlMFI.RestorePoints, SaveRestorePoints&: RestorePoints))
957 return true;
958 MFI.setRestorePoints(RestorePoints);
959
960 std::vector<CalleeSavedInfo> CSIInfo;
961 // Initialize the fixed frame objects.
962 for (const auto &Object : YamlMF.FixedStackObjects) {
963 int ObjectIdx;
964 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
965 ObjectIdx = MFI.CreateFixedObject(Size: Object.Size, SPOffset: Object.Offset,
966 IsImmutable: Object.IsImmutable, isAliased: Object.IsAliased);
967 else
968 ObjectIdx = MFI.CreateFixedSpillStackObject(Size: Object.Size, SPOffset: Object.Offset);
969
970 if (!TFI->isSupportedStackID(ID: Object.StackID))
971 return error(Loc: Object.ID.SourceRange.Start,
972 Message: Twine("StackID is not supported by target"));
973 MFI.setStackID(ObjectIdx, ID: Object.StackID);
974 MFI.setObjectAlignment(ObjectIdx, Alignment: Object.Alignment.valueOrOne());
975 if (!PFS.FixedStackObjectSlots.insert(KV: std::make_pair(x: Object.ID.Value,
976 y&: ObjectIdx))
977 .second)
978 return error(Loc: Object.ID.SourceRange.Start,
979 Message: Twine("redefinition of fixed stack object '%fixed-stack.") +
980 Twine(Object.ID.Value) + "'");
981 if (parseCalleeSavedRegister(PFS, CSIInfo, RegisterSource: Object.CalleeSavedRegister,
982 IsRestored: Object.CalleeSavedRestored, FrameIdx: ObjectIdx))
983 return true;
984 if (parseStackObjectsDebugInfo(PFS, Object, FrameIdx: ObjectIdx))
985 return true;
986 }
987
988 for (const auto &Object : YamlMF.EntryValueObjects) {
989 SMDiagnostic Error;
990 Register Reg;
991 if (parseNamedRegisterReference(PFS, Reg, Src: Object.EntryValueRegister.Value,
992 Error))
993 return error(Error, SourceRange: Object.EntryValueRegister.SourceRange);
994 if (!Reg.isPhysical())
995 return error(Loc: Object.EntryValueRegister.SourceRange.Start,
996 Message: "Expected physical register for entry value field");
997 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
998 PFS, VarStr: Object.DebugVar, ExprStr: Object.DebugExpr, LocStr: Object.DebugLoc);
999 if (!MaybeInfo)
1000 return true;
1001 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1002 PFS.MF.setVariableDbgInfo(Var: MaybeInfo->DIVar, Expr: MaybeInfo->DIExpr,
1003 Reg: Reg.asMCReg(), Loc: MaybeInfo->DILoc);
1004 }
1005
1006 // Initialize the ordinary frame objects.
1007 for (const auto &Object : YamlMF.StackObjects) {
1008 int ObjectIdx;
1009 const AllocaInst *Alloca = nullptr;
1010 const yaml::StringValue &Name = Object.Name;
1011 if (!Name.Value.empty()) {
1012 Alloca = dyn_cast_or_null<AllocaInst>(
1013 Val: F.getValueSymbolTable()->lookup(Name: Name.Value));
1014 if (!Alloca)
1015 return error(Loc: Name.SourceRange.Start,
1016 Message: "alloca instruction named '" + Name.Value +
1017 "' isn't defined in the function '" + F.getName() +
1018 "'");
1019 }
1020 if (!TFI->isSupportedStackID(ID: Object.StackID))
1021 return error(Loc: Object.ID.SourceRange.Start,
1022 Message: Twine("StackID is not supported by target"));
1023 if (Object.Type == yaml::MachineStackObject::VariableSized)
1024 ObjectIdx =
1025 MFI.CreateVariableSizedObject(Alignment: Object.Alignment.valueOrOne(), Alloca);
1026 else
1027 ObjectIdx = MFI.CreateStackObject(
1028 Size: Object.Size, Alignment: Object.Alignment.valueOrOne(),
1029 isSpillSlot: Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
1030 ID: Object.StackID);
1031 MFI.setObjectOffset(ObjectIdx, SPOffset: Object.Offset);
1032
1033 if (!PFS.StackObjectSlots.insert(KV: std::make_pair(x: Object.ID.Value, y&: ObjectIdx))
1034 .second)
1035 return error(Loc: Object.ID.SourceRange.Start,
1036 Message: Twine("redefinition of stack object '%stack.") +
1037 Twine(Object.ID.Value) + "'");
1038 if (parseCalleeSavedRegister(PFS, CSIInfo, RegisterSource: Object.CalleeSavedRegister,
1039 IsRestored: Object.CalleeSavedRestored, FrameIdx: ObjectIdx))
1040 return true;
1041 if (Object.LocalOffset)
1042 MFI.mapLocalFrameObject(ObjectIndex: ObjectIdx, Offset: *Object.LocalOffset);
1043 if (parseStackObjectsDebugInfo(PFS, Object, FrameIdx: ObjectIdx))
1044 return true;
1045 }
1046 MFI.setCalleeSavedInfo(CSIInfo);
1047 if (!CSIInfo.empty())
1048 MFI.setCalleeSavedInfoValid(true);
1049
1050 // Initialize the various stack object references after initializing the
1051 // stack objects.
1052 if (!YamlMFI.StackProtector.Value.empty()) {
1053 SMDiagnostic Error;
1054 int FI;
1055 if (parseStackObjectReference(PFS, FI, Src: YamlMFI.StackProtector.Value, Error))
1056 return error(Error, SourceRange: YamlMFI.StackProtector.SourceRange);
1057 MFI.setStackProtectorIndex(FI);
1058 }
1059
1060 if (!YamlMFI.FunctionContext.Value.empty()) {
1061 SMDiagnostic Error;
1062 int FI;
1063 if (parseStackObjectReference(PFS, FI, Src: YamlMFI.FunctionContext.Value, Error))
1064 return error(Error, SourceRange: YamlMFI.FunctionContext.SourceRange);
1065 MFI.setFunctionContextIndex(FI);
1066 }
1067
1068 return false;
1069}
1070
1071bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
1072 std::vector<CalleeSavedInfo> &CSIInfo,
1073 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
1074 if (RegisterSource.Value.empty())
1075 return false;
1076 Register Reg;
1077 SMDiagnostic Error;
1078 if (parseNamedRegisterReference(PFS, Reg, Src: RegisterSource.Value, Error))
1079 return error(Error, SourceRange: RegisterSource.SourceRange);
1080 CalleeSavedInfo CSI(Reg, FrameIdx);
1081 CSI.setRestored(IsRestored);
1082 CSIInfo.push_back(x: CSI);
1083 return false;
1084}
1085
1086/// Verify that given node is of a certain type. Return true on error.
1087template <typename T>
1088static bool typecheckMDNode(T *&Result, MDNode *Node,
1089 const yaml::StringValue &Source,
1090 StringRef TypeString, MIRParserImpl &Parser) {
1091 if (!Node)
1092 return false;
1093 Result = dyn_cast<T>(Node);
1094 if (!Result)
1095 return Parser.error(Loc: Source.SourceRange.Start,
1096 Message: "expected a reference to a '" + TypeString +
1097 "' metadata node");
1098 return false;
1099}
1100
1101std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
1102 PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr,
1103 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
1104 MDNode *Var = nullptr;
1105 MDNode *Expr = nullptr;
1106 MDNode *Loc = nullptr;
1107 if (parseMDNode(PFS, Node&: Var, Source: VarStr) || parseMDNode(PFS, Node&: Expr, Source: ExprStr) ||
1108 parseMDNode(PFS, Node&: Loc, Source: LocStr))
1109 return std::nullopt;
1110 DILocalVariable *DIVar = nullptr;
1111 DIExpression *DIExpr = nullptr;
1112 DILocation *DILoc = nullptr;
1113 if (typecheckMDNode(Result&: DIVar, Node: Var, Source: VarStr, TypeString: "DILocalVariable", Parser&: *this) ||
1114 typecheckMDNode(Result&: DIExpr, Node: Expr, Source: ExprStr, TypeString: "DIExpression", Parser&: *this) ||
1115 typecheckMDNode(Result&: DILoc, Node: Loc, Source: LocStr, TypeString: "DILocation", Parser&: *this))
1116 return std::nullopt;
1117 return VarExprLoc{.DIVar: DIVar, .DIExpr: DIExpr, .DILoc: DILoc};
1118}
1119
1120template <typename T>
1121bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
1122 const T &Object, int FrameIdx) {
1123 std::optional<VarExprLoc> MaybeInfo =
1124 parseVarExprLoc(PFS, VarStr: Object.DebugVar, ExprStr: Object.DebugExpr, LocStr: Object.DebugLoc);
1125 if (!MaybeInfo)
1126 return true;
1127 // Debug information can only be attached to stack objects; Fixed stack
1128 // objects aren't supported.
1129 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1130 PFS.MF.setVariableDbgInfo(Var: MaybeInfo->DIVar, Expr: MaybeInfo->DIExpr, Slot: FrameIdx,
1131 Loc: MaybeInfo->DILoc);
1132 return false;
1133}
1134
1135bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
1136 MDNode *&Node, const yaml::StringValue &Source) {
1137 if (Source.Value.empty())
1138 return false;
1139 SMDiagnostic Error;
1140 if (llvm::parseMDNode(PFS, Node, Src: Source.Value, Error))
1141 return error(Error, SourceRange: Source.SourceRange);
1142 return false;
1143}
1144
1145bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
1146 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
1147 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
1148 const MachineFunction &MF = PFS.MF;
1149 const auto &M = *MF.getFunction().getParent();
1150 SMDiagnostic Error;
1151 for (const auto &YamlConstant : YamlMF.Constants) {
1152 if (YamlConstant.IsTargetSpecific)
1153 // FIXME: Support target-specific constant pools
1154 return error(Loc: YamlConstant.Value.SourceRange.Start,
1155 Message: "Can't parse target-specific constant pool entries yet");
1156 const Constant *Value = dyn_cast_or_null<Constant>(
1157 Val: parseConstantValue(Asm: YamlConstant.Value.Value, Err&: Error, M));
1158 if (!Value)
1159 return error(Error, SourceRange: YamlConstant.Value.SourceRange);
1160 const Align PrefTypeAlign =
1161 M.getDataLayout().getPrefTypeAlign(Ty: Value->getType());
1162 const Align Alignment = YamlConstant.Alignment.value_or(u: PrefTypeAlign);
1163 unsigned Index = ConstantPool.getConstantPoolIndex(C: Value, Alignment);
1164 if (!ConstantPoolSlots.insert(KV: std::make_pair(x: YamlConstant.ID.Value, y&: Index))
1165 .second)
1166 return error(Loc: YamlConstant.ID.SourceRange.Start,
1167 Message: Twine("redefinition of constant pool item '%const.") +
1168 Twine(YamlConstant.ID.Value) + "'");
1169 }
1170 return false;
1171}
1172
1173// Return true if basic block was incorrectly specified in MIR
1174bool MIRParserImpl::initializeSaveRestorePoints(
1175 PerFunctionMIParsingState &PFS,
1176 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
1177 llvm::SaveRestorePoints &SaveRestorePoints) {
1178 SMDiagnostic Error;
1179 MachineBasicBlock *MBB = nullptr;
1180 for (const yaml::SaveRestorePointEntry &Entry : YamlSRPoints) {
1181 if (parseMBBReference(PFS, MBB, Source: Entry.Point.Value))
1182 return true;
1183
1184 std::vector<CalleeSavedInfo> Registers;
1185 for (auto &RegStr : Entry.Registers) {
1186 Register Reg;
1187 if (parseNamedRegisterReference(PFS, Reg, Src: RegStr.Value, Error))
1188 return error(Error, SourceRange: RegStr.SourceRange);
1189 Registers.push_back(x: CalleeSavedInfo(Reg));
1190 }
1191 SaveRestorePoints.try_emplace(Key: MBB, Args: std::move(Registers));
1192 }
1193 return false;
1194}
1195
1196bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
1197 const yaml::MachineJumpTable &YamlJTI) {
1198 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(JTEntryKind: YamlJTI.Kind);
1199 for (const auto &Entry : YamlJTI.Entries) {
1200 std::vector<MachineBasicBlock *> Blocks;
1201 for (const auto &MBBSource : Entry.Blocks) {
1202 MachineBasicBlock *MBB = nullptr;
1203 if (parseMBBReference(PFS, MBB, Source: MBBSource.Value))
1204 return true;
1205 Blocks.push_back(x: MBB);
1206 }
1207 unsigned Index = JTI->createJumpTableIndex(DestBBs: Blocks);
1208 if (!PFS.JumpTableSlots.insert(KV: std::make_pair(x: Entry.ID.Value, y&: Index))
1209 .second)
1210 return error(Loc: Entry.ID.SourceRange.Start,
1211 Message: Twine("redefinition of jump table entry '%jump-table.") +
1212 Twine(Entry.ID.Value) + "'");
1213 }
1214 return false;
1215}
1216
1217bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1218 MachineBasicBlock *&MBB,
1219 const yaml::StringValue &Source) {
1220 SMDiagnostic Error;
1221 if (llvm::parseMBBReference(PFS, MBB, Src: Source.Value, Error))
1222 return error(Error, SourceRange: Source.SourceRange);
1223 return false;
1224}
1225
1226bool MIRParserImpl::parseMachineMetadataNodes(
1227 PerFunctionMIParsingState &PFS, MachineFunction &MF,
1228 const yaml::MachineFunction &YMF) {
1229 SmallVector<StringRef> Definitions;
1230 for (const auto &MDS : YMF.MachineMetadataNodes)
1231 Definitions.push_back(Elt: MDS.Value);
1232
1233 SlotMapping Slots = PFS.IRSlots;
1234 SMDiagnostic Error;
1235 unsigned ErrorDefinitionIndex = 0;
1236 if (parseMetadataDefinitions(Definitions, Err&: Error,
1237 M: *MF.getFunction().getParent(), Slots,
1238 ErrorDefinitionIndex)) {
1239 const yaml::StringValue &Source =
1240 YMF.MachineMetadataNodes[ErrorDefinitionIndex];
1241 if (StringRef(Source.Value).contains(C: '\n')) {
1242 reportDiagnostic(Diag: diagFromBlockStringDiag(Error, SourceRange: Source.SourceRange));
1243 return true;
1244 }
1245 return error(Error, SourceRange: Source.SourceRange);
1246 }
1247
1248 for (auto &[ID, MD] : Slots.MetadataNodes)
1249 if (PFS.IRSlots.MetadataNodes.find(x: ID) == PFS.IRSlots.MetadataNodes.end())
1250 PFS.MachineMetadataNodes.try_emplace(k: ID, args&: MD);
1251 return false;
1252}
1253
1254bool MIRParserImpl::parseCalledGlobals(PerFunctionMIParsingState &PFS,
1255 MachineFunction &MF,
1256 const yaml::MachineFunction &YMF) {
1257 Function &F = MF.getFunction();
1258 for (const auto &YamlCG : YMF.CalledGlobals) {
1259 yaml::MachineInstrLoc MILoc = YamlCG.CallSite;
1260 const MachineInstr *CallI;
1261 if (parseMachineInst(MF, MILoc, MI&: CallI))
1262 return true;
1263 if (!CallI->isCall(Type: MachineInstr::IgnoreBundle))
1264 return error(Message: Twine(MF.getName()) +
1265 Twine(" called global should reference call "
1266 "instruction. Instruction at bb:") +
1267 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
1268 " is not a call instruction");
1269
1270 auto Callee =
1271 F.getParent()->getValueSymbolTable().lookup(Name: YamlCG.Callee.Value);
1272 if (!Callee)
1273 return error(Loc: YamlCG.Callee.SourceRange.Start,
1274 Message: "use of undefined global '" + YamlCG.Callee.Value + "'");
1275 if (!isa<GlobalValue>(Val: Callee))
1276 return error(Loc: YamlCG.Callee.SourceRange.Start,
1277 Message: "use of non-global value '" + YamlCG.Callee.Value + "'");
1278
1279 MF.addCalledGlobal(MI: CallI, Details: {.Callee: cast<GlobalValue>(Val: Callee), .TargetFlags: YamlCG.Flags});
1280 }
1281
1282 return false;
1283}
1284
1285SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1286 SMRange SourceRange) {
1287 assert(SourceRange.isValid() && "Invalid source range");
1288 SMLoc Loc = SourceRange.Start;
1289 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1290 *Loc.getPointer() == '\'';
1291 // Translate the location of the error from the location in the MI string to
1292 // the corresponding location in the MIR file.
1293 Loc = Loc.getFromPointer(Ptr: Loc.getPointer() + Error.getColumnNo() +
1294 (HasQuote ? 1 : 0));
1295
1296 // TODO: Translate any source ranges as well.
1297 return SM.GetMessage(Loc, Kind: Error.getKind(), Msg: Error.getMessage(), Ranges: {},
1298 FixIts: Error.getFixIts());
1299}
1300
1301SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1302 SMRange SourceRange) {
1303 assert(SourceRange.isValid());
1304
1305 // Translate the location of the error from the location in the llvm IR string
1306 // to the corresponding location in the MIR file.
1307 auto LineAndColumn = SM.getLineAndColumn(Loc: SourceRange.Start);
1308 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1309 unsigned Column = Error.getColumnNo();
1310 StringRef LineStr = Error.getLineContents();
1311 SMLoc Loc = Error.getLoc();
1312
1313 // Get the full line and adjust the column number by taking the indentation of
1314 // LLVM IR into account.
1315 for (line_iterator L(*SM.getMemoryBuffer(i: SM.getMainFileID()), false), E;
1316 L != E; ++L) {
1317 if (L.line_number() == Line) {
1318 LineStr = *L;
1319 Loc = SMLoc::getFromPointer(Ptr: LineStr.data());
1320 auto Indent = LineStr.find(Str: Error.getLineContents());
1321 if (Indent != StringRef::npos)
1322 Column += Indent;
1323 break;
1324 }
1325 }
1326
1327 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1328 Error.getMessage(), LineStr, Error.getRanges(),
1329 Error.getFixIts());
1330}
1331
1332MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1333 : Impl(std::move(Impl)) {}
1334
1335MIRParser::~MIRParser() = default;
1336
1337std::unique_ptr<Module>
1338MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
1339 return Impl->parseIRModule(DataLayoutCallback);
1340}
1341
1342bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
1343 return Impl->parseMachineFunctions(M, MMI);
1344}
1345
1346bool MIRParser::parseMachineFunctions(Module &M, ModuleAnalysisManager &MAM) {
1347 auto &MMI = MAM.getResult<MachineModuleAnalysis>(IR&: M).getMMI();
1348 return Impl->parseMachineFunctions(M, MMI, MAM: &MAM);
1349}
1350
1351std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1352 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1353 std::function<void(Function &)> ProcessIRFunction) {
1354 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1355 if (std::error_code EC = FileOrErr.getError()) {
1356 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
1357 "could not open input file: " + EC.message());
1358 return nullptr;
1359 }
1360 return createMIRParser(Contents: std::move(FileOrErr.get()), Context,
1361 ProcessIRFunction);
1362}
1363
1364std::unique_ptr<MIRParser>
1365llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1366 LLVMContext &Context,
1367 std::function<void(Function &)> ProcessIRFunction) {
1368 auto Filename = Contents->getBufferIdentifier();
1369 if (Context.shouldDiscardValueNames()) {
1370 Context.diagnose(DI: DiagnosticInfoMIRParser(
1371 DS_Error,
1372 SMDiagnostic(
1373 Filename, SourceMgr::DK_Error,
1374 "cannot read MIR with a Context that discards named Values")));
1375 return nullptr;
1376 }
1377 return std::make_unique<MIRParser>(args: std::make_unique<MIRParserImpl>(
1378 args: std::move(Contents), args&: Filename, args&: Context, args&: ProcessIRFunction));
1379}
1380