MIR Serialization: Print and parse simple machine function attributes.
[oota-llvm.git] / lib / CodeGen / MIRParser / MIRParser.cpp
1 //===- 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"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/AsmParser/Parser.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/LineIterator.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/YAMLTraits.h"
31 #include <memory>
32
33 using namespace llvm;
34
35 namespace llvm {
36
37 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
38 /// file.
39 class MIRParserImpl {
40   SourceMgr SM;
41   StringRef Filename;
42   LLVMContext &Context;
43   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
44
45 public:
46   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
47                 LLVMContext &Context);
48
49   void reportDiagnostic(const SMDiagnostic &Diag);
50
51   /// Report an error with the given message at unknown location.
52   ///
53   /// Always returns true.
54   bool error(const Twine &Message);
55
56   /// Try to parse the optional LLVM module and the machine functions in the MIR
57   /// file.
58   ///
59   /// Return null if an error occurred.
60   std::unique_ptr<Module> parse();
61
62   /// Parse the machine function in the current YAML document.
63   ///
64   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
65   /// A dummy IR function is created and inserted into the given module when
66   /// this parameter is true.
67   ///
68   /// Return true if an error occurred.
69   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
70
71   /// Initialize the machine function to the state that's described in the MIR
72   /// file.
73   ///
74   /// Return true if error occurred.
75   bool initializeMachineFunction(MachineFunction &MF);
76
77 private:
78   /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
79   SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
80                                         SMRange SourceRange);
81
82   /// Create an empty function with the given name.
83   void createDummyFunction(StringRef Name, Module &M);
84 };
85
86 } // end namespace llvm
87
88 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
89                              StringRef Filename, LLVMContext &Context)
90     : SM(), Filename(Filename), Context(Context) {
91   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
92 }
93
94 bool MIRParserImpl::error(const Twine &Message) {
95   Context.diagnose(DiagnosticInfoMIRParser(
96       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
97   return true;
98 }
99
100 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
101   DiagnosticSeverity Kind;
102   switch (Diag.getKind()) {
103   case SourceMgr::DK_Error:
104     Kind = DS_Error;
105     break;
106   case SourceMgr::DK_Warning:
107     Kind = DS_Warning;
108     break;
109   case SourceMgr::DK_Note:
110     Kind = DS_Note;
111     break;
112   }
113   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
114 }
115
116 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
117   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
118 }
119
120 std::unique_ptr<Module> MIRParserImpl::parse() {
121   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
122                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
123
124   if (!In.setCurrentDocument()) {
125     if (In.error())
126       return nullptr;
127     // Create an empty module when the MIR file is empty.
128     return llvm::make_unique<Module>(Filename, Context);
129   }
130
131   std::unique_ptr<Module> M;
132   bool NoLLVMIR = false;
133   // Parse the block scalar manually so that we can return unique pointer
134   // without having to go trough YAML traits.
135   if (const auto *BSN =
136           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
137     SMDiagnostic Error;
138     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
139                       Context);
140     if (!M) {
141       reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
142       return M;
143     }
144     In.nextDocument();
145     if (!In.setCurrentDocument())
146       return M;
147   } else {
148     // Create an new, empty module.
149     M = llvm::make_unique<Module>(Filename, Context);
150     NoLLVMIR = true;
151   }
152
153   // Parse the machine functions.
154   do {
155     if (parseMachineFunction(In, *M, NoLLVMIR))
156       return nullptr;
157     In.nextDocument();
158   } while (In.setCurrentDocument());
159
160   return M;
161 }
162
163 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
164                                          bool NoLLVMIR) {
165   auto MF = llvm::make_unique<yaml::MachineFunction>();
166   yaml::yamlize(In, *MF, false);
167   if (In.error())
168     return true;
169   auto FunctionName = MF->Name;
170   if (Functions.find(FunctionName) != Functions.end())
171     return error(Twine("redefinition of machine function '") + FunctionName +
172                  "'");
173   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
174   if (NoLLVMIR)
175     createDummyFunction(FunctionName, M);
176   return false;
177 }
178
179 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
180   auto &Context = M.getContext();
181   Function *F = cast<Function>(M.getOrInsertFunction(
182       Name, FunctionType::get(Type::getVoidTy(Context), false)));
183   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
184   new UnreachableInst(Context, BB);
185 }
186
187 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
188   auto It = Functions.find(MF.getName());
189   if (It == Functions.end())
190     return error(Twine("no machine function information for function '") +
191                  MF.getName() + "' in the MIR file");
192   // TODO: Recreate the machine function.
193   const yaml::MachineFunction &YamlMF = *It->getValue();
194   if (YamlMF.Alignment)
195     MF.setAlignment(YamlMF.Alignment);
196   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
197   MF.setHasInlineAsm(YamlMF.HasInlineAsm);
198   return false;
199 }
200
201 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
202                                                      SMRange SourceRange) {
203   assert(SourceRange.isValid());
204
205   // Translate the location of the error from the location in the llvm IR string
206   // to the corresponding location in the MIR file.
207   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
208   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
209   unsigned Column = Error.getColumnNo();
210   StringRef LineStr = Error.getLineContents();
211   SMLoc Loc = Error.getLoc();
212
213   // Get the full line and adjust the column number by taking the indentation of
214   // LLVM IR into account.
215   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
216        L != E; ++L) {
217     if (L.line_number() == Line) {
218       LineStr = *L;
219       Loc = SMLoc::getFromPointer(LineStr.data());
220       auto Indent = LineStr.find(Error.getLineContents());
221       if (Indent != StringRef::npos)
222         Column += Indent;
223       break;
224     }
225   }
226
227   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
228                       Error.getMessage(), LineStr, Error.getRanges(),
229                       Error.getFixIts());
230 }
231
232 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
233     : Impl(std::move(Impl)) {}
234
235 MIRParser::~MIRParser() {}
236
237 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
238
239 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
240   return Impl->initializeMachineFunction(MF);
241 }
242
243 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
244                                                          SMDiagnostic &Error,
245                                                          LLVMContext &Context) {
246   auto FileOrErr = MemoryBuffer::getFile(Filename);
247   if (std::error_code EC = FileOrErr.getError()) {
248     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
249                          "Could not open input file: " + EC.message());
250     return nullptr;
251   }
252   return createMIRParser(std::move(FileOrErr.get()), Context);
253 }
254
255 std::unique_ptr<MIRParser>
256 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
257                       LLVMContext &Context) {
258   auto Filename = Contents->getBufferIdentifier();
259   return llvm::make_unique<MIRParser>(
260       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
261 }