blob: 064b2f15d65dad6b8dde562e873a18fb95c3345f [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/StringRef.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000019#include "llvm/ADT/StringMap.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/AsmParser/Parser.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000022#include "llvm/AsmParser/SlotMapping.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000023#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz78d78312015-05-28 22:41:12 +000025#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000026#include "llvm/IR/BasicBlock.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000027#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000028#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000029#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000030#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000031#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000032#include "llvm/Support/LineIterator.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000033#include "llvm/Support/SMLoc.h"
34#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/YAMLTraits.h"
37#include <memory>
38
39using namespace llvm;
40
Alex Lorenz735c47e2015-06-15 20:30:22 +000041namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000042
43/// This class implements the parsing of LLVM IR that's embedded inside a MIR
44/// file.
45class MIRParserImpl {
46 SourceMgr SM;
47 StringRef Filename;
48 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000049 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000050 SlotMapping IRSlots;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000051
52public:
53 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
54 LLVMContext &Context);
55
Alex Lorenz735c47e2015-06-15 20:30:22 +000056 void reportDiagnostic(const SMDiagnostic &Diag);
57
58 /// Report an error with the given message at unknown location.
59 ///
60 /// Always returns true.
61 bool error(const Twine &Message);
62
Alex Lorenz0fd7c622015-06-30 17:55:00 +000063 /// Report a given error with the location translated from the location in an
64 /// embedded string literal to a location in the MIR file.
65 ///
66 /// Always returns true.
67 bool error(const SMDiagnostic &Error, SMRange SourceRange);
68
Alex Lorenz78d78312015-05-28 22:41:12 +000069 /// Try to parse the optional LLVM module and the machine functions in the MIR
70 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000071 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000072 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000073 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000074
75 /// Parse the machine function in the current YAML document.
76 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000077 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
78 /// A dummy IR function is created and inserted into the given module when
79 /// this parameter is true.
80 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000081 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000082 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000083
Alex Lorenz735c47e2015-06-15 20:30:22 +000084 /// Initialize the machine function to the state that's described in the MIR
85 /// file.
86 ///
87 /// Return true if error occurred.
88 bool initializeMachineFunction(MachineFunction &MF);
89
Alex Lorenz4f093bf2015-06-19 17:43:07 +000090 /// Initialize the machine basic block using it's YAML representation.
91 ///
92 /// Return true if an error occurred.
Alex Lorenz33f0aef2015-06-26 16:46:11 +000093 bool initializeMachineBasicBlock(
94 MachineFunction &MF, MachineBasicBlock &MBB,
95 const yaml::MachineBasicBlock &YamlMBB,
96 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
Alex Lorenz4f093bf2015-06-19 17:43:07 +000097
Alex Lorenz54565cf2015-06-24 19:56:10 +000098 bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
99 const yaml::MachineFunction &YamlMF);
100
Alex Lorenz09b832c2015-05-29 17:05:41 +0000101private:
Alex Lorenz51af1602015-06-23 22:39:23 +0000102 /// Return a MIR diagnostic converted from an MI string diagnostic.
103 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
104 SMRange SourceRange);
105
Alex Lorenz09b832c2015-05-29 17:05:41 +0000106 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
107 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
108 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000109
110 /// Create an empty function with the given name.
111 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000112};
113
Alex Lorenz735c47e2015-06-15 20:30:22 +0000114} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000115
116MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
117 StringRef Filename, LLVMContext &Context)
118 : SM(), Filename(Filename), Context(Context) {
119 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
120}
121
Alex Lorenz735c47e2015-06-15 20:30:22 +0000122bool MIRParserImpl::error(const Twine &Message) {
123 Context.diagnose(DiagnosticInfoMIRParser(
124 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
125 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000126}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000127
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000128bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
129 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
130 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
131 return true;
132}
133
Alex Lorenz735c47e2015-06-15 20:30:22 +0000134void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
135 DiagnosticSeverity Kind;
136 switch (Diag.getKind()) {
137 case SourceMgr::DK_Error:
138 Kind = DS_Error;
139 break;
140 case SourceMgr::DK_Warning:
141 Kind = DS_Warning;
142 break;
143 case SourceMgr::DK_Note:
144 Kind = DS_Note;
145 break;
146 }
147 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
148}
149
150static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
151 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
152}
153
154std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000155 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000156 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000157 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000158
159 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000160 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000161 return nullptr;
162 // Create an empty module when the MIR file is empty.
163 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000164 }
165
Alex Lorenz78d78312015-05-28 22:41:12 +0000166 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000167 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000168 // Parse the block scalar manually so that we can return unique pointer
169 // without having to go trough YAML traits.
170 if (const auto *BSN =
171 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000172 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000173 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000174 Context, &IRSlots);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000175 if (!M) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000176 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000177 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000178 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000179 In.nextDocument();
180 if (!In.setCurrentDocument())
181 return M;
182 } else {
183 // Create an new, empty module.
184 M = llvm::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000185 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000186 }
187
188 // Parse the machine functions.
189 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000190 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000191 return nullptr;
192 In.nextDocument();
193 } while (In.setCurrentDocument());
194
195 return M;
196}
197
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000198bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
199 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000200 auto MF = llvm::make_unique<yaml::MachineFunction>();
201 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000202 if (In.error())
203 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000204 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000205 if (Functions.find(FunctionName) != Functions.end())
206 return error(Twine("redefinition of machine function '") + FunctionName +
207 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000208 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000209 if (NoLLVMIR)
210 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000211 else if (!M.getFunction(FunctionName))
212 return error(Twine("function '") + FunctionName +
213 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000214 return false;
215}
216
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000217void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
218 auto &Context = M.getContext();
219 Function *F = cast<Function>(M.getOrInsertFunction(
220 Name, FunctionType::get(Type::getVoidTy(Context), false)));
221 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
222 new UnreachableInst(Context, BB);
223}
224
Alex Lorenz735c47e2015-06-15 20:30:22 +0000225bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
226 auto It = Functions.find(MF.getName());
227 if (It == Functions.end())
228 return error(Twine("no machine function information for function '") +
229 MF.getName() + "' in the MIR file");
230 // TODO: Recreate the machine function.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000231 const yaml::MachineFunction &YamlMF = *It->getValue();
232 if (YamlMF.Alignment)
233 MF.setAlignment(YamlMF.Alignment);
234 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
235 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000236 if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
237 return true;
238
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000239 const auto &F = *MF.getFunction();
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000240 DenseMap<unsigned, MachineBasicBlock *> MBBSlots;
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000241 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
242 const BasicBlock *BB = nullptr;
243 if (!YamlMBB.Name.empty()) {
244 BB = dyn_cast_or_null<BasicBlock>(
245 F.getValueSymbolTable().lookup(YamlMBB.Name));
Alex Lorenz00302df2015-06-19 20:12:03 +0000246 if (!BB)
247 return error(Twine("basic block '") + YamlMBB.Name +
248 "' is not defined in the function '" + MF.getName() + "'");
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000249 }
250 auto *MBB = MF.CreateMachineBasicBlock(BB);
251 MF.insert(MF.end(), MBB);
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000252 bool WasInserted = MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
253 if (!WasInserted)
254 return error(Twine("redefinition of machine basic block with id #") +
255 Twine(YamlMBB.ID));
256 }
257
258 // Initialize the machine basic blocks after creating them all so that the
259 // machine instructions parser can resolve the MBB references.
260 unsigned I = 0;
261 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
262 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
263 MBBSlots))
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000264 return true;
265 }
266 return false;
267}
268
269bool MIRParserImpl::initializeMachineBasicBlock(
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000270 MachineFunction &MF, MachineBasicBlock &MBB,
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000271 const yaml::MachineBasicBlock &YamlMBB,
272 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000273 MBB.setAlignment(YamlMBB.Alignment);
274 if (YamlMBB.AddressTaken)
275 MBB.setHasAddressTaken();
276 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000277 // Parse the instructions.
278 for (const auto &MISource : YamlMBB.Instructions) {
279 SMDiagnostic Error;
Alex Lorenz3708a642015-06-30 17:47:50 +0000280 MachineInstr *MI = nullptr;
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000281 if (parseMachineInstr(MI, SM, MF, MISource.Value, MBBSlots, IRSlots, Error))
282 return error(Error, MISource.SourceRange);
Alex Lorenz3708a642015-06-30 17:47:50 +0000283 MBB.insert(MBB.end(), MI);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000284 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000285 return false;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000286}
287
Alex Lorenz54565cf2015-06-24 19:56:10 +0000288bool MIRParserImpl::initializeRegisterInfo(
289 MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
290 assert(RegInfo.isSSA());
291 if (!YamlMF.IsSSA)
292 RegInfo.leaveSSA();
293 assert(RegInfo.tracksLiveness());
294 if (!YamlMF.TracksRegLiveness)
295 RegInfo.invalidateLiveness();
296 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
297 return false;
298}
299
Alex Lorenz51af1602015-06-23 22:39:23 +0000300SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
301 SMRange SourceRange) {
302 assert(SourceRange.isValid() && "Invalid source range");
303 SMLoc Loc = SourceRange.Start;
304 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
305 *Loc.getPointer() == '\'';
306 // Translate the location of the error from the location in the MI string to
307 // the corresponding location in the MIR file.
308 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
309 (HasQuote ? 1 : 0));
310
311 // TODO: Translate any source ranges as well.
312 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
313 Error.getFixIts());
314}
315
Alex Lorenz09b832c2015-05-29 17:05:41 +0000316SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
317 SMRange SourceRange) {
318 assert(SourceRange.isValid());
319
320 // Translate the location of the error from the location in the llvm IR string
321 // to the corresponding location in the MIR file.
322 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
323 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
324 unsigned Column = Error.getColumnNo();
325 StringRef LineStr = Error.getLineContents();
326 SMLoc Loc = Error.getLoc();
327
328 // Get the full line and adjust the column number by taking the indentation of
329 // LLVM IR into account.
330 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
331 L != E; ++L) {
332 if (L.line_number() == Line) {
333 LineStr = *L;
334 Loc = SMLoc::getFromPointer(LineStr.data());
335 auto Indent = LineStr.find(Error.getLineContents());
336 if (Indent != StringRef::npos)
337 Column += Indent;
338 break;
339 }
340 }
341
342 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
343 Error.getMessage(), LineStr, Error.getRanges(),
344 Error.getFixIts());
345}
346
Alex Lorenz735c47e2015-06-15 20:30:22 +0000347MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
348 : Impl(std::move(Impl)) {}
349
350MIRParser::~MIRParser() {}
351
352std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
353
354bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
355 return Impl->initializeMachineFunction(MF);
356}
357
358std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
359 SMDiagnostic &Error,
360 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000361 auto FileOrErr = MemoryBuffer::getFile(Filename);
362 if (std::error_code EC = FileOrErr.getError()) {
363 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
364 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000365 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000366 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000367 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000368}
369
Alex Lorenz735c47e2015-06-15 20:30:22 +0000370std::unique_ptr<MIRParser>
371llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
372 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000373 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000374 return llvm::make_unique<MIRParser>(
375 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000376}