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