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/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"
44 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
50 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
52 /// Maps from register class names to register classes.
53 StringMap<const TargetRegisterClass *> Names2RegClasses;
56 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
57 LLVMContext &Context);
59 void reportDiagnostic(const SMDiagnostic &Diag);
61 /// Report an error with the given message at unknown location.
63 /// Always returns true.
64 bool error(const Twine &Message);
66 /// Report an error with the given message at the given location.
68 /// Always returns true.
69 bool error(SMLoc Loc, const Twine &Message);
71 /// Report a given error with the location translated from the location in an
72 /// embedded string literal to a location in the MIR file.
74 /// Always returns true.
75 bool error(const SMDiagnostic &Error, SMRange SourceRange);
77 /// Try to parse the optional LLVM module and the machine functions in the MIR
80 /// Return null if an error occurred.
81 std::unique_ptr<Module> parse();
83 /// Parse the machine function in the current YAML document.
85 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
86 /// A dummy IR function is created and inserted into the given module when
87 /// this parameter is true.
89 /// Return true if an error occurred.
90 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
92 /// Initialize the machine function to the state that's described in the MIR
95 /// Return true if error occurred.
96 bool initializeMachineFunction(MachineFunction &MF);
98 /// Initialize the machine basic block using it's YAML representation.
100 /// Return true if an error occurred.
101 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
102 const yaml::MachineBasicBlock &YamlMBB,
103 const PerFunctionMIParsingState &PFS);
106 initializeRegisterInfo(const MachineFunction &MF,
107 MachineRegisterInfo &RegInfo,
108 const yaml::MachineFunction &YamlMF,
109 DenseMap<unsigned, unsigned> &VirtualRegisterSlots);
111 bool initializeFrameInfo(MachineFrameInfo &MFI,
112 const yaml::MachineFunction &YamlMF);
115 /// Return a MIR diagnostic converted from an MI string diagnostic.
116 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
117 SMRange SourceRange);
119 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
120 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
121 SMRange SourceRange);
123 /// Create an empty function with the given name.
124 void createDummyFunction(StringRef Name, Module &M);
126 void initNames2RegClasses(const MachineFunction &MF);
128 /// Check if the given identifier is a name of a register class.
130 /// Return null if the name isn't a register class.
131 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
135 } // end namespace llvm
137 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
138 StringRef Filename, LLVMContext &Context)
139 : SM(), Filename(Filename), Context(Context) {
140 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
143 bool MIRParserImpl::error(const Twine &Message) {
144 Context.diagnose(DiagnosticInfoMIRParser(
145 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
149 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
150 Context.diagnose(DiagnosticInfoMIRParser(
151 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
155 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
156 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
157 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
161 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
162 DiagnosticSeverity Kind;
163 switch (Diag.getKind()) {
164 case SourceMgr::DK_Error:
167 case SourceMgr::DK_Warning:
170 case SourceMgr::DK_Note:
174 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
177 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
178 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
181 std::unique_ptr<Module> MIRParserImpl::parse() {
182 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
183 /*Ctxt=*/nullptr, handleYAMLDiag, this);
186 if (!In.setCurrentDocument()) {
189 // Create an empty module when the MIR file is empty.
190 return llvm::make_unique<Module>(Filename, Context);
193 std::unique_ptr<Module> M;
194 bool NoLLVMIR = false;
195 // Parse the block scalar manually so that we can return unique pointer
196 // without having to go trough YAML traits.
197 if (const auto *BSN =
198 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
200 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
203 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
207 if (!In.setCurrentDocument())
210 // Create an new, empty module.
211 M = llvm::make_unique<Module>(Filename, Context);
215 // Parse the machine functions.
217 if (parseMachineFunction(In, *M, NoLLVMIR))
220 } while (In.setCurrentDocument());
225 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
227 auto MF = llvm::make_unique<yaml::MachineFunction>();
228 yaml::yamlize(In, *MF, false);
231 auto FunctionName = MF->Name;
232 if (Functions.find(FunctionName) != Functions.end())
233 return error(Twine("redefinition of machine function '") + FunctionName +
235 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
237 createDummyFunction(FunctionName, M);
238 else if (!M.getFunction(FunctionName))
239 return error(Twine("function '") + FunctionName +
240 "' isn't defined in the provided LLVM IR");
244 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
245 auto &Context = M.getContext();
246 Function *F = cast<Function>(M.getOrInsertFunction(
247 Name, FunctionType::get(Type::getVoidTy(Context), false)));
248 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
249 new UnreachableInst(Context, BB);
252 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
253 auto It = Functions.find(MF.getName());
254 if (It == Functions.end())
255 return error(Twine("no machine function information for function '") +
256 MF.getName() + "' in the MIR file");
257 // TODO: Recreate the machine function.
258 const yaml::MachineFunction &YamlMF = *It->getValue();
259 if (YamlMF.Alignment)
260 MF.setAlignment(YamlMF.Alignment);
261 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
262 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
263 PerFunctionMIParsingState PFS;
264 if (initializeRegisterInfo(MF, MF.getRegInfo(), YamlMF,
265 PFS.VirtualRegisterSlots))
267 if (initializeFrameInfo(*MF.getFrameInfo(), YamlMF))
270 const auto &F = *MF.getFunction();
271 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
272 const BasicBlock *BB = nullptr;
273 const yaml::StringValue &Name = YamlMBB.Name;
274 if (!Name.Value.empty()) {
275 BB = dyn_cast_or_null<BasicBlock>(
276 F.getValueSymbolTable().lookup(Name.Value));
278 return error(Name.SourceRange.Start,
279 Twine("basic block '") + Name.Value +
280 "' is not defined in the function '" + MF.getName() +
283 auto *MBB = MF.CreateMachineBasicBlock(BB);
284 MF.insert(MF.end(), MBB);
286 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
288 return error(Twine("redefinition of machine basic block with id #") +
292 if (YamlMF.BasicBlocks.empty())
293 return error(Twine("machine function '") + Twine(MF.getName()) +
294 "' requires at least one machine basic block in its body");
295 // Initialize the machine basic blocks after creating them all so that the
296 // machine instructions parser can resolve the MBB references.
298 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
299 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
306 bool MIRParserImpl::initializeMachineBasicBlock(
307 MachineFunction &MF, MachineBasicBlock &MBB,
308 const yaml::MachineBasicBlock &YamlMBB,
309 const PerFunctionMIParsingState &PFS) {
310 MBB.setAlignment(YamlMBB.Alignment);
311 if (YamlMBB.AddressTaken)
312 MBB.setHasAddressTaken();
313 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
315 // Parse the successors.
316 for (const auto &MBBSource : YamlMBB.Successors) {
317 MachineBasicBlock *SuccMBB = nullptr;
318 if (parseMBBReference(SuccMBB, SM, MF, MBBSource.Value, PFS, IRSlots,
320 return error(Error, MBBSource.SourceRange);
321 // TODO: Report an error when adding the same successor more than once.
322 MBB.addSuccessor(SuccMBB);
324 // Parse the instructions.
325 for (const auto &MISource : YamlMBB.Instructions) {
326 MachineInstr *MI = nullptr;
327 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
328 return error(Error, MISource.SourceRange);
329 MBB.insert(MBB.end(), MI);
334 bool MIRParserImpl::initializeRegisterInfo(
335 const MachineFunction &MF, MachineRegisterInfo &RegInfo,
336 const yaml::MachineFunction &YamlMF,
337 DenseMap<unsigned, unsigned> &VirtualRegisterSlots) {
338 assert(RegInfo.isSSA());
341 assert(RegInfo.tracksLiveness());
342 if (!YamlMF.TracksRegLiveness)
343 RegInfo.invalidateLiveness();
344 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
346 // Parse the virtual register information.
347 for (const auto &VReg : YamlMF.VirtualRegisters) {
348 const auto *RC = getRegClass(MF, VReg.Class.Value);
350 return error(VReg.Class.SourceRange.Start,
351 Twine("use of undefined register class '") +
352 VReg.Class.Value + "'");
353 unsigned Reg = RegInfo.createVirtualRegister(RC);
354 // TODO: Report an error when the same virtual register with the same ID is
356 VirtualRegisterSlots.insert(std::make_pair(VReg.ID, Reg));
361 bool MIRParserImpl::initializeFrameInfo(MachineFrameInfo &MFI,
362 const yaml::MachineFunction &YamlMF) {
363 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
364 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
365 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
366 MFI.setHasStackMap(YamlMFI.HasStackMap);
367 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
368 MFI.setStackSize(YamlMFI.StackSize);
369 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
370 if (YamlMFI.MaxAlignment)
371 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
372 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
373 MFI.setHasCalls(YamlMFI.HasCalls);
374 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
375 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
376 MFI.setHasVAStart(YamlMFI.HasVAStart);
377 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
379 // Initialize the fixed frame objects.
380 for (const auto &Object : YamlMF.FixedStackObjects) {
382 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
383 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
384 Object.IsImmutable, Object.IsAliased);
386 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
387 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
388 // TODO: Store the mapping between fixed object IDs and object indices to
389 // parse fixed stack object references correctly.
392 // Initialize the ordinary frame objects.
393 for (const auto &Object : YamlMF.StackObjects) {
394 int ObjectIdx = MFI.CreateStackObject(
395 Object.Size, Object.Alignment,
396 Object.Type == yaml::MachineStackObject::SpillSlot);
397 MFI.setObjectOffset(ObjectIdx, Object.Offset);
398 // TODO: Store the mapping between object IDs and object indices to parse
399 // stack object references correctly.
404 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
405 SMRange SourceRange) {
406 assert(SourceRange.isValid() && "Invalid source range");
407 SMLoc Loc = SourceRange.Start;
408 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
409 *Loc.getPointer() == '\'';
410 // Translate the location of the error from the location in the MI string to
411 // the corresponding location in the MIR file.
412 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
415 // TODO: Translate any source ranges as well.
416 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
420 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
421 SMRange SourceRange) {
422 assert(SourceRange.isValid());
424 // Translate the location of the error from the location in the llvm IR string
425 // to the corresponding location in the MIR file.
426 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
427 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
428 unsigned Column = Error.getColumnNo();
429 StringRef LineStr = Error.getLineContents();
430 SMLoc Loc = Error.getLoc();
432 // Get the full line and adjust the column number by taking the indentation of
433 // LLVM IR into account.
434 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
436 if (L.line_number() == Line) {
438 Loc = SMLoc::getFromPointer(LineStr.data());
439 auto Indent = LineStr.find(Error.getLineContents());
440 if (Indent != StringRef::npos)
446 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
447 Error.getMessage(), LineStr, Error.getRanges(),
451 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
452 if (!Names2RegClasses.empty())
454 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
455 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
456 const auto *RC = TRI->getRegClass(I);
457 Names2RegClasses.insert(
458 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
462 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
464 initNames2RegClasses(MF);
465 auto RegClassInfo = Names2RegClasses.find(Name);
466 if (RegClassInfo == Names2RegClasses.end())
468 return RegClassInfo->getValue();
471 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
472 : Impl(std::move(Impl)) {}
474 MIRParser::~MIRParser() {}
476 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
478 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
479 return Impl->initializeMachineFunction(MF);
482 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
484 LLVMContext &Context) {
485 auto FileOrErr = MemoryBuffer::getFile(Filename);
486 if (std::error_code EC = FileOrErr.getError()) {
487 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
488 "Could not open input file: " + EC.message());
491 return createMIRParser(std::move(FileOrErr.get()), Context);
494 std::unique_ptr<MIRParser>
495 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
496 LLVMContext &Context) {
497 auto Filename = Contents->getBufferIdentifier();
498 return llvm::make_unique<MIRParser>(
499 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));