1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the class that parses the optional LLVM IR and machine 11 // functions that are stored in MIR files. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MIRParser/MIRParser.h" 16 #include "MIParser.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/StringMap.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/AsmParser/Parser.h" 22 #include "llvm/AsmParser/SlotMapping.h" 23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 24 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 25 #include "llvm/CodeGen/MIRYamlMapping.h" 26 #include "llvm/CodeGen/MachineConstantPool.h" 27 #include "llvm/CodeGen/MachineFrameInfo.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineModuleInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DiagnosticInfo.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/LLVMContext.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/ValueSymbolTable.h" 38 #include "llvm/Support/LineIterator.h" 39 #include "llvm/Support/MemoryBuffer.h" 40 #include "llvm/Support/SMLoc.h" 41 #include "llvm/Support/SourceMgr.h" 42 #include "llvm/Support/YAMLTraits.h" 43 #include <memory> 44 45 using namespace llvm; 46 47 namespace llvm { 48 49 /// This class implements the parsing of LLVM IR that's embedded inside a MIR 50 /// file. 51 class MIRParserImpl { 52 SourceMgr SM; 53 yaml::Input In; 54 StringRef Filename; 55 LLVMContext &Context; 56 SlotMapping IRSlots; 57 /// Maps from register class names to register classes. 58 Name2RegClassMap Names2RegClasses; 59 /// Maps from register bank names to register banks. 60 Name2RegBankMap Names2RegBanks; 61 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are 62 /// created and inserted into the given module when this is true. 63 bool NoLLVMIR = false; 64 /// True when a well formed MIR file does not contain any MIR/machine function 65 /// parts. 66 bool NoMIRDocuments = false; 67 68 public: 69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, 70 StringRef Filename, LLVMContext &Context); 71 72 void reportDiagnostic(const SMDiagnostic &Diag); 73 74 /// Report an error with the given message at unknown location. 75 /// 76 /// Always returns true. 77 bool error(const Twine &Message); 78 79 /// Report an error with the given message at the given location. 80 /// 81 /// Always returns true. 82 bool error(SMLoc Loc, const Twine &Message); 83 84 /// Report a given error with the location translated from the location in an 85 /// embedded string literal to a location in the MIR file. 86 /// 87 /// Always returns true. 88 bool error(const SMDiagnostic &Error, SMRange SourceRange); 89 90 /// Try to parse the optional LLVM module and the machine functions in the MIR 91 /// file. 92 /// 93 /// Return null if an error occurred. 94 std::unique_ptr<Module> parseIRModule(); 95 96 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI); 97 98 /// Parse the machine function in the current YAML document. 99 /// 100 /// 101 /// Return true if an error occurred. 102 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI); 103 104 /// Initialize the machine function to the state that's described in the MIR 105 /// file. 106 /// 107 /// Return true if error occurred. 108 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF, 109 MachineFunction &MF); 110 111 bool parseRegisterInfo(PerFunctionMIParsingState &PFS, 112 const yaml::MachineFunction &YamlMF); 113 114 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, 115 const yaml::MachineFunction &YamlMF); 116 117 bool initializeFrameInfo(PerFunctionMIParsingState &PFS, 118 const yaml::MachineFunction &YamlMF); 119 120 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, 121 std::vector<CalleeSavedInfo> &CSIInfo, 122 const yaml::StringValue &RegisterSource, 123 bool IsRestored, int FrameIdx); 124 125 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, 126 const yaml::MachineStackObject &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 358 if (YamlMF.Legalized) 359 MF.getProperties().set(MachineFunctionProperties::Property::Legalized); 360 if (YamlMF.RegBankSelected) 361 MF.getProperties().set( 362 MachineFunctionProperties::Property::RegBankSelected); 363 if (YamlMF.Selected) 364 MF.getProperties().set(MachineFunctionProperties::Property::Selected); 365 if (YamlMF.FailedISel) 366 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 367 368 PerFunctionMIParsingState PFS(MF, SM, IRSlots, Names2RegClasses, 369 Names2RegBanks); 370 if (parseRegisterInfo(PFS, YamlMF)) 371 return true; 372 if (!YamlMF.Constants.empty()) { 373 auto *ConstantPool = MF.getConstantPool(); 374 assert(ConstantPool && "Constant pool must be created"); 375 if (initializeConstantPool(PFS, *ConstantPool, YamlMF)) 376 return true; 377 } 378 379 StringRef BlockStr = YamlMF.Body.Value.Value; 380 SMDiagnostic Error; 381 SourceMgr BlockSM; 382 BlockSM.AddNewSourceBuffer( 383 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false), 384 SMLoc()); 385 PFS.SM = &BlockSM; 386 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) { 387 reportDiagnostic( 388 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange)); 389 return true; 390 } 391 PFS.SM = &SM; 392 393 // Initialize the frame information after creating all the MBBs so that the 394 // MBB references in the frame information can be resolved. 395 if (initializeFrameInfo(PFS, YamlMF)) 396 return true; 397 // Initialize the jump table after creating all the MBBs so that the MBB 398 // references can be resolved. 399 if (!YamlMF.JumpTableInfo.Entries.empty() && 400 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo)) 401 return true; 402 // Parse the machine instructions after creating all of the MBBs so that the 403 // parser can resolve the MBB references. 404 StringRef InsnStr = YamlMF.Body.Value.Value; 405 SourceMgr InsnSM; 406 InsnSM.AddNewSourceBuffer( 407 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false), 408 SMLoc()); 409 PFS.SM = &InsnSM; 410 if (parseMachineInstructions(PFS, InsnStr, Error)) { 411 reportDiagnostic( 412 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange)); 413 return true; 414 } 415 PFS.SM = &SM; 416 417 if (setupRegisterInfo(PFS, YamlMF)) 418 return true; 419 420 computeFunctionProperties(MF); 421 422 MF.getSubtarget().mirFileLoaded(MF); 423 424 MF.verify(); 425 return false; 426 } 427 428 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS, 429 const yaml::MachineFunction &YamlMF) { 430 MachineFunction &MF = PFS.MF; 431 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 432 assert(RegInfo.tracksLiveness()); 433 if (!YamlMF.TracksRegLiveness) 434 RegInfo.invalidateLiveness(); 435 436 SMDiagnostic Error; 437 // Parse the virtual register information. 438 for (const auto &VReg : YamlMF.VirtualRegisters) { 439 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value); 440 if (Info.Explicit) 441 return error(VReg.ID.SourceRange.Start, 442 Twine("redefinition of virtual register '%") + 443 Twine(VReg.ID.Value) + "'"); 444 Info.Explicit = true; 445 446 if (StringRef(VReg.Class.Value).equals("_")) { 447 Info.Kind = VRegInfo::GENERIC; 448 Info.D.RegBank = nullptr; 449 } else { 450 const auto *RC = getRegClass(MF, VReg.Class.Value); 451 if (RC) { 452 Info.Kind = VRegInfo::NORMAL; 453 Info.D.RC = RC; 454 } else { 455 const RegisterBank *RegBank = getRegBank(MF, VReg.Class.Value); 456 if (!RegBank) 457 return error( 458 VReg.Class.SourceRange.Start, 459 Twine("use of undefined register class or register bank '") + 460 VReg.Class.Value + "'"); 461 Info.Kind = VRegInfo::REGBANK; 462 Info.D.RegBank = RegBank; 463 } 464 } 465 466 if (!VReg.PreferredRegister.Value.empty()) { 467 if (Info.Kind != VRegInfo::NORMAL) 468 return error(VReg.Class.SourceRange.Start, 469 Twine("preferred register can only be set for normal vregs")); 470 471 if (parseRegisterReference(PFS, Info.PreferredReg, 472 VReg.PreferredRegister.Value, Error)) 473 return error(Error, VReg.PreferredRegister.SourceRange); 474 } 475 } 476 477 // Parse the liveins. 478 for (const auto &LiveIn : YamlMF.LiveIns) { 479 unsigned Reg = 0; 480 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error)) 481 return error(Error, LiveIn.Register.SourceRange); 482 unsigned VReg = 0; 483 if (!LiveIn.VirtualRegister.Value.empty()) { 484 VRegInfo *Info; 485 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value, 486 Error)) 487 return error(Error, LiveIn.VirtualRegister.SourceRange); 488 VReg = Info->VReg; 489 } 490 RegInfo.addLiveIn(Reg, VReg); 491 } 492 493 // Parse the callee saved registers (Registers that will 494 // be saved for the caller). 495 if (YamlMF.CalleeSavedRegisters) { 496 SmallVector<MCPhysReg, 16> CalleeSavedRegisters; 497 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) { 498 unsigned Reg = 0; 499 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error)) 500 return error(Error, RegSource.SourceRange); 501 CalleeSavedRegisters.push_back(Reg); 502 } 503 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters); 504 } 505 506 return false; 507 } 508 509 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS, 510 const yaml::MachineFunction &YamlMF) { 511 MachineFunction &MF = PFS.MF; 512 MachineRegisterInfo &MRI = MF.getRegInfo(); 513 bool Error = false; 514 // Create VRegs 515 auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) { 516 unsigned Reg = Info.VReg; 517 switch (Info.Kind) { 518 case VRegInfo::UNKNOWN: 519 error(Twine("Cannot determine class/bank of virtual register ") + 520 Name + " in function '" + MF.getName() + "'"); 521 Error = true; 522 break; 523 case VRegInfo::NORMAL: 524 MRI.setRegClass(Reg, Info.D.RC); 525 if (Info.PreferredReg != 0) 526 MRI.setSimpleHint(Reg, Info.PreferredReg); 527 break; 528 case VRegInfo::GENERIC: 529 break; 530 case VRegInfo::REGBANK: 531 MRI.setRegBank(Reg, *Info.D.RegBank); 532 break; 533 } 534 }; 535 536 for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end(); 537 I != E; I++) { 538 const VRegInfo &Info = *I->second; 539 populateVRegInfo(Info, Twine(I->first())); 540 } 541 542 for (auto P : PFS.VRegInfos) { 543 const VRegInfo &Info = *P.second; 544 populateVRegInfo(Info, Twine(P.first)); 545 } 546 547 // Compute MachineRegisterInfo::UsedPhysRegMask 548 for (const MachineBasicBlock &MBB : MF) { 549 for (const MachineInstr &MI : MBB) { 550 for (const MachineOperand &MO : MI.operands()) { 551 if (!MO.isRegMask()) 552 continue; 553 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask()); 554 } 555 } 556 } 557 558 // FIXME: This is a temporary workaround until the reserved registers can be 559 // serialized. 560 MRI.freezeReservedRegs(MF); 561 return Error; 562 } 563 564 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS, 565 const yaml::MachineFunction &YamlMF) { 566 MachineFunction &MF = PFS.MF; 567 MachineFrameInfo &MFI = MF.getFrameInfo(); 568 const Function &F = MF.getFunction(); 569 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo; 570 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken); 571 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken); 572 MFI.setHasStackMap(YamlMFI.HasStackMap); 573 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint); 574 MFI.setStackSize(YamlMFI.StackSize); 575 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment); 576 if (YamlMFI.MaxAlignment) 577 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment); 578 MFI.setAdjustsStack(YamlMFI.AdjustsStack); 579 MFI.setHasCalls(YamlMFI.HasCalls); 580 if (YamlMFI.MaxCallFrameSize != ~0u) 581 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize); 582 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment); 583 MFI.setHasVAStart(YamlMFI.HasVAStart); 584 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc); 585 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize); 586 if (!YamlMFI.SavePoint.Value.empty()) { 587 MachineBasicBlock *MBB = nullptr; 588 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint)) 589 return true; 590 MFI.setSavePoint(MBB); 591 } 592 if (!YamlMFI.RestorePoint.Value.empty()) { 593 MachineBasicBlock *MBB = nullptr; 594 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint)) 595 return true; 596 MFI.setRestorePoint(MBB); 597 } 598 599 std::vector<CalleeSavedInfo> CSIInfo; 600 // Initialize the fixed frame objects. 601 for (const auto &Object : YamlMF.FixedStackObjects) { 602 int ObjectIdx; 603 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot) 604 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset, 605 Object.IsImmutable, Object.IsAliased); 606 else 607 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset); 608 MFI.setObjectAlignment(ObjectIdx, Object.Alignment); 609 MFI.setStackID(ObjectIdx, Object.StackID); 610 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value, 611 ObjectIdx)) 612 .second) 613 return error(Object.ID.SourceRange.Start, 614 Twine("redefinition of fixed stack object '%fixed-stack.") + 615 Twine(Object.ID.Value) + "'"); 616 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister, 617 Object.CalleeSavedRestored, ObjectIdx)) 618 return true; 619 } 620 621 // Initialize the ordinary frame objects. 622 for (const auto &Object : YamlMF.StackObjects) { 623 int ObjectIdx; 624 const AllocaInst *Alloca = nullptr; 625 const yaml::StringValue &Name = Object.Name; 626 if (!Name.Value.empty()) { 627 Alloca = dyn_cast_or_null<AllocaInst>( 628 F.getValueSymbolTable()->lookup(Name.Value)); 629 if (!Alloca) 630 return error(Name.SourceRange.Start, 631 "alloca instruction named '" + Name.Value + 632 "' isn't defined in the function '" + F.getName() + 633 "'"); 634 } 635 if (Object.Type == yaml::MachineStackObject::VariableSized) 636 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca); 637 else 638 ObjectIdx = MFI.CreateStackObject( 639 Object.Size, Object.Alignment, 640 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca); 641 MFI.setObjectOffset(ObjectIdx, Object.Offset); 642 MFI.setStackID(ObjectIdx, Object.StackID); 643 644 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx)) 645 .second) 646 return error(Object.ID.SourceRange.Start, 647 Twine("redefinition of stack object '%stack.") + 648 Twine(Object.ID.Value) + "'"); 649 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister, 650 Object.CalleeSavedRestored, ObjectIdx)) 651 return true; 652 if (Object.LocalOffset) 653 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue()); 654 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx)) 655 return true; 656 } 657 MFI.setCalleeSavedInfo(CSIInfo); 658 if (!CSIInfo.empty()) 659 MFI.setCalleeSavedInfoValid(true); 660 661 // Initialize the various stack object references after initializing the 662 // stack objects. 663 if (!YamlMFI.StackProtector.Value.empty()) { 664 SMDiagnostic Error; 665 int FI; 666 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error)) 667 return error(Error, YamlMFI.StackProtector.SourceRange); 668 MFI.setStackProtectorIndex(FI); 669 } 670 return false; 671 } 672 673 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, 674 std::vector<CalleeSavedInfo> &CSIInfo, 675 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) { 676 if (RegisterSource.Value.empty()) 677 return false; 678 unsigned Reg = 0; 679 SMDiagnostic Error; 680 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error)) 681 return error(Error, RegisterSource.SourceRange); 682 CalleeSavedInfo CSI(Reg, FrameIdx); 683 CSI.setRestored(IsRestored); 684 CSIInfo.push_back(CSI); 685 return false; 686 } 687 688 /// Verify that given node is of a certain type. Return true on error. 689 template <typename T> 690 static bool typecheckMDNode(T *&Result, MDNode *Node, 691 const yaml::StringValue &Source, 692 StringRef TypeString, MIRParserImpl &Parser) { 693 if (!Node) 694 return false; 695 Result = dyn_cast<T>(Node); 696 if (!Result) 697 return Parser.error(Source.SourceRange.Start, 698 "expected a reference to a '" + TypeString + 699 "' metadata node"); 700 return false; 701 } 702 703 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, 704 const yaml::MachineStackObject &Object, int FrameIdx) { 705 // Debug information can only be attached to stack objects; Fixed stack 706 // objects aren't supported. 707 assert(FrameIdx >= 0 && "Expected a stack object frame index"); 708 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr; 709 if (parseMDNode(PFS, Var, Object.DebugVar) || 710 parseMDNode(PFS, Expr, Object.DebugExpr) || 711 parseMDNode(PFS, Loc, Object.DebugLoc)) 712 return true; 713 if (!Var && !Expr && !Loc) 714 return false; 715 DILocalVariable *DIVar = nullptr; 716 DIExpression *DIExpr = nullptr; 717 DILocation *DILoc = nullptr; 718 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) || 719 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) || 720 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this)) 721 return true; 722 PFS.MF.setVariableDbgInfo(DIVar, DIExpr, unsigned(FrameIdx), DILoc); 723 return false; 724 } 725 726 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS, 727 MDNode *&Node, const yaml::StringValue &Source) { 728 if (Source.Value.empty()) 729 return false; 730 SMDiagnostic Error; 731 if (llvm::parseMDNode(PFS, Node, Source.Value, Error)) 732 return error(Error, Source.SourceRange); 733 return false; 734 } 735 736 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS, 737 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) { 738 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots; 739 const MachineFunction &MF = PFS.MF; 740 const auto &M = *MF.getFunction().getParent(); 741 SMDiagnostic Error; 742 for (const auto &YamlConstant : YamlMF.Constants) { 743 if (YamlConstant.IsTargetSpecific) 744 // FIXME: Support target-specific constant pools 745 return error(YamlConstant.Value.SourceRange.Start, 746 "Can't parse target-specific constant pool entries yet"); 747 const Constant *Value = dyn_cast_or_null<Constant>( 748 parseConstantValue(YamlConstant.Value.Value, Error, M)); 749 if (!Value) 750 return error(Error, YamlConstant.Value.SourceRange); 751 unsigned Alignment = 752 YamlConstant.Alignment 753 ? YamlConstant.Alignment 754 : M.getDataLayout().getPrefTypeAlignment(Value->getType()); 755 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment); 756 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index)) 757 .second) 758 return error(YamlConstant.ID.SourceRange.Start, 759 Twine("redefinition of constant pool item '%const.") + 760 Twine(YamlConstant.ID.Value) + "'"); 761 } 762 return false; 763 } 764 765 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS, 766 const yaml::MachineJumpTable &YamlJTI) { 767 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind); 768 for (const auto &Entry : YamlJTI.Entries) { 769 std::vector<MachineBasicBlock *> Blocks; 770 for (const auto &MBBSource : Entry.Blocks) { 771 MachineBasicBlock *MBB = nullptr; 772 if (parseMBBReference(PFS, MBB, MBBSource.Value)) 773 return true; 774 Blocks.push_back(MBB); 775 } 776 unsigned Index = JTI->createJumpTableIndex(Blocks); 777 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index)) 778 .second) 779 return error(Entry.ID.SourceRange.Start, 780 Twine("redefinition of jump table entry '%jump-table.") + 781 Twine(Entry.ID.Value) + "'"); 782 } 783 return false; 784 } 785 786 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS, 787 MachineBasicBlock *&MBB, 788 const yaml::StringValue &Source) { 789 SMDiagnostic Error; 790 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error)) 791 return error(Error, Source.SourceRange); 792 return false; 793 } 794 795 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error, 796 SMRange SourceRange) { 797 assert(SourceRange.isValid() && "Invalid source range"); 798 SMLoc Loc = SourceRange.Start; 799 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() && 800 *Loc.getPointer() == '\''; 801 // Translate the location of the error from the location in the MI string to 802 // the corresponding location in the MIR file. 803 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() + 804 (HasQuote ? 1 : 0)); 805 806 // TODO: Translate any source ranges as well. 807 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None, 808 Error.getFixIts()); 809 } 810 811 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error, 812 SMRange SourceRange) { 813 assert(SourceRange.isValid()); 814 815 // Translate the location of the error from the location in the llvm IR string 816 // to the corresponding location in the MIR file. 817 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start); 818 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1; 819 unsigned Column = Error.getColumnNo(); 820 StringRef LineStr = Error.getLineContents(); 821 SMLoc Loc = Error.getLoc(); 822 823 // Get the full line and adjust the column number by taking the indentation of 824 // LLVM IR into account. 825 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E; 826 L != E; ++L) { 827 if (L.line_number() == Line) { 828 LineStr = *L; 829 Loc = SMLoc::getFromPointer(LineStr.data()); 830 auto Indent = LineStr.find(Error.getLineContents()); 831 if (Indent != StringRef::npos) 832 Column += Indent; 833 break; 834 } 835 } 836 837 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(), 838 Error.getMessage(), LineStr, Error.getRanges(), 839 Error.getFixIts()); 840 } 841 842 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) { 843 if (!Names2RegClasses.empty()) 844 return; 845 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 846 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) { 847 const auto *RC = TRI->getRegClass(I); 848 Names2RegClasses.insert( 849 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC)); 850 } 851 } 852 853 void MIRParserImpl::initNames2RegBanks(const MachineFunction &MF) { 854 if (!Names2RegBanks.empty()) 855 return; 856 const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo(); 857 // If the target does not support GlobalISel, we may not have a 858 // register bank info. 859 if (!RBI) 860 return; 861 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) { 862 const auto &RegBank = RBI->getRegBank(I); 863 Names2RegBanks.insert( 864 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank)); 865 } 866 } 867 868 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF, 869 StringRef Name) { 870 auto RegClassInfo = Names2RegClasses.find(Name); 871 if (RegClassInfo == Names2RegClasses.end()) 872 return nullptr; 873 return RegClassInfo->getValue(); 874 } 875 876 const RegisterBank *MIRParserImpl::getRegBank(const MachineFunction &MF, 877 StringRef Name) { 878 auto RegBankInfo = Names2RegBanks.find(Name); 879 if (RegBankInfo == Names2RegBanks.end()) 880 return nullptr; 881 return RegBankInfo->getValue(); 882 } 883 884 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl) 885 : Impl(std::move(Impl)) {} 886 887 MIRParser::~MIRParser() {} 888 889 std::unique_ptr<Module> MIRParser::parseIRModule() { 890 return Impl->parseIRModule(); 891 } 892 893 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) { 894 return Impl->parseMachineFunctions(M, MMI); 895 } 896 897 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename, 898 SMDiagnostic &Error, 899 LLVMContext &Context) { 900 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename); 901 if (std::error_code EC = FileOrErr.getError()) { 902 Error = SMDiagnostic(Filename, SourceMgr::DK_Error, 903 "Could not open input file: " + EC.message()); 904 return nullptr; 905 } 906 return createMIRParser(std::move(FileOrErr.get()), Context); 907 } 908 909 std::unique_ptr<MIRParser> 910 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents, 911 LLVMContext &Context) { 912 auto Filename = Contents->getBufferIdentifier(); 913 if (Context.shouldDiscardValueNames()) { 914 Context.diagnose(DiagnosticInfoMIRParser( 915 DS_Error, 916 SMDiagnostic( 917 Filename, SourceMgr::DK_Error, 918 "Can't read MIR with a Context that discards named Values"))); 919 return nullptr; 920 } 921 return llvm::make_unique<MIRParser>( 922 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context)); 923 } 924