MIR Parser: Report an error when parsing machine function with an empty body.
[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 "MIParser.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/MIRYamlMapping.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueSymbolTable.h"
33 #include "llvm/Support/LineIterator.h"
34 #include "llvm/Support/SMLoc.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/YAMLTraits.h"
38 #include <memory>
39
40 using namespace llvm;
41
42 namespace llvm {
43
44 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
45 /// file.
46 class MIRParserImpl {
47   SourceMgr SM;
48   StringRef Filename;
49   LLVMContext &Context;
50   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
51   SlotMapping IRSlots;
52
53 public:
54   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
55                 LLVMContext &Context);
56
57   void reportDiagnostic(const SMDiagnostic &Diag);
58
59   /// Report an error with the given message at unknown location.
60   ///
61   /// Always returns true.
62   bool error(const Twine &Message);
63
64   /// Report an error with the given message at the given location.
65   ///
66   /// Always returns true.
67   bool error(SMLoc Loc, const Twine &Message);
68
69   /// Report a given error with the location translated from the location in an
70   /// embedded string literal to a location in the MIR file.
71   ///
72   /// Always returns true.
73   bool error(const SMDiagnostic &Error, SMRange SourceRange);
74
75   /// Try to parse the optional LLVM module and the machine functions in the MIR
76   /// file.
77   ///
78   /// Return null if an error occurred.
79   std::unique_ptr<Module> parse();
80
81   /// Parse the machine function in the current YAML document.
82   ///
83   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
84   /// A dummy IR function is created and inserted into the given module when
85   /// this parameter is true.
86   ///
87   /// Return true if an error occurred.
88   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
89
90   /// Initialize the machine function to the state that's described in the MIR
91   /// file.
92   ///
93   /// Return true if error occurred.
94   bool initializeMachineFunction(MachineFunction &MF);
95
96   /// Initialize the machine basic block using it's YAML representation.
97   ///
98   /// Return true if an error occurred.
99   bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
100                                    const yaml::MachineBasicBlock &YamlMBB,
101                                    const PerFunctionMIParsingState &PFS);
102
103   bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
104                               const yaml::MachineFunction &YamlMF);
105
106   bool initializeFrameInfo(MachineFrameInfo &MFI,
107                            const yaml::MachineFrameInfo &YamlMFI);
108
109 private:
110   /// Return a MIR diagnostic converted from an MI string diagnostic.
111   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
112                                     SMRange SourceRange);
113
114   /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
115   SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
116                                         SMRange SourceRange);
117
118   /// Create an empty function with the given name.
119   void createDummyFunction(StringRef Name, Module &M);
120 };
121
122 } // end namespace llvm
123
124 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
125                              StringRef Filename, LLVMContext &Context)
126     : SM(), Filename(Filename), Context(Context) {
127   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
128 }
129
130 bool MIRParserImpl::error(const Twine &Message) {
131   Context.diagnose(DiagnosticInfoMIRParser(
132       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
133   return true;
134 }
135
136 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
137   Context.diagnose(DiagnosticInfoMIRParser(
138       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
139   return true;
140 }
141
142 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
143   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
144   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
145   return true;
146 }
147
148 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
149   DiagnosticSeverity Kind;
150   switch (Diag.getKind()) {
151   case SourceMgr::DK_Error:
152     Kind = DS_Error;
153     break;
154   case SourceMgr::DK_Warning:
155     Kind = DS_Warning;
156     break;
157   case SourceMgr::DK_Note:
158     Kind = DS_Note;
159     break;
160   }
161   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
162 }
163
164 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
165   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
166 }
167
168 std::unique_ptr<Module> MIRParserImpl::parse() {
169   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
170                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
171   In.setContext(&In);
172
173   if (!In.setCurrentDocument()) {
174     if (In.error())
175       return nullptr;
176     // Create an empty module when the MIR file is empty.
177     return llvm::make_unique<Module>(Filename, Context);
178   }
179
180   std::unique_ptr<Module> M;
181   bool NoLLVMIR = false;
182   // Parse the block scalar manually so that we can return unique pointer
183   // without having to go trough YAML traits.
184   if (const auto *BSN =
185           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
186     SMDiagnostic Error;
187     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
188                       Context, &IRSlots);
189     if (!M) {
190       reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
191       return M;
192     }
193     In.nextDocument();
194     if (!In.setCurrentDocument())
195       return M;
196   } else {
197     // Create an new, empty module.
198     M = llvm::make_unique<Module>(Filename, Context);
199     NoLLVMIR = true;
200   }
201
202   // Parse the machine functions.
203   do {
204     if (parseMachineFunction(In, *M, NoLLVMIR))
205       return nullptr;
206     In.nextDocument();
207   } while (In.setCurrentDocument());
208
209   return M;
210 }
211
212 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
213                                          bool NoLLVMIR) {
214   auto MF = llvm::make_unique<yaml::MachineFunction>();
215   yaml::yamlize(In, *MF, false);
216   if (In.error())
217     return true;
218   auto FunctionName = MF->Name;
219   if (Functions.find(FunctionName) != Functions.end())
220     return error(Twine("redefinition of machine function '") + FunctionName +
221                  "'");
222   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
223   if (NoLLVMIR)
224     createDummyFunction(FunctionName, M);
225   else if (!M.getFunction(FunctionName))
226     return error(Twine("function '") + FunctionName +
227                  "' isn't defined in the provided LLVM IR");
228   return false;
229 }
230
231 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
232   auto &Context = M.getContext();
233   Function *F = cast<Function>(M.getOrInsertFunction(
234       Name, FunctionType::get(Type::getVoidTy(Context), false)));
235   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
236   new UnreachableInst(Context, BB);
237 }
238
239 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
240   auto It = Functions.find(MF.getName());
241   if (It == Functions.end())
242     return error(Twine("no machine function information for function '") +
243                  MF.getName() + "' in the MIR file");
244   // TODO: Recreate the machine function.
245   const yaml::MachineFunction &YamlMF = *It->getValue();
246   if (YamlMF.Alignment)
247     MF.setAlignment(YamlMF.Alignment);
248   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
249   MF.setHasInlineAsm(YamlMF.HasInlineAsm);
250   if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
251     return true;
252   if (initializeFrameInfo(*MF.getFrameInfo(), YamlMF.FrameInfo))
253     return true;
254
255   PerFunctionMIParsingState PFS;
256   const auto &F = *MF.getFunction();
257   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
258     const BasicBlock *BB = nullptr;
259     const yaml::StringValue &Name = YamlMBB.Name;
260     if (!Name.Value.empty()) {
261       BB = dyn_cast_or_null<BasicBlock>(
262           F.getValueSymbolTable().lookup(Name.Value));
263       if (!BB)
264         return error(Name.SourceRange.Start,
265                      Twine("basic block '") + Name.Value +
266                          "' is not defined in the function '" + MF.getName() +
267                          "'");
268     }
269     auto *MBB = MF.CreateMachineBasicBlock(BB);
270     MF.insert(MF.end(), MBB);
271     bool WasInserted =
272         PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
273     if (!WasInserted)
274       return error(Twine("redefinition of machine basic block with id #") +
275                    Twine(YamlMBB.ID));
276   }
277
278   if (YamlMF.BasicBlocks.empty())
279     return error(Twine("machine function '") + Twine(MF.getName()) +
280                  "' requires at least one machine basic block in its body");
281   // Initialize the machine basic blocks after creating them all so that the
282   // machine instructions parser can resolve the MBB references.
283   unsigned I = 0;
284   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
285     if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
286                                     PFS))
287       return true;
288   }
289   return false;
290 }
291
292 bool MIRParserImpl::initializeMachineBasicBlock(
293     MachineFunction &MF, MachineBasicBlock &MBB,
294     const yaml::MachineBasicBlock &YamlMBB,
295     const PerFunctionMIParsingState &PFS) {
296   MBB.setAlignment(YamlMBB.Alignment);
297   if (YamlMBB.AddressTaken)
298     MBB.setHasAddressTaken();
299   MBB.setIsLandingPad(YamlMBB.IsLandingPad);
300   SMDiagnostic Error;
301   // Parse the successors.
302   for (const auto &MBBSource : YamlMBB.Successors) {
303     MachineBasicBlock *SuccMBB = nullptr;
304     if (parseMBBReference(SuccMBB, SM, MF, MBBSource.Value, PFS, IRSlots,
305                           Error))
306       return error(Error, MBBSource.SourceRange);
307     // TODO: Report an error when adding the same successor more than once.
308     MBB.addSuccessor(SuccMBB);
309   }
310   // Parse the instructions.
311   for (const auto &MISource : YamlMBB.Instructions) {
312     MachineInstr *MI = nullptr;
313     if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
314       return error(Error, MISource.SourceRange);
315     MBB.insert(MBB.end(), MI);
316   }
317   return false;
318 }
319
320 bool MIRParserImpl::initializeRegisterInfo(
321     MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
322   assert(RegInfo.isSSA());
323   if (!YamlMF.IsSSA)
324     RegInfo.leaveSSA();
325   assert(RegInfo.tracksLiveness());
326   if (!YamlMF.TracksRegLiveness)
327     RegInfo.invalidateLiveness();
328   RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
329   return false;
330 }
331
332 bool MIRParserImpl::initializeFrameInfo(MachineFrameInfo &MFI,
333                                         const yaml::MachineFrameInfo &YamlMFI) {
334   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
335   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
336   MFI.setHasStackMap(YamlMFI.HasStackMap);
337   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
338   MFI.setStackSize(YamlMFI.StackSize);
339   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
340   if (YamlMFI.MaxAlignment)
341     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
342   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
343   MFI.setHasCalls(YamlMFI.HasCalls);
344   MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
345   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
346   MFI.setHasVAStart(YamlMFI.HasVAStart);
347   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
348   return false;
349 }
350
351 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
352                                                  SMRange SourceRange) {
353   assert(SourceRange.isValid() && "Invalid source range");
354   SMLoc Loc = SourceRange.Start;
355   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
356                   *Loc.getPointer() == '\'';
357   // Translate the location of the error from the location in the MI string to
358   // the corresponding location in the MIR file.
359   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
360                            (HasQuote ? 1 : 0));
361
362   // TODO: Translate any source ranges as well.
363   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
364                        Error.getFixIts());
365 }
366
367 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
368                                                      SMRange SourceRange) {
369   assert(SourceRange.isValid());
370
371   // Translate the location of the error from the location in the llvm IR string
372   // to the corresponding location in the MIR file.
373   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
374   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
375   unsigned Column = Error.getColumnNo();
376   StringRef LineStr = Error.getLineContents();
377   SMLoc Loc = Error.getLoc();
378
379   // Get the full line and adjust the column number by taking the indentation of
380   // LLVM IR into account.
381   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
382        L != E; ++L) {
383     if (L.line_number() == Line) {
384       LineStr = *L;
385       Loc = SMLoc::getFromPointer(LineStr.data());
386       auto Indent = LineStr.find(Error.getLineContents());
387       if (Indent != StringRef::npos)
388         Column += Indent;
389       break;
390     }
391   }
392
393   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
394                       Error.getMessage(), LineStr, Error.getRanges(),
395                       Error.getFixIts());
396 }
397
398 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
399     : Impl(std::move(Impl)) {}
400
401 MIRParser::~MIRParser() {}
402
403 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
404
405 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
406   return Impl->initializeMachineFunction(MF);
407 }
408
409 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
410                                                          SMDiagnostic &Error,
411                                                          LLVMContext &Context) {
412   auto FileOrErr = MemoryBuffer::getFile(Filename);
413   if (std::error_code EC = FileOrErr.getError()) {
414     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
415                          "Could not open input file: " + EC.message());
416     return nullptr;
417   }
418   return createMIRParser(std::move(FileOrErr.get()), Context);
419 }
420
421 std::unique_ptr<MIRParser>
422 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
423                       LLVMContext &Context) {
424   auto Filename = Contents->getBufferIdentifier();
425   return llvm::make_unique<MIRParser>(
426       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
427 }