1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the class that parses the optional LLVM IR and machine 10 // functions that are stored in MIR files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MIRParser/MIRParser.h" 15 #include "MIParser.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/StringMap.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/AsmParser/Parser.h" 21 #include "llvm/AsmParser/SlotMapping.h" 22 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 23 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 24 #include "llvm/CodeGen/MIRYamlMapping.h" 25 #include "llvm/CodeGen/MachineConstantPool.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineModuleInfo.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/ValueSymbolTable.h" 37 #include "llvm/Support/LineIterator.h" 38 #include "llvm/Support/MemoryBuffer.h" 39 #include "llvm/Support/SMLoc.h" 40 #include "llvm/Support/SourceMgr.h" 41 #include "llvm/Support/YAMLTraits.h" 42 #include <memory> 43 44 using namespace llvm; 45 46 namespace llvm { 47 48 /// This class implements the parsing of LLVM IR that's embedded inside a MIR 49 /// file. 50 class MIRParserImpl { 51 SourceMgr SM; 52 yaml::Input In; 53 StringRef Filename; 54 LLVMContext &Context; 55 SlotMapping IRSlots; 56 /// Maps from register class names to register classes. 57 Name2RegClassMap Names2RegClasses; 58 /// Maps from register bank names to register banks. 59 Name2RegBankMap Names2RegBanks; 60 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are 61 /// created and inserted into the given module when this is true. 62 bool NoLLVMIR = false; 63 /// True when a well formed MIR file does not contain any MIR/machine function 64 /// parts. 65 bool NoMIRDocuments = false; 66 67 public: 68 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, 69 StringRef Filename, LLVMContext &Context); 70 71 void reportDiagnostic(const SMDiagnostic &Diag); 72 73 /// Report an error with the given message at unknown location. 74 /// 75 /// Always returns true. 76 bool error(const Twine &Message); 77 78 /// Report an error with the given message at the given location. 79 /// 80 /// Always returns true. 81 bool error(SMLoc Loc, const Twine &Message); 82 83 /// Report a given error with the location translated from the location in an 84 /// embedded string literal to a location in the MIR file. 85 /// 86 /// Always returns true. 87 bool error(const SMDiagnostic &Error, SMRange SourceRange); 88 89 /// Try to parse the optional LLVM module and the machine functions in the MIR 90 /// file. 91 /// 92 /// Return null if an error occurred. 93 std::unique_ptr<Module> parseIRModule(); 94 95 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI); 96 97 /// Parse the machine function in the current YAML document. 98 /// 99 /// 100 /// Return true if an error occurred. 101 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI); 102 103 /// Initialize the machine function to the state that's described in the MIR 104 /// file. 105 /// 106 /// Return true if error occurred. 107 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF, 108 MachineFunction &MF); 109 110 bool parseRegisterInfo(PerFunctionMIParsingState &PFS, 111 const yaml::MachineFunction &YamlMF); 112 113 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, 114 const yaml::MachineFunction &YamlMF); 115 116 bool initializeFrameInfo(PerFunctionMIParsingState &PFS, 117 const yaml::MachineFunction &YamlMF); 118 119 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, 120 std::vector<CalleeSavedInfo> &CSIInfo, 121 const yaml::StringValue &RegisterSource, 122 bool IsRestored, int FrameIdx); 123 124 template <typename T> 125 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, 126 const T &Object, 127 int FrameIdx); 128 129 bool initializeConstantPool(PerFunctionMIParsingState &PFS, 130 MachineConstantPool &ConstantPool, 131 const yaml::MachineFunction &YamlMF); 132 133 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, 134 const yaml::MachineJumpTable &YamlJTI); 135 136 private: 137 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, 138 const yaml::StringValue &Source); 139 140 bool parseMBBReference(PerFunctionMIParsingState &PFS, 141 MachineBasicBlock *&MBB, 142 const yaml::StringValue &Source); 143 144 /// Return a MIR diagnostic converted from an MI string diagnostic. 145 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error, 146 SMRange SourceRange); 147 148 /// Return a MIR diagnostic converted from a diagnostic located in a YAML 149 /// block scalar string. 150 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error, 151 SMRange SourceRange); 152 153 void initNames2RegClasses(const MachineFunction &MF); 154 void initNames2RegBanks(const MachineFunction &MF); 155 156 /// Check if the given identifier is a name of a register class. 157 /// 158 /// Return null if the name isn't a register class. 159 const TargetRegisterClass *getRegClass(const MachineFunction &MF, 160 StringRef Name); 161 162 /// Check if the given identifier is a name of a register bank. 163 /// 164 /// Return null if the name isn't a register bank. 165 const RegisterBank *getRegBank(const MachineFunction &MF, StringRef Name); 166 167 void computeFunctionProperties(MachineFunction &MF); 168 }; 169 170 } // end namespace llvm 171 172 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) { 173 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag); 174 } 175 176 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, 177 StringRef Filename, LLVMContext &Context) 178 : SM(), 179 In(SM.getMemoryBuffer( 180 SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))->getBuffer(), 181 nullptr, handleYAMLDiag, this), 182 Filename(Filename), 183 Context(Context) { 184 In.setContext(&In); 185 } 186 187 bool MIRParserImpl::error(const Twine &Message) { 188 Context.diagnose(DiagnosticInfoMIRParser( 189 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str()))); 190 return true; 191 } 192 193 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) { 194 Context.diagnose(DiagnosticInfoMIRParser( 195 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message))); 196 return true; 197 } 198 199 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) { 200 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error"); 201 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange)); 202 return true; 203 } 204 205 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) { 206 DiagnosticSeverity Kind; 207 switch (Diag.getKind()) { 208 case SourceMgr::DK_Error: 209 Kind = DS_Error; 210 break; 211 case SourceMgr::DK_Warning: 212 Kind = DS_Warning; 213 break; 214 case SourceMgr::DK_Note: 215 Kind = DS_Note; 216 break; 217 case SourceMgr::DK_Remark: 218 llvm_unreachable("remark unexpected"); 219 break; 220 } 221 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag)); 222 } 223 224 std::unique_ptr<Module> MIRParserImpl::parseIRModule() { 225 if (!In.setCurrentDocument()) { 226 if (In.error()) 227 return nullptr; 228 // Create an empty module when the MIR file is empty. 229 NoMIRDocuments = true; 230 return llvm::make_unique<Module>(Filename, Context); 231 } 232 233 std::unique_ptr<Module> M; 234 // Parse the block scalar manually so that we can return unique pointer 235 // without having to go trough YAML traits. 236 if (const auto *BSN = 237 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) { 238 SMDiagnostic Error; 239 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error, 240 Context, &IRSlots, /*UpgradeDebugInfo=*/false); 241 if (!M) { 242 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange())); 243 return nullptr; 244 } 245 In.nextDocument(); 246 if (!In.setCurrentDocument()) 247 NoMIRDocuments = true; 248 } else { 249 // Create an new, empty module. 250 M = llvm::make_unique<Module>(Filename, Context); 251 NoLLVMIR = true; 252 } 253 return M; 254 } 255 256 bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) { 257 if (NoMIRDocuments) 258 return false; 259 260 // Parse the machine functions. 261 do { 262 if (parseMachineFunction(M, MMI)) 263 return true; 264 In.nextDocument(); 265 } while (In.setCurrentDocument()); 266 267 return false; 268 } 269 270 /// Create an empty function with the given name. 271 static Function *createDummyFunction(StringRef Name, Module &M) { 272 auto &Context = M.getContext(); 273 Function *F = cast<Function>(M.getOrInsertFunction( 274 Name, FunctionType::get(Type::getVoidTy(Context), false))); 275 BasicBlock *BB = BasicBlock::Create(Context, "entry", F); 276 new UnreachableInst(Context, BB); 277 return F; 278 } 279 280 bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) { 281 // Parse the yaml. 282 yaml::MachineFunction YamlMF; 283 yaml::EmptyContext Ctx; 284 yaml::yamlize(In, YamlMF, false, Ctx); 285 if (In.error()) 286 return true; 287 288 // Search for the corresponding IR function. 289 StringRef FunctionName = YamlMF.Name; 290 Function *F = M.getFunction(FunctionName); 291 if (!F) { 292 if (NoLLVMIR) { 293 F = createDummyFunction(FunctionName, M); 294 } else { 295 return error(Twine("function '") + FunctionName + 296 "' isn't defined in the provided LLVM IR"); 297 } 298 } 299 if (MMI.getMachineFunction(*F) != nullptr) 300 return error(Twine("redefinition of machine function '") + FunctionName + 301 "'"); 302 303 // Create the MachineFunction. 304 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); 305 if (initializeMachineFunction(YamlMF, MF)) 306 return true; 307 308 return false; 309 } 310 311 static bool isSSA(const MachineFunction &MF) { 312 const MachineRegisterInfo &MRI = MF.getRegInfo(); 313 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 314 unsigned Reg = TargetRegisterInfo::index2VirtReg(I); 315 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg)) 316 return false; 317 } 318 return true; 319 } 320 321 void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) { 322 MachineFunctionProperties &Properties = MF.getProperties(); 323 324 bool HasPHI = false; 325 bool HasInlineAsm = false; 326 for (const MachineBasicBlock &MBB : MF) { 327 for (const MachineInstr &MI : MBB) { 328 if (MI.isPHI()) 329 HasPHI = true; 330 if (MI.isInlineAsm()) 331 HasInlineAsm = true; 332 } 333 } 334 if (!HasPHI) 335 Properties.set(MachineFunctionProperties::Property::NoPHIs); 336 MF.setHasInlineAsm(HasInlineAsm); 337 338 if (isSSA(MF)) 339 Properties.set(MachineFunctionProperties::Property::IsSSA); 340 else 341 Properties.reset(MachineFunctionProperties::Property::IsSSA); 342 343 const MachineRegisterInfo &MRI = MF.getRegInfo(); 344 if (MRI.getNumVirtRegs() == 0) 345 Properties.set(MachineFunctionProperties::Property::NoVRegs); 346 } 347 348 bool 349 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF, 350 MachineFunction &MF) { 351 // TODO: Recreate the machine function. 352 initNames2RegClasses(MF); 353 initNames2RegBanks(MF); 354 if (YamlMF.Alignment) 355 MF.setAlignment(YamlMF.Alignment); 356 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice); 357 MF.setHasWinCFI(YamlMF.HasWinCFI); 358 359 if (YamlMF.Legalized) 360 MF.getProperties().set(MachineFunctionProperties::Property::Legalized); 361 if (YamlMF.RegBankSelected) 362 MF.getProperties().set( 363 MachineFunctionProperties::Property::RegBankSelected); 364 if (YamlMF.Selected) 365 MF.getProperties().set(MachineFunctionProperties::Property::Selected); 366 if (YamlMF.FailedISel) 367 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 368 369 PerFunctionMIParsingState PFS(MF, SM, IRSlots, Names2RegClasses, 370 Names2RegBanks); 371 if (parseRegisterInfo(PFS, YamlMF)) 372 return true; 373 if (!YamlMF.Constants.empty()) { 374 auto *ConstantPool = MF.getConstantPool(); 375 assert(ConstantPool && "Constant pool must be created"); 376 if (initializeConstantPool(PFS, *ConstantPool, YamlMF)) 377 return true; 378 } 379 380 StringRef BlockStr = YamlMF.Body.Value.Value; 381 SMDiagnostic Error; 382 SourceMgr BlockSM; 383 BlockSM.AddNewSourceBuffer( 384 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false), 385 SMLoc()); 386 PFS.SM = &BlockSM; 387 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) { 388 reportDiagnostic( 389 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange)); 390 return true; 391 } 392 PFS.SM = &SM; 393 394 // Initialize the frame information after creating all the MBBs so that the 395 // MBB references in the frame information can be resolved. 396 if (initializeFrameInfo(PFS, YamlMF)) 397 return true; 398 // Initialize the jump table after creating all the MBBs so that the MBB 399 // references can be resolved. 400 if (!YamlMF.JumpTableInfo.Entries.empty() && 401 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo)) 402 return true; 403 // Parse the machine instructions after creating all of the MBBs so that the 404 // parser can resolve the MBB references. 405 StringRef InsnStr = YamlMF.Body.Value.Value; 406 SourceMgr InsnSM; 407 InsnSM.AddNewSourceBuffer( 408 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false), 409 SMLoc()); 410 PFS.SM = &InsnSM; 411 if (parseMachineInstructions(PFS, InsnStr, Error)) { 412 reportDiagnostic( 413 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange)); 414 return true; 415 } 416 PFS.SM = &SM; 417 418 if (setupRegisterInfo(PFS, YamlMF)) 419 return true; 420 421 computeFunctionProperties(MF); 422 423 MF.getSubtarget().mirFileLoaded(MF); 424 425 MF.verify(); 426 return false; 427 } 428 429 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS, 430 const yaml::MachineFunction &YamlMF) { 431 MachineFunction &MF = PFS.MF; 432 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 433 assert(RegInfo.tracksLiveness()); 434 if (!YamlMF.TracksRegLiveness) 435 RegInfo.invalidateLiveness(); 436 437 SMDiagnostic Error; 438 // Parse the virtual register information. 439 for (const auto &VReg : YamlMF.VirtualRegisters) { 440 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value); 441 if (Info.Explicit) 442 return error(VReg.ID.SourceRange.Start, 443 Twine("redefinition of virtual register '%") + 444 Twine(VReg.ID.Value) + "'"); 445 Info.Explicit = true; 446 447 if (StringRef(VReg.Class.Value).equals("_")) { 448 Info.Kind = VRegInfo::GENERIC; 449 Info.D.RegBank = nullptr; 450 } else { 451 const auto *RC = getRegClass(MF, VReg.Class.Value); 452 if (RC) { 453 Info.Kind = VRegInfo::NORMAL; 454 Info.D.RC = RC; 455 } else { 456 const RegisterBank *RegBank = getRegBank(MF, VReg.Class.Value); 457 if (!RegBank) 458 return error( 459 VReg.Class.SourceRange.Start, 460 Twine("use of undefined register class or register bank '") + 461 VReg.Class.Value + "'"); 462 Info.Kind = VRegInfo::REGBANK; 463 Info.D.RegBank = RegBank; 464 } 465 } 466 467 if (!VReg.PreferredRegister.Value.empty()) { 468 if (Info.Kind != VRegInfo::NORMAL) 469 return error(VReg.Class.SourceRange.Start, 470 Twine("preferred register can only be set for normal vregs")); 471 472 if (parseRegisterReference(PFS, Info.PreferredReg, 473 VReg.PreferredRegister.Value, Error)) 474 return error(Error, VReg.PreferredRegister.SourceRange); 475 } 476 } 477 478 // Parse the liveins. 479 for (const auto &LiveIn : YamlMF.LiveIns) { 480 unsigned Reg = 0; 481 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error)) 482 return error(Error, LiveIn.Register.SourceRange); 483 unsigned VReg = 0; 484 if (!LiveIn.VirtualRegister.Value.empty()) { 485 VRegInfo *Info; 486 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value, 487 Error)) 488 return error(Error, LiveIn.VirtualRegister.SourceRange); 489 VReg = Info->VReg; 490 } 491 RegInfo.addLiveIn(Reg, VReg); 492 } 493 494 // Parse the callee saved registers (Registers that will 495 // be saved for the caller). 496 if (YamlMF.CalleeSavedRegisters) { 497 SmallVector<MCPhysReg, 16> CalleeSavedRegisters; 498 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) { 499 unsigned Reg = 0; 500 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error)) 501 return error(Error, RegSource.SourceRange); 502 CalleeSavedRegisters.push_back(Reg); 503 } 504 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters); 505 } 506 507 return false; 508 } 509 510 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS, 511 const yaml::MachineFunction &YamlMF) { 512 MachineFunction &MF = PFS.MF; 513 MachineRegisterInfo &MRI = MF.getRegInfo(); 514 bool Error = false; 515 // Create VRegs 516 auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) { 517 unsigned Reg = Info.VReg; 518 switch (Info.Kind) { 519 case VRegInfo::UNKNOWN: 520 error(Twine("Cannot determine class/bank of virtual register ") + 521 Name + " in function '" + MF.getName() + "'"); 522 Error = true; 523 break; 524 case VRegInfo::NORMAL: 525 MRI.setRegClass(Reg, Info.D.RC); 526 if (Info.PreferredReg != 0) 527 MRI.setSimpleHint(Reg, Info.PreferredReg); 528 break; 529 case VRegInfo::GENERIC: 530 break; 531 case VRegInfo::REGBANK: 532 MRI.setRegBank(Reg, *Info.D.RegBank); 533 break; 534 } 535 }; 536 537 for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end(); 538 I != E; I++) { 539 const VRegInfo &Info = *I->second; 540 populateVRegInfo(Info, Twine(I->first())); 541 } 542 543 for (auto P : PFS.VRegInfos) { 544 const VRegInfo &Info = *P.second; 545 populateVRegInfo(Info, Twine(P.first)); 546 } 547 548 // Compute MachineRegisterInfo::UsedPhysRegMask 549 for (const MachineBasicBlock &MBB : MF) { 550 for (const MachineInstr &MI : MBB) { 551 for (const MachineOperand &MO : MI.operands()) { 552 if (!MO.isRegMask()) 553 continue; 554 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask()); 555 } 556 } 557 } 558 559 // FIXME: This is a temporary workaround until the reserved registers can be 560 // serialized. 561 MRI.freezeReservedRegs(MF); 562 return Error; 563 } 564 565 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS, 566 const yaml::MachineFunction &YamlMF) { 567 MachineFunction &MF = PFS.MF; 568 MachineFrameInfo &MFI = MF.getFrameInfo(); 569 const Function &F = MF.getFunction(); 570 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo; 571 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken); 572 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken); 573 MFI.setHasStackMap(YamlMFI.HasStackMap); 574 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint); 575 MFI.setStackSize(YamlMFI.StackSize); 576 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment); 577 if (YamlMFI.MaxAlignment) 578 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment); 579 MFI.setAdjustsStack(YamlMFI.AdjustsStack); 580 MFI.setHasCalls(YamlMFI.HasCalls); 581 if (YamlMFI.MaxCallFrameSize != ~0u) 582 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize); 583 MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters); 584 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment); 585 MFI.setHasVAStart(YamlMFI.HasVAStart); 586 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc); 587 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize); 588 if (!YamlMFI.SavePoint.Value.empty()) { 589 MachineBasicBlock *MBB = nullptr; 590 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint)) 591 return true; 592 MFI.setSavePoint(MBB); 593 } 594 if (!YamlMFI.RestorePoint.Value.empty()) { 595 MachineBasicBlock *MBB = nullptr; 596 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint)) 597 return true; 598 MFI.setRestorePoint(MBB); 599 } 600 601 std::vector<CalleeSavedInfo> CSIInfo; 602 // Initialize the fixed frame objects. 603 for (const auto &Object : YamlMF.FixedStackObjects) { 604 int ObjectIdx; 605 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot) 606 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset, 607 Object.IsImmutable, Object.IsAliased); 608 else 609 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset); 610 MFI.setObjectAlignment(ObjectIdx, Object.Alignment); 611 MFI.setStackID(ObjectIdx, Object.StackID); 612 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value, 613 ObjectIdx)) 614 .second) 615 return error(Object.ID.SourceRange.Start, 616 Twine("redefinition of fixed stack object '%fixed-stack.") + 617 Twine(Object.ID.Value) + "'"); 618 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister, 619 Object.CalleeSavedRestored, ObjectIdx)) 620 return true; 621 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx)) 622 return true; 623 } 624 625 // Initialize the ordinary frame objects. 626 for (const auto &Object : YamlMF.StackObjects) { 627 int ObjectIdx; 628 const AllocaInst *Alloca = nullptr; 629 const yaml::StringValue &Name = Object.Name; 630 if (!Name.Value.empty()) { 631 Alloca = dyn_cast_or_null<AllocaInst>( 632 F.getValueSymbolTable()->lookup(Name.Value)); 633 if (!Alloca) 634 return error(Name.SourceRange.Start, 635 "alloca instruction named '" + Name.Value + 636 "' isn't defined in the function '" + F.getName() + 637 "'"); 638 } 639 if (Object.Type == yaml::MachineStackObject::VariableSized) 640 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca); 641 else 642 ObjectIdx = MFI.CreateStackObject( 643 Object.Size, Object.Alignment, 644 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca); 645 MFI.setObjectOffset(ObjectIdx, Object.Offset); 646 MFI.setStackID(ObjectIdx, Object.StackID); 647 648 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx)) 649 .second) 650 return error(Object.ID.SourceRange.Start, 651 Twine("redefinition of stack object '%stack.") + 652 Twine(Object.ID.Value) + "'"); 653 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister, 654 Object.CalleeSavedRestored, ObjectIdx)) 655 return true; 656 if (Object.LocalOffset) 657 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue()); 658 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx)) 659 return true; 660 } 661 MFI.setCalleeSavedInfo(CSIInfo); 662 if (!CSIInfo.empty()) 663 MFI.setCalleeSavedInfoValid(true); 664 665 // Initialize the various stack object references after initializing the 666 // stack objects. 667 if (!YamlMFI.StackProtector.Value.empty()) { 668 SMDiagnostic Error; 669 int FI; 670 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error)) 671 return error(Error, YamlMFI.StackProtector.SourceRange); 672 MFI.setStackProtectorIndex(FI); 673 } 674 return false; 675 } 676 677 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, 678 std::vector<CalleeSavedInfo> &CSIInfo, 679 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) { 680 if (RegisterSource.Value.empty()) 681 return false; 682 unsigned Reg = 0; 683 SMDiagnostic Error; 684 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error)) 685 return error(Error, RegisterSource.SourceRange); 686 CalleeSavedInfo CSI(Reg, FrameIdx); 687 CSI.setRestored(IsRestored); 688 CSIInfo.push_back(CSI); 689 return false; 690 } 691 692 /// Verify that given node is of a certain type. Return true on error. 693 template <typename T> 694 static bool typecheckMDNode(T *&Result, MDNode *Node, 695 const yaml::StringValue &Source, 696 StringRef TypeString, MIRParserImpl &Parser) { 697 if (!Node) 698 return false; 699 Result = dyn_cast<T>(Node); 700 if (!Result) 701 return Parser.error(Source.SourceRange.Start, 702 "expected a reference to a '" + TypeString + 703 "' metadata node"); 704 return false; 705 } 706 707 template <typename T> 708 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, 709 const T &Object, int FrameIdx) { 710 // Debug information can only be attached to stack objects; Fixed stack 711 // objects aren't supported. 712 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr; 713 if (parseMDNode(PFS, Var, Object.DebugVar) || 714 parseMDNode(PFS, Expr, Object.DebugExpr) || 715 parseMDNode(PFS, Loc, Object.DebugLoc)) 716 return true; 717 if (!Var && !Expr && !Loc) 718 return false; 719 DILocalVariable *DIVar = nullptr; 720 DIExpression *DIExpr = nullptr; 721 DILocation *DILoc = nullptr; 722 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) || 723 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) || 724 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this)) 725 return true; 726 PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc); 727 return false; 728 } 729 730 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS, 731 MDNode *&Node, const yaml::StringValue &Source) { 732 if (Source.Value.empty()) 733 return false; 734 SMDiagnostic Error; 735 if (llvm::parseMDNode(PFS, Node, Source.Value, Error)) 736 return error(Error, Source.SourceRange); 737 return false; 738 } 739 740 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS, 741 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) { 742 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots; 743 const MachineFunction &MF = PFS.MF; 744 const auto &M = *MF.getFunction().getParent(); 745 SMDiagnostic Error; 746 for (const auto &YamlConstant : YamlMF.Constants) { 747 if (YamlConstant.IsTargetSpecific) 748 // FIXME: Support target-specific constant pools 749 return error(YamlConstant.Value.SourceRange.Start, 750 "Can't parse target-specific constant pool entries yet"); 751 const Constant *Value = dyn_cast_or_null<Constant>( 752 parseConstantValue(YamlConstant.Value.Value, Error, M)); 753 if (!Value) 754 return error(Error, YamlConstant.Value.SourceRange); 755 unsigned Alignment = 756 YamlConstant.Alignment 757 ? YamlConstant.Alignment 758 : M.getDataLayout().getPrefTypeAlignment(Value->getType()); 759 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment); 760 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index)) 761 .second) 762 return error(YamlConstant.ID.SourceRange.Start, 763 Twine("redefinition of constant pool item '%const.") + 764 Twine(YamlConstant.ID.Value) + "'"); 765 } 766 return false; 767 } 768 769 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS, 770 const yaml::MachineJumpTable &YamlJTI) { 771 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind); 772 for (const auto &Entry : YamlJTI.Entries) { 773 std::vector<MachineBasicBlock *> Blocks; 774 for (const auto &MBBSource : Entry.Blocks) { 775 MachineBasicBlock *MBB = nullptr; 776 if (parseMBBReference(PFS, MBB, MBBSource.Value)) 777 return true; 778 Blocks.push_back(MBB); 779 } 780 unsigned Index = JTI->createJumpTableIndex(Blocks); 781 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index)) 782 .second) 783 return error(Entry.ID.SourceRange.Start, 784 Twine("redefinition of jump table entry '%jump-table.") + 785 Twine(Entry.ID.Value) + "'"); 786 } 787 return false; 788 } 789 790 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS, 791 MachineBasicBlock *&MBB, 792 const yaml::StringValue &Source) { 793 SMDiagnostic Error; 794 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error)) 795 return error(Error, Source.SourceRange); 796 return false; 797 } 798 799 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error, 800 SMRange SourceRange) { 801 assert(SourceRange.isValid() && "Invalid source range"); 802 SMLoc Loc = SourceRange.Start; 803 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() && 804 *Loc.getPointer() == '\''; 805 // Translate the location of the error from the location in the MI string to 806 // the corresponding location in the MIR file. 807 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() + 808 (HasQuote ? 1 : 0)); 809 810 // TODO: Translate any source ranges as well. 811 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None, 812 Error.getFixIts()); 813 } 814 815 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error, 816 SMRange SourceRange) { 817 assert(SourceRange.isValid()); 818 819 // Translate the location of the error from the location in the llvm IR string 820 // to the corresponding location in the MIR file. 821 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start); 822 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1; 823 unsigned Column = Error.getColumnNo(); 824 StringRef LineStr = Error.getLineContents(); 825 SMLoc Loc = Error.getLoc(); 826 827 // Get the full line and adjust the column number by taking the indentation of 828 // LLVM IR into account. 829 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E; 830 L != E; ++L) { 831 if (L.line_number() == Line) { 832 LineStr = *L; 833 Loc = SMLoc::getFromPointer(LineStr.data()); 834 auto Indent = LineStr.find(Error.getLineContents()); 835 if (Indent != StringRef::npos) 836 Column += Indent; 837 break; 838 } 839 } 840 841 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(), 842 Error.getMessage(), LineStr, Error.getRanges(), 843 Error.getFixIts()); 844 } 845 846 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) { 847 if (!Names2RegClasses.empty()) 848 return; 849 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 850 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) { 851 const auto *RC = TRI->getRegClass(I); 852 Names2RegClasses.insert( 853 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC)); 854 } 855 } 856 857 void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) { 858 if (!Names2RegBanks.empty()) 859 return; 860 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo(); 861 // If the target does not support GlobalISel, we may not have a 862 // register bank info. 863 if (!RBI) 864 return; 865 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) { 866 const auto &RegBank = RBI->getRegBank(I); 867 Names2RegBanks.insert( 868 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank)); 869 } 870 } 871 872 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF, 873 StringRef Name) { 874 auto RegClassInfo = Names2RegClasses.find(Name); 875 if (RegClassInfo == Names2RegClasses.end()) 876 return nullptr; 877 return RegClassInfo->getValue(); 878 } 879 880 const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF, 881 StringRef Name) { 882 auto RegBankInfo = Names2RegBanks.find(Name); 883 if (RegBankInfo == Names2RegBanks.end()) 884 return nullptr; 885 return RegBankInfo->getValue(); 886 } 887 888 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl) 889 : Impl(std::move(Impl)) {} 890 891 MIRParser::~MIRParser() {} 892 893 std::unique_ptr<Module> MIRParser::parseIRModule() { 894 return Impl->parseIRModule(); 895 } 896 897 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) { 898 return Impl->parseMachineFunctions(M, MMI); 899 } 900 901 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename, 902 SMDiagnostic &Error, 903 LLVMContext &Context) { 904 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename); 905 if (std::error_code EC = FileOrErr.getError()) { 906 Error = SMDiagnostic(Filename, SourceMgr::DK_Error, 907 "Could not open input file: " + EC.message()); 908 return nullptr; 909 } 910 return createMIRParser(std::move(FileOrErr.get()), Context); 911 } 912 913 std::unique_ptr<MIRParser> 914 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents, 915 LLVMContext &Context) { 916 auto Filename = Contents->getBufferIdentifier(); 917 if (Context.shouldDiscardValueNames()) { 918 Context.diagnose(DiagnosticInfoMIRParser( 919 DS_Error, 920 SMDiagnostic( 921 Filename, SourceMgr::DK_Error, 922 "Can't read MIR with a Context that discards named Values"))); 923 return nullptr; 924 } 925 return llvm::make_unique<MIRParser>( 926 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context)); 927 } 928