blob: 9b112e34b0380d5b2d09082f3474f0ef2ea6d874 [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 Lorenzab980492015-07-20 20:51:18 +000023#include "llvm/CodeGen/MachineConstantPool.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000024#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenz60541c12015-07-09 19:55:27 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz78d78312015-05-28 22:41:12 +000027#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000028#include "llvm/IR/BasicBlock.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000029#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000030#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000031#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000032#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000033#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000034#include "llvm/Support/LineIterator.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000035#include "llvm/Support/SMLoc.h"
36#include "llvm/Support/SourceMgr.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/YAMLTraits.h"
39#include <memory>
40
41using namespace llvm;
42
Alex Lorenz735c47e2015-06-15 20:30:22 +000043namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000044
45/// This class implements the parsing of LLVM IR that's embedded inside a MIR
46/// file.
47class MIRParserImpl {
48 SourceMgr SM;
49 StringRef Filename;
50 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000051 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000052 SlotMapping IRSlots;
Alex Lorenz28148ba2015-07-09 22:23:13 +000053 /// Maps from register class names to register classes.
54 StringMap<const TargetRegisterClass *> Names2RegClasses;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000055
56public:
57 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58 LLVMContext &Context);
59
Alex Lorenz735c47e2015-06-15 20:30:22 +000060 void reportDiagnostic(const SMDiagnostic &Diag);
61
62 /// Report an error with the given message at unknown location.
63 ///
64 /// Always returns true.
65 bool error(const Twine &Message);
66
Alex Lorenzb1f9ce82015-07-08 20:22:20 +000067 /// Report an error with the given message at the given location.
68 ///
69 /// Always returns true.
70 bool error(SMLoc Loc, const Twine &Message);
71
Alex Lorenz0fd7c622015-06-30 17:55:00 +000072 /// Report a given error with the location translated from the location in an
73 /// embedded string literal to a location in the MIR file.
74 ///
75 /// Always returns true.
76 bool error(const SMDiagnostic &Error, SMRange SourceRange);
77
Alex Lorenz78d78312015-05-28 22:41:12 +000078 /// Try to parse the optional LLVM module and the machine functions in the MIR
79 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000080 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000081 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000082 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000083
84 /// Parse the machine function in the current YAML document.
85 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000086 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
87 /// A dummy IR function is created and inserted into the given module when
88 /// this parameter is true.
89 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000090 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000091 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000092
Alex Lorenz735c47e2015-06-15 20:30:22 +000093 /// Initialize the machine function to the state that's described in the MIR
94 /// file.
95 ///
96 /// Return true if error occurred.
97 bool initializeMachineFunction(MachineFunction &MF);
98
Alex Lorenz4f093bf2015-06-19 17:43:07 +000099 /// Initialize the machine basic block using it's YAML representation.
100 ///
101 /// Return true if an error occurred.
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000102 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
103 const yaml::MachineBasicBlock &YamlMBB,
104 const PerFunctionMIParsingState &PFS);
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000105
Alex Lorenzdb07c402015-07-28 16:48:37 +0000106 bool initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000107 const yaml::MachineFunction &YamlMF,
108 PerFunctionMIParsingState &PFS);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000109
Alex Lorenzc4838082015-08-11 00:32:49 +0000110 void inferRegisterInfo(MachineFunction &MF,
111 const yaml::MachineFunction &YamlMF);
112
Alex Lorenzdb07c402015-07-28 16:48:37 +0000113 bool initializeFrameInfo(MachineFunction &MF,
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000114 const yaml::MachineFunction &YamlMF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000115 PerFunctionMIParsingState &PFS);
116
117 bool parseCalleeSavedRegister(MachineFunction &MF,
118 PerFunctionMIParsingState &PFS,
119 std::vector<CalleeSavedInfo> &CSIInfo,
120 const yaml::StringValue &RegisterSource,
121 int FrameIdx);
Alex Lorenz60541c12015-07-09 19:55:27 +0000122
Alex Lorenzab980492015-07-20 20:51:18 +0000123 bool initializeConstantPool(MachineConstantPool &ConstantPool,
124 const yaml::MachineFunction &YamlMF,
125 const MachineFunction &MF,
126 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
127
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000128 bool initializeJumpTableInfo(MachineFunction &MF,
129 const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000130 PerFunctionMIParsingState &PFS);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000131
Alex Lorenz09b832c2015-05-29 17:05:41 +0000132private:
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000133 bool parseMBBReference(MachineBasicBlock *&MBB,
134 const yaml::StringValue &Source, MachineFunction &MF,
135 const PerFunctionMIParsingState &PFS);
136
Alex Lorenz51af1602015-06-23 22:39:23 +0000137 /// Return a MIR diagnostic converted from an MI string diagnostic.
138 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
139 SMRange SourceRange);
140
Alex Lorenz09b832c2015-05-29 17:05:41 +0000141 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
142 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
143 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000144
145 /// Create an empty function with the given name.
146 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000147
148 void initNames2RegClasses(const MachineFunction &MF);
149
150 /// Check if the given identifier is a name of a register class.
151 ///
152 /// Return null if the name isn't a register class.
153 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
154 StringRef Name);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000155};
156
Alex Lorenz735c47e2015-06-15 20:30:22 +0000157} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000158
159MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
160 StringRef Filename, LLVMContext &Context)
161 : SM(), Filename(Filename), Context(Context) {
162 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
163}
164
Alex Lorenz735c47e2015-06-15 20:30:22 +0000165bool MIRParserImpl::error(const Twine &Message) {
166 Context.diagnose(DiagnosticInfoMIRParser(
167 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
168 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000169}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000170
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000171bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
172 Context.diagnose(DiagnosticInfoMIRParser(
173 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
174 return true;
175}
176
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000177bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
178 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
179 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
180 return true;
181}
182
Alex Lorenz735c47e2015-06-15 20:30:22 +0000183void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
184 DiagnosticSeverity Kind;
185 switch (Diag.getKind()) {
186 case SourceMgr::DK_Error:
187 Kind = DS_Error;
188 break;
189 case SourceMgr::DK_Warning:
190 Kind = DS_Warning;
191 break;
192 case SourceMgr::DK_Note:
193 Kind = DS_Note;
194 break;
195 }
196 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
197}
198
199static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
200 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
201}
202
203std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000204 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000205 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000206 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000207
208 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000209 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000210 return nullptr;
211 // Create an empty module when the MIR file is empty.
212 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000213 }
214
Alex Lorenz78d78312015-05-28 22:41:12 +0000215 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000216 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000217 // Parse the block scalar manually so that we can return unique pointer
218 // without having to go trough YAML traits.
219 if (const auto *BSN =
220 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000221 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000222 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000223 Context, &IRSlots);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000224 if (!M) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000225 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000226 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000227 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000228 In.nextDocument();
229 if (!In.setCurrentDocument())
230 return M;
231 } else {
232 // Create an new, empty module.
233 M = llvm::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000234 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000235 }
236
237 // Parse the machine functions.
238 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000239 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000240 return nullptr;
241 In.nextDocument();
242 } while (In.setCurrentDocument());
243
244 return M;
245}
246
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000247bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
248 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000249 auto MF = llvm::make_unique<yaml::MachineFunction>();
250 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000251 if (In.error())
252 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000253 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000254 if (Functions.find(FunctionName) != Functions.end())
255 return error(Twine("redefinition of machine function '") + FunctionName +
256 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000257 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000258 if (NoLLVMIR)
259 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000260 else if (!M.getFunction(FunctionName))
261 return error(Twine("function '") + FunctionName +
262 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000263 return false;
264}
265
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000266void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
267 auto &Context = M.getContext();
268 Function *F = cast<Function>(M.getOrInsertFunction(
269 Name, FunctionType::get(Type::getVoidTy(Context), false)));
270 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
271 new UnreachableInst(Context, BB);
272}
273
Alex Lorenz735c47e2015-06-15 20:30:22 +0000274bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
275 auto It = Functions.find(MF.getName());
276 if (It == Functions.end())
277 return error(Twine("no machine function information for function '") +
278 MF.getName() + "' in the MIR file");
279 // TODO: Recreate the machine function.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000280 const yaml::MachineFunction &YamlMF = *It->getValue();
281 if (YamlMF.Alignment)
282 MF.setAlignment(YamlMF.Alignment);
283 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
284 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
Alex Lorenz53464512015-07-10 22:51:20 +0000285 PerFunctionMIParsingState PFS;
Alex Lorenzdb07c402015-07-28 16:48:37 +0000286 if (initializeRegisterInfo(MF, YamlMF, PFS))
Alex Lorenz54565cf2015-06-24 19:56:10 +0000287 return true;
Alex Lorenzab980492015-07-20 20:51:18 +0000288 if (!YamlMF.Constants.empty()) {
289 auto *ConstantPool = MF.getConstantPool();
290 assert(ConstantPool && "Constant pool must be created");
291 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
292 PFS.ConstantPoolSlots))
293 return true;
294 }
Alex Lorenz54565cf2015-06-24 19:56:10 +0000295
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000296 const auto &F = *MF.getFunction();
297 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
298 const BasicBlock *BB = nullptr;
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000299 const yaml::StringValue &Name = YamlMBB.Name;
Alex Lorenz8a1915b2015-07-27 22:42:41 +0000300 const yaml::StringValue &IRBlock = YamlMBB.IRBlock;
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000301 if (!Name.Value.empty()) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000302 BB = dyn_cast_or_null<BasicBlock>(
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000303 F.getValueSymbolTable().lookup(Name.Value));
Alex Lorenz00302df2015-06-19 20:12:03 +0000304 if (!BB)
Alex Lorenzb1f9ce82015-07-08 20:22:20 +0000305 return error(Name.SourceRange.Start,
306 Twine("basic block '") + Name.Value +
307 "' is not defined in the function '" + MF.getName() +
308 "'");
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000309 }
Alex Lorenz8a1915b2015-07-27 22:42:41 +0000310 if (!IRBlock.Value.empty()) {
311 // TODO: Report an error when both name and ir block are specified.
312 SMDiagnostic Error;
313 if (parseIRBlockReference(BB, SM, MF, IRBlock.Value, PFS, IRSlots, Error))
314 return error(Error, IRBlock.SourceRange);
315 }
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000316 auto *MBB = MF.CreateMachineBasicBlock(BB);
317 MF.insert(MF.end(), MBB);
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000318 bool WasInserted =
319 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000320 if (!WasInserted)
321 return error(Twine("redefinition of machine basic block with id #") +
322 Twine(YamlMBB.ID));
323 }
324
Alex Lorenzc8704b02015-07-09 21:21:33 +0000325 if (YamlMF.BasicBlocks.empty())
326 return error(Twine("machine function '") + Twine(MF.getName()) +
327 "' requires at least one machine basic block in its body");
Alex Lorenza6f9a372015-07-29 21:09:09 +0000328 // Initialize the frame information after creating all the MBBs so that the
329 // MBB references in the frame information can be resolved.
330 if (initializeFrameInfo(MF, YamlMF, PFS))
331 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000332 // Initialize the jump table after creating all the MBBs so that the MBB
333 // references can be resolved.
334 if (!YamlMF.JumpTableInfo.Entries.empty() &&
335 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
336 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000337 // Initialize the machine basic blocks after creating them all so that the
338 // machine instructions parser can resolve the MBB references.
339 unsigned I = 0;
340 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
341 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000342 PFS))
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000343 return true;
344 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000345 inferRegisterInfo(MF, YamlMF);
Alex Lorenzc7bf2042015-07-24 17:44:49 +0000346 // FIXME: This is a temporary workaround until the reserved registers can be
347 // serialized.
348 MF.getRegInfo().freezeReservedRegs(MF);
349 MF.verify();
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000350 return false;
351}
352
353bool MIRParserImpl::initializeMachineBasicBlock(
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000354 MachineFunction &MF, MachineBasicBlock &MBB,
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000355 const yaml::MachineBasicBlock &YamlMBB,
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000356 const PerFunctionMIParsingState &PFS) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000357 MBB.setAlignment(YamlMBB.Alignment);
358 if (YamlMBB.AddressTaken)
359 MBB.setHasAddressTaken();
360 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
Alex Lorenzf09df002015-06-30 18:16:42 +0000361 SMDiagnostic Error;
362 // Parse the successors.
Alex Lorenz618b2832015-07-30 16:54:38 +0000363 const auto &Weights = YamlMBB.SuccessorWeights;
364 bool HasWeights = !Weights.empty();
365 if (HasWeights && Weights.size() != YamlMBB.Successors.size()) {
366 bool IsFew = Weights.size() < YamlMBB.Successors.size();
367 return error(IsFew ? Weights.back().SourceRange.End
368 : Weights[YamlMBB.Successors.size()].SourceRange.Start,
369 Twine("too ") + (IsFew ? "few" : "many") +
370 " successor weights, expected " +
371 Twine(YamlMBB.Successors.size()) + ", have " +
372 Twine(Weights.size()));
373 }
374 size_t SuccessorIndex = 0;
Alex Lorenzf09df002015-06-30 18:16:42 +0000375 for (const auto &MBBSource : YamlMBB.Successors) {
376 MachineBasicBlock *SuccMBB = nullptr;
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000377 if (parseMBBReference(SuccMBB, MBBSource, MF, PFS))
378 return true;
Alex Lorenzf09df002015-06-30 18:16:42 +0000379 // TODO: Report an error when adding the same successor more than once.
Alex Lorenz618b2832015-07-30 16:54:38 +0000380 MBB.addSuccessor(SuccMBB, HasWeights ? Weights[SuccessorIndex++].Value : 0);
Alex Lorenzf09df002015-06-30 18:16:42 +0000381 }
Alex Lorenz9fab3702015-07-14 21:24:41 +0000382 // Parse the liveins.
383 for (const auto &LiveInSource : YamlMBB.LiveIns) {
384 unsigned Reg = 0;
385 if (parseNamedRegisterReference(Reg, SM, MF, LiveInSource.Value, PFS,
386 IRSlots, Error))
387 return error(Error, LiveInSource.SourceRange);
388 MBB.addLiveIn(Reg);
389 }
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000390 // Parse the instructions.
391 for (const auto &MISource : YamlMBB.Instructions) {
Alex Lorenz3708a642015-06-30 17:47:50 +0000392 MachineInstr *MI = nullptr;
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000393 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
Alex Lorenz0fd7c622015-06-30 17:55:00 +0000394 return error(Error, MISource.SourceRange);
Alex Lorenz3708a642015-06-30 17:47:50 +0000395 MBB.insert(MBB.end(), MI);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000396 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000397 return false;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000398}
399
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000400bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000401 const yaml::MachineFunction &YamlMF,
402 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000403 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Alex Lorenz54565cf2015-06-24 19:56:10 +0000404 assert(RegInfo.isSSA());
405 if (!YamlMF.IsSSA)
406 RegInfo.leaveSSA();
407 assert(RegInfo.tracksLiveness());
408 if (!YamlMF.TracksRegLiveness)
409 RegInfo.invalidateLiveness();
410 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
Alex Lorenz28148ba2015-07-09 22:23:13 +0000411
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000412 SMDiagnostic Error;
Alex Lorenz28148ba2015-07-09 22:23:13 +0000413 // Parse the virtual register information.
414 for (const auto &VReg : YamlMF.VirtualRegisters) {
415 const auto *RC = getRegClass(MF, VReg.Class.Value);
416 if (!RC)
417 return error(VReg.Class.SourceRange.Start,
418 Twine("use of undefined register class '") +
419 VReg.Class.Value + "'");
Alex Lorenz53464512015-07-10 22:51:20 +0000420 unsigned Reg = RegInfo.createVirtualRegister(RC);
Alex Lorenza06c0c62015-07-30 21:54:10 +0000421 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
422 .second)
423 return error(VReg.ID.SourceRange.Start,
424 Twine("redefinition of virtual register '%") +
425 Twine(VReg.ID.Value) + "'");
Alex Lorenzab4cbcf2015-07-24 20:35:40 +0000426 if (!VReg.PreferredRegister.Value.empty()) {
427 unsigned PreferredReg = 0;
428 if (parseNamedRegisterReference(PreferredReg, SM, MF,
429 VReg.PreferredRegister.Value, PFS,
430 IRSlots, Error))
431 return error(Error, VReg.PreferredRegister.SourceRange);
432 RegInfo.setSimpleHint(Reg, PreferredReg);
433 }
Alex Lorenz28148ba2015-07-09 22:23:13 +0000434 }
Alex Lorenz12045a42015-07-27 17:42:45 +0000435
436 // Parse the liveins.
437 for (const auto &LiveIn : YamlMF.LiveIns) {
438 unsigned Reg = 0;
439 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
440 IRSlots, Error))
441 return error(Error, LiveIn.Register.SourceRange);
442 unsigned VReg = 0;
443 if (!LiveIn.VirtualRegister.Value.empty()) {
444 if (parseVirtualRegisterReference(
445 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
446 return error(Error, LiveIn.VirtualRegister.SourceRange);
447 }
448 RegInfo.addLiveIn(Reg, VReg);
449 }
Alex Lorenzc4838082015-08-11 00:32:49 +0000450
451 // Parse the callee saved register mask.
452 BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
453 if (!YamlMF.CalleeSavedRegisters)
454 return false;
455 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
456 unsigned Reg = 0;
457 if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
458 Error))
459 return error(Error, RegSource.SourceRange);
460 CalleeSavedRegisterMask[Reg] = true;
461 }
462 RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
Alex Lorenz54565cf2015-06-24 19:56:10 +0000463 return false;
464}
465
Alex Lorenzc4838082015-08-11 00:32:49 +0000466void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
467 const yaml::MachineFunction &YamlMF) {
468 if (YamlMF.CalleeSavedRegisters)
469 return;
470 for (const MachineBasicBlock &MBB : MF) {
471 for (const MachineInstr &MI : MBB) {
472 for (const MachineOperand &MO : MI.operands()) {
473 if (!MO.isRegMask())
474 continue;
475 MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
476 }
477 }
478 }
479}
480
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000481bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000482 const yaml::MachineFunction &YamlMF,
483 PerFunctionMIParsingState &PFS) {
Alex Lorenzdb07c402015-07-28 16:48:37 +0000484 MachineFrameInfo &MFI = *MF.getFrameInfo();
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000485 const Function &F = *MF.getFunction();
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000486 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
Alex Lorenz60541c12015-07-09 19:55:27 +0000487 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
488 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
489 MFI.setHasStackMap(YamlMFI.HasStackMap);
490 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
491 MFI.setStackSize(YamlMFI.StackSize);
492 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
493 if (YamlMFI.MaxAlignment)
494 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
495 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
496 MFI.setHasCalls(YamlMFI.HasCalls);
497 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
498 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
499 MFI.setHasVAStart(YamlMFI.HasVAStart);
500 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
Alex Lorenza6f9a372015-07-29 21:09:09 +0000501 if (!YamlMFI.SavePoint.Value.empty()) {
502 MachineBasicBlock *MBB = nullptr;
503 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
504 return true;
505 MFI.setSavePoint(MBB);
506 }
507 if (!YamlMFI.RestorePoint.Value.empty()) {
508 MachineBasicBlock *MBB = nullptr;
509 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
510 return true;
511 MFI.setRestorePoint(MBB);
512 }
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000513
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000514 std::vector<CalleeSavedInfo> CSIInfo;
Alex Lorenzde491f02015-07-13 18:07:26 +0000515 // Initialize the fixed frame objects.
516 for (const auto &Object : YamlMF.FixedStackObjects) {
517 int ObjectIdx;
518 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
519 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
520 Object.IsImmutable, Object.IsAliased);
521 else
522 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
523 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
Alex Lorenz1d9a3032015-08-10 23:45:02 +0000524 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
525 ObjectIdx))
526 .second)
527 return error(Object.ID.SourceRange.Start,
528 Twine("redefinition of fixed stack object '%fixed-stack.") +
529 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000530 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
531 ObjectIdx))
532 return true;
Alex Lorenzde491f02015-07-13 18:07:26 +0000533 }
534
535 // Initialize the ordinary frame objects.
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000536 for (const auto &Object : YamlMF.StackObjects) {
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000537 int ObjectIdx;
Alex Lorenz37643a02015-07-15 22:14:49 +0000538 const AllocaInst *Alloca = nullptr;
539 const yaml::StringValue &Name = Object.Name;
540 if (!Name.Value.empty()) {
541 Alloca = dyn_cast_or_null<AllocaInst>(
542 F.getValueSymbolTable().lookup(Name.Value));
543 if (!Alloca)
544 return error(Name.SourceRange.Start,
545 "alloca instruction named '" + Name.Value +
546 "' isn't defined in the function '" + F.getName() +
547 "'");
548 }
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000549 if (Object.Type == yaml::MachineStackObject::VariableSized)
Alex Lorenz37643a02015-07-15 22:14:49 +0000550 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
Alex Lorenz418f3ec2015-07-14 00:26:26 +0000551 else
552 ObjectIdx = MFI.CreateStackObject(
553 Object.Size, Object.Alignment,
Alex Lorenz37643a02015-07-15 22:14:49 +0000554 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000555 MFI.setObjectOffset(ObjectIdx, Object.Offset);
Alex Lorenzc5d35ba2015-08-10 23:50:41 +0000556 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
557 .second)
558 return error(Object.ID.SourceRange.Start,
559 Twine("redefinition of stack object '%stack.") +
560 Twine(Object.ID.Value) + "'");
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000561 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
562 ObjectIdx))
563 return true;
Alex Lorenzf6bc8662015-07-10 18:13:57 +0000564 }
Alex Lorenz1bb48de2015-07-24 22:22:50 +0000565 MFI.setCalleeSavedInfo(CSIInfo);
566 if (!CSIInfo.empty())
567 MFI.setCalleeSavedInfoValid(true);
568 return false;
569}
570
571bool MIRParserImpl::parseCalleeSavedRegister(
572 MachineFunction &MF, PerFunctionMIParsingState &PFS,
573 std::vector<CalleeSavedInfo> &CSIInfo,
574 const yaml::StringValue &RegisterSource, int FrameIdx) {
575 if (RegisterSource.Value.empty())
576 return false;
577 unsigned Reg = 0;
578 SMDiagnostic Error;
579 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
580 IRSlots, Error))
581 return error(Error, RegisterSource.SourceRange);
582 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
Alex Lorenz60541c12015-07-09 19:55:27 +0000583 return false;
584}
585
Alex Lorenzab980492015-07-20 20:51:18 +0000586bool MIRParserImpl::initializeConstantPool(
587 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
588 const MachineFunction &MF,
589 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
590 const auto &M = *MF.getFunction()->getParent();
591 SMDiagnostic Error;
592 for (const auto &YamlConstant : YamlMF.Constants) {
593 const Constant *Value = dyn_cast_or_null<Constant>(
594 parseConstantValue(YamlConstant.Value.Value, Error, M));
595 if (!Value)
596 return error(Error, YamlConstant.Value.SourceRange);
597 unsigned Alignment =
598 YamlConstant.Alignment
599 ? YamlConstant.Alignment
600 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
Alex Lorenz60bf5992015-07-30 22:00:17 +0000601 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
602 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
603 .second)
604 return error(YamlConstant.ID.SourceRange.Start,
605 Twine("redefinition of constant pool item '%const.") +
606 Twine(YamlConstant.ID.Value) + "'");
Alex Lorenzab980492015-07-20 20:51:18 +0000607 }
608 return false;
609}
610
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000611bool MIRParserImpl::initializeJumpTableInfo(
612 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
Alex Lorenz31d70682015-07-15 23:38:35 +0000613 PerFunctionMIParsingState &PFS) {
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000614 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000615 for (const auto &Entry : YamlJTI.Entries) {
616 std::vector<MachineBasicBlock *> Blocks;
617 for (const auto &MBBSource : Entry.Blocks) {
618 MachineBasicBlock *MBB = nullptr;
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000619 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
620 return true;
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000621 Blocks.push_back(MBB);
622 }
Alex Lorenz31d70682015-07-15 23:38:35 +0000623 unsigned Index = JTI->createJumpTableIndex(Blocks);
Alex Lorenz59ed5912015-07-31 23:13:23 +0000624 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
625 .second)
626 return error(Entry.ID.SourceRange.Start,
627 Twine("redefinition of jump table entry '%jump-table.") +
628 Twine(Entry.ID.Value) + "'");
Alex Lorenz6799e9b2015-07-15 23:31:07 +0000629 }
630 return false;
631}
632
Alex Lorenz05fa73b2015-07-29 20:57:11 +0000633bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
634 const yaml::StringValue &Source,
635 MachineFunction &MF,
636 const PerFunctionMIParsingState &PFS) {
637 SMDiagnostic Error;
638 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
639 return error(Error, Source.SourceRange);
640 return false;
641}
642
Alex Lorenz51af1602015-06-23 22:39:23 +0000643SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
644 SMRange SourceRange) {
645 assert(SourceRange.isValid() && "Invalid source range");
646 SMLoc Loc = SourceRange.Start;
647 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
648 *Loc.getPointer() == '\'';
649 // Translate the location of the error from the location in the MI string to
650 // the corresponding location in the MIR file.
651 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
652 (HasQuote ? 1 : 0));
653
654 // TODO: Translate any source ranges as well.
655 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
656 Error.getFixIts());
657}
658
Alex Lorenz09b832c2015-05-29 17:05:41 +0000659SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
660 SMRange SourceRange) {
661 assert(SourceRange.isValid());
662
663 // Translate the location of the error from the location in the llvm IR string
664 // to the corresponding location in the MIR file.
665 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
666 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
667 unsigned Column = Error.getColumnNo();
668 StringRef LineStr = Error.getLineContents();
669 SMLoc Loc = Error.getLoc();
670
671 // Get the full line and adjust the column number by taking the indentation of
672 // LLVM IR into account.
673 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
674 L != E; ++L) {
675 if (L.line_number() == Line) {
676 LineStr = *L;
677 Loc = SMLoc::getFromPointer(LineStr.data());
678 auto Indent = LineStr.find(Error.getLineContents());
679 if (Indent != StringRef::npos)
680 Column += Indent;
681 break;
682 }
683 }
684
685 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
686 Error.getMessage(), LineStr, Error.getRanges(),
687 Error.getFixIts());
688}
689
Alex Lorenz28148ba2015-07-09 22:23:13 +0000690void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
691 if (!Names2RegClasses.empty())
692 return;
693 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
694 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
695 const auto *RC = TRI->getRegClass(I);
696 Names2RegClasses.insert(
697 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
698 }
699}
700
701const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
702 StringRef Name) {
703 initNames2RegClasses(MF);
704 auto RegClassInfo = Names2RegClasses.find(Name);
705 if (RegClassInfo == Names2RegClasses.end())
706 return nullptr;
707 return RegClassInfo->getValue();
708}
709
Alex Lorenz735c47e2015-06-15 20:30:22 +0000710MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
711 : Impl(std::move(Impl)) {}
712
713MIRParser::~MIRParser() {}
714
715std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
716
717bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
718 return Impl->initializeMachineFunction(MF);
719}
720
721std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
722 SMDiagnostic &Error,
723 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000724 auto FileOrErr = MemoryBuffer::getFile(Filename);
725 if (std::error_code EC = FileOrErr.getError()) {
726 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
727 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000728 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000729 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000730 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000731}
732
Alex Lorenz735c47e2015-06-15 20:30:22 +0000733std::unique_ptr<MIRParser>
734llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
735 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000736 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000737 return llvm::make_unique<MIRParser>(
738 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000739}