blob: 199d077ac66ee1414489f6aabb1c5f37374962fa [file] [log] [blame]
Alex Lorenz2bdb4e12015-05-27 18:02:19 +00001//===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alex Lorenz2bdb4e12015-05-27 18:02:19 +00006//
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"
Alex Lorenz33f0aef2015-06-26 16:46:11 +000015#include "llvm/ADT/DenseMap.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000016#include "llvm/ADT/STLExtras.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000017#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000019#include "llvm/AsmParser/Parser.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000020#include "llvm/AsmParser/SlotMapping.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000021#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
22#include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
Matt Arsenaultbc6d07c2019-03-14 22:54:43 +000023#include "llvm/CodeGen/MIRParser/MIParser.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000024#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenzab980492015-07-20 20:51:18 +000025#include "llvm/CodeGen/MachineConstantPool.h"
Alex Lorenz60541c12015-07-09 19:55:27 +000026#include "llvm/CodeGen/MachineFrameInfo.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000027#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenzdf9e3c62015-08-19 00:13:25 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Sander de Smalen5d6ee762019-06-17 09:13:29 +000030#include "llvm/CodeGen/TargetFrameLowering.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000031#include "llvm/IR/BasicBlock.h"
Reid Kleckner28865802016-04-14 18:29:59 +000032#include "llvm/IR/DebugInfo.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000033#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000034#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000035#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000036#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000037#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000038#include "llvm/Support/LineIterator.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000039#include "llvm/Support/MemoryBuffer.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000040#include "llvm/Support/SMLoc.h"
41#include "llvm/Support/SourceMgr.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000042#include "llvm/Support/YAMLTraits.h"
Matt Arsenaultbc6d07c2019-03-14 22:54:43 +000043#include "llvm/Target/TargetMachine.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000044#include <memory>
45
46using namespace llvm;
47
Alex Lorenz735c47e2015-06-15 20:30:22 +000048namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000049
50/// This class implements the parsing of LLVM IR that's embedded inside a MIR
51/// file.
52class MIRParserImpl {
53 SourceMgr SM;
Matthias Braun7bda1952017-06-06 00:44:35 +000054 yaml::Input In;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000055 StringRef Filename;
56 LLVMContext &Context;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000057 SlotMapping IRSlots;
Matt Arsenaultbdfb6cf2019-03-12 20:42:12 +000058 std::unique_ptr<PerTargetMIParsingState> Target;
59
Matthias Braun7bda1952017-06-06 00:44:35 +000060 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
61 /// created and inserted into the given module when this is true.
62 bool NoLLVMIR = false;
63 /// True when a well formed MIR file does not contain any MIR/machine function
64 /// parts.
65 bool NoMIRDocuments = false;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000066
Matt Arsenault5518a022019-12-07 00:06:34 +053067 std::function<void(Function &)> ProcessIRFunction;
68
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000069public:
Matt Arsenault5518a022019-12-07 00:06:34 +053070 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
71 LLVMContext &Context,
72 std::function<void(Function &)> ProcessIRFunction);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000073
Alex Lorenz735c47e2015-06-15 20:30:22 +000074 void reportDiagnostic(const SMDiagnostic &Diag);
75
76 /// Report an error with the given message at unknown location.
77 ///
78 /// Always returns true.
79 bool error(const Twine &Message);
80
Alex Lorenzb1f9ce82015-07-08 20:22:20 +000081 /// Report an error with the given message at the given location.
82 ///
83 /// Always returns true.
84 bool error(SMLoc Loc, const Twine &Message);
85
Alex Lorenz0fd7c622015-06-30 17:55:00 +000086 /// Report a given error with the location translated from the location in an
87 /// embedded string literal to a location in the MIR file.
88 ///
89 /// Always returns true.
90 bool error(const SMDiagnostic &Error, SMRange SourceRange);
91
Alex Lorenz78d78312015-05-28 22:41:12 +000092 /// Try to parse the optional LLVM module and the machine functions in the MIR
93 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000094 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000095 /// Return null if an error occurred.
Matthias Braun7bda1952017-06-06 00:44:35 +000096 std::unique_ptr<Module> parseIRModule();
97
Matt Arsenault5518a022019-12-07 00:06:34 +053098 /// Create an empty function with the given name.
99 Function *createDummyFunction(StringRef Name, Module &M);
100
Matthias Braun7bda1952017-06-06 00:44:35 +0000101 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI);
Alex Lorenz78d78312015-05-28 22:41:12 +0000102
103 /// Parse the machine function in the current YAML document.
104 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000105 ///
Alex Lorenz78d78312015-05-28 22:41:12 +0000106 /// Return true if an error occurred.
Matthias Braun7bda1952017-06-06 00:44:35 +0000107 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000108
Alex Lorenz735c47e2015-06-15 20:30:22 +0000109 /// Initialize the machine function to the state that's described in the MIR
110 /// file.
111 ///
112 /// Return true if error occurred.
Matthias Braun7bda1952017-06-06 00:44:35 +0000113 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
114 MachineFunction &MF);
Alex Lorenz735c47e2015-06-15 20:30:22 +0000115
Matthias Braun74ad41c2016-10-11 03:13:01 +0000116 bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
117 const yaml::MachineFunction &YamlMF);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000118
Matthias Braun74ad41c2016-10-11 03:13:01 +0000119 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
Alex Lorenzc4838082015-08-11 00:32:49 +0000120 const yaml::MachineFunction &YamlMF);
121
Matthias Braun83947862016-07-13 22:23:23 +0000122 bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
123 const yaml::MachineFunction &YamlMF);
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000124
Djordje Todorovica7cde102019-06-27 07:48:06 +0000125 bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS,
126 const yaml::MachineFunction &YamlMF);
127
Matthias Braun83947862016-07-13 22:23:23 +0000128 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000129 std::vector<CalleeSavedInfo> &CSIInfo,
130 const yaml::StringValue &RegisterSource,
Matthias Braun5c3e8a42017-09-28 18:52:14 +0000131 bool IsRestored, int FrameIdx);
Alex Lorenz60541c12015-07-09 19:55:27 +0000132
Francis Visoiu Mistrih57fcd342018-04-25 18:58:06 +0000133 template <typename T>
Matthias Braun83947862016-07-13 22:23:23 +0000134 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
Francis Visoiu Mistrih57fcd342018-04-25 18:58:06 +0000135 const T &Object,
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000136 int FrameIdx);
137
Matthias Braun83947862016-07-13 22:23:23 +0000138 bool initializeConstantPool(PerFunctionMIParsingState &PFS,
139 MachineConstantPool &ConstantPool,
140 const yaml::MachineFunction &YamlMF);
Alex Lorenzab980492015-07-20 20:51:18 +0000141
Matthias Braun83947862016-07-13 22:23:23 +0000142 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
143 const yaml::MachineJumpTable &YamlJTI);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000144
Alex Lorenz09b832c2015-05-29 17:05:41 +0000145private:
Matthias Braun74ad41c2016-10-11 03:13:01 +0000146 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
Matthias Braun83947862016-07-13 22:23:23 +0000147 const yaml::StringValue &Source);
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000148
Matthias Braun74ad41c2016-10-11 03:13:01 +0000149 bool parseMBBReference(PerFunctionMIParsingState &PFS,
Matthias Braun83947862016-07-13 22:23:23 +0000150 MachineBasicBlock *&MBB,
151 const yaml::StringValue &Source);
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000152
Alex Lorenz51af1602015-06-23 22:39:23 +0000153 /// Return a MIR diagnostic converted from an MI string diagnostic.
154 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
155 SMRange SourceRange);
156
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000157 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
158 /// block scalar string.
159 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
160 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000161
Matthias Braun90799ce2016-08-23 21:19:49 +0000162 void computeFunctionProperties(MachineFunction &MF);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000163};
164
Alex Lorenz735c47e2015-06-15 20:30:22 +0000165} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000166
Matthias Braun7bda1952017-06-06 00:44:35 +0000167static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
168 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
169}
170
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000171MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
Matt Arsenault5518a022019-12-07 00:06:34 +0530172 StringRef Filename, LLVMContext &Context,
173 std::function<void(Function &)> Callback)
Matthias Braun7bda1952017-06-06 00:44:35 +0000174 : SM(),
Matt Arsenault5518a022019-12-07 00:06:34 +0530175 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
176 ->getBuffer(),
177 nullptr, handleYAMLDiag, this),
178 Filename(Filename), Context(Context), ProcessIRFunction(Callback) {
Matthias Braun7bda1952017-06-06 00:44:35 +0000179 In.setContext(&In);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000180}
181
Alex Lorenz735c47e2015-06-15 20:30:22 +0000182bool MIRParserImpl::error(const Twine &Message) {
183 Context.diagnose(DiagnosticInfoMIRParser(
184 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
185 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000186}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000187
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000188bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
189 Context.diagnose(DiagnosticInfoMIRParser(
190 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
191 return true;
192}
193
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000194bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
195 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
196 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
197 return true;
198}
199
Alex Lorenz735c47e2015-06-15 20:30:22 +0000200void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
201 DiagnosticSeverity Kind;
202 switch (Diag.getKind()) {
203 case SourceMgr::DK_Error:
204 Kind = DS_Error;
205 break;
206 case SourceMgr::DK_Warning:
207 Kind = DS_Warning;
208 break;
209 case SourceMgr::DK_Note:
210 Kind = DS_Note;
211 break;
Adam Nemet01104ae2017-10-12 23:56:02 +0000212 case SourceMgr::DK_Remark:
213 llvm_unreachable("remark unexpected");
214 break;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000215 }
216 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
217}
218
Matthias Braun7bda1952017-06-06 00:44:35 +0000219std::unique_ptr<Module> MIRParserImpl::parseIRModule() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000220 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000221 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000222 return nullptr;
223 // Create an empty module when the MIR file is empty.
Matthias Braun7bda1952017-06-06 00:44:35 +0000224 NoMIRDocuments = true;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000225 return std::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000226 }
227
Alex Lorenz78d78312015-05-28 22:41:12 +0000228 std::unique_ptr<Module> M;
229 // Parse the block scalar manually so that we can return unique pointer
230 // without having to go trough YAML traits.
231 if (const auto *BSN =
232 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000233 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000234 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Yaxun Liuc00d81e2018-01-30 22:32:39 +0000235 Context, &IRSlots, /*UpgradeDebugInfo=*/false);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000236 if (!M) {
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000237 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
Matthias Braund6f95622016-07-14 00:42:37 +0000238 return nullptr;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000239 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000240 In.nextDocument();
241 if (!In.setCurrentDocument())
Matthias Braun7bda1952017-06-06 00:44:35 +0000242 NoMIRDocuments = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000243 } else {
244 // Create an new, empty module.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000245 M = std::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000246 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000247 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000248 return M;
249}
250
Matthias Braun7bda1952017-06-06 00:44:35 +0000251bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
252 if (NoMIRDocuments)
253 return false;
254
255 // Parse the machine functions.
256 do {
257 if (parseMachineFunction(M, MMI))
258 return true;
259 In.nextDocument();
260 } while (In.setCurrentDocument());
261
Alex Lorenz735c47e2015-06-15 20:30:22 +0000262 return false;
263}
264
Matt Arsenault5518a022019-12-07 00:06:34 +0530265Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000266 auto &Context = M.getContext();
James Y Knight13680222019-02-01 02:28:03 +0000267 Function *F =
268 Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
269 Function::ExternalLinkage, Name, M);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000270 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
271 new UnreachableInst(Context, BB);
Matt Arsenault5518a022019-12-07 00:06:34 +0530272
273 if (ProcessIRFunction)
274 ProcessIRFunction(*F);
275
Matthias Braun7bda1952017-06-06 00:44:35 +0000276 return F;
277}
278
279bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) {
280 // Parse the yaml.
281 yaml::MachineFunction YamlMF;
282 yaml::EmptyContext Ctx;
Matt Arsenaultbc6d07c2019-03-14 22:54:43 +0000283
284 const LLVMTargetMachine &TM = MMI.getTarget();
285 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
286 TM.createDefaultFuncInfoYAML());
287
Matthias Braun7bda1952017-06-06 00:44:35 +0000288 yaml::yamlize(In, YamlMF, false, Ctx);
289 if (In.error())
290 return true;
291
292 // Search for the corresponding IR function.
293 StringRef FunctionName = YamlMF.Name;
294 Function *F = M.getFunction(FunctionName);
295 if (!F) {
296 if (NoLLVMIR) {
297 F = createDummyFunction(FunctionName, M);
298 } else {
299 return error(Twine("function '") + FunctionName +
300 "' isn't defined in the provided LLVM IR");
301 }
302 }
303 if (MMI.getMachineFunction(*F) != nullptr)
304 return error(Twine("redefinition of machine function '") + FunctionName +
305 "'");
306
307 // Create the MachineFunction.
308 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
309 if (initializeMachineFunction(YamlMF, MF))
310 return true;
311
312 return false;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000313}
314
Matthias Braun79f85b32016-08-24 01:32:41 +0000315static bool isSSA(const MachineFunction &MF) {
316 const MachineRegisterInfo &MRI = MF.getRegInfo();
317 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000318 unsigned Reg = Register::index2VirtReg(I);
Matthias Braun79f85b32016-08-24 01:32:41 +0000319 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
320 return false;
321 }
322 return true;
323}
324
Matthias Braun90799ce2016-08-23 21:19:49 +0000325void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
Matthias Braun79f85b32016-08-24 01:32:41 +0000326 MachineFunctionProperties &Properties = MF.getProperties();
Matthias Brauna319e2c2016-08-24 22:34:06 +0000327
328 bool HasPHI = false;
329 bool HasInlineAsm = false;
330 for (const MachineBasicBlock &MBB : MF) {
331 for (const MachineInstr &MI : MBB) {
332 if (MI.isPHI())
333 HasPHI = true;
334 if (MI.isInlineAsm())
335 HasInlineAsm = true;
336 }
337 }
338 if (!HasPHI)
Matthias Braun79f85b32016-08-24 01:32:41 +0000339 Properties.set(MachineFunctionProperties::Property::NoPHIs);
Matthias Brauna319e2c2016-08-24 22:34:06 +0000340 MF.setHasInlineAsm(HasInlineAsm);
Matthias Braun79f85b32016-08-24 01:32:41 +0000341
342 if (isSSA(MF))
343 Properties.set(MachineFunctionProperties::Property::IsSSA);
344 else
Quentin Colombete609a9a2016-08-26 22:09:11 +0000345 Properties.reset(MachineFunctionProperties::Property::IsSSA);
Matthias Braun1eb47362016-08-25 01:27:13 +0000346
347 const MachineRegisterInfo &MRI = MF.getRegInfo();
348 if (MRI.getNumVirtRegs() == 0)
349 Properties.set(MachineFunctionProperties::Property::NoVRegs);
Matthias Braun90799ce2016-08-23 21:19:49 +0000350}
351
Djordje Todorovica7cde102019-06-27 07:48:06 +0000352bool MIRParserImpl::initializeCallSiteInfo(
353 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
354 MachineFunction &MF = PFS.MF;
355 SMDiagnostic Error;
356 const LLVMTargetMachine &TM = MF.getTarget();
357 for (auto YamlCSInfo : YamlMF.CallSitesInfo) {
358 yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
359 if (MILoc.BlockNum >= MF.size())
360 return error(Twine(MF.getName()) +
361 Twine(" call instruction block out of range.") +
362 " Unable to reference bb:" + Twine(MILoc.BlockNum));
363 auto CallB = std::next(MF.begin(), MILoc.BlockNum);
364 if (MILoc.Offset >= CallB->size())
365 return error(Twine(MF.getName()) +
366 Twine(" call instruction offset out of range.") +
David Stenbergb71d8d42019-09-20 14:41:41 +0000367 " Unable to reference instruction at bb: " +
Djordje Todorovica7cde102019-06-27 07:48:06 +0000368 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
David Stenberg88df53e2019-08-19 12:41:22 +0000369 auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
370 if (!CallI->isCall(MachineInstr::IgnoreBundle))
Djordje Todorovica7cde102019-06-27 07:48:06 +0000371 return error(Twine(MF.getName()) +
372 Twine(" call site info should reference call "
373 "instruction. Instruction at bb:") +
374 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
375 " is not a call instruction");
376 MachineFunction::CallSiteInfo CSInfo;
377 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
378 unsigned Reg = 0;
379 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
380 return error(Error, ArgRegPair.Reg.SourceRange);
381 CSInfo.emplace_back(Reg, ArgRegPair.ArgNo);
382 }
383
Djordje Todorovicc15c68a2020-03-09 11:02:35 +0100384 if (TM.Options.EmitCallSiteInfo)
Djordje Todorovica7cde102019-06-27 07:48:06 +0000385 MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo));
386 }
387
Djordje Todorovicc15c68a2020-03-09 11:02:35 +0100388 if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
Djordje Todorovica7cde102019-06-27 07:48:06 +0000389 return error(Twine("Call site info provided but not used"));
390 return false;
391}
392
Matthias Braun7bda1952017-06-06 00:44:35 +0000393bool
394MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
395 MachineFunction &MF) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000396 // TODO: Recreate the machine function.
Matt Arsenaultbdfb6cf2019-03-12 20:42:12 +0000397 if (Target) {
398 // Avoid clearing state if we're using the same subtarget again.
399 Target->setTarget(MF.getSubtarget());
400 } else {
401 Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
402 }
403
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000404 if (YamlMF.Alignment)
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000405 MF.setAlignment(Align(YamlMF.Alignment));
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000406 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
Sanjin Sijaric625d08e2018-10-24 21:07:38 +0000407 MF.setHasWinCFI(YamlMF.HasWinCFI);
Ahmed Bougacha0d7b0cb2016-08-02 15:10:25 +0000408
409 if (YamlMF.Legalized)
410 MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
Ahmed Bougacha24712652016-08-02 16:17:10 +0000411 if (YamlMF.RegBankSelected)
412 MF.getProperties().set(
413 MachineFunctionProperties::Property::RegBankSelected);
Ahmed Bougachab109d512016-08-02 16:49:19 +0000414 if (YamlMF.Selected)
415 MF.getProperties().set(MachineFunctionProperties::Property::Selected);
Roman Tereshin3054ece2018-02-28 17:55:45 +0000416 if (YamlMF.FailedISel)
417 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
Ahmed Bougacha0d7b0cb2016-08-02 15:10:25 +0000418
Matt Arsenaultbdfb6cf2019-03-12 20:42:12 +0000419 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
Matthias Braun74ad41c2016-10-11 03:13:01 +0000420 if (parseRegisterInfo(PFS, YamlMF))
Alex Lorenz54565cf2015-06-24 19:56:10 +0000421 return true;
Alex Lorenzab980492015-07-20 20:51:18 +0000422 if (!YamlMF.Constants.empty()) {
423 auto *ConstantPool = MF.getConstantPool();
424 assert(ConstantPool && "Constant pool must be created");
Matthias Braun83947862016-07-13 22:23:23 +0000425 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
Alex Lorenzab980492015-07-20 20:51:18 +0000426 return true;
427 }
Alex Lorenz54565cf2015-06-24 19:56:10 +0000428
Matthias Braune35861d2016-07-13 23:27:50 +0000429 StringRef BlockStr = YamlMF.Body.Value.Value;
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000430 SMDiagnostic Error;
Matthias Braune35861d2016-07-13 23:27:50 +0000431 SourceMgr BlockSM;
432 BlockSM.AddNewSourceBuffer(
433 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
434 SMLoc());
435 PFS.SM = &BlockSM;
436 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000437 reportDiagnostic(
438 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
439 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000440 }
Sriraman Tallamdf082ac2020-03-16 15:56:02 -0700441 // Check Basic Block Section Flags.
442 if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels) {
443 MF.createBBLabels();
444 MF.setBBSectionsType(BasicBlockSection::Labels);
445 } else if (MF.hasBBSections()) {
446 MF.setSectionRange();
447 MF.createBBLabels();
448 }
Matthias Braune35861d2016-07-13 23:27:50 +0000449 PFS.SM = &SM;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000450
Alex Lorenza6f9a372015-07-29 21:09:09 +0000451 // Initialize the frame information after creating all the MBBs so that the
452 // MBB references in the frame information can be resolved.
Matthias Braun83947862016-07-13 22:23:23 +0000453 if (initializeFrameInfo(PFS, YamlMF))
Alex Lorenza6f9a372015-07-29 21:09:09 +0000454 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000455 // Initialize the jump table after creating all the MBBs so that the MBB
456 // references can be resolved.
457 if (!YamlMF.JumpTableInfo.Entries.empty() &&
Matthias Braun83947862016-07-13 22:23:23 +0000458 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000459 return true;
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000460 // Parse the machine instructions after creating all of the MBBs so that the
461 // parser can resolve the MBB references.
Matthias Braune35861d2016-07-13 23:27:50 +0000462 StringRef InsnStr = YamlMF.Body.Value.Value;
463 SourceMgr InsnSM;
464 InsnSM.AddNewSourceBuffer(
465 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
466 SMLoc());
467 PFS.SM = &InsnSM;
468 if (parseMachineInstructions(PFS, InsnStr, Error)) {
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000469 reportDiagnostic(
470 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
471 return true;
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000472 }
Matthias Braune35861d2016-07-13 23:27:50 +0000473 PFS.SM = &SM;
474
Matthias Braun74ad41c2016-10-11 03:13:01 +0000475 if (setupRegisterInfo(PFS, YamlMF))
476 return true;
Matthias Braun90799ce2016-08-23 21:19:49 +0000477
Matt Arsenaultbc6d07c2019-03-14 22:54:43 +0000478 if (YamlMF.MachineFuncInfo) {
479 const LLVMTargetMachine &TM = MF.getTarget();
480 // Note this is called after the initial constructor of the
481 // MachineFunctionInfo based on the MachineFunction, which may depend on the
482 // IR.
483
484 SMRange SrcRange;
485 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
486 SrcRange)) {
487 return error(Error, SrcRange);
488 }
489 }
490
Matt Arsenault733b8572019-03-27 16:12:26 +0000491 // Set the reserved registers after parsing MachineFuncInfo. The target may
492 // have been recording information used to select the reserved registers
493 // there.
494 // FIXME: This is a temporary workaround until the reserved registers can be
495 // serialized.
496 MachineRegisterInfo &MRI = MF.getRegInfo();
497 MRI.freezeReservedRegs(MF);
498
Matthias Braun90799ce2016-08-23 21:19:49 +0000499 computeFunctionProperties(MF);
500
Djordje Todorovica7cde102019-06-27 07:48:06 +0000501 if (initializeCallSiteInfo(PFS, YamlMF))
502 return false;
503
Matthias Braun5c290dc2018-01-19 03:16:36 +0000504 MF.getSubtarget().mirFileLoaded(MF);
505
Alex Lorenzc7bf2042015-07-24 17:44:49 +0000506 MF.verify();
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000507 return false;
508}
509
Matthias Braun74ad41c2016-10-11 03:13:01 +0000510bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
511 const yaml::MachineFunction &YamlMF) {
Matthias Braun83947862016-07-13 22:23:23 +0000512 MachineFunction &MF = PFS.MF;
Alex Lorenzdb07c402015-07-28 16:48:37 +0000513 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Alex Lorenz54565cf2015-06-24 19:56:10 +0000514 assert(RegInfo.tracksLiveness());
515 if (!YamlMF.TracksRegLiveness)
516 RegInfo.invalidateLiveness();
Alex Lorenz28148ba2015-07-09 22:23:13 +0000517
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000518 SMDiagnostic Error;
Alex Lorenz28148ba2015-07-09 22:23:13 +0000519 // Parse the virtual register information.
520 for (const auto &VReg : YamlMF.VirtualRegisters) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000521 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
522 if (Info.Explicit)
523 return error(VReg.ID.SourceRange.Start,
524 Twine("redefinition of virtual register '%") +
525 Twine(VReg.ID.Value) + "'");
526 Info.Explicit = true;
527
Quentin Colombet050b2112016-03-08 01:17:03 +0000528 if (StringRef(VReg.Class.Value).equals("_")) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000529 Info.Kind = VRegInfo::GENERIC;
Justin Bogner6c7663f2017-11-17 18:51:20 +0000530 Info.D.RegBank = nullptr;
Quentin Colombet050b2112016-03-08 01:17:03 +0000531 } else {
Matt Arsenaultbdfb6cf2019-03-12 20:42:12 +0000532 const auto *RC = Target->getRegClass(VReg.Class.Value);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000533 if (RC) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000534 Info.Kind = VRegInfo::NORMAL;
535 Info.D.RC = RC;
Quentin Colombet876ddf82016-04-08 16:40:43 +0000536 } else {
Matt Arsenaultbdfb6cf2019-03-12 20:42:12 +0000537 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000538 if (!RegBank)
539 return error(
540 VReg.Class.SourceRange.Start,
541 Twine("use of undefined register class or register bank '") +
542 VReg.Class.Value + "'");
Matthias Braun74ad41c2016-10-11 03:13:01 +0000543 Info.Kind = VRegInfo::REGBANK;
544 Info.D.RegBank = RegBank;
Quentin Colombet876ddf82016-04-08 16:40:43 +0000545 }
Quentin Colombet050b2112016-03-08 01:17:03 +0000546 }
Matthias Braun74ad41c2016-10-11 03:13:01 +0000547
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000548 if (!VReg.PreferredRegister.Value.empty()) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000549 if (Info.Kind != VRegInfo::NORMAL)
550 return error(VReg.Class.SourceRange.Start,
551 Twine("preferred register can only be set for normal vregs"));
Tom Stellard9c884e42016-11-15 00:03:14 +0000552
553 if (parseRegisterReference(PFS, Info.PreferredReg,
554 VReg.PreferredRegister.Value, Error))
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000555 return error(Error, VReg.PreferredRegister.SourceRange);
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000556 }
Alex Lorenz28148ba2015-07-09 22:23:13 +0000557 }
Alex Lorenz12045a42015-07-27 17:42:45 +0000558
559 // Parse the liveins.
560 for (const auto &LiveIn : YamlMF.LiveIns) {
561 unsigned Reg = 0;
Matthias Braune35861d2016-07-13 23:27:50 +0000562 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
Alex Lorenz12045a42015-07-27 17:42:45 +0000563 return error(Error, LiveIn.Register.SourceRange);
564 unsigned VReg = 0;
565 if (!LiveIn.VirtualRegister.Value.empty()) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000566 VRegInfo *Info;
567 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
Matthias Braune35861d2016-07-13 23:27:50 +0000568 Error))
Alex Lorenz12045a42015-07-27 17:42:45 +0000569 return error(Error, LiveIn.VirtualRegister.SourceRange);
Matthias Braun74ad41c2016-10-11 03:13:01 +0000570 VReg = Info->VReg;
Alex Lorenz12045a42015-07-27 17:42:45 +0000571 }
572 RegInfo.addLiveIn(Reg, VReg);
573 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000574
Oren Ben Simhon0ef61ec2017-03-19 08:14:18 +0000575 // Parse the callee saved registers (Registers that will
576 // be saved for the caller).
577 if (YamlMF.CalleeSavedRegisters) {
578 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
579 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
580 unsigned Reg = 0;
581 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
582 return error(Error, RegSource.SourceRange);
583 CalleeSavedRegisters.push_back(Reg);
584 }
585 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
Alex Lorenzc4838082015-08-11 00:32:49 +0000586 }
Oren Ben Simhon0ef61ec2017-03-19 08:14:18 +0000587
Alex Lorenz54565cf2015-06-24 19:56:10 +0000588 return false;
589}
590
Matthias Braun74ad41c2016-10-11 03:13:01 +0000591bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
Alex Lorenzc4838082015-08-11 00:32:49 +0000592 const yaml::MachineFunction &YamlMF) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000593 MachineFunction &MF = PFS.MF;
594 MachineRegisterInfo &MRI = MF.getRegInfo();
595 bool Error = false;
596 // Create VRegs
Puyan Lotfi399b46c2018-03-30 18:15:54 +0000597 auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
Matthias Braun74ad41c2016-10-11 03:13:01 +0000598 unsigned Reg = Info.VReg;
599 switch (Info.Kind) {
600 case VRegInfo::UNKNOWN:
601 error(Twine("Cannot determine class/bank of virtual register ") +
Puyan Lotfi399b46c2018-03-30 18:15:54 +0000602 Name + " in function '" + MF.getName() + "'");
Matthias Braun74ad41c2016-10-11 03:13:01 +0000603 Error = true;
604 break;
605 case VRegInfo::NORMAL:
606 MRI.setRegClass(Reg, Info.D.RC);
607 if (Info.PreferredReg != 0)
608 MRI.setSimpleHint(Reg, Info.PreferredReg);
609 break;
610 case VRegInfo::GENERIC:
611 break;
612 case VRegInfo::REGBANK:
613 MRI.setRegBank(Reg, *Info.D.RegBank);
614 break;
615 }
Puyan Lotfi399b46c2018-03-30 18:15:54 +0000616 };
617
618 for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end();
619 I != E; I++) {
620 const VRegInfo &Info = *I->second;
621 populateVRegInfo(Info, Twine(I->first()));
622 }
623
624 for (auto P : PFS.VRegInfos) {
625 const VRegInfo &Info = *P.second;
626 populateVRegInfo(Info, Twine(P.first));
Matthias Braun74ad41c2016-10-11 03:13:01 +0000627 }
628
629 // Compute MachineRegisterInfo::UsedPhysRegMask
Oren Ben Simhon0ef61ec2017-03-19 08:14:18 +0000630 for (const MachineBasicBlock &MBB : MF) {
631 for (const MachineInstr &MI : MBB) {
632 for (const MachineOperand &MO : MI.operands()) {
633 if (!MO.isRegMask())
634 continue;
635 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
Alex Lorenzc4838082015-08-11 00:32:49 +0000636 }
637 }
638 }
Matthias Braun74ad41c2016-10-11 03:13:01 +0000639
Matthias Braun74ad41c2016-10-11 03:13:01 +0000640 return Error;
Alex Lorenzc4838082015-08-11 00:32:49 +0000641}
642
Matthias Braun83947862016-07-13 22:23:23 +0000643bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
644 const yaml::MachineFunction &YamlMF) {
645 MachineFunction &MF = PFS.MF;
Matthias Braun941a7052016-07-28 18:40:00 +0000646 MachineFrameInfo &MFI = MF.getFrameInfo();
Sander de Smalen5d6ee762019-06-17 09:13:29 +0000647 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000648 const Function &F = MF.getFunction();
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000649 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
Alex Lorenz60541c12015-07-09 19:55:27 +0000650 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
651 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
652 MFI.setHasStackMap(YamlMFI.HasStackMap);
653 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
654 MFI.setStackSize(YamlMFI.StackSize);
655 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
656 if (YamlMFI.MaxAlignment)
657 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
658 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
659 MFI.setHasCalls(YamlMFI.HasCalls);
Matthias Braunab9438c2017-05-01 22:32:25 +0000660 if (YamlMFI.MaxCallFrameSize != ~0u)
661 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000662 MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
Alex Lorenz60541c12015-07-09 19:55:27 +0000663 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
664 MFI.setHasVAStart(YamlMFI.HasVAStart);
665 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
Francis Visoiu Mistrih537d7ee2018-04-06 08:56:25 +0000666 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
Alex Lorenza6f9a372015-07-29 21:09:09 +0000667 if (!YamlMFI.SavePoint.Value.empty()) {
668 MachineBasicBlock *MBB = nullptr;
Matthias Braun83947862016-07-13 22:23:23 +0000669 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
Alex Lorenza6f9a372015-07-29 21:09:09 +0000670 return true;
671 MFI.setSavePoint(MBB);
672 }
673 if (!YamlMFI.RestorePoint.Value.empty()) {
674 MachineBasicBlock *MBB = nullptr;
Matthias Braun83947862016-07-13 22:23:23 +0000675 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
Alex Lorenza6f9a372015-07-29 21:09:09 +0000676 return true;
677 MFI.setRestorePoint(MBB);
678 }
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000679
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000680 std::vector<CalleeSavedInfo> CSIInfo;
Alex Lorenzde491f02015-07-13 18:07:26 +0000681 // Initialize the fixed frame objects.
682 for (const auto &Object : YamlMF.FixedStackObjects) {
683 int ObjectIdx;
684 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
685 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
686 Object.IsImmutable, Object.IsAliased);
687 else
688 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
Sander de Smalen5d6ee762019-06-17 09:13:29 +0000689
690 if (!TFI->isSupportedStackID(Object.StackID))
691 return error(Object.ID.SourceRange.Start,
692 Twine("StackID is not supported by target"));
Matt Arsenaultdb782732017-07-20 21:03:45 +0000693 MFI.setStackID(ObjectIdx, Object.StackID);
Sander de Smalen7f23e0a2019-04-02 09:46:52 +0000694 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
Alex Lorenz1d9a3032015-08-10 23:45:02 +0000695 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
696 ObjectIdx))
697 .second)
698 return error(Object.ID.SourceRange.Start,
699 Twine("redefinition of fixed stack object '%fixed-stack.") +
700 Twine(Object.ID.Value) + "'");
Matthias Braun83947862016-07-13 22:23:23 +0000701 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
Matthias Braun5c3e8a42017-09-28 18:52:14 +0000702 Object.CalleeSavedRestored, ObjectIdx))
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000703 return true;
Francis Visoiu Mistrih57fcd342018-04-25 18:58:06 +0000704 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
705 return true;
Alex Lorenzde491f02015-07-13 18:07:26 +0000706 }
707
708 // Initialize the ordinary frame objects.
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000709 for (const auto &Object : YamlMF.StackObjects) {
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000710 int ObjectIdx;
Alex Lorenz37643a02015-07-15 22:14:49 +0000711 const AllocaInst *Alloca = nullptr;
712 const yaml::StringValue &Name = Object.Name;
713 if (!Name.Value.empty()) {
714 Alloca = dyn_cast_or_null<AllocaInst>(
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000715 F.getValueSymbolTable()->lookup(Name.Value));
Alex Lorenz37643a02015-07-15 22:14:49 +0000716 if (!Alloca)
717 return error(Name.SourceRange.Start,
718 "alloca instruction named '" + Name.Value +
719 "' isn't defined in the function '" + F.getName() +
720 "'");
721 }
Sander de Smalen5d6ee762019-06-17 09:13:29 +0000722 if (!TFI->isSupportedStackID(Object.StackID))
723 return error(Object.ID.SourceRange.Start,
724 Twine("StackID is not supported by target"));
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000725 if (Object.Type == yaml::MachineStackObject::VariableSized)
Alex Lorenz37643a02015-07-15 22:14:49 +0000726 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000727 else
728 ObjectIdx = MFI.CreateStackObject(
729 Object.Size, Object.Alignment,
Sander de Smalen7f23e0a2019-04-02 09:46:52 +0000730 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
731 Object.StackID);
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000732 MFI.setObjectOffset(ObjectIdx, Object.Offset);
Matt Arsenaultdb782732017-07-20 21:03:45 +0000733
Alex Lorenzc5d35ba2015-08-10 23:50:41 +0000734 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
735 .second)
736 return error(Object.ID.SourceRange.Start,
737 Twine("redefinition of stack object '%stack.") +
738 Twine(Object.ID.Value) + "'");
Matthias Braun83947862016-07-13 22:23:23 +0000739 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
Matthias Braun5c3e8a42017-09-28 18:52:14 +0000740 Object.CalleeSavedRestored, ObjectIdx))
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000741 return true;
Alex Lorenza56ba6a2015-08-17 22:17:42 +0000742 if (Object.LocalOffset)
743 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
Matthias Braun83947862016-07-13 22:23:23 +0000744 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000745 return true;
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000746 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000747 MFI.setCalleeSavedInfo(CSIInfo);
748 if (!CSIInfo.empty())
749 MFI.setCalleeSavedInfoValid(true);
Alex Lorenza314d812015-08-18 22:26:26 +0000750
751 // Initialize the various stack object references after initializing the
752 // stack objects.
753 if (!YamlMFI.StackProtector.Value.empty()) {
754 SMDiagnostic Error;
755 int FI;
Matthias Braune35861d2016-07-13 23:27:50 +0000756 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
Alex Lorenza314d812015-08-18 22:26:26 +0000757 return error(Error, YamlMFI.StackProtector.SourceRange);
758 MFI.setStackProtectorIndex(FI);
759 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000760 return false;
761}
762
Matthias Braun83947862016-07-13 22:23:23 +0000763bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000764 std::vector<CalleeSavedInfo> &CSIInfo,
Matthias Braun5c3e8a42017-09-28 18:52:14 +0000765 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000766 if (RegisterSource.Value.empty())
767 return false;
768 unsigned Reg = 0;
769 SMDiagnostic Error;
Matthias Braune35861d2016-07-13 23:27:50 +0000770 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000771 return error(Error, RegisterSource.SourceRange);
Matthias Braun5c3e8a42017-09-28 18:52:14 +0000772 CalleeSavedInfo CSI(Reg, FrameIdx);
773 CSI.setRestored(IsRestored);
774 CSIInfo.push_back(CSI);
Alex Lorenz60541c12015-07-09 19:55:27 +0000775 return false;
776}
777
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000778/// Verify that given node is of a certain type. Return true on error.
779template <typename T>
780static bool typecheckMDNode(T *&Result, MDNode *Node,
781 const yaml::StringValue &Source,
782 StringRef TypeString, MIRParserImpl &Parser) {
783 if (!Node)
784 return false;
785 Result = dyn_cast<T>(Node);
786 if (!Result)
787 return Parser.error(Source.SourceRange.Start,
788 "expected a reference to a '" + TypeString +
789 "' metadata node");
790 return false;
791}
792
Francis Visoiu Mistrih57fcd342018-04-25 18:58:06 +0000793template <typename T>
Matthias Braun83947862016-07-13 22:23:23 +0000794bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
Francis Visoiu Mistrih57fcd342018-04-25 18:58:06 +0000795 const T &Object, int FrameIdx) {
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000796 // Debug information can only be attached to stack objects; Fixed stack
797 // objects aren't supported.
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000798 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
Matthias Braun83947862016-07-13 22:23:23 +0000799 if (parseMDNode(PFS, Var, Object.DebugVar) ||
800 parseMDNode(PFS, Expr, Object.DebugExpr) ||
801 parseMDNode(PFS, Loc, Object.DebugLoc))
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000802 return true;
803 if (!Var && !Expr && !Loc)
804 return false;
805 DILocalVariable *DIVar = nullptr;
806 DIExpression *DIExpr = nullptr;
807 DILocation *DILoc = nullptr;
808 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
809 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
810 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
811 return true;
Francis Visoiu Mistrih57fcd342018-04-25 18:58:06 +0000812 PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000813 return false;
814}
815
Matthias Braun74ad41c2016-10-11 03:13:01 +0000816bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
Matthias Braun83947862016-07-13 22:23:23 +0000817 MDNode *&Node, const yaml::StringValue &Source) {
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000818 if (Source.Value.empty())
819 return false;
820 SMDiagnostic Error;
Matthias Braune35861d2016-07-13 23:27:50 +0000821 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000822 return error(Error, Source.SourceRange);
823 return false;
824}
825
Matthias Braun83947862016-07-13 22:23:23 +0000826bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
827 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
828 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
829 const MachineFunction &MF = PFS.MF;
Matthias Braunf1caa282017-12-15 22:22:58 +0000830 const auto &M = *MF.getFunction().getParent();
Alex Lorenzab980492015-07-20 20:51:18 +0000831 SMDiagnostic Error;
832 for (const auto &YamlConstant : YamlMF.Constants) {
Diana Picusd5a00b02017-08-02 11:09:30 +0000833 if (YamlConstant.IsTargetSpecific)
834 // FIXME: Support target-specific constant pools
835 return error(YamlConstant.Value.SourceRange.Start,
836 "Can't parse target-specific constant pool entries yet");
Alex Lorenzab980492015-07-20 20:51:18 +0000837 const Constant *Value = dyn_cast_or_null<Constant>(
838 parseConstantValue(YamlConstant.Value.Value, Error, M));
839 if (!Value)
840 return error(Error, YamlConstant.Value.SourceRange);
841 unsigned Alignment =
842 YamlConstant.Alignment
843 ? YamlConstant.Alignment
844 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
Alex Lorenz60bf5992015-07-30 22:00:17 +0000845 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
846 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
847 .second)
848 return error(YamlConstant.ID.SourceRange.Start,
849 Twine("redefinition of constant pool item '%const.") +
850 Twine(YamlConstant.ID.Value) + "'");
Alex Lorenzab980492015-07-20 20:51:18 +0000851 }
852 return false;
853}
854
Matthias Braun83947862016-07-13 22:23:23 +0000855bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
856 const yaml::MachineJumpTable &YamlJTI) {
857 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000858 for (const auto &Entry : YamlJTI.Entries) {
859 std::vector<MachineBasicBlock *> Blocks;
860 for (const auto &MBBSource : Entry.Blocks) {
861 MachineBasicBlock *MBB = nullptr;
Matthias Braun83947862016-07-13 22:23:23 +0000862 if (parseMBBReference(PFS, MBB, MBBSource.Value))
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000863 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000864 Blocks.push_back(MBB);
865 }
Alex Lorenz31d70682015-07-15 23:38:35 +0000866 unsigned Index = JTI->createJumpTableIndex(Blocks);
Alex Lorenz59ed5912015-07-31 23:13:23 +0000867 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
868 .second)
869 return error(Entry.ID.SourceRange.Start,
870 Twine("redefinition of jump table entry '%jump-table.") +
871 Twine(Entry.ID.Value) + "'");
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000872 }
873 return false;
874}
875
Matthias Braun74ad41c2016-10-11 03:13:01 +0000876bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
Matthias Braun83947862016-07-13 22:23:23 +0000877 MachineBasicBlock *&MBB,
878 const yaml::StringValue &Source) {
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000879 SMDiagnostic Error;
Matthias Braune35861d2016-07-13 23:27:50 +0000880 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000881 return error(Error, Source.SourceRange);
882 return false;
883}
884
Alex Lorenz51af1602015-06-23 22:39:23 +0000885SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
886 SMRange SourceRange) {
887 assert(SourceRange.isValid() && "Invalid source range");
888 SMLoc Loc = SourceRange.Start;
889 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
890 *Loc.getPointer() == '\'';
891 // Translate the location of the error from the location in the MI string to
892 // the corresponding location in the MIR file.
893 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
894 (HasQuote ? 1 : 0));
895
896 // TODO: Translate any source ranges as well.
897 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
898 Error.getFixIts());
899}
900
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000901SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
902 SMRange SourceRange) {
Alex Lorenz09b832c2015-05-29 17:05:41 +0000903 assert(SourceRange.isValid());
904
905 // Translate the location of the error from the location in the llvm IR string
906 // to the corresponding location in the MIR file.
907 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
908 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
909 unsigned Column = Error.getColumnNo();
910 StringRef LineStr = Error.getLineContents();
911 SMLoc Loc = Error.getLoc();
912
913 // Get the full line and adjust the column number by taking the indentation of
914 // LLVM IR into account.
915 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
916 L != E; ++L) {
917 if (L.line_number() == Line) {
918 LineStr = *L;
919 Loc = SMLoc::getFromPointer(LineStr.data());
920 auto Indent = LineStr.find(Error.getLineContents());
921 if (Indent != StringRef::npos)
922 Column += Indent;
923 break;
924 }
925 }
926
927 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
928 Error.getMessage(), LineStr, Error.getRanges(),
929 Error.getFixIts());
930}
931
Alex Lorenz735c47e2015-06-15 20:30:22 +0000932MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
933 : Impl(std::move(Impl)) {}
934
935MIRParser::~MIRParser() {}
936
Matthias Braun7bda1952017-06-06 00:44:35 +0000937std::unique_ptr<Module> MIRParser::parseIRModule() {
938 return Impl->parseIRModule();
939}
Alex Lorenz735c47e2015-06-15 20:30:22 +0000940
Matthias Braun7bda1952017-06-06 00:44:35 +0000941bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
942 return Impl->parseMachineFunctions(M, MMI);
Alex Lorenz735c47e2015-06-15 20:30:22 +0000943}
944
Matt Arsenault5518a022019-12-07 00:06:34 +0530945std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
946 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
947 std::function<void(Function &)> ProcessIRFunction) {
Matthias Braun7e23fc02017-06-06 20:06:57 +0000948 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000949 if (std::error_code EC = FileOrErr.getError()) {
950 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
951 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000952 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000953 }
Matt Arsenault5518a022019-12-07 00:06:34 +0530954 return createMIRParser(std::move(FileOrErr.get()), Context,
955 ProcessIRFunction);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000956}
957
Alex Lorenz735c47e2015-06-15 20:30:22 +0000958std::unique_ptr<MIRParser>
959llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
Matt Arsenault5518a022019-12-07 00:06:34 +0530960 LLVMContext &Context,
961 std::function<void(Function &)> ProcessIRFunction) {
Mehdi Amini05188a62016-09-17 05:41:02 +0000962 auto Filename = Contents->getBufferIdentifier();
Mehdi Amini8d904e92016-09-17 05:33:58 +0000963 if (Context.shouldDiscardValueNames()) {
964 Context.diagnose(DiagnosticInfoMIRParser(
965 DS_Error,
966 SMDiagnostic(
967 Filename, SourceMgr::DK_Error,
968 "Can't read MIR with a Context that discards named Values")));
969 return nullptr;
970 }
Matt Arsenault5518a022019-12-07 00:06:34 +0530971 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
972 std::move(Contents), Filename, Context, ProcessIRFunction));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000973}