1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MIRParser/MIRParser.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/AsmParser/Parser.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/MIRYamlMapping.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/Support/LineIterator.h"
31 #include "llvm/Support/SMLoc.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/YAMLTraits.h"
41 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
47 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
50 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
51 LLVMContext &Context);
53 void reportDiagnostic(const SMDiagnostic &Diag);
55 /// Report an error with the given message at unknown location.
57 /// Always returns true.
58 bool error(const Twine &Message);
60 /// Try to parse the optional LLVM module and the machine functions in the MIR
63 /// Return null if an error occurred.
64 std::unique_ptr<Module> parse();
66 /// Parse the machine function in the current YAML document.
68 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
69 /// A dummy IR function is created and inserted into the given module when
70 /// this parameter is true.
72 /// Return true if an error occurred.
73 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
75 /// Initialize the machine function to the state that's described in the MIR
78 /// Return true if error occurred.
79 bool initializeMachineFunction(MachineFunction &MF);
81 /// Initialize the machine basic block using it's YAML representation.
83 /// Return true if an error occurred.
84 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
85 const yaml::MachineBasicBlock &YamlMBB);
87 bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
88 const yaml::MachineFunction &YamlMF);
91 /// Return a MIR diagnostic converted from an MI string diagnostic.
92 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
95 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
96 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
99 /// Create an empty function with the given name.
100 void createDummyFunction(StringRef Name, Module &M);
103 } // end namespace llvm
105 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
106 StringRef Filename, LLVMContext &Context)
107 : SM(), Filename(Filename), Context(Context) {
108 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
111 bool MIRParserImpl::error(const Twine &Message) {
112 Context.diagnose(DiagnosticInfoMIRParser(
113 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
117 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
118 DiagnosticSeverity Kind;
119 switch (Diag.getKind()) {
120 case SourceMgr::DK_Error:
123 case SourceMgr::DK_Warning:
126 case SourceMgr::DK_Note:
130 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
133 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
134 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
137 std::unique_ptr<Module> MIRParserImpl::parse() {
138 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
139 /*Ctxt=*/nullptr, handleYAMLDiag, this);
142 if (!In.setCurrentDocument()) {
145 // Create an empty module when the MIR file is empty.
146 return llvm::make_unique<Module>(Filename, Context);
149 std::unique_ptr<Module> M;
150 bool NoLLVMIR = false;
151 // Parse the block scalar manually so that we can return unique pointer
152 // without having to go trough YAML traits.
153 if (const auto *BSN =
154 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
156 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
159 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
163 if (!In.setCurrentDocument())
166 // Create an new, empty module.
167 M = llvm::make_unique<Module>(Filename, Context);
171 // Parse the machine functions.
173 if (parseMachineFunction(In, *M, NoLLVMIR))
176 } while (In.setCurrentDocument());
181 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
183 auto MF = llvm::make_unique<yaml::MachineFunction>();
184 yaml::yamlize(In, *MF, false);
187 auto FunctionName = MF->Name;
188 if (Functions.find(FunctionName) != Functions.end())
189 return error(Twine("redefinition of machine function '") + FunctionName +
191 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
193 createDummyFunction(FunctionName, M);
194 else if (!M.getFunction(FunctionName))
195 return error(Twine("function '") + FunctionName +
196 "' isn't defined in the provided LLVM IR");
200 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
201 auto &Context = M.getContext();
202 Function *F = cast<Function>(M.getOrInsertFunction(
203 Name, FunctionType::get(Type::getVoidTy(Context), false)));
204 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
205 new UnreachableInst(Context, BB);
208 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
209 auto It = Functions.find(MF.getName());
210 if (It == Functions.end())
211 return error(Twine("no machine function information for function '") +
212 MF.getName() + "' in the MIR file");
213 // TODO: Recreate the machine function.
214 const yaml::MachineFunction &YamlMF = *It->getValue();
215 if (YamlMF.Alignment)
216 MF.setAlignment(YamlMF.Alignment);
217 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
218 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
219 if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
222 const auto &F = *MF.getFunction();
223 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
224 const BasicBlock *BB = nullptr;
225 if (!YamlMBB.Name.empty()) {
226 BB = dyn_cast_or_null<BasicBlock>(
227 F.getValueSymbolTable().lookup(YamlMBB.Name));
229 return error(Twine("basic block '") + YamlMBB.Name +
230 "' is not defined in the function '" + MF.getName() + "'");
232 auto *MBB = MF.CreateMachineBasicBlock(BB);
233 MF.insert(MF.end(), MBB);
234 if (initializeMachineBasicBlock(MF, *MBB, YamlMBB))
240 bool MIRParserImpl::initializeMachineBasicBlock(
241 MachineFunction &MF, MachineBasicBlock &MBB,
242 const yaml::MachineBasicBlock &YamlMBB) {
243 MBB.setAlignment(YamlMBB.Alignment);
244 if (YamlMBB.AddressTaken)
245 MBB.setHasAddressTaken();
246 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
247 // Parse the instructions.
248 for (const auto &MISource : YamlMBB.Instructions) {
250 if (auto *MI = parseMachineInstr(SM, MF, MISource.Value, Error)) {
251 MBB.insert(MBB.end(), MI);
254 reportDiagnostic(diagFromMIStringDiag(Error, MISource.SourceRange));
260 bool MIRParserImpl::initializeRegisterInfo(
261 MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
262 assert(RegInfo.isSSA());
265 assert(RegInfo.tracksLiveness());
266 if (!YamlMF.TracksRegLiveness)
267 RegInfo.invalidateLiveness();
268 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
272 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
273 SMRange SourceRange) {
274 assert(SourceRange.isValid() && "Invalid source range");
275 SMLoc Loc = SourceRange.Start;
276 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
277 *Loc.getPointer() == '\'';
278 // Translate the location of the error from the location in the MI string to
279 // the corresponding location in the MIR file.
280 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
283 // TODO: Translate any source ranges as well.
284 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
288 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
289 SMRange SourceRange) {
290 assert(SourceRange.isValid());
292 // Translate the location of the error from the location in the llvm IR string
293 // to the corresponding location in the MIR file.
294 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
295 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
296 unsigned Column = Error.getColumnNo();
297 StringRef LineStr = Error.getLineContents();
298 SMLoc Loc = Error.getLoc();
300 // Get the full line and adjust the column number by taking the indentation of
301 // LLVM IR into account.
302 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
304 if (L.line_number() == Line) {
306 Loc = SMLoc::getFromPointer(LineStr.data());
307 auto Indent = LineStr.find(Error.getLineContents());
308 if (Indent != StringRef::npos)
314 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
315 Error.getMessage(), LineStr, Error.getRanges(),
319 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
320 : Impl(std::move(Impl)) {}
322 MIRParser::~MIRParser() {}
324 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
326 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
327 return Impl->initializeMachineFunction(MF);
330 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
332 LLVMContext &Context) {
333 auto FileOrErr = MemoryBuffer::getFile(Filename);
334 if (std::error_code EC = FileOrErr.getError()) {
335 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
336 "Could not open input file: " + EC.message());
339 return createMIRParser(std::move(FileOrErr.get()), Context);
342 std::unique_ptr<MIRParser>
343 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
344 LLVMContext &Context) {
345 auto Filename = Contents->getBufferIdentifier();
346 return llvm::make_unique<MIRParser>(
347 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));