MIR Serialization: Serialize the simple MachineFrameInfo 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 "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   // Initialize the machine basic blocks after creating them all so that the
279   // machine instructions parser can resolve the MBB references.
280   unsigned I = 0;
281   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
282     if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
283                                     PFS))
284       return true;
285   }
286   return false;
287 }
288
289 bool MIRParserImpl::initializeMachineBasicBlock(
290     MachineFunction &MF, MachineBasicBlock &MBB,
291     const yaml::MachineBasicBlock &YamlMBB,
292     const PerFunctionMIParsingState &PFS) {
293   MBB.setAlignment(YamlMBB.Alignment);
294   if (YamlMBB.AddressTaken)
295     MBB.setHasAddressTaken();
296   MBB.setIsLandingPad(YamlMBB.IsLandingPad);
297   SMDiagnostic Error;
298   // Parse the successors.
299   for (const auto &MBBSource : YamlMBB.Successors) {
300     MachineBasicBlock *SuccMBB = nullptr;
301     if (parseMBBReference(SuccMBB, SM, MF, MBBSource.Value, PFS, IRSlots,
302                           Error))
303       return error(Error, MBBSource.SourceRange);
304     // TODO: Report an error when adding the same successor more than once.
305     MBB.addSuccessor(SuccMBB);
306   }
307   // Parse the instructions.
308   for (const auto &MISource : YamlMBB.Instructions) {
309     MachineInstr *MI = nullptr;
310     if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
311       return error(Error, MISource.SourceRange);
312     MBB.insert(MBB.end(), MI);
313   }
314   return false;
315 }
316
317 bool MIRParserImpl::initializeRegisterInfo(
318     MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
319   assert(RegInfo.isSSA());
320   if (!YamlMF.IsSSA)
321     RegInfo.leaveSSA();
322   assert(RegInfo.tracksLiveness());
323   if (!YamlMF.TracksRegLiveness)
324     RegInfo.invalidateLiveness();
325   RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
326   return false;
327 }
328
329 bool MIRParserImpl::initializeFrameInfo(MachineFrameInfo &MFI,
330                                         const yaml::MachineFrameInfo &YamlMFI) {
331   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
332   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
333   MFI.setHasStackMap(YamlMFI.HasStackMap);
334   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
335   MFI.setStackSize(YamlMFI.StackSize);
336   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
337   if (YamlMFI.MaxAlignment)
338     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
339   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
340   MFI.setHasCalls(YamlMFI.HasCalls);
341   MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
342   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
343   MFI.setHasVAStart(YamlMFI.HasVAStart);
344   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
345   return false;
346 }
347
348 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
349                                                  SMRange SourceRange) {
350   assert(SourceRange.isValid() && "Invalid source range");
351   SMLoc Loc = SourceRange.Start;
352   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
353                   *Loc.getPointer() == '\'';
354   // Translate the location of the error from the location in the MI string to
355   // the corresponding location in the MIR file.
356   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
357                            (HasQuote ? 1 : 0));
358
359   // TODO: Translate any source ranges as well.
360   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
361                        Error.getFixIts());
362 }
363
364 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
365                                                      SMRange SourceRange) {
366   assert(SourceRange.isValid());
367
368   // Translate the location of the error from the location in the llvm IR string
369   // to the corresponding location in the MIR file.
370   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
371   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
372   unsigned Column = Error.getColumnNo();
373   StringRef LineStr = Error.getLineContents();
374   SMLoc Loc = Error.getLoc();
375
376   // Get the full line and adjust the column number by taking the indentation of
377   // LLVM IR into account.
378   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
379        L != E; ++L) {
380     if (L.line_number() == Line) {
381       LineStr = *L;
382       Loc = SMLoc::getFromPointer(LineStr.data());
383       auto Indent = LineStr.find(Error.getLineContents());
384       if (Indent != StringRef::npos)
385         Column += Indent;
386       break;
387     }
388   }
389
390   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
391                       Error.getMessage(), LineStr, Error.getRanges(),
392                       Error.getFixIts());
393 }
394
395 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
396     : Impl(std::move(Impl)) {}
397
398 MIRParser::~MIRParser() {}
399
400 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
401
402 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
403   return Impl->initializeMachineFunction(MF);
404 }
405
406 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
407                                                          SMDiagnostic &Error,
408                                                          LLVMContext &Context) {
409   auto FileOrErr = MemoryBuffer::getFile(Filename);
410   if (std::error_code EC = FileOrErr.getError()) {
411     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
412                          "Could not open input file: " + EC.message());
413     return nullptr;
414   }
415   return createMIRParser(std::move(FileOrErr.get()), Context);
416 }
417
418 std::unique_ptr<MIRParser>
419 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
420                       LLVMContext &Context) {
421   auto Filename = Contents->getBufferIdentifier();
422   return llvm::make_unique<MIRParser>(
423       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
424 }