blob: 69aae373f2e455ee94c294f5ea6765ad8a7f33b8 [file] [log] [blame]
Alex Lorenz2bdb4e12015-05-27 18:02:19 +00001//===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the class that parses the optional LLVM IR and machine
11// functions that are stored in MIR files.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/MIRParser/MIRParser.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000016#include "MIParser.h"
Alex Lorenz33f0aef2015-06-26 16:46:11 +000017#include "llvm/ADT/DenseMap.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000018#include "llvm/ADT/STLExtras.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000019#include "llvm/ADT/StringMap.h"
20#include "llvm/ADT/StringRef.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000021#include "llvm/AsmParser/Parser.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000022#include "llvm/AsmParser/SlotMapping.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000023#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24#include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
25#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenzab980492015-07-20 20:51:18 +000026#include "llvm/CodeGen/MachineConstantPool.h"
Alex Lorenz60541c12015-07-09 19:55:27 +000027#include "llvm/CodeGen/MachineFrameInfo.h"
Quentin Colombet876ddf82016-04-08 16:40:43 +000028#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenzdf9e3c62015-08-19 00:13:25 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000030#include "llvm/CodeGen/MachineRegisterInfo.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"
43#include <memory>
44
45using namespace llvm;
46
Alex Lorenz735c47e2015-06-15 20:30:22 +000047namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000048
49/// This class implements the parsing of LLVM IR that's embedded inside a MIR
50/// file.
51class MIRParserImpl {
52 SourceMgr SM;
53 StringRef Filename;
54 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000055 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000056 SlotMapping IRSlots;
Alex Lorenz28148ba2015-07-09 22:23:13 +000057 /// Maps from register class names to register classes.
58 StringMap<const TargetRegisterClass *> Names2RegClasses;
Quentin Colombet876ddf82016-04-08 16:40:43 +000059 /// Maps from register bank names to register banks.
60 StringMap<const RegisterBank *> Names2RegBanks;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000061
62public:
63 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
64 LLVMContext &Context);
65
Alex Lorenz735c47e2015-06-15 20:30:22 +000066 void reportDiagnostic(const SMDiagnostic &Diag);
67
68 /// Report an error with the given message at unknown location.
69 ///
70 /// Always returns true.
71 bool error(const Twine &Message);
72
Alex Lorenzb1f9ce82015-07-08 20:22:20 +000073 /// Report an error with the given message at the given location.
74 ///
75 /// Always returns true.
76 bool error(SMLoc Loc, const Twine &Message);
77
Alex Lorenz0fd7c622015-06-30 17:55:00 +000078 /// Report a given error with the location translated from the location in an
79 /// embedded string literal to a location in the MIR file.
80 ///
81 /// Always returns true.
82 bool error(const SMDiagnostic &Error, SMRange SourceRange);
83
Alex Lorenz78d78312015-05-28 22:41:12 +000084 /// Try to parse the optional LLVM module and the machine functions in the MIR
85 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000086 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000087 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000088 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000089
90 /// Parse the machine function in the current YAML document.
91 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000092 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
93 /// A dummy IR function is created and inserted into the given module when
94 /// this parameter is true.
95 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000096 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000097 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000098
Alex Lorenz735c47e2015-06-15 20:30:22 +000099 /// Initialize the machine function to the state that's described in the MIR
100 /// file.
101 ///
102 /// Return true if error occurred.
103 bool initializeMachineFunction(MachineFunction &MF);
104
Alex Lorenzdb07c402015-07-28 16:48:37 +0000105 bool initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000106 const yaml::MachineFunction &YamlMF,
107 PerFunctionMIParsingState &PFS);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000108
Alex Lorenzc4838082015-08-11 00:32:49 +0000109 void inferRegisterInfo(MachineFunction &MF,
110 const yaml::MachineFunction &YamlMF);
111
Alex Lorenzdb07c402015-07-28 16:48:37 +0000112 bool initializeFrameInfo(MachineFunction &MF,
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000113 const yaml::MachineFunction &YamlMF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000114 PerFunctionMIParsingState &PFS);
115
116 bool parseCalleeSavedRegister(MachineFunction &MF,
117 PerFunctionMIParsingState &PFS,
118 std::vector<CalleeSavedInfo> &CSIInfo,
119 const yaml::StringValue &RegisterSource,
120 int FrameIdx);
Alex Lorenz60541c12015-07-09 19:55:27 +0000121
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000122 bool parseStackObjectsDebugInfo(MachineFunction &MF,
123 PerFunctionMIParsingState &PFS,
124 const yaml::MachineStackObject &Object,
125 int FrameIdx);
126
Alex Lorenzab980492015-07-20 20:51:18 +0000127 bool initializeConstantPool(MachineConstantPool &ConstantPool,
128 const yaml::MachineFunction &YamlMF,
129 const MachineFunction &MF,
130 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
131
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000132 bool initializeJumpTableInfo(MachineFunction &MF,
133 const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000134 PerFunctionMIParsingState &PFS);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000135
Alex Lorenz09b832c2015-05-29 17:05:41 +0000136private:
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000137 bool parseMDNode(MDNode *&Node, const yaml::StringValue &Source,
138 MachineFunction &MF, const PerFunctionMIParsingState &PFS);
139
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000140 bool parseMBBReference(MachineBasicBlock *&MBB,
141 const yaml::StringValue &Source, MachineFunction &MF,
142 const PerFunctionMIParsingState &PFS);
143
Alex Lorenz51af1602015-06-23 22:39:23 +0000144 /// Return a MIR diagnostic converted from an MI string diagnostic.
145 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
146 SMRange SourceRange);
147
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000148 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
149 /// block scalar string.
150 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
151 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000152
153 /// Create an empty function with the given name.
154 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000155
156 void initNames2RegClasses(const MachineFunction &MF);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000157 void initNames2RegBanks(const MachineFunction &MF);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000158
159 /// Check if the given identifier is a name of a register class.
160 ///
161 /// Return null if the name isn't a register class.
162 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
163 StringRef Name);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000164
165 /// Check if the given identifier is a name of a register bank.
166 ///
167 /// Return null if the name isn't a register bank.
168 const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000169};
170
Alex Lorenz735c47e2015-06-15 20:30:22 +0000171} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000172
173MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
174 StringRef Filename, LLVMContext &Context)
175 : SM(), Filename(Filename), Context(Context) {
176 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
177}
178
Alex Lorenz735c47e2015-06-15 20:30:22 +0000179bool MIRParserImpl::error(const Twine &Message) {
180 Context.diagnose(DiagnosticInfoMIRParser(
181 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
182 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000183}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000184
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000185bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
186 Context.diagnose(DiagnosticInfoMIRParser(
187 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
188 return true;
189}
190
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000191bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
192 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
193 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
194 return true;
195}
196
Alex Lorenz735c47e2015-06-15 20:30:22 +0000197void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
198 DiagnosticSeverity Kind;
199 switch (Diag.getKind()) {
200 case SourceMgr::DK_Error:
201 Kind = DS_Error;
202 break;
203 case SourceMgr::DK_Warning:
204 Kind = DS_Warning;
205 break;
206 case SourceMgr::DK_Note:
207 Kind = DS_Note;
208 break;
209 }
210 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
211}
212
213static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
214 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
215}
216
217std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000218 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000219 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000220 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000221
222 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000223 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000224 return nullptr;
225 // Create an empty module when the MIR file is empty.
226 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000227 }
228
Alex Lorenz78d78312015-05-28 22:41:12 +0000229 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000230 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000231 // Parse the block scalar manually so that we can return unique pointer
232 // without having to go trough YAML traits.
233 if (const auto *BSN =
234 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000235 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000236 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000237 Context, &IRSlots);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000238 if (!M) {
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000239 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000240 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000241 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000242 In.nextDocument();
243 if (!In.setCurrentDocument())
244 return M;
245 } else {
246 // Create an new, empty module.
247 M = llvm::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000248 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000249 }
250
251 // Parse the machine functions.
252 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000253 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000254 return nullptr;
255 In.nextDocument();
256 } while (In.setCurrentDocument());
257
258 return M;
259}
260
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000261bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
262 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000263 auto MF = llvm::make_unique<yaml::MachineFunction>();
264 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000265 if (In.error())
266 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000267 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000268 if (Functions.find(FunctionName) != Functions.end())
269 return error(Twine("redefinition of machine function '") + FunctionName +
270 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000271 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000272 if (NoLLVMIR)
273 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000274 else if (!M.getFunction(FunctionName))
275 return error(Twine("function '") + FunctionName +
276 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000277 return false;
278}
279
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000280void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
281 auto &Context = M.getContext();
282 Function *F = cast<Function>(M.getOrInsertFunction(
283 Name, FunctionType::get(Type::getVoidTy(Context), false)));
284 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
285 new UnreachableInst(Context, BB);
286}
287
Alex Lorenz735c47e2015-06-15 20:30:22 +0000288bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
289 auto It = Functions.find(MF.getName());
290 if (It == Functions.end())
291 return error(Twine("no machine function information for function '") +
292 MF.getName() + "' in the MIR file");
293 // TODO: Recreate the machine function.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000294 const yaml::MachineFunction &YamlMF = *It->getValue();
295 if (YamlMF.Alignment)
296 MF.setAlignment(YamlMF.Alignment);
297 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
298 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
Derek Schuffad154c82016-03-28 17:05:30 +0000299 if (YamlMF.AllVRegsAllocated)
300 MF.getProperties().set(MachineFunctionProperties::Property::AllVRegsAllocated);
Alex Lorenz53464512015-07-10 22:51:20 +0000301 PerFunctionMIParsingState PFS;
Alex Lorenzdb07c402015-07-28 16:48:37 +0000302 if (initializeRegisterInfo(MF, YamlMF, PFS))
Alex Lorenz54565cf2015-06-24 19:56:10 +0000303 return true;
Alex Lorenzab980492015-07-20 20:51:18 +0000304 if (!YamlMF.Constants.empty()) {
305 auto *ConstantPool = MF.getConstantPool();
306 assert(ConstantPool && "Constant pool must be created");
307 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
308 PFS.ConstantPoolSlots))
309 return true;
310 }
Alex Lorenz54565cf2015-06-24 19:56:10 +0000311
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000312 SMDiagnostic Error;
313 if (parseMachineBasicBlockDefinitions(MF, YamlMF.Body.Value.Value, PFS,
314 IRSlots, Error)) {
315 reportDiagnostic(
316 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
317 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000318 }
319
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000320 if (MF.empty())
Alex Lorenzc8704b02015-07-09 21:21:33 +0000321 return error(Twine("machine function '") + Twine(MF.getName()) +
322 "' requires at least one machine basic block in its body");
Alex Lorenza6f9a372015-07-29 21:09:09 +0000323 // Initialize the frame information after creating all the MBBs so that the
324 // MBB references in the frame information can be resolved.
325 if (initializeFrameInfo(MF, YamlMF, PFS))
326 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000327 // Initialize the jump table after creating all the MBBs so that the MBB
328 // references can be resolved.
329 if (!YamlMF.JumpTableInfo.Entries.empty() &&
330 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
331 return true;
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000332 // Parse the machine instructions after creating all of the MBBs so that the
333 // parser can resolve the MBB references.
334 if (parseMachineInstructions(MF, YamlMF.Body.Value.Value, PFS, IRSlots,
335 Error)) {
336 reportDiagnostic(
337 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
338 return true;
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000339 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000340 inferRegisterInfo(MF, YamlMF);
Alex Lorenzc7bf2042015-07-24 17:44:49 +0000341 // FIXME: This is a temporary workaround until the reserved registers can be
342 // serialized.
343 MF.getRegInfo().freezeReservedRegs(MF);
344 MF.verify();
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000345 return false;
346}
347
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000348bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000349 const yaml::MachineFunction &YamlMF,
350 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000351 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Alex Lorenz54565cf2015-06-24 19:56:10 +0000352 assert(RegInfo.isSSA());
353 if (!YamlMF.IsSSA)
354 RegInfo.leaveSSA();
355 assert(RegInfo.tracksLiveness());
356 if (!YamlMF.TracksRegLiveness)
357 RegInfo.invalidateLiveness();
358 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000359
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000360 SMDiagnostic Error;
Alex Lorenz28148ba2015-07-09 22:23:13 +0000361 // Parse the virtual register information.
362 for (const auto &VReg : YamlMF.VirtualRegisters) {
Quentin Colombet050b2112016-03-08 01:17:03 +0000363 unsigned Reg;
364 if (StringRef(VReg.Class.Value).equals("_")) {
365 // This is a generic virtual register.
366 // The size will be set appropriately when we reach the definition.
367 Reg = RegInfo.createGenericVirtualRegister(/*Size*/ 1);
368 } else {
369 const auto *RC = getRegClass(MF, VReg.Class.Value);
Quentin Colombet876ddf82016-04-08 16:40:43 +0000370 if (RC) {
371 Reg = RegInfo.createVirtualRegister(RC);
372 } else {
373 const auto *RegBank = getRegBank(MF, VReg.Class.Value);
374 if (!RegBank)
375 return error(
376 VReg.Class.SourceRange.Start,
377 Twine("use of undefined register class or register bank '") +
378 VReg.Class.Value + "'");
379 Reg = RegInfo.createGenericVirtualRegister(/*Size*/ 1);
380 RegInfo.setRegBank(Reg, *RegBank);
381 }
Quentin Colombet050b2112016-03-08 01:17:03 +0000382 }
Alex Lorenza06c0c62015-07-30 21:54:10 +0000383 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
384 .second)
385 return error(VReg.ID.SourceRange.Start,
386 Twine("redefinition of virtual register '%") +
387 Twine(VReg.ID.Value) + "'");
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000388 if (!VReg.PreferredRegister.Value.empty()) {
389 unsigned PreferredReg = 0;
390 if (parseNamedRegisterReference(PreferredReg, SM, MF,
391 VReg.PreferredRegister.Value, PFS,
392 IRSlots, Error))
393 return error(Error, VReg.PreferredRegister.SourceRange);
394 RegInfo.setSimpleHint(Reg, PreferredReg);
395 }
Alex Lorenz28148ba2015-07-09 22:23:13 +0000396 }
Alex Lorenz12045a42015-07-27 17:42:45 +0000397
398 // Parse the liveins.
399 for (const auto &LiveIn : YamlMF.LiveIns) {
400 unsigned Reg = 0;
401 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
402 IRSlots, Error))
403 return error(Error, LiveIn.Register.SourceRange);
404 unsigned VReg = 0;
405 if (!LiveIn.VirtualRegister.Value.empty()) {
406 if (parseVirtualRegisterReference(
407 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
408 return error(Error, LiveIn.VirtualRegister.SourceRange);
409 }
410 RegInfo.addLiveIn(Reg, VReg);
411 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000412
413 // Parse the callee saved register mask.
414 BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
415 if (!YamlMF.CalleeSavedRegisters)
416 return false;
417 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
418 unsigned Reg = 0;
419 if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
420 Error))
421 return error(Error, RegSource.SourceRange);
422 CalleeSavedRegisterMask[Reg] = true;
423 }
424 RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
Alex Lorenz54565cf2015-06-24 19:56:10 +0000425 return false;
426}
427
Alex Lorenzc4838082015-08-11 00:32:49 +0000428void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
429 const yaml::MachineFunction &YamlMF) {
430 if (YamlMF.CalleeSavedRegisters)
431 return;
432 for (const MachineBasicBlock &MBB : MF) {
433 for (const MachineInstr &MI : MBB) {
434 for (const MachineOperand &MO : MI.operands()) {
435 if (!MO.isRegMask())
436 continue;
437 MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
438 }
439 }
440 }
441}
442
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000443bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000444 const yaml::MachineFunction &YamlMF,
445 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000446 MachineFrameInfo &MFI = *MF.getFrameInfo();
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000447 const Function &F = *MF.getFunction();
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000448 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
Alex Lorenz60541c12015-07-09 19:55:27 +0000449 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
450 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
451 MFI.setHasStackMap(YamlMFI.HasStackMap);
452 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
453 MFI.setStackSize(YamlMFI.StackSize);
454 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
455 if (YamlMFI.MaxAlignment)
456 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
457 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
458 MFI.setHasCalls(YamlMFI.HasCalls);
459 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
460 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
461 MFI.setHasVAStart(YamlMFI.HasVAStart);
462 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
Alex Lorenza6f9a372015-07-29 21:09:09 +0000463 if (!YamlMFI.SavePoint.Value.empty()) {
464 MachineBasicBlock *MBB = nullptr;
465 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
466 return true;
467 MFI.setSavePoint(MBB);
468 }
469 if (!YamlMFI.RestorePoint.Value.empty()) {
470 MachineBasicBlock *MBB = nullptr;
471 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
472 return true;
473 MFI.setRestorePoint(MBB);
474 }
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000475
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000476 std::vector<CalleeSavedInfo> CSIInfo;
Alex Lorenzde491f02015-07-13 18:07:26 +0000477 // Initialize the fixed frame objects.
478 for (const auto &Object : YamlMF.FixedStackObjects) {
479 int ObjectIdx;
480 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
481 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
482 Object.IsImmutable, Object.IsAliased);
483 else
484 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
485 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
Alex Lorenz1d9a3032015-08-10 23:45:02 +0000486 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
487 ObjectIdx))
488 .second)
489 return error(Object.ID.SourceRange.Start,
490 Twine("redefinition of fixed stack object '%fixed-stack.") +
491 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000492 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
493 ObjectIdx))
494 return true;
Alex Lorenzde491f02015-07-13 18:07:26 +0000495 }
496
497 // Initialize the ordinary frame objects.
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000498 for (const auto &Object : YamlMF.StackObjects) {
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000499 int ObjectIdx;
Alex Lorenz37643a02015-07-15 22:14:49 +0000500 const AllocaInst *Alloca = nullptr;
501 const yaml::StringValue &Name = Object.Name;
502 if (!Name.Value.empty()) {
503 Alloca = dyn_cast_or_null<AllocaInst>(
504 F.getValueSymbolTable().lookup(Name.Value));
505 if (!Alloca)
506 return error(Name.SourceRange.Start,
507 "alloca instruction named '" + Name.Value +
508 "' isn't defined in the function '" + F.getName() +
509 "'");
510 }
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000511 if (Object.Type == yaml::MachineStackObject::VariableSized)
Alex Lorenz37643a02015-07-15 22:14:49 +0000512 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000513 else
514 ObjectIdx = MFI.CreateStackObject(
515 Object.Size, Object.Alignment,
Alex Lorenz37643a02015-07-15 22:14:49 +0000516 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000517 MFI.setObjectOffset(ObjectIdx, Object.Offset);
Alex Lorenzc5d35ba2015-08-10 23:50:41 +0000518 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
519 .second)
520 return error(Object.ID.SourceRange.Start,
521 Twine("redefinition of stack object '%stack.") +
522 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000523 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
524 ObjectIdx))
525 return true;
Alex Lorenza56ba6a2015-08-17 22:17:42 +0000526 if (Object.LocalOffset)
527 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000528 if (parseStackObjectsDebugInfo(MF, PFS, Object, ObjectIdx))
529 return true;
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000530 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000531 MFI.setCalleeSavedInfo(CSIInfo);
532 if (!CSIInfo.empty())
533 MFI.setCalleeSavedInfoValid(true);
Alex Lorenza314d812015-08-18 22:26:26 +0000534
535 // Initialize the various stack object references after initializing the
536 // stack objects.
537 if (!YamlMFI.StackProtector.Value.empty()) {
538 SMDiagnostic Error;
539 int FI;
540 if (parseStackObjectReference(FI, SM, MF, YamlMFI.StackProtector.Value, PFS,
541 IRSlots, Error))
542 return error(Error, YamlMFI.StackProtector.SourceRange);
543 MFI.setStackProtectorIndex(FI);
544 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000545 return false;
546}
547
548bool MIRParserImpl::parseCalleeSavedRegister(
549 MachineFunction &MF, PerFunctionMIParsingState &PFS,
550 std::vector<CalleeSavedInfo> &CSIInfo,
551 const yaml::StringValue &RegisterSource, int FrameIdx) {
552 if (RegisterSource.Value.empty())
553 return false;
554 unsigned Reg = 0;
555 SMDiagnostic Error;
556 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
557 IRSlots, Error))
558 return error(Error, RegisterSource.SourceRange);
559 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
Alex Lorenz60541c12015-07-09 19:55:27 +0000560 return false;
561}
562
Alex Lorenzdf9e3c62015-08-19 00:13:25 +0000563/// Verify that given node is of a certain type. Return true on error.
564template <typename T>
565static bool typecheckMDNode(T *&Result, MDNode *Node,
566 const yaml::StringValue &Source,
567 StringRef TypeString, MIRParserImpl &Parser) {
568 if (!Node)
569 return false;
570 Result = dyn_cast<T>(Node);
571 if (!Result)
572 return Parser.error(Source.SourceRange.Start,
573 "expected a reference to a '" + TypeString +
574 "' metadata node");
575 return false;
576}
577
578bool MIRParserImpl::parseStackObjectsDebugInfo(
579 MachineFunction &MF, PerFunctionMIParsingState &PFS,
580 const yaml::MachineStackObject &Object, int FrameIdx) {
581 // Debug information can only be attached to stack objects; Fixed stack
582 // objects aren't supported.
583 assert(FrameIdx >= 0 && "Expected a stack object frame index");
584 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
585 if (parseMDNode(Var, Object.DebugVar, MF, PFS) ||
586 parseMDNode(Expr, Object.DebugExpr, MF, PFS) ||
587 parseMDNode(Loc, Object.DebugLoc, MF, PFS))
588 return true;
589 if (!Var && !Expr && !Loc)
590 return false;
591 DILocalVariable *DIVar = nullptr;
592 DIExpression *DIExpr = nullptr;
593 DILocation *DILoc = nullptr;
594 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
595 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
596 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
597 return true;
598 MF.getMMI().setVariableDbgInfo(DIVar, DIExpr, unsigned(FrameIdx), DILoc);
599 return false;
600}
601
602bool MIRParserImpl::parseMDNode(MDNode *&Node, const yaml::StringValue &Source,
603 MachineFunction &MF,
604 const PerFunctionMIParsingState &PFS) {
605 if (Source.Value.empty())
606 return false;
607 SMDiagnostic Error;
608 if (llvm::parseMDNode(Node, SM, MF, Source.Value, PFS, IRSlots, Error))
609 return error(Error, Source.SourceRange);
610 return false;
611}
612
Alex Lorenzab980492015-07-20 20:51:18 +0000613bool MIRParserImpl::initializeConstantPool(
614 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
615 const MachineFunction &MF,
616 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
617 const auto &M = *MF.getFunction()->getParent();
618 SMDiagnostic Error;
619 for (const auto &YamlConstant : YamlMF.Constants) {
620 const Constant *Value = dyn_cast_or_null<Constant>(
621 parseConstantValue(YamlConstant.Value.Value, Error, M));
622 if (!Value)
623 return error(Error, YamlConstant.Value.SourceRange);
624 unsigned Alignment =
625 YamlConstant.Alignment
626 ? YamlConstant.Alignment
627 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
Alex Lorenz60bf5992015-07-30 22:00:17 +0000628 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
629 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
630 .second)
631 return error(YamlConstant.ID.SourceRange.Start,
632 Twine("redefinition of constant pool item '%const.") +
633 Twine(YamlConstant.ID.Value) + "'");
Alex Lorenzab980492015-07-20 20:51:18 +0000634 }
635 return false;
636}
637
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000638bool MIRParserImpl::initializeJumpTableInfo(
639 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000640 PerFunctionMIParsingState &PFS) {
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000641 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000642 for (const auto &Entry : YamlJTI.Entries) {
643 std::vector<MachineBasicBlock *> Blocks;
644 for (const auto &MBBSource : Entry.Blocks) {
645 MachineBasicBlock *MBB = nullptr;
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000646 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
647 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000648 Blocks.push_back(MBB);
649 }
Alex Lorenz31d70682015-07-15 23:38:35 +0000650 unsigned Index = JTI->createJumpTableIndex(Blocks);
Alex Lorenz59ed5912015-07-31 23:13:23 +0000651 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
652 .second)
653 return error(Entry.ID.SourceRange.Start,
654 Twine("redefinition of jump table entry '%jump-table.") +
655 Twine(Entry.ID.Value) + "'");
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000656 }
657 return false;
658}
659
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000660bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
661 const yaml::StringValue &Source,
662 MachineFunction &MF,
663 const PerFunctionMIParsingState &PFS) {
664 SMDiagnostic Error;
665 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
666 return error(Error, Source.SourceRange);
667 return false;
668}
669
Alex Lorenz51af1602015-06-23 22:39:23 +0000670SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
671 SMRange SourceRange) {
672 assert(SourceRange.isValid() && "Invalid source range");
673 SMLoc Loc = SourceRange.Start;
674 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
675 *Loc.getPointer() == '\'';
676 // Translate the location of the error from the location in the MI string to
677 // the corresponding location in the MIR file.
678 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
679 (HasQuote ? 1 : 0));
680
681 // TODO: Translate any source ranges as well.
682 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
683 Error.getFixIts());
684}
685
Alex Lorenz9b62cf62015-08-13 20:30:11 +0000686SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
687 SMRange SourceRange) {
Alex Lorenz09b832c2015-05-29 17:05:41 +0000688 assert(SourceRange.isValid());
689
690 // Translate the location of the error from the location in the llvm IR string
691 // to the corresponding location in the MIR file.
692 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
693 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
694 unsigned Column = Error.getColumnNo();
695 StringRef LineStr = Error.getLineContents();
696 SMLoc Loc = Error.getLoc();
697
698 // Get the full line and adjust the column number by taking the indentation of
699 // LLVM IR into account.
700 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
701 L != E; ++L) {
702 if (L.line_number() == Line) {
703 LineStr = *L;
704 Loc = SMLoc::getFromPointer(LineStr.data());
705 auto Indent = LineStr.find(Error.getLineContents());
706 if (Indent != StringRef::npos)
707 Column += Indent;
708 break;
709 }
710 }
711
712 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
713 Error.getMessage(), LineStr, Error.getRanges(),
714 Error.getFixIts());
715}
716
Alex Lorenz28148ba2015-07-09 22:23:13 +0000717void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
718 if (!Names2RegClasses.empty())
719 return;
720 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
721 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
722 const auto *RC = TRI->getRegClass(I);
723 Names2RegClasses.insert(
724 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
725 }
726}
727
Quentin Colombet876ddf82016-04-08 16:40:43 +0000728void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) {
729 if (!Names2RegBanks.empty())
730 return;
731 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
732 // If the target does not support GlobalISel, we may not have a
733 // register bank info.
734 if (!RBI)
735 return;
736 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
737 const auto &RegBank = RBI->getRegBank(I);
738 Names2RegBanks.insert(
739 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
740 }
741}
742
Alex Lorenz28148ba2015-07-09 22:23:13 +0000743const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
744 StringRef Name) {
745 initNames2RegClasses(MF);
746 auto RegClassInfo = Names2RegClasses.find(Name);
747 if (RegClassInfo == Names2RegClasses.end())
748 return nullptr;
749 return RegClassInfo->getValue();
750}
751
Quentin Colombet876ddf82016-04-08 16:40:43 +0000752const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF,
753 StringRef Name) {
754 initNames2RegBanks(MF);
755 auto RegBankInfo = Names2RegBanks.find(Name);
756 if (RegBankInfo == Names2RegBanks.end())
757 return nullptr;
758 return RegBankInfo->getValue();
759}
760
Alex Lorenz735c47e2015-06-15 20:30:22 +0000761MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
762 : Impl(std::move(Impl)) {}
763
764MIRParser::~MIRParser() {}
765
766std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
767
768bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
769 return Impl->initializeMachineFunction(MF);
770}
771
772std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
773 SMDiagnostic &Error,
774 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000775 auto FileOrErr = MemoryBuffer::getFile(Filename);
776 if (std::error_code EC = FileOrErr.getError()) {
777 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
778 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000779 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000780 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000781 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000782}
783
Alex Lorenz735c47e2015-06-15 20:30:22 +0000784std::unique_ptr<MIRParser>
785llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
786 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000787 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000788 return llvm::make_unique<MIRParser>(
789 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000790}