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/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/MIRYamlMapping.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueSymbolTable.h"
34 #include "llvm/Support/LineIterator.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/YAMLTraits.h"
45 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
51 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
53 /// Maps from register class names to register classes.
54 StringMap<const TargetRegisterClass *> Names2RegClasses;
57 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58 LLVMContext &Context);
60 void reportDiagnostic(const SMDiagnostic &Diag);
62 /// Report an error with the given message at unknown location.
64 /// Always returns true.
65 bool error(const Twine &Message);
67 /// Report an error with the given message at the given location.
69 /// Always returns true.
70 bool error(SMLoc Loc, const Twine &Message);
72 /// Report a given error with the location translated from the location in an
73 /// embedded string literal to a location in the MIR file.
75 /// Always returns true.
76 bool error(const SMDiagnostic &Error, SMRange SourceRange);
78 /// Try to parse the optional LLVM module and the machine functions in the MIR
81 /// Return null if an error occurred.
82 std::unique_ptr<Module> parse();
84 /// Parse the machine function in the current YAML document.
86 /// \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.
90 /// Return true if an error occurred.
91 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
93 /// Initialize the machine function to the state that's described in the MIR
96 /// Return true if error occurred.
97 bool initializeMachineFunction(MachineFunction &MF);
99 /// Initialize the machine basic block using it's YAML representation.
101 /// Return true if an error occurred.
102 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
103 const yaml::MachineBasicBlock &YamlMBB,
104 const PerFunctionMIParsingState &PFS);
106 bool initializeRegisterInfo(MachineFunction &MF,
107 const yaml::MachineFunction &YamlMF,
108 PerFunctionMIParsingState &PFS);
110 void inferRegisterInfo(MachineFunction &MF,
111 const yaml::MachineFunction &YamlMF);
113 bool initializeFrameInfo(MachineFunction &MF,
114 const yaml::MachineFunction &YamlMF,
115 PerFunctionMIParsingState &PFS);
117 bool parseCalleeSavedRegister(MachineFunction &MF,
118 PerFunctionMIParsingState &PFS,
119 std::vector<CalleeSavedInfo> &CSIInfo,
120 const yaml::StringValue &RegisterSource,
123 bool initializeConstantPool(MachineConstantPool &ConstantPool,
124 const yaml::MachineFunction &YamlMF,
125 const MachineFunction &MF,
126 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
128 bool initializeJumpTableInfo(MachineFunction &MF,
129 const yaml::MachineJumpTable &YamlJTI,
130 PerFunctionMIParsingState &PFS);
133 bool parseMBBReference(MachineBasicBlock *&MBB,
134 const yaml::StringValue &Source, MachineFunction &MF,
135 const PerFunctionMIParsingState &PFS);
137 /// Return a MIR diagnostic converted from an MI string diagnostic.
138 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
139 SMRange SourceRange);
141 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
142 /// block scalar string.
143 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
144 SMRange SourceRange);
146 /// Create an empty function with the given name.
147 void createDummyFunction(StringRef Name, Module &M);
149 void initNames2RegClasses(const MachineFunction &MF);
151 /// Check if the given identifier is a name of a register class.
153 /// Return null if the name isn't a register class.
154 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
158 } // end namespace llvm
160 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
161 StringRef Filename, LLVMContext &Context)
162 : SM(), Filename(Filename), Context(Context) {
163 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
166 bool MIRParserImpl::error(const Twine &Message) {
167 Context.diagnose(DiagnosticInfoMIRParser(
168 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
172 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
173 Context.diagnose(DiagnosticInfoMIRParser(
174 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
178 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
179 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
180 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
184 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
185 DiagnosticSeverity Kind;
186 switch (Diag.getKind()) {
187 case SourceMgr::DK_Error:
190 case SourceMgr::DK_Warning:
193 case SourceMgr::DK_Note:
197 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
200 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
201 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
204 std::unique_ptr<Module> MIRParserImpl::parse() {
205 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
206 /*Ctxt=*/nullptr, handleYAMLDiag, this);
209 if (!In.setCurrentDocument()) {
212 // Create an empty module when the MIR file is empty.
213 return llvm::make_unique<Module>(Filename, Context);
216 std::unique_ptr<Module> M;
217 bool NoLLVMIR = false;
218 // Parse the block scalar manually so that we can return unique pointer
219 // without having to go trough YAML traits.
220 if (const auto *BSN =
221 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
223 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
226 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
230 if (!In.setCurrentDocument())
233 // Create an new, empty module.
234 M = llvm::make_unique<Module>(Filename, Context);
238 // Parse the machine functions.
240 if (parseMachineFunction(In, *M, NoLLVMIR))
243 } while (In.setCurrentDocument());
248 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
250 auto MF = llvm::make_unique<yaml::MachineFunction>();
251 yaml::yamlize(In, *MF, false);
254 auto FunctionName = MF->Name;
255 if (Functions.find(FunctionName) != Functions.end())
256 return error(Twine("redefinition of machine function '") + FunctionName +
258 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
260 createDummyFunction(FunctionName, M);
261 else if (!M.getFunction(FunctionName))
262 return error(Twine("function '") + FunctionName +
263 "' isn't defined in the provided LLVM IR");
267 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
268 auto &Context = M.getContext();
269 Function *F = cast<Function>(M.getOrInsertFunction(
270 Name, FunctionType::get(Type::getVoidTy(Context), false)));
271 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
272 new UnreachableInst(Context, BB);
275 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
276 auto It = Functions.find(MF.getName());
277 if (It == Functions.end())
278 return error(Twine("no machine function information for function '") +
279 MF.getName() + "' in the MIR file");
280 // TODO: Recreate the machine function.
281 const yaml::MachineFunction &YamlMF = *It->getValue();
282 if (YamlMF.Alignment)
283 MF.setAlignment(YamlMF.Alignment);
284 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
285 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
286 PerFunctionMIParsingState PFS;
287 if (initializeRegisterInfo(MF, YamlMF, PFS))
289 if (!YamlMF.Constants.empty()) {
290 auto *ConstantPool = MF.getConstantPool();
291 assert(ConstantPool && "Constant pool must be created");
292 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
293 PFS.ConstantPoolSlots))
297 const auto &F = *MF.getFunction();
298 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
299 const BasicBlock *BB = nullptr;
300 const yaml::StringValue &Name = YamlMBB.Name;
301 const yaml::StringValue &IRBlock = YamlMBB.IRBlock;
302 if (!Name.Value.empty()) {
303 BB = dyn_cast_or_null<BasicBlock>(
304 F.getValueSymbolTable().lookup(Name.Value));
306 return error(Name.SourceRange.Start,
307 Twine("basic block '") + Name.Value +
308 "' is not defined in the function '" + MF.getName() +
311 if (!IRBlock.Value.empty()) {
312 // TODO: Report an error when both name and ir block are specified.
314 if (parseIRBlockReference(BB, SM, MF, IRBlock.Value, PFS, IRSlots, Error))
315 return error(Error, IRBlock.SourceRange);
317 auto *MBB = MF.CreateMachineBasicBlock(BB);
318 MF.insert(MF.end(), MBB);
320 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
322 return error(Twine("redefinition of machine basic block with id #") +
326 if (YamlMF.BasicBlocks.empty())
327 return error(Twine("machine function '") + Twine(MF.getName()) +
328 "' requires at least one machine basic block in its body");
329 // Initialize the frame information after creating all the MBBs so that the
330 // MBB references in the frame information can be resolved.
331 if (initializeFrameInfo(MF, YamlMF, PFS))
333 // Initialize the jump table after creating all the MBBs so that the MBB
334 // references can be resolved.
335 if (!YamlMF.JumpTableInfo.Entries.empty() &&
336 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
338 // Initialize the machine basic blocks after creating them all so that the
339 // machine instructions parser can resolve the MBB references.
341 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
342 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
346 inferRegisterInfo(MF, YamlMF);
347 // FIXME: This is a temporary workaround until the reserved registers can be
349 MF.getRegInfo().freezeReservedRegs(MF);
354 bool MIRParserImpl::initializeMachineBasicBlock(
355 MachineFunction &MF, MachineBasicBlock &MBB,
356 const yaml::MachineBasicBlock &YamlMBB,
357 const PerFunctionMIParsingState &PFS) {
358 MBB.setAlignment(YamlMBB.Alignment);
359 if (YamlMBB.AddressTaken)
360 MBB.setHasAddressTaken();
361 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
363 // Parse the successors.
364 const auto &Weights = YamlMBB.SuccessorWeights;
365 bool HasWeights = !Weights.empty();
366 if (HasWeights && Weights.size() != YamlMBB.Successors.size()) {
367 bool IsFew = Weights.size() < YamlMBB.Successors.size();
368 return error(IsFew ? Weights.back().SourceRange.End
369 : Weights[YamlMBB.Successors.size()].SourceRange.Start,
370 Twine("too ") + (IsFew ? "few" : "many") +
371 " successor weights, expected " +
372 Twine(YamlMBB.Successors.size()) + ", have " +
373 Twine(Weights.size()));
375 size_t SuccessorIndex = 0;
376 for (const auto &MBBSource : YamlMBB.Successors) {
377 MachineBasicBlock *SuccMBB = nullptr;
378 if (parseMBBReference(SuccMBB, MBBSource, MF, PFS))
380 // TODO: Report an error when adding the same successor more than once.
381 MBB.addSuccessor(SuccMBB, HasWeights ? Weights[SuccessorIndex++].Value : 0);
383 // Parse the liveins.
384 for (const auto &LiveInSource : YamlMBB.LiveIns) {
386 if (parseNamedRegisterReference(Reg, SM, MF, LiveInSource.Value, PFS,
388 return error(Error, LiveInSource.SourceRange);
391 // Parse the instructions.
392 for (const auto &MISource : YamlMBB.Instructions) {
393 MachineInstr *MI = nullptr;
394 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
395 return error(Error, MISource.SourceRange);
396 MBB.insert(MBB.end(), MI);
401 bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
402 const yaml::MachineFunction &YamlMF,
403 PerFunctionMIParsingState &PFS) {
404 MachineRegisterInfo &RegInfo = MF.getRegInfo();
405 assert(RegInfo.isSSA());
408 assert(RegInfo.tracksLiveness());
409 if (!YamlMF.TracksRegLiveness)
410 RegInfo.invalidateLiveness();
411 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
414 // Parse the virtual register information.
415 for (const auto &VReg : YamlMF.VirtualRegisters) {
416 const auto *RC = getRegClass(MF, VReg.Class.Value);
418 return error(VReg.Class.SourceRange.Start,
419 Twine("use of undefined register class '") +
420 VReg.Class.Value + "'");
421 unsigned Reg = RegInfo.createVirtualRegister(RC);
422 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
424 return error(VReg.ID.SourceRange.Start,
425 Twine("redefinition of virtual register '%") +
426 Twine(VReg.ID.Value) + "'");
427 if (!VReg.PreferredRegister.Value.empty()) {
428 unsigned PreferredReg = 0;
429 if (parseNamedRegisterReference(PreferredReg, SM, MF,
430 VReg.PreferredRegister.Value, PFS,
432 return error(Error, VReg.PreferredRegister.SourceRange);
433 RegInfo.setSimpleHint(Reg, PreferredReg);
437 // Parse the liveins.
438 for (const auto &LiveIn : YamlMF.LiveIns) {
440 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
442 return error(Error, LiveIn.Register.SourceRange);
444 if (!LiveIn.VirtualRegister.Value.empty()) {
445 if (parseVirtualRegisterReference(
446 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
447 return error(Error, LiveIn.VirtualRegister.SourceRange);
449 RegInfo.addLiveIn(Reg, VReg);
452 // Parse the callee saved register mask.
453 BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
454 if (!YamlMF.CalleeSavedRegisters)
456 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
458 if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
460 return error(Error, RegSource.SourceRange);
461 CalleeSavedRegisterMask[Reg] = true;
463 RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
467 void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
468 const yaml::MachineFunction &YamlMF) {
469 if (YamlMF.CalleeSavedRegisters)
471 for (const MachineBasicBlock &MBB : MF) {
472 for (const MachineInstr &MI : MBB) {
473 for (const MachineOperand &MO : MI.operands()) {
476 MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
482 bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
483 const yaml::MachineFunction &YamlMF,
484 PerFunctionMIParsingState &PFS) {
485 MachineFrameInfo &MFI = *MF.getFrameInfo();
486 const Function &F = *MF.getFunction();
487 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
488 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
489 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
490 MFI.setHasStackMap(YamlMFI.HasStackMap);
491 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
492 MFI.setStackSize(YamlMFI.StackSize);
493 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
494 if (YamlMFI.MaxAlignment)
495 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
496 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
497 MFI.setHasCalls(YamlMFI.HasCalls);
498 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
499 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
500 MFI.setHasVAStart(YamlMFI.HasVAStart);
501 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
502 if (!YamlMFI.SavePoint.Value.empty()) {
503 MachineBasicBlock *MBB = nullptr;
504 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
506 MFI.setSavePoint(MBB);
508 if (!YamlMFI.RestorePoint.Value.empty()) {
509 MachineBasicBlock *MBB = nullptr;
510 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
512 MFI.setRestorePoint(MBB);
515 std::vector<CalleeSavedInfo> CSIInfo;
516 // Initialize the fixed frame objects.
517 for (const auto &Object : YamlMF.FixedStackObjects) {
519 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
520 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
521 Object.IsImmutable, Object.IsAliased);
523 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
524 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
525 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
528 return error(Object.ID.SourceRange.Start,
529 Twine("redefinition of fixed stack object '%fixed-stack.") +
530 Twine(Object.ID.Value) + "'");
531 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
536 // Initialize the ordinary frame objects.
537 for (const auto &Object : YamlMF.StackObjects) {
539 const AllocaInst *Alloca = nullptr;
540 const yaml::StringValue &Name = Object.Name;
541 if (!Name.Value.empty()) {
542 Alloca = dyn_cast_or_null<AllocaInst>(
543 F.getValueSymbolTable().lookup(Name.Value));
545 return error(Name.SourceRange.Start,
546 "alloca instruction named '" + Name.Value +
547 "' isn't defined in the function '" + F.getName() +
550 if (Object.Type == yaml::MachineStackObject::VariableSized)
551 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
553 ObjectIdx = MFI.CreateStackObject(
554 Object.Size, Object.Alignment,
555 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
556 MFI.setObjectOffset(ObjectIdx, Object.Offset);
557 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
559 return error(Object.ID.SourceRange.Start,
560 Twine("redefinition of stack object '%stack.") +
561 Twine(Object.ID.Value) + "'");
562 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
566 MFI.setCalleeSavedInfo(CSIInfo);
567 if (!CSIInfo.empty())
568 MFI.setCalleeSavedInfoValid(true);
572 bool MIRParserImpl::parseCalleeSavedRegister(
573 MachineFunction &MF, PerFunctionMIParsingState &PFS,
574 std::vector<CalleeSavedInfo> &CSIInfo,
575 const yaml::StringValue &RegisterSource, int FrameIdx) {
576 if (RegisterSource.Value.empty())
580 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
582 return error(Error, RegisterSource.SourceRange);
583 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
587 bool MIRParserImpl::initializeConstantPool(
588 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
589 const MachineFunction &MF,
590 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
591 const auto &M = *MF.getFunction()->getParent();
593 for (const auto &YamlConstant : YamlMF.Constants) {
594 const Constant *Value = dyn_cast_or_null<Constant>(
595 parseConstantValue(YamlConstant.Value.Value, Error, M));
597 return error(Error, YamlConstant.Value.SourceRange);
599 YamlConstant.Alignment
600 ? YamlConstant.Alignment
601 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
602 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
603 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
605 return error(YamlConstant.ID.SourceRange.Start,
606 Twine("redefinition of constant pool item '%const.") +
607 Twine(YamlConstant.ID.Value) + "'");
612 bool MIRParserImpl::initializeJumpTableInfo(
613 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
614 PerFunctionMIParsingState &PFS) {
615 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
616 for (const auto &Entry : YamlJTI.Entries) {
617 std::vector<MachineBasicBlock *> Blocks;
618 for (const auto &MBBSource : Entry.Blocks) {
619 MachineBasicBlock *MBB = nullptr;
620 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
622 Blocks.push_back(MBB);
624 unsigned Index = JTI->createJumpTableIndex(Blocks);
625 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
627 return error(Entry.ID.SourceRange.Start,
628 Twine("redefinition of jump table entry '%jump-table.") +
629 Twine(Entry.ID.Value) + "'");
634 bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
635 const yaml::StringValue &Source,
637 const PerFunctionMIParsingState &PFS) {
639 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
640 return error(Error, Source.SourceRange);
644 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
645 SMRange SourceRange) {
646 assert(SourceRange.isValid() && "Invalid source range");
647 SMLoc Loc = SourceRange.Start;
648 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
649 *Loc.getPointer() == '\'';
650 // Translate the location of the error from the location in the MI string to
651 // the corresponding location in the MIR file.
652 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
655 // TODO: Translate any source ranges as well.
656 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
660 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
661 SMRange SourceRange) {
662 assert(SourceRange.isValid());
664 // Translate the location of the error from the location in the llvm IR string
665 // to the corresponding location in the MIR file.
666 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
667 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
668 unsigned Column = Error.getColumnNo();
669 StringRef LineStr = Error.getLineContents();
670 SMLoc Loc = Error.getLoc();
672 // Get the full line and adjust the column number by taking the indentation of
673 // LLVM IR into account.
674 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
676 if (L.line_number() == Line) {
678 Loc = SMLoc::getFromPointer(LineStr.data());
679 auto Indent = LineStr.find(Error.getLineContents());
680 if (Indent != StringRef::npos)
686 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
687 Error.getMessage(), LineStr, Error.getRanges(),
691 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
692 if (!Names2RegClasses.empty())
694 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
695 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
696 const auto *RC = TRI->getRegClass(I);
697 Names2RegClasses.insert(
698 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
702 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
704 initNames2RegClasses(MF);
705 auto RegClassInfo = Names2RegClasses.find(Name);
706 if (RegClassInfo == Names2RegClasses.end())
708 return RegClassInfo->getValue();
711 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
712 : Impl(std::move(Impl)) {}
714 MIRParser::~MIRParser() {}
716 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
718 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
719 return Impl->initializeMachineFunction(MF);
722 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
724 LLVMContext &Context) {
725 auto FileOrErr = MemoryBuffer::getFile(Filename);
726 if (std::error_code EC = FileOrErr.getError()) {
727 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
728 "Could not open input file: " + EC.message());
731 return createMIRParser(std::move(FileOrErr.get()), Context);
734 std::unique_ptr<MIRParser>
735 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
736 LLVMContext &Context) {
737 auto Filename = Contents->getBufferIdentifier();
738 return llvm::make_unique<MIRParser>(
739 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));