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