1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===// 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 // Pass to verify generated machine code. The following is checked: 10 // 11 // Operand counts: All explicit operands must be present. 12 // 13 // Register classes: All physical and virtual register operands must be 14 // compatible with the register class required by the instruction descriptor. 15 // 16 // Register live intervals: Registers must be defined only once, and must be 17 // defined before use. 18 // 19 // The machine code verifier is enabled with the command-line option 20 // -verify-machineinstrs. 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/BitVector.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/DenseSet.h" 26 #include "llvm/ADT/DepthFirstIterator.h" 27 #include "llvm/ADT/PostOrderIterator.h" 28 #include "llvm/ADT/STLExtras.h" 29 #include "llvm/ADT/SetOperations.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallVector.h" 32 #include "llvm/ADT/StringRef.h" 33 #include "llvm/ADT/Twine.h" 34 #include "llvm/Analysis/EHPersonalities.h" 35 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 36 #include "llvm/CodeGen/LiveInterval.h" 37 #include "llvm/CodeGen/LiveIntervalCalc.h" 38 #include "llvm/CodeGen/LiveIntervals.h" 39 #include "llvm/CodeGen/LiveStacks.h" 40 #include "llvm/CodeGen/LiveVariables.h" 41 #include "llvm/CodeGen/MachineBasicBlock.h" 42 #include "llvm/CodeGen/MachineFrameInfo.h" 43 #include "llvm/CodeGen/MachineFunction.h" 44 #include "llvm/CodeGen/MachineFunctionPass.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBundle.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/PseudoSourceValue.h" 51 #include "llvm/CodeGen/SlotIndexes.h" 52 #include "llvm/CodeGen/StackMaps.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/IR/BasicBlock.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/InlineAsm.h" 60 #include "llvm/IR/Instructions.h" 61 #include "llvm/InitializePasses.h" 62 #include "llvm/MC/LaneBitmask.h" 63 #include "llvm/MC/MCAsmInfo.h" 64 #include "llvm/MC/MCInstrDesc.h" 65 #include "llvm/MC/MCRegisterInfo.h" 66 #include "llvm/MC/MCTargetOptions.h" 67 #include "llvm/Pass.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/LowLevelTypeImpl.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/Target/TargetMachine.h" 74 #include <algorithm> 75 #include <cassert> 76 #include <cstddef> 77 #include <cstdint> 78 #include <iterator> 79 #include <string> 80 #include <utility> 81 82 using namespace llvm; 83 84 namespace { 85 86 struct MachineVerifier { 87 MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {} 88 89 unsigned verify(const MachineFunction &MF); 90 91 Pass *const PASS; 92 const char *Banner; 93 const MachineFunction *MF; 94 const TargetMachine *TM; 95 const TargetInstrInfo *TII; 96 const TargetRegisterInfo *TRI; 97 const MachineRegisterInfo *MRI; 98 99 unsigned foundErrors; 100 101 // Avoid querying the MachineFunctionProperties for each operand. 102 bool isFunctionRegBankSelected; 103 bool isFunctionSelected; 104 105 using RegVector = SmallVector<Register, 16>; 106 using RegMaskVector = SmallVector<const uint32_t *, 4>; 107 using RegSet = DenseSet<Register>; 108 using RegMap = DenseMap<Register, const MachineInstr *>; 109 using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>; 110 111 const MachineInstr *FirstNonPHI; 112 const MachineInstr *FirstTerminator; 113 BlockSet FunctionBlocks; 114 115 BitVector regsReserved; 116 RegSet regsLive; 117 RegVector regsDefined, regsDead, regsKilled; 118 RegMaskVector regMasks; 119 120 SlotIndex lastIndex; 121 122 // Add Reg and any sub-registers to RV 123 void addRegWithSubRegs(RegVector &RV, Register Reg) { 124 RV.push_back(Reg); 125 if (Reg.isPhysical()) 126 for (const MCPhysReg &SubReg : TRI->subregs(Reg.asMCReg())) 127 RV.push_back(SubReg); 128 } 129 130 struct BBInfo { 131 // Is this MBB reachable from the MF entry point? 132 bool reachable = false; 133 134 // Vregs that must be live in because they are used without being 135 // defined. Map value is the user. vregsLiveIn doesn't include regs 136 // that only are used by PHI nodes. 137 RegMap vregsLiveIn; 138 139 // Regs killed in MBB. They may be defined again, and will then be in both 140 // regsKilled and regsLiveOut. 141 RegSet regsKilled; 142 143 // Regs defined in MBB and live out. Note that vregs passing through may 144 // be live out without being mentioned here. 145 RegSet regsLiveOut; 146 147 // Vregs that pass through MBB untouched. This set is disjoint from 148 // regsKilled and regsLiveOut. 149 RegSet vregsPassed; 150 151 // Vregs that must pass through MBB because they are needed by a successor 152 // block. This set is disjoint from regsLiveOut. 153 RegSet vregsRequired; 154 155 // Set versions of block's predecessor and successor lists. 156 BlockSet Preds, Succs; 157 158 BBInfo() = default; 159 160 // Add register to vregsRequired if it belongs there. Return true if 161 // anything changed. 162 bool addRequired(Register Reg) { 163 if (!Reg.isVirtual()) 164 return false; 165 if (regsLiveOut.count(Reg)) 166 return false; 167 return vregsRequired.insert(Reg).second; 168 } 169 170 // Same for a full set. 171 bool addRequired(const RegSet &RS) { 172 bool Changed = false; 173 for (Register Reg : RS) 174 Changed |= addRequired(Reg); 175 return Changed; 176 } 177 178 // Same for a full map. 179 bool addRequired(const RegMap &RM) { 180 bool Changed = false; 181 for (const auto &I : RM) 182 Changed |= addRequired(I.first); 183 return Changed; 184 } 185 186 // Live-out registers are either in regsLiveOut or vregsPassed. 187 bool isLiveOut(Register Reg) const { 188 return regsLiveOut.count(Reg) || vregsPassed.count(Reg); 189 } 190 }; 191 192 // Extra register info per MBB. 193 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap; 194 195 bool isReserved(Register Reg) { 196 return Reg.id() < regsReserved.size() && regsReserved.test(Reg.id()); 197 } 198 199 bool isAllocatable(Register Reg) const { 200 return Reg.id() < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) && 201 !regsReserved.test(Reg.id()); 202 } 203 204 // Analysis information if available 205 LiveVariables *LiveVars; 206 LiveIntervals *LiveInts; 207 LiveStacks *LiveStks; 208 SlotIndexes *Indexes; 209 210 void visitMachineFunctionBefore(); 211 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB); 212 void visitMachineBundleBefore(const MachineInstr *MI); 213 214 bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI); 215 void verifyPreISelGenericInstruction(const MachineInstr *MI); 216 void visitMachineInstrBefore(const MachineInstr *MI); 217 void visitMachineOperand(const MachineOperand *MO, unsigned MONum); 218 void visitMachineBundleAfter(const MachineInstr *MI); 219 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB); 220 void visitMachineFunctionAfter(); 221 222 void report(const char *msg, const MachineFunction *MF); 223 void report(const char *msg, const MachineBasicBlock *MBB); 224 void report(const char *msg, const MachineInstr *MI); 225 void report(const char *msg, const MachineOperand *MO, unsigned MONum, 226 LLT MOVRegType = LLT{}); 227 228 void report_context(const LiveInterval &LI) const; 229 void report_context(const LiveRange &LR, Register VRegUnit, 230 LaneBitmask LaneMask) const; 231 void report_context(const LiveRange::Segment &S) const; 232 void report_context(const VNInfo &VNI) const; 233 void report_context(SlotIndex Pos) const; 234 void report_context(MCPhysReg PhysReg) const; 235 void report_context_liverange(const LiveRange &LR) const; 236 void report_context_lanemask(LaneBitmask LaneMask) const; 237 void report_context_vreg(Register VReg) const; 238 void report_context_vreg_regunit(Register VRegOrUnit) const; 239 240 void verifyInlineAsm(const MachineInstr *MI); 241 242 void checkLiveness(const MachineOperand *MO, unsigned MONum); 243 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum, 244 SlotIndex UseIdx, const LiveRange &LR, 245 Register VRegOrUnit, 246 LaneBitmask LaneMask = LaneBitmask::getNone()); 247 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum, 248 SlotIndex DefIdx, const LiveRange &LR, 249 Register VRegOrUnit, bool SubRangeCheck = false, 250 LaneBitmask LaneMask = LaneBitmask::getNone()); 251 252 void markReachable(const MachineBasicBlock *MBB); 253 void calcRegsPassed(); 254 void checkPHIOps(const MachineBasicBlock &MBB); 255 256 void calcRegsRequired(); 257 void verifyLiveVariables(); 258 void verifyLiveIntervals(); 259 void verifyLiveInterval(const LiveInterval&); 260 void verifyLiveRangeValue(const LiveRange &, const VNInfo *, Register, 261 LaneBitmask); 262 void verifyLiveRangeSegment(const LiveRange &, 263 const LiveRange::const_iterator I, Register, 264 LaneBitmask); 265 void verifyLiveRange(const LiveRange &, Register, 266 LaneBitmask LaneMask = LaneBitmask::getNone()); 267 268 void verifyStackFrame(); 269 270 void verifySlotIndexes() const; 271 void verifyProperties(const MachineFunction &MF); 272 }; 273 274 struct MachineVerifierPass : public MachineFunctionPass { 275 static char ID; // Pass ID, replacement for typeid 276 277 const std::string Banner; 278 279 MachineVerifierPass(std::string banner = std::string()) 280 : MachineFunctionPass(ID), Banner(std::move(banner)) { 281 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry()); 282 } 283 284 void getAnalysisUsage(AnalysisUsage &AU) const override { 285 AU.setPreservesAll(); 286 MachineFunctionPass::getAnalysisUsage(AU); 287 } 288 289 bool runOnMachineFunction(MachineFunction &MF) override { 290 unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF); 291 if (FoundErrors) 292 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors."); 293 return false; 294 } 295 }; 296 297 } // end anonymous namespace 298 299 char MachineVerifierPass::ID = 0; 300 301 INITIALIZE_PASS(MachineVerifierPass, "machineverifier", 302 "Verify generated machine code", false, false) 303 304 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) { 305 return new MachineVerifierPass(Banner); 306 } 307 308 void llvm::verifyMachineFunction(MachineFunctionAnalysisManager *, 309 const std::string &Banner, 310 const MachineFunction &MF) { 311 // TODO: Use MFAM after porting below analyses. 312 // LiveVariables *LiveVars; 313 // LiveIntervals *LiveInts; 314 // LiveStacks *LiveStks; 315 // SlotIndexes *Indexes; 316 unsigned FoundErrors = MachineVerifier(nullptr, Banner.c_str()).verify(MF); 317 if (FoundErrors) 318 report_fatal_error("Found " + Twine(FoundErrors) + " machine code errors."); 319 } 320 321 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors) 322 const { 323 MachineFunction &MF = const_cast<MachineFunction&>(*this); 324 unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF); 325 if (AbortOnErrors && FoundErrors) 326 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors."); 327 return FoundErrors == 0; 328 } 329 330 void MachineVerifier::verifySlotIndexes() const { 331 if (Indexes == nullptr) 332 return; 333 334 // Ensure the IdxMBB list is sorted by slot indexes. 335 SlotIndex Last; 336 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(), 337 E = Indexes->MBBIndexEnd(); I != E; ++I) { 338 assert(!Last.isValid() || I->first > Last); 339 Last = I->first; 340 } 341 } 342 343 void MachineVerifier::verifyProperties(const MachineFunction &MF) { 344 // If a pass has introduced virtual registers without clearing the 345 // NoVRegs property (or set it without allocating the vregs) 346 // then report an error. 347 if (MF.getProperties().hasProperty( 348 MachineFunctionProperties::Property::NoVRegs) && 349 MRI->getNumVirtRegs()) 350 report("Function has NoVRegs property but there are VReg operands", &MF); 351 } 352 353 unsigned MachineVerifier::verify(const MachineFunction &MF) { 354 foundErrors = 0; 355 356 this->MF = &MF; 357 TM = &MF.getTarget(); 358 TII = MF.getSubtarget().getInstrInfo(); 359 TRI = MF.getSubtarget().getRegisterInfo(); 360 MRI = &MF.getRegInfo(); 361 362 const bool isFunctionFailedISel = MF.getProperties().hasProperty( 363 MachineFunctionProperties::Property::FailedISel); 364 365 // If we're mid-GlobalISel and we already triggered the fallback path then 366 // it's expected that the MIR is somewhat broken but that's ok since we'll 367 // reset it and clear the FailedISel attribute in ResetMachineFunctions. 368 if (isFunctionFailedISel) 369 return foundErrors; 370 371 isFunctionRegBankSelected = MF.getProperties().hasProperty( 372 MachineFunctionProperties::Property::RegBankSelected); 373 isFunctionSelected = MF.getProperties().hasProperty( 374 MachineFunctionProperties::Property::Selected); 375 376 LiveVars = nullptr; 377 LiveInts = nullptr; 378 LiveStks = nullptr; 379 Indexes = nullptr; 380 if (PASS) { 381 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>(); 382 // We don't want to verify LiveVariables if LiveIntervals is available. 383 if (!LiveInts) 384 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>(); 385 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>(); 386 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>(); 387 } 388 389 verifySlotIndexes(); 390 391 verifyProperties(MF); 392 393 visitMachineFunctionBefore(); 394 for (const MachineBasicBlock &MBB : MF) { 395 visitMachineBasicBlockBefore(&MBB); 396 // Keep track of the current bundle header. 397 const MachineInstr *CurBundle = nullptr; 398 // Do we expect the next instruction to be part of the same bundle? 399 bool InBundle = false; 400 401 for (const MachineInstr &MI : MBB.instrs()) { 402 if (MI.getParent() != &MBB) { 403 report("Bad instruction parent pointer", &MBB); 404 errs() << "Instruction: " << MI; 405 continue; 406 } 407 408 // Check for consistent bundle flags. 409 if (InBundle && !MI.isBundledWithPred()) 410 report("Missing BundledPred flag, " 411 "BundledSucc was set on predecessor", 412 &MI); 413 if (!InBundle && MI.isBundledWithPred()) 414 report("BundledPred flag is set, " 415 "but BundledSucc not set on predecessor", 416 &MI); 417 418 // Is this a bundle header? 419 if (!MI.isInsideBundle()) { 420 if (CurBundle) 421 visitMachineBundleAfter(CurBundle); 422 CurBundle = &MI; 423 visitMachineBundleBefore(CurBundle); 424 } else if (!CurBundle) 425 report("No bundle header", &MI); 426 visitMachineInstrBefore(&MI); 427 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 428 const MachineOperand &Op = MI.getOperand(I); 429 if (Op.getParent() != &MI) { 430 // Make sure to use correct addOperand / RemoveOperand / ChangeTo 431 // functions when replacing operands of a MachineInstr. 432 report("Instruction has operand with wrong parent set", &MI); 433 } 434 435 visitMachineOperand(&Op, I); 436 } 437 438 // Was this the last bundled instruction? 439 InBundle = MI.isBundledWithSucc(); 440 } 441 if (CurBundle) 442 visitMachineBundleAfter(CurBundle); 443 if (InBundle) 444 report("BundledSucc flag set on last instruction in block", &MBB.back()); 445 visitMachineBasicBlockAfter(&MBB); 446 } 447 visitMachineFunctionAfter(); 448 449 // Clean up. 450 regsLive.clear(); 451 regsDefined.clear(); 452 regsDead.clear(); 453 regsKilled.clear(); 454 regMasks.clear(); 455 MBBInfoMap.clear(); 456 457 return foundErrors; 458 } 459 460 void MachineVerifier::report(const char *msg, const MachineFunction *MF) { 461 assert(MF); 462 errs() << '\n'; 463 if (!foundErrors++) { 464 if (Banner) 465 errs() << "# " << Banner << '\n'; 466 if (LiveInts != nullptr) 467 LiveInts->print(errs()); 468 else 469 MF->print(errs(), Indexes); 470 } 471 errs() << "*** Bad machine code: " << msg << " ***\n" 472 << "- function: " << MF->getName() << "\n"; 473 } 474 475 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) { 476 assert(MBB); 477 report(msg, MBB->getParent()); 478 errs() << "- basic block: " << printMBBReference(*MBB) << ' ' 479 << MBB->getName() << " (" << (const void *)MBB << ')'; 480 if (Indexes) 481 errs() << " [" << Indexes->getMBBStartIdx(MBB) 482 << ';' << Indexes->getMBBEndIdx(MBB) << ')'; 483 errs() << '\n'; 484 } 485 486 void MachineVerifier::report(const char *msg, const MachineInstr *MI) { 487 assert(MI); 488 report(msg, MI->getParent()); 489 errs() << "- instruction: "; 490 if (Indexes && Indexes->hasIndex(*MI)) 491 errs() << Indexes->getInstructionIndex(*MI) << '\t'; 492 MI->print(errs(), /*IsStandalone=*/true); 493 } 494 495 void MachineVerifier::report(const char *msg, const MachineOperand *MO, 496 unsigned MONum, LLT MOVRegType) { 497 assert(MO); 498 report(msg, MO->getParent()); 499 errs() << "- operand " << MONum << ": "; 500 MO->print(errs(), MOVRegType, TRI); 501 errs() << "\n"; 502 } 503 504 void MachineVerifier::report_context(SlotIndex Pos) const { 505 errs() << "- at: " << Pos << '\n'; 506 } 507 508 void MachineVerifier::report_context(const LiveInterval &LI) const { 509 errs() << "- interval: " << LI << '\n'; 510 } 511 512 void MachineVerifier::report_context(const LiveRange &LR, Register VRegUnit, 513 LaneBitmask LaneMask) const { 514 report_context_liverange(LR); 515 report_context_vreg_regunit(VRegUnit); 516 if (LaneMask.any()) 517 report_context_lanemask(LaneMask); 518 } 519 520 void MachineVerifier::report_context(const LiveRange::Segment &S) const { 521 errs() << "- segment: " << S << '\n'; 522 } 523 524 void MachineVerifier::report_context(const VNInfo &VNI) const { 525 errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n"; 526 } 527 528 void MachineVerifier::report_context_liverange(const LiveRange &LR) const { 529 errs() << "- liverange: " << LR << '\n'; 530 } 531 532 void MachineVerifier::report_context(MCPhysReg PReg) const { 533 errs() << "- p. register: " << printReg(PReg, TRI) << '\n'; 534 } 535 536 void MachineVerifier::report_context_vreg(Register VReg) const { 537 errs() << "- v. register: " << printReg(VReg, TRI) << '\n'; 538 } 539 540 void MachineVerifier::report_context_vreg_regunit(Register VRegOrUnit) const { 541 if (Register::isVirtualRegister(VRegOrUnit)) { 542 report_context_vreg(VRegOrUnit); 543 } else { 544 errs() << "- regunit: " << printRegUnit(VRegOrUnit, TRI) << '\n'; 545 } 546 } 547 548 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const { 549 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n'; 550 } 551 552 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) { 553 BBInfo &MInfo = MBBInfoMap[MBB]; 554 if (!MInfo.reachable) { 555 MInfo.reachable = true; 556 for (const MachineBasicBlock *Succ : MBB->successors()) 557 markReachable(Succ); 558 } 559 } 560 561 void MachineVerifier::visitMachineFunctionBefore() { 562 lastIndex = SlotIndex(); 563 regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs() 564 : TRI->getReservedRegs(*MF); 565 566 if (!MF->empty()) 567 markReachable(&MF->front()); 568 569 // Build a set of the basic blocks in the function. 570 FunctionBlocks.clear(); 571 for (const auto &MBB : *MF) { 572 FunctionBlocks.insert(&MBB); 573 BBInfo &MInfo = MBBInfoMap[&MBB]; 574 575 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end()); 576 if (MInfo.Preds.size() != MBB.pred_size()) 577 report("MBB has duplicate entries in its predecessor list.", &MBB); 578 579 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end()); 580 if (MInfo.Succs.size() != MBB.succ_size()) 581 report("MBB has duplicate entries in its successor list.", &MBB); 582 } 583 584 // Check that the register use lists are sane. 585 MRI->verifyUseLists(); 586 587 if (!MF->empty()) 588 verifyStackFrame(); 589 } 590 591 void 592 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) { 593 FirstTerminator = nullptr; 594 FirstNonPHI = nullptr; 595 596 if (!MF->getProperties().hasProperty( 597 MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) { 598 // If this block has allocatable physical registers live-in, check that 599 // it is an entry block or landing pad. 600 for (const auto &LI : MBB->liveins()) { 601 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() && 602 MBB->getIterator() != MBB->getParent()->begin()) { 603 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB); 604 report_context(LI.PhysReg); 605 } 606 } 607 } 608 609 // Count the number of landing pad successors. 610 SmallPtrSet<const MachineBasicBlock*, 4> LandingPadSuccs; 611 for (const auto *succ : MBB->successors()) { 612 if (succ->isEHPad()) 613 LandingPadSuccs.insert(succ); 614 if (!FunctionBlocks.count(succ)) 615 report("MBB has successor that isn't part of the function.", MBB); 616 if (!MBBInfoMap[succ].Preds.count(MBB)) { 617 report("Inconsistent CFG", MBB); 618 errs() << "MBB is not in the predecessor list of the successor " 619 << printMBBReference(*succ) << ".\n"; 620 } 621 } 622 623 // Check the predecessor list. 624 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 625 if (!FunctionBlocks.count(Pred)) 626 report("MBB has predecessor that isn't part of the function.", MBB); 627 if (!MBBInfoMap[Pred].Succs.count(MBB)) { 628 report("Inconsistent CFG", MBB); 629 errs() << "MBB is not in the successor list of the predecessor " 630 << printMBBReference(*Pred) << ".\n"; 631 } 632 } 633 634 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo(); 635 const BasicBlock *BB = MBB->getBasicBlock(); 636 const Function &F = MF->getFunction(); 637 if (LandingPadSuccs.size() > 1 && 638 !(AsmInfo && 639 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj && 640 BB && isa<SwitchInst>(BB->getTerminator())) && 641 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 642 report("MBB has more than one landing pad successor", MBB); 643 644 // Call analyzeBranch. If it succeeds, there several more conditions to check. 645 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 646 SmallVector<MachineOperand, 4> Cond; 647 if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB, 648 Cond)) { 649 // Ok, analyzeBranch thinks it knows what's going on with this block. Let's 650 // check whether its answers match up with reality. 651 if (!TBB && !FBB) { 652 // Block falls through to its successor. 653 if (!MBB->empty() && MBB->back().isBarrier() && 654 !TII->isPredicated(MBB->back())) { 655 report("MBB exits via unconditional fall-through but ends with a " 656 "barrier instruction!", MBB); 657 } 658 if (!Cond.empty()) { 659 report("MBB exits via unconditional fall-through but has a condition!", 660 MBB); 661 } 662 } else if (TBB && !FBB && Cond.empty()) { 663 // Block unconditionally branches somewhere. 664 if (MBB->empty()) { 665 report("MBB exits via unconditional branch but doesn't contain " 666 "any instructions!", MBB); 667 } else if (!MBB->back().isBarrier()) { 668 report("MBB exits via unconditional branch but doesn't end with a " 669 "barrier instruction!", MBB); 670 } else if (!MBB->back().isTerminator()) { 671 report("MBB exits via unconditional branch but the branch isn't a " 672 "terminator instruction!", MBB); 673 } 674 } else if (TBB && !FBB && !Cond.empty()) { 675 // Block conditionally branches somewhere, otherwise falls through. 676 if (MBB->empty()) { 677 report("MBB exits via conditional branch/fall-through but doesn't " 678 "contain any instructions!", MBB); 679 } else if (MBB->back().isBarrier()) { 680 report("MBB exits via conditional branch/fall-through but ends with a " 681 "barrier instruction!", MBB); 682 } else if (!MBB->back().isTerminator()) { 683 report("MBB exits via conditional branch/fall-through but the branch " 684 "isn't a terminator instruction!", MBB); 685 } 686 } else if (TBB && FBB) { 687 // Block conditionally branches somewhere, otherwise branches 688 // somewhere else. 689 if (MBB->empty()) { 690 report("MBB exits via conditional branch/branch but doesn't " 691 "contain any instructions!", MBB); 692 } else if (!MBB->back().isBarrier()) { 693 report("MBB exits via conditional branch/branch but doesn't end with a " 694 "barrier instruction!", MBB); 695 } else if (!MBB->back().isTerminator()) { 696 report("MBB exits via conditional branch/branch but the branch " 697 "isn't a terminator instruction!", MBB); 698 } 699 if (Cond.empty()) { 700 report("MBB exits via conditional branch/branch but there's no " 701 "condition!", MBB); 702 } 703 } else { 704 report("analyzeBranch returned invalid data!", MBB); 705 } 706 707 // Now check that the successors match up with the answers reported by 708 // analyzeBranch. 709 if (TBB && !MBB->isSuccessor(TBB)) 710 report("MBB exits via jump or conditional branch, but its target isn't a " 711 "CFG successor!", 712 MBB); 713 if (FBB && !MBB->isSuccessor(FBB)) 714 report("MBB exits via conditional branch, but its target isn't a CFG " 715 "successor!", 716 MBB); 717 718 // There might be a fallthrough to the next block if there's either no 719 // unconditional true branch, or if there's a condition, and one of the 720 // branches is missing. 721 bool Fallthrough = !TBB || (!Cond.empty() && !FBB); 722 723 // A conditional fallthrough must be an actual CFG successor, not 724 // unreachable. (Conversely, an unconditional fallthrough might not really 725 // be a successor, because the block might end in unreachable.) 726 if (!Cond.empty() && !FBB) { 727 MachineFunction::const_iterator MBBI = std::next(MBB->getIterator()); 728 if (MBBI == MF->end()) { 729 report("MBB conditionally falls through out of function!", MBB); 730 } else if (!MBB->isSuccessor(&*MBBI)) 731 report("MBB exits via conditional branch/fall-through but the CFG " 732 "successors don't match the actual successors!", 733 MBB); 734 } 735 736 // Verify that there aren't any extra un-accounted-for successors. 737 for (const MachineBasicBlock *SuccMBB : MBB->successors()) { 738 // If this successor is one of the branch targets, it's okay. 739 if (SuccMBB == TBB || SuccMBB == FBB) 740 continue; 741 // If we might have a fallthrough, and the successor is the fallthrough 742 // block, that's also ok. 743 if (Fallthrough && SuccMBB == MBB->getNextNode()) 744 continue; 745 // Also accept successors which are for exception-handling or might be 746 // inlineasm_br targets. 747 if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget()) 748 continue; 749 report("MBB has unexpected successors which are not branch targets, " 750 "fallthrough, EHPads, or inlineasm_br targets.", 751 MBB); 752 } 753 } 754 755 regsLive.clear(); 756 if (MRI->tracksLiveness()) { 757 for (const auto &LI : MBB->liveins()) { 758 if (!Register::isPhysicalRegister(LI.PhysReg)) { 759 report("MBB live-in list contains non-physical register", MBB); 760 continue; 761 } 762 for (const MCPhysReg &SubReg : TRI->subregs_inclusive(LI.PhysReg)) 763 regsLive.insert(SubReg); 764 } 765 } 766 767 const MachineFrameInfo &MFI = MF->getFrameInfo(); 768 BitVector PR = MFI.getPristineRegs(*MF); 769 for (unsigned I : PR.set_bits()) { 770 for (const MCPhysReg &SubReg : TRI->subregs_inclusive(I)) 771 regsLive.insert(SubReg); 772 } 773 774 regsKilled.clear(); 775 regsDefined.clear(); 776 777 if (Indexes) 778 lastIndex = Indexes->getMBBStartIdx(MBB); 779 } 780 781 // This function gets called for all bundle headers, including normal 782 // stand-alone unbundled instructions. 783 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) { 784 if (Indexes && Indexes->hasIndex(*MI)) { 785 SlotIndex idx = Indexes->getInstructionIndex(*MI); 786 if (!(idx > lastIndex)) { 787 report("Instruction index out of order", MI); 788 errs() << "Last instruction was at " << lastIndex << '\n'; 789 } 790 lastIndex = idx; 791 } 792 793 // Ensure non-terminators don't follow terminators. 794 if (MI->isTerminator()) { 795 if (!FirstTerminator) 796 FirstTerminator = MI; 797 } else if (FirstTerminator) { 798 report("Non-terminator instruction after the first terminator", MI); 799 errs() << "First terminator was:\t" << *FirstTerminator; 800 } 801 } 802 803 // The operands on an INLINEASM instruction must follow a template. 804 // Verify that the flag operands make sense. 805 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) { 806 // The first two operands on INLINEASM are the asm string and global flags. 807 if (MI->getNumOperands() < 2) { 808 report("Too few operands on inline asm", MI); 809 return; 810 } 811 if (!MI->getOperand(0).isSymbol()) 812 report("Asm string must be an external symbol", MI); 813 if (!MI->getOperand(1).isImm()) 814 report("Asm flags must be an immediate", MI); 815 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2, 816 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16, 817 // and Extra_IsConvergent = 32. 818 if (!isUInt<6>(MI->getOperand(1).getImm())) 819 report("Unknown asm flags", &MI->getOperand(1), 1); 820 821 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed"); 822 823 unsigned OpNo = InlineAsm::MIOp_FirstOperand; 824 unsigned NumOps; 825 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) { 826 const MachineOperand &MO = MI->getOperand(OpNo); 827 // There may be implicit ops after the fixed operands. 828 if (!MO.isImm()) 829 break; 830 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm()); 831 } 832 833 if (OpNo > MI->getNumOperands()) 834 report("Missing operands in last group", MI); 835 836 // An optional MDNode follows the groups. 837 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata()) 838 ++OpNo; 839 840 // All trailing operands must be implicit registers. 841 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) { 842 const MachineOperand &MO = MI->getOperand(OpNo); 843 if (!MO.isReg() || !MO.isImplicit()) 844 report("Expected implicit register after groups", &MO, OpNo); 845 } 846 } 847 848 /// Check that types are consistent when two operands need to have the same 849 /// number of vector elements. 850 /// \return true if the types are valid. 851 bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1, 852 const MachineInstr *MI) { 853 if (Ty0.isVector() != Ty1.isVector()) { 854 report("operand types must be all-vector or all-scalar", MI); 855 // Generally we try to report as many issues as possible at once, but in 856 // this case it's not clear what should we be comparing the size of the 857 // scalar with: the size of the whole vector or its lane. Instead of 858 // making an arbitrary choice and emitting not so helpful message, let's 859 // avoid the extra noise and stop here. 860 return false; 861 } 862 863 if (Ty0.isVector() && Ty0.getNumElements() != Ty1.getNumElements()) { 864 report("operand types must preserve number of vector elements", MI); 865 return false; 866 } 867 868 return true; 869 } 870 871 void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) { 872 if (isFunctionSelected) 873 report("Unexpected generic instruction in a Selected function", MI); 874 875 const MCInstrDesc &MCID = MI->getDesc(); 876 unsigned NumOps = MI->getNumOperands(); 877 878 // Branches must reference a basic block if they are not indirect 879 if (MI->isBranch() && !MI->isIndirectBranch()) { 880 bool HasMBB = false; 881 for (const MachineOperand &Op : MI->operands()) { 882 if (Op.isMBB()) { 883 HasMBB = true; 884 break; 885 } 886 } 887 888 if (!HasMBB) { 889 report("Branch instruction is missing a basic block operand or " 890 "isIndirectBranch property", 891 MI); 892 } 893 } 894 895 // Check types. 896 SmallVector<LLT, 4> Types; 897 for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps); 898 I != E; ++I) { 899 if (!MCID.OpInfo[I].isGenericType()) 900 continue; 901 // Generic instructions specify type equality constraints between some of 902 // their operands. Make sure these are consistent. 903 size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex(); 904 Types.resize(std::max(TypeIdx + 1, Types.size())); 905 906 const MachineOperand *MO = &MI->getOperand(I); 907 if (!MO->isReg()) { 908 report("generic instruction must use register operands", MI); 909 continue; 910 } 911 912 LLT OpTy = MRI->getType(MO->getReg()); 913 // Don't report a type mismatch if there is no actual mismatch, only a 914 // type missing, to reduce noise: 915 if (OpTy.isValid()) { 916 // Only the first valid type for a type index will be printed: don't 917 // overwrite it later so it's always clear which type was expected: 918 if (!Types[TypeIdx].isValid()) 919 Types[TypeIdx] = OpTy; 920 else if (Types[TypeIdx] != OpTy) 921 report("Type mismatch in generic instruction", MO, I, OpTy); 922 } else { 923 // Generic instructions must have types attached to their operands. 924 report("Generic instruction is missing a virtual register type", MO, I); 925 } 926 } 927 928 // Generic opcodes must not have physical register operands. 929 for (unsigned I = 0; I < MI->getNumOperands(); ++I) { 930 const MachineOperand *MO = &MI->getOperand(I); 931 if (MO->isReg() && Register::isPhysicalRegister(MO->getReg())) 932 report("Generic instruction cannot have physical register", MO, I); 933 } 934 935 // Avoid out of bounds in checks below. This was already reported earlier. 936 if (MI->getNumOperands() < MCID.getNumOperands()) 937 return; 938 939 StringRef ErrorInfo; 940 if (!TII->verifyInstruction(*MI, ErrorInfo)) 941 report(ErrorInfo.data(), MI); 942 943 // Verify properties of various specific instruction types 944 switch (MI->getOpcode()) { 945 case TargetOpcode::G_CONSTANT: 946 case TargetOpcode::G_FCONSTANT: { 947 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 948 if (DstTy.isVector()) 949 report("Instruction cannot use a vector result type", MI); 950 951 if (MI->getOpcode() == TargetOpcode::G_CONSTANT) { 952 if (!MI->getOperand(1).isCImm()) { 953 report("G_CONSTANT operand must be cimm", MI); 954 break; 955 } 956 957 const ConstantInt *CI = MI->getOperand(1).getCImm(); 958 if (CI->getBitWidth() != DstTy.getSizeInBits()) 959 report("inconsistent constant size", MI); 960 } else { 961 if (!MI->getOperand(1).isFPImm()) { 962 report("G_FCONSTANT operand must be fpimm", MI); 963 break; 964 } 965 const ConstantFP *CF = MI->getOperand(1).getFPImm(); 966 967 if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) != 968 DstTy.getSizeInBits()) { 969 report("inconsistent constant size", MI); 970 } 971 } 972 973 break; 974 } 975 case TargetOpcode::G_LOAD: 976 case TargetOpcode::G_STORE: 977 case TargetOpcode::G_ZEXTLOAD: 978 case TargetOpcode::G_SEXTLOAD: { 979 LLT ValTy = MRI->getType(MI->getOperand(0).getReg()); 980 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg()); 981 if (!PtrTy.isPointer()) 982 report("Generic memory instruction must access a pointer", MI); 983 984 // Generic loads and stores must have a single MachineMemOperand 985 // describing that access. 986 if (!MI->hasOneMemOperand()) { 987 report("Generic instruction accessing memory must have one mem operand", 988 MI); 989 } else { 990 const MachineMemOperand &MMO = **MI->memoperands_begin(); 991 if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD || 992 MI->getOpcode() == TargetOpcode::G_SEXTLOAD) { 993 if (MMO.getSizeInBits() >= ValTy.getSizeInBits()) 994 report("Generic extload must have a narrower memory type", MI); 995 } else if (MI->getOpcode() == TargetOpcode::G_LOAD) { 996 if (MMO.getSize() > ValTy.getSizeInBytes()) 997 report("load memory size cannot exceed result size", MI); 998 } else if (MI->getOpcode() == TargetOpcode::G_STORE) { 999 if (ValTy.getSizeInBytes() < MMO.getSize()) 1000 report("store memory size cannot exceed value size", MI); 1001 } 1002 } 1003 1004 break; 1005 } 1006 case TargetOpcode::G_PHI: { 1007 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1008 if (!DstTy.isValid() || 1009 !std::all_of(MI->operands_begin() + 1, MI->operands_end(), 1010 [this, &DstTy](const MachineOperand &MO) { 1011 if (!MO.isReg()) 1012 return true; 1013 LLT Ty = MRI->getType(MO.getReg()); 1014 if (!Ty.isValid() || (Ty != DstTy)) 1015 return false; 1016 return true; 1017 })) 1018 report("Generic Instruction G_PHI has operands with incompatible/missing " 1019 "types", 1020 MI); 1021 break; 1022 } 1023 case TargetOpcode::G_BITCAST: { 1024 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1025 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1026 if (!DstTy.isValid() || !SrcTy.isValid()) 1027 break; 1028 1029 if (SrcTy.isPointer() != DstTy.isPointer()) 1030 report("bitcast cannot convert between pointers and other types", MI); 1031 1032 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits()) 1033 report("bitcast sizes must match", MI); 1034 1035 if (SrcTy == DstTy) 1036 report("bitcast must change the type", MI); 1037 1038 break; 1039 } 1040 case TargetOpcode::G_INTTOPTR: 1041 case TargetOpcode::G_PTRTOINT: 1042 case TargetOpcode::G_ADDRSPACE_CAST: { 1043 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1044 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1045 if (!DstTy.isValid() || !SrcTy.isValid()) 1046 break; 1047 1048 verifyVectorElementMatch(DstTy, SrcTy, MI); 1049 1050 DstTy = DstTy.getScalarType(); 1051 SrcTy = SrcTy.getScalarType(); 1052 1053 if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) { 1054 if (!DstTy.isPointer()) 1055 report("inttoptr result type must be a pointer", MI); 1056 if (SrcTy.isPointer()) 1057 report("inttoptr source type must not be a pointer", MI); 1058 } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) { 1059 if (!SrcTy.isPointer()) 1060 report("ptrtoint source type must be a pointer", MI); 1061 if (DstTy.isPointer()) 1062 report("ptrtoint result type must not be a pointer", MI); 1063 } else { 1064 assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST); 1065 if (!SrcTy.isPointer() || !DstTy.isPointer()) 1066 report("addrspacecast types must be pointers", MI); 1067 else { 1068 if (SrcTy.getAddressSpace() == DstTy.getAddressSpace()) 1069 report("addrspacecast must convert different address spaces", MI); 1070 } 1071 } 1072 1073 break; 1074 } 1075 case TargetOpcode::G_PTR_ADD: { 1076 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1077 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg()); 1078 LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg()); 1079 if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid()) 1080 break; 1081 1082 if (!PtrTy.getScalarType().isPointer()) 1083 report("gep first operand must be a pointer", MI); 1084 1085 if (OffsetTy.getScalarType().isPointer()) 1086 report("gep offset operand must not be a pointer", MI); 1087 1088 // TODO: Is the offset allowed to be a scalar with a vector? 1089 break; 1090 } 1091 case TargetOpcode::G_PTRMASK: { 1092 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1093 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1094 LLT MaskTy = MRI->getType(MI->getOperand(2).getReg()); 1095 if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid()) 1096 break; 1097 1098 if (!DstTy.getScalarType().isPointer()) 1099 report("ptrmask result type must be a pointer", MI); 1100 1101 if (!MaskTy.getScalarType().isScalar()) 1102 report("ptrmask mask type must be an integer", MI); 1103 1104 verifyVectorElementMatch(DstTy, MaskTy, MI); 1105 break; 1106 } 1107 case TargetOpcode::G_SEXT: 1108 case TargetOpcode::G_ZEXT: 1109 case TargetOpcode::G_ANYEXT: 1110 case TargetOpcode::G_TRUNC: 1111 case TargetOpcode::G_FPEXT: 1112 case TargetOpcode::G_FPTRUNC: { 1113 // Number of operands and presense of types is already checked (and 1114 // reported in case of any issues), so no need to report them again. As 1115 // we're trying to report as many issues as possible at once, however, the 1116 // instructions aren't guaranteed to have the right number of operands or 1117 // types attached to them at this point 1118 assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}"); 1119 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1120 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1121 if (!DstTy.isValid() || !SrcTy.isValid()) 1122 break; 1123 1124 LLT DstElTy = DstTy.getScalarType(); 1125 LLT SrcElTy = SrcTy.getScalarType(); 1126 if (DstElTy.isPointer() || SrcElTy.isPointer()) 1127 report("Generic extend/truncate can not operate on pointers", MI); 1128 1129 verifyVectorElementMatch(DstTy, SrcTy, MI); 1130 1131 unsigned DstSize = DstElTy.getSizeInBits(); 1132 unsigned SrcSize = SrcElTy.getSizeInBits(); 1133 switch (MI->getOpcode()) { 1134 default: 1135 if (DstSize <= SrcSize) 1136 report("Generic extend has destination type no larger than source", MI); 1137 break; 1138 case TargetOpcode::G_TRUNC: 1139 case TargetOpcode::G_FPTRUNC: 1140 if (DstSize >= SrcSize) 1141 report("Generic truncate has destination type no smaller than source", 1142 MI); 1143 break; 1144 } 1145 break; 1146 } 1147 case TargetOpcode::G_SELECT: { 1148 LLT SelTy = MRI->getType(MI->getOperand(0).getReg()); 1149 LLT CondTy = MRI->getType(MI->getOperand(1).getReg()); 1150 if (!SelTy.isValid() || !CondTy.isValid()) 1151 break; 1152 1153 // Scalar condition select on a vector is valid. 1154 if (CondTy.isVector()) 1155 verifyVectorElementMatch(SelTy, CondTy, MI); 1156 break; 1157 } 1158 case TargetOpcode::G_MERGE_VALUES: { 1159 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar, 1160 // e.g. s2N = MERGE sN, sN 1161 // Merging multiple scalars into a vector is not allowed, should use 1162 // G_BUILD_VECTOR for that. 1163 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1164 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1165 if (DstTy.isVector() || SrcTy.isVector()) 1166 report("G_MERGE_VALUES cannot operate on vectors", MI); 1167 1168 const unsigned NumOps = MI->getNumOperands(); 1169 if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1)) 1170 report("G_MERGE_VALUES result size is inconsistent", MI); 1171 1172 for (unsigned I = 2; I != NumOps; ++I) { 1173 if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy) 1174 report("G_MERGE_VALUES source types do not match", MI); 1175 } 1176 1177 break; 1178 } 1179 case TargetOpcode::G_UNMERGE_VALUES: { 1180 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1181 LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg()); 1182 // For now G_UNMERGE can split vectors. 1183 for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) { 1184 if (MRI->getType(MI->getOperand(i).getReg()) != DstTy) 1185 report("G_UNMERGE_VALUES destination types do not match", MI); 1186 } 1187 if (SrcTy.getSizeInBits() != 1188 (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) { 1189 report("G_UNMERGE_VALUES source operand does not cover dest operands", 1190 MI); 1191 } 1192 break; 1193 } 1194 case TargetOpcode::G_BUILD_VECTOR: { 1195 // Source types must be scalars, dest type a vector. Total size of scalars 1196 // must match the dest vector size. 1197 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1198 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg()); 1199 if (!DstTy.isVector() || SrcEltTy.isVector()) { 1200 report("G_BUILD_VECTOR must produce a vector from scalar operands", MI); 1201 break; 1202 } 1203 1204 if (DstTy.getElementType() != SrcEltTy) 1205 report("G_BUILD_VECTOR result element type must match source type", MI); 1206 1207 if (DstTy.getNumElements() != MI->getNumOperands() - 1) 1208 report("G_BUILD_VECTOR must have an operand for each elemement", MI); 1209 1210 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1211 if (MRI->getType(MI->getOperand(1).getReg()) != 1212 MRI->getType(MI->getOperand(i).getReg())) 1213 report("G_BUILD_VECTOR source operand types are not homogeneous", MI); 1214 } 1215 1216 break; 1217 } 1218 case TargetOpcode::G_BUILD_VECTOR_TRUNC: { 1219 // Source types must be scalars, dest type a vector. Scalar types must be 1220 // larger than the dest vector elt type, as this is a truncating operation. 1221 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1222 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg()); 1223 if (!DstTy.isVector() || SrcEltTy.isVector()) 1224 report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands", 1225 MI); 1226 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1227 if (MRI->getType(MI->getOperand(1).getReg()) != 1228 MRI->getType(MI->getOperand(i).getReg())) 1229 report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous", 1230 MI); 1231 } 1232 if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits()) 1233 report("G_BUILD_VECTOR_TRUNC source operand types are not larger than " 1234 "dest elt type", 1235 MI); 1236 break; 1237 } 1238 case TargetOpcode::G_CONCAT_VECTORS: { 1239 // Source types should be vectors, and total size should match the dest 1240 // vector size. 1241 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1242 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1243 if (!DstTy.isVector() || !SrcTy.isVector()) 1244 report("G_CONCAT_VECTOR requires vector source and destination operands", 1245 MI); 1246 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1247 if (MRI->getType(MI->getOperand(1).getReg()) != 1248 MRI->getType(MI->getOperand(i).getReg())) 1249 report("G_CONCAT_VECTOR source operand types are not homogeneous", MI); 1250 } 1251 if (DstTy.getNumElements() != 1252 SrcTy.getNumElements() * (MI->getNumOperands() - 1)) 1253 report("G_CONCAT_VECTOR num dest and source elements should match", MI); 1254 break; 1255 } 1256 case TargetOpcode::G_ICMP: 1257 case TargetOpcode::G_FCMP: { 1258 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1259 LLT SrcTy = MRI->getType(MI->getOperand(2).getReg()); 1260 1261 if ((DstTy.isVector() != SrcTy.isVector()) || 1262 (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements())) 1263 report("Generic vector icmp/fcmp must preserve number of lanes", MI); 1264 1265 break; 1266 } 1267 case TargetOpcode::G_EXTRACT: { 1268 const MachineOperand &SrcOp = MI->getOperand(1); 1269 if (!SrcOp.isReg()) { 1270 report("extract source must be a register", MI); 1271 break; 1272 } 1273 1274 const MachineOperand &OffsetOp = MI->getOperand(2); 1275 if (!OffsetOp.isImm()) { 1276 report("extract offset must be a constant", MI); 1277 break; 1278 } 1279 1280 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits(); 1281 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits(); 1282 if (SrcSize == DstSize) 1283 report("extract source must be larger than result", MI); 1284 1285 if (DstSize + OffsetOp.getImm() > SrcSize) 1286 report("extract reads past end of register", MI); 1287 break; 1288 } 1289 case TargetOpcode::G_INSERT: { 1290 const MachineOperand &SrcOp = MI->getOperand(2); 1291 if (!SrcOp.isReg()) { 1292 report("insert source must be a register", MI); 1293 break; 1294 } 1295 1296 const MachineOperand &OffsetOp = MI->getOperand(3); 1297 if (!OffsetOp.isImm()) { 1298 report("insert offset must be a constant", MI); 1299 break; 1300 } 1301 1302 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits(); 1303 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits(); 1304 1305 if (DstSize <= SrcSize) 1306 report("inserted size must be smaller than total register", MI); 1307 1308 if (SrcSize + OffsetOp.getImm() > DstSize) 1309 report("insert writes past end of register", MI); 1310 1311 break; 1312 } 1313 case TargetOpcode::G_JUMP_TABLE: { 1314 if (!MI->getOperand(1).isJTI()) 1315 report("G_JUMP_TABLE source operand must be a jump table index", MI); 1316 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1317 if (!DstTy.isPointer()) 1318 report("G_JUMP_TABLE dest operand must have a pointer type", MI); 1319 break; 1320 } 1321 case TargetOpcode::G_BRJT: { 1322 if (!MRI->getType(MI->getOperand(0).getReg()).isPointer()) 1323 report("G_BRJT src operand 0 must be a pointer type", MI); 1324 1325 if (!MI->getOperand(1).isJTI()) 1326 report("G_BRJT src operand 1 must be a jump table index", MI); 1327 1328 const auto &IdxOp = MI->getOperand(2); 1329 if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer()) 1330 report("G_BRJT src operand 2 must be a scalar reg type", MI); 1331 break; 1332 } 1333 case TargetOpcode::G_INTRINSIC: 1334 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS: { 1335 // TODO: Should verify number of def and use operands, but the current 1336 // interface requires passing in IR types for mangling. 1337 const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs()); 1338 if (!IntrIDOp.isIntrinsicID()) { 1339 report("G_INTRINSIC first src operand must be an intrinsic ID", MI); 1340 break; 1341 } 1342 1343 bool NoSideEffects = MI->getOpcode() == TargetOpcode::G_INTRINSIC; 1344 unsigned IntrID = IntrIDOp.getIntrinsicID(); 1345 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) { 1346 AttributeList Attrs 1347 = Intrinsic::getAttributes(MF->getFunction().getContext(), 1348 static_cast<Intrinsic::ID>(IntrID)); 1349 bool DeclHasSideEffects = !Attrs.hasFnAttribute(Attribute::ReadNone); 1350 if (NoSideEffects && DeclHasSideEffects) { 1351 report("G_INTRINSIC used with intrinsic that accesses memory", MI); 1352 break; 1353 } 1354 if (!NoSideEffects && !DeclHasSideEffects) { 1355 report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI); 1356 break; 1357 } 1358 } 1359 1360 break; 1361 } 1362 case TargetOpcode::G_SEXT_INREG: { 1363 if (!MI->getOperand(2).isImm()) { 1364 report("G_SEXT_INREG expects an immediate operand #2", MI); 1365 break; 1366 } 1367 1368 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1369 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1370 verifyVectorElementMatch(DstTy, SrcTy, MI); 1371 1372 int64_t Imm = MI->getOperand(2).getImm(); 1373 if (Imm <= 0) 1374 report("G_SEXT_INREG size must be >= 1", MI); 1375 if (Imm >= SrcTy.getScalarSizeInBits()) 1376 report("G_SEXT_INREG size must be less than source bit width", MI); 1377 break; 1378 } 1379 case TargetOpcode::G_SHUFFLE_VECTOR: { 1380 const MachineOperand &MaskOp = MI->getOperand(3); 1381 if (!MaskOp.isShuffleMask()) { 1382 report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI); 1383 break; 1384 } 1385 1386 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1387 LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg()); 1388 LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg()); 1389 1390 if (Src0Ty != Src1Ty) 1391 report("Source operands must be the same type", MI); 1392 1393 if (Src0Ty.getScalarType() != DstTy.getScalarType()) 1394 report("G_SHUFFLE_VECTOR cannot change element type", MI); 1395 1396 // Don't check that all operands are vector because scalars are used in 1397 // place of 1 element vectors. 1398 int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1; 1399 int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1; 1400 1401 ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask(); 1402 1403 if (static_cast<int>(MaskIdxes.size()) != DstNumElts) 1404 report("Wrong result type for shufflemask", MI); 1405 1406 for (int Idx : MaskIdxes) { 1407 if (Idx < 0) 1408 continue; 1409 1410 if (Idx >= 2 * SrcNumElts) 1411 report("Out of bounds shuffle index", MI); 1412 } 1413 1414 break; 1415 } 1416 case TargetOpcode::G_DYN_STACKALLOC: { 1417 const MachineOperand &DstOp = MI->getOperand(0); 1418 const MachineOperand &AllocOp = MI->getOperand(1); 1419 const MachineOperand &AlignOp = MI->getOperand(2); 1420 1421 if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) { 1422 report("dst operand 0 must be a pointer type", MI); 1423 break; 1424 } 1425 1426 if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) { 1427 report("src operand 1 must be a scalar reg type", MI); 1428 break; 1429 } 1430 1431 if (!AlignOp.isImm()) { 1432 report("src operand 2 must be an immediate type", MI); 1433 break; 1434 } 1435 break; 1436 } 1437 case TargetOpcode::G_MEMCPY: 1438 case TargetOpcode::G_MEMMOVE: { 1439 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands(); 1440 if (MMOs.size() != 2) { 1441 report("memcpy/memmove must have 2 memory operands", MI); 1442 break; 1443 } 1444 1445 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) || 1446 (MMOs[1]->isStore() || !MMOs[1]->isLoad())) { 1447 report("wrong memory operand types", MI); 1448 break; 1449 } 1450 1451 if (MMOs[0]->getSize() != MMOs[1]->getSize()) 1452 report("inconsistent memory operand sizes", MI); 1453 1454 LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg()); 1455 LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg()); 1456 1457 if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) { 1458 report("memory instruction operand must be a pointer", MI); 1459 break; 1460 } 1461 1462 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace()) 1463 report("inconsistent store address space", MI); 1464 if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace()) 1465 report("inconsistent load address space", MI); 1466 1467 break; 1468 } 1469 case TargetOpcode::G_MEMSET: { 1470 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands(); 1471 if (MMOs.size() != 1) { 1472 report("memset must have 1 memory operand", MI); 1473 break; 1474 } 1475 1476 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) { 1477 report("memset memory operand must be a store", MI); 1478 break; 1479 } 1480 1481 LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg()); 1482 if (!DstPtrTy.isPointer()) { 1483 report("memset operand must be a pointer", MI); 1484 break; 1485 } 1486 1487 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace()) 1488 report("inconsistent memset address space", MI); 1489 1490 break; 1491 } 1492 case TargetOpcode::G_VECREDUCE_SEQ_FADD: 1493 case TargetOpcode::G_VECREDUCE_SEQ_FMUL: { 1494 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1495 LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg()); 1496 LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg()); 1497 if (!DstTy.isScalar()) 1498 report("Vector reduction requires a scalar destination type", MI); 1499 if (!Src1Ty.isScalar()) 1500 report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI); 1501 if (!Src2Ty.isVector()) 1502 report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI); 1503 break; 1504 } 1505 case TargetOpcode::G_VECREDUCE_FADD: 1506 case TargetOpcode::G_VECREDUCE_FMUL: 1507 case TargetOpcode::G_VECREDUCE_FMAX: 1508 case TargetOpcode::G_VECREDUCE_FMIN: 1509 case TargetOpcode::G_VECREDUCE_ADD: 1510 case TargetOpcode::G_VECREDUCE_MUL: 1511 case TargetOpcode::G_VECREDUCE_AND: 1512 case TargetOpcode::G_VECREDUCE_OR: 1513 case TargetOpcode::G_VECREDUCE_XOR: 1514 case TargetOpcode::G_VECREDUCE_SMAX: 1515 case TargetOpcode::G_VECREDUCE_SMIN: 1516 case TargetOpcode::G_VECREDUCE_UMAX: 1517 case TargetOpcode::G_VECREDUCE_UMIN: { 1518 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1519 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1520 if (!DstTy.isScalar()) 1521 report("Vector reduction requires a scalar destination type", MI); 1522 if (!SrcTy.isVector()) 1523 report("Vector reduction requires vector source=", MI); 1524 break; 1525 } 1526 default: 1527 break; 1528 } 1529 } 1530 1531 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) { 1532 const MCInstrDesc &MCID = MI->getDesc(); 1533 if (MI->getNumOperands() < MCID.getNumOperands()) { 1534 report("Too few operands", MI); 1535 errs() << MCID.getNumOperands() << " operands expected, but " 1536 << MI->getNumOperands() << " given.\n"; 1537 } 1538 1539 if (MI->isPHI()) { 1540 if (MF->getProperties().hasProperty( 1541 MachineFunctionProperties::Property::NoPHIs)) 1542 report("Found PHI instruction with NoPHIs property set", MI); 1543 1544 if (FirstNonPHI) 1545 report("Found PHI instruction after non-PHI", MI); 1546 } else if (FirstNonPHI == nullptr) 1547 FirstNonPHI = MI; 1548 1549 // Check the tied operands. 1550 if (MI->isInlineAsm()) 1551 verifyInlineAsm(MI); 1552 1553 // Check that unspillable terminators define a reg and have at most one use. 1554 if (TII->isUnspillableTerminator(MI)) { 1555 if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef()) 1556 report("Unspillable Terminator does not define a reg", MI); 1557 Register Def = MI->getOperand(0).getReg(); 1558 if (Def.isVirtual() && 1559 std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1) 1560 report("Unspillable Terminator expected to have at most one use!", MI); 1561 } 1562 1563 // A fully-formed DBG_VALUE must have a location. Ignore partially formed 1564 // DBG_VALUEs: these are convenient to use in tests, but should never get 1565 // generated. 1566 if (MI->isDebugValue() && MI->getNumOperands() == 4) 1567 if (!MI->getDebugLoc()) 1568 report("Missing DebugLoc for debug instruction", MI); 1569 1570 // Meta instructions should never be the subject of debug value tracking, 1571 // they don't create a value in the output program at all. 1572 if (MI->isMetaInstruction() && MI->peekDebugInstrNum()) 1573 report("Metadata instruction should not have a value tracking number", MI); 1574 1575 // Check the MachineMemOperands for basic consistency. 1576 for (MachineMemOperand *Op : MI->memoperands()) { 1577 if (Op->isLoad() && !MI->mayLoad()) 1578 report("Missing mayLoad flag", MI); 1579 if (Op->isStore() && !MI->mayStore()) 1580 report("Missing mayStore flag", MI); 1581 } 1582 1583 // Debug values must not have a slot index. 1584 // Other instructions must have one, unless they are inside a bundle. 1585 if (LiveInts) { 1586 bool mapped = !LiveInts->isNotInMIMap(*MI); 1587 if (MI->isDebugInstr()) { 1588 if (mapped) 1589 report("Debug instruction has a slot index", MI); 1590 } else if (MI->isInsideBundle()) { 1591 if (mapped) 1592 report("Instruction inside bundle has a slot index", MI); 1593 } else { 1594 if (!mapped) 1595 report("Missing slot index", MI); 1596 } 1597 } 1598 1599 if (isPreISelGenericOpcode(MCID.getOpcode())) { 1600 verifyPreISelGenericInstruction(MI); 1601 return; 1602 } 1603 1604 StringRef ErrorInfo; 1605 if (!TII->verifyInstruction(*MI, ErrorInfo)) 1606 report(ErrorInfo.data(), MI); 1607 1608 // Verify properties of various specific instruction types 1609 switch (MI->getOpcode()) { 1610 case TargetOpcode::COPY: { 1611 if (foundErrors) 1612 break; 1613 const MachineOperand &DstOp = MI->getOperand(0); 1614 const MachineOperand &SrcOp = MI->getOperand(1); 1615 LLT DstTy = MRI->getType(DstOp.getReg()); 1616 LLT SrcTy = MRI->getType(SrcOp.getReg()); 1617 if (SrcTy.isValid() && DstTy.isValid()) { 1618 // If both types are valid, check that the types are the same. 1619 if (SrcTy != DstTy) { 1620 report("Copy Instruction is illegal with mismatching types", MI); 1621 errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n"; 1622 } 1623 } 1624 if (SrcTy.isValid() || DstTy.isValid()) { 1625 // If one of them have valid types, let's just check they have the same 1626 // size. 1627 unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI); 1628 unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI); 1629 assert(SrcSize && "Expecting size here"); 1630 assert(DstSize && "Expecting size here"); 1631 if (SrcSize != DstSize) 1632 if (!DstOp.getSubReg() && !SrcOp.getSubReg()) { 1633 report("Copy Instruction is illegal with mismatching sizes", MI); 1634 errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize 1635 << "\n"; 1636 } 1637 } 1638 break; 1639 } 1640 case TargetOpcode::STATEPOINT: { 1641 StatepointOpers SO(MI); 1642 if (!MI->getOperand(SO.getIDPos()).isImm() || 1643 !MI->getOperand(SO.getNBytesPos()).isImm() || 1644 !MI->getOperand(SO.getNCallArgsPos()).isImm()) { 1645 report("meta operands to STATEPOINT not constant!", MI); 1646 break; 1647 } 1648 1649 auto VerifyStackMapConstant = [&](unsigned Offset) { 1650 if (Offset >= MI->getNumOperands()) { 1651 report("stack map constant to STATEPOINT is out of range!", MI); 1652 return; 1653 } 1654 if (!MI->getOperand(Offset - 1).isImm() || 1655 MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp || 1656 !MI->getOperand(Offset).isImm()) 1657 report("stack map constant to STATEPOINT not well formed!", MI); 1658 }; 1659 VerifyStackMapConstant(SO.getCCIdx()); 1660 VerifyStackMapConstant(SO.getFlagsIdx()); 1661 VerifyStackMapConstant(SO.getNumDeoptArgsIdx()); 1662 VerifyStackMapConstant(SO.getNumGCPtrIdx()); 1663 VerifyStackMapConstant(SO.getNumAllocaIdx()); 1664 VerifyStackMapConstant(SO.getNumGcMapEntriesIdx()); 1665 1666 // Verify that all explicit statepoint defs are tied to gc operands as 1667 // they are expected to be a relocation of gc operands. 1668 unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx(); 1669 unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2; 1670 for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) { 1671 unsigned UseOpIdx; 1672 if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) { 1673 report("STATEPOINT defs expected to be tied", MI); 1674 break; 1675 } 1676 if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) { 1677 report("STATEPOINT def tied to non-gc operand", MI); 1678 break; 1679 } 1680 } 1681 1682 // TODO: verify we have properly encoded deopt arguments 1683 } break; 1684 } 1685 } 1686 1687 void 1688 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) { 1689 const MachineInstr *MI = MO->getParent(); 1690 const MCInstrDesc &MCID = MI->getDesc(); 1691 unsigned NumDefs = MCID.getNumDefs(); 1692 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT) 1693 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0; 1694 1695 // The first MCID.NumDefs operands must be explicit register defines 1696 if (MONum < NumDefs) { 1697 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 1698 if (!MO->isReg()) 1699 report("Explicit definition must be a register", MO, MONum); 1700 else if (!MO->isDef() && !MCOI.isOptionalDef()) 1701 report("Explicit definition marked as use", MO, MONum); 1702 else if (MO->isImplicit()) 1703 report("Explicit definition marked as implicit", MO, MONum); 1704 } else if (MONum < MCID.getNumOperands()) { 1705 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 1706 // Don't check if it's the last operand in a variadic instruction. See, 1707 // e.g., LDM_RET in the arm back end. Check non-variadic operands only. 1708 bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1; 1709 if (!IsOptional) { 1710 if (MO->isReg()) { 1711 if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs()) 1712 report("Explicit operand marked as def", MO, MONum); 1713 if (MO->isImplicit()) 1714 report("Explicit operand marked as implicit", MO, MONum); 1715 } 1716 1717 // Check that an instruction has register operands only as expected. 1718 if (MCOI.OperandType == MCOI::OPERAND_REGISTER && 1719 !MO->isReg() && !MO->isFI()) 1720 report("Expected a register operand.", MO, MONum); 1721 if ((MCOI.OperandType == MCOI::OPERAND_IMMEDIATE || 1722 MCOI.OperandType == MCOI::OPERAND_PCREL) && MO->isReg()) 1723 report("Expected a non-register operand.", MO, MONum); 1724 } 1725 1726 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO); 1727 if (TiedTo != -1) { 1728 if (!MO->isReg()) 1729 report("Tied use must be a register", MO, MONum); 1730 else if (!MO->isTied()) 1731 report("Operand should be tied", MO, MONum); 1732 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum)) 1733 report("Tied def doesn't match MCInstrDesc", MO, MONum); 1734 else if (Register::isPhysicalRegister(MO->getReg())) { 1735 const MachineOperand &MOTied = MI->getOperand(TiedTo); 1736 if (!MOTied.isReg()) 1737 report("Tied counterpart must be a register", &MOTied, TiedTo); 1738 else if (Register::isPhysicalRegister(MOTied.getReg()) && 1739 MO->getReg() != MOTied.getReg()) 1740 report("Tied physical registers must match.", &MOTied, TiedTo); 1741 } 1742 } else if (MO->isReg() && MO->isTied()) 1743 report("Explicit operand should not be tied", MO, MONum); 1744 } else { 1745 // ARM adds %reg0 operands to indicate predicates. We'll allow that. 1746 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg()) 1747 report("Extra explicit operand on non-variadic instruction", MO, MONum); 1748 } 1749 1750 switch (MO->getType()) { 1751 case MachineOperand::MO_Register: { 1752 const Register Reg = MO->getReg(); 1753 if (!Reg) 1754 return; 1755 if (MRI->tracksLiveness() && !MI->isDebugValue()) 1756 checkLiveness(MO, MONum); 1757 1758 // Verify the consistency of tied operands. 1759 if (MO->isTied()) { 1760 unsigned OtherIdx = MI->findTiedOperandIdx(MONum); 1761 const MachineOperand &OtherMO = MI->getOperand(OtherIdx); 1762 if (!OtherMO.isReg()) 1763 report("Must be tied to a register", MO, MONum); 1764 if (!OtherMO.isTied()) 1765 report("Missing tie flags on tied operand", MO, MONum); 1766 if (MI->findTiedOperandIdx(OtherIdx) != MONum) 1767 report("Inconsistent tie links", MO, MONum); 1768 if (MONum < MCID.getNumDefs()) { 1769 if (OtherIdx < MCID.getNumOperands()) { 1770 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO)) 1771 report("Explicit def tied to explicit use without tie constraint", 1772 MO, MONum); 1773 } else { 1774 if (!OtherMO.isImplicit()) 1775 report("Explicit def should be tied to implicit use", MO, MONum); 1776 } 1777 } 1778 } 1779 1780 // Verify two-address constraints after the twoaddressinstruction pass. 1781 // Both twoaddressinstruction pass and phi-node-elimination pass call 1782 // MRI->leaveSSA() to set MF as NoSSA, we should do the verification after 1783 // twoaddressinstruction pass not after phi-node-elimination pass. So we 1784 // shouldn't use the NoSSA as the condition, we should based on 1785 // TiedOpsRewritten property to verify two-address constraints, this 1786 // property will be set in twoaddressinstruction pass. 1787 unsigned DefIdx; 1788 if (MF->getProperties().hasProperty( 1789 MachineFunctionProperties::Property::TiedOpsRewritten) && 1790 MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) && 1791 Reg != MI->getOperand(DefIdx).getReg()) 1792 report("Two-address instruction operands must be identical", MO, MONum); 1793 1794 // Check register classes. 1795 unsigned SubIdx = MO->getSubReg(); 1796 1797 if (Register::isPhysicalRegister(Reg)) { 1798 if (SubIdx) { 1799 report("Illegal subregister index for physical register", MO, MONum); 1800 return; 1801 } 1802 if (MONum < MCID.getNumOperands()) { 1803 if (const TargetRegisterClass *DRC = 1804 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1805 if (!DRC->contains(Reg)) { 1806 report("Illegal physical register for instruction", MO, MONum); 1807 errs() << printReg(Reg, TRI) << " is not a " 1808 << TRI->getRegClassName(DRC) << " register.\n"; 1809 } 1810 } 1811 } 1812 if (MO->isRenamable()) { 1813 if (MRI->isReserved(Reg)) { 1814 report("isRenamable set on reserved register", MO, MONum); 1815 return; 1816 } 1817 } 1818 if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) { 1819 report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum); 1820 return; 1821 } 1822 } else { 1823 // Virtual register. 1824 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg); 1825 if (!RC) { 1826 // This is a generic virtual register. 1827 1828 // Do not allow undef uses for generic virtual registers. This ensures 1829 // getVRegDef can never fail and return null on a generic register. 1830 // 1831 // FIXME: This restriction should probably be broadened to all SSA 1832 // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still 1833 // run on the SSA function just before phi elimination. 1834 if (MO->isUndef()) 1835 report("Generic virtual register use cannot be undef", MO, MONum); 1836 1837 // If we're post-Select, we can't have gvregs anymore. 1838 if (isFunctionSelected) { 1839 report("Generic virtual register invalid in a Selected function", 1840 MO, MONum); 1841 return; 1842 } 1843 1844 // The gvreg must have a type and it must not have a SubIdx. 1845 LLT Ty = MRI->getType(Reg); 1846 if (!Ty.isValid()) { 1847 report("Generic virtual register must have a valid type", MO, 1848 MONum); 1849 return; 1850 } 1851 1852 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg); 1853 1854 // If we're post-RegBankSelect, the gvreg must have a bank. 1855 if (!RegBank && isFunctionRegBankSelected) { 1856 report("Generic virtual register must have a bank in a " 1857 "RegBankSelected function", 1858 MO, MONum); 1859 return; 1860 } 1861 1862 // Make sure the register fits into its register bank if any. 1863 if (RegBank && Ty.isValid() && 1864 RegBank->getSize() < Ty.getSizeInBits()) { 1865 report("Register bank is too small for virtual register", MO, 1866 MONum); 1867 errs() << "Register bank " << RegBank->getName() << " too small(" 1868 << RegBank->getSize() << ") to fit " << Ty.getSizeInBits() 1869 << "-bits\n"; 1870 return; 1871 } 1872 if (SubIdx) { 1873 report("Generic virtual register does not allow subregister index", MO, 1874 MONum); 1875 return; 1876 } 1877 1878 // If this is a target specific instruction and this operand 1879 // has register class constraint, the virtual register must 1880 // comply to it. 1881 if (!isPreISelGenericOpcode(MCID.getOpcode()) && 1882 MONum < MCID.getNumOperands() && 1883 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1884 report("Virtual register does not match instruction constraint", MO, 1885 MONum); 1886 errs() << "Expect register class " 1887 << TRI->getRegClassName( 1888 TII->getRegClass(MCID, MONum, TRI, *MF)) 1889 << " but got nothing\n"; 1890 return; 1891 } 1892 1893 break; 1894 } 1895 if (SubIdx) { 1896 const TargetRegisterClass *SRC = 1897 TRI->getSubClassWithSubReg(RC, SubIdx); 1898 if (!SRC) { 1899 report("Invalid subregister index for virtual register", MO, MONum); 1900 errs() << "Register class " << TRI->getRegClassName(RC) 1901 << " does not support subreg index " << SubIdx << "\n"; 1902 return; 1903 } 1904 if (RC != SRC) { 1905 report("Invalid register class for subregister index", MO, MONum); 1906 errs() << "Register class " << TRI->getRegClassName(RC) 1907 << " does not fully support subreg index " << SubIdx << "\n"; 1908 return; 1909 } 1910 } 1911 if (MONum < MCID.getNumOperands()) { 1912 if (const TargetRegisterClass *DRC = 1913 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1914 if (SubIdx) { 1915 const TargetRegisterClass *SuperRC = 1916 TRI->getLargestLegalSuperClass(RC, *MF); 1917 if (!SuperRC) { 1918 report("No largest legal super class exists.", MO, MONum); 1919 return; 1920 } 1921 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx); 1922 if (!DRC) { 1923 report("No matching super-reg register class.", MO, MONum); 1924 return; 1925 } 1926 } 1927 if (!RC->hasSuperClassEq(DRC)) { 1928 report("Illegal virtual register for instruction", MO, MONum); 1929 errs() << "Expected a " << TRI->getRegClassName(DRC) 1930 << " register, but got a " << TRI->getRegClassName(RC) 1931 << " register\n"; 1932 } 1933 } 1934 } 1935 } 1936 break; 1937 } 1938 1939 case MachineOperand::MO_RegisterMask: 1940 regMasks.push_back(MO->getRegMask()); 1941 break; 1942 1943 case MachineOperand::MO_MachineBasicBlock: 1944 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent())) 1945 report("PHI operand is not in the CFG", MO, MONum); 1946 break; 1947 1948 case MachineOperand::MO_FrameIndex: 1949 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) && 1950 LiveInts && !LiveInts->isNotInMIMap(*MI)) { 1951 int FI = MO->getIndex(); 1952 LiveInterval &LI = LiveStks->getInterval(FI); 1953 SlotIndex Idx = LiveInts->getInstructionIndex(*MI); 1954 1955 bool stores = MI->mayStore(); 1956 bool loads = MI->mayLoad(); 1957 // For a memory-to-memory move, we need to check if the frame 1958 // index is used for storing or loading, by inspecting the 1959 // memory operands. 1960 if (stores && loads) { 1961 for (auto *MMO : MI->memoperands()) { 1962 const PseudoSourceValue *PSV = MMO->getPseudoValue(); 1963 if (PSV == nullptr) continue; 1964 const FixedStackPseudoSourceValue *Value = 1965 dyn_cast<FixedStackPseudoSourceValue>(PSV); 1966 if (Value == nullptr) continue; 1967 if (Value->getFrameIndex() != FI) continue; 1968 1969 if (MMO->isStore()) 1970 loads = false; 1971 else 1972 stores = false; 1973 break; 1974 } 1975 if (loads == stores) 1976 report("Missing fixed stack memoperand.", MI); 1977 } 1978 if (loads && !LI.liveAt(Idx.getRegSlot(true))) { 1979 report("Instruction loads from dead spill slot", MO, MONum); 1980 errs() << "Live stack: " << LI << '\n'; 1981 } 1982 if (stores && !LI.liveAt(Idx.getRegSlot())) { 1983 report("Instruction stores to dead spill slot", MO, MONum); 1984 errs() << "Live stack: " << LI << '\n'; 1985 } 1986 } 1987 break; 1988 1989 default: 1990 break; 1991 } 1992 } 1993 1994 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO, 1995 unsigned MONum, SlotIndex UseIdx, 1996 const LiveRange &LR, 1997 Register VRegOrUnit, 1998 LaneBitmask LaneMask) { 1999 LiveQueryResult LRQ = LR.Query(UseIdx); 2000 // Check if we have a segment at the use, note however that we only need one 2001 // live subregister range, the others may be dead. 2002 if (!LRQ.valueIn() && LaneMask.none()) { 2003 report("No live segment at use", MO, MONum); 2004 report_context_liverange(LR); 2005 report_context_vreg_regunit(VRegOrUnit); 2006 report_context(UseIdx); 2007 } 2008 if (MO->isKill() && !LRQ.isKill()) { 2009 report("Live range continues after kill flag", MO, MONum); 2010 report_context_liverange(LR); 2011 report_context_vreg_regunit(VRegOrUnit); 2012 if (LaneMask.any()) 2013 report_context_lanemask(LaneMask); 2014 report_context(UseIdx); 2015 } 2016 } 2017 2018 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO, 2019 unsigned MONum, SlotIndex DefIdx, 2020 const LiveRange &LR, 2021 Register VRegOrUnit, 2022 bool SubRangeCheck, 2023 LaneBitmask LaneMask) { 2024 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) { 2025 assert(VNI && "NULL valno is not allowed"); 2026 if (VNI->def != DefIdx) { 2027 report("Inconsistent valno->def", MO, MONum); 2028 report_context_liverange(LR); 2029 report_context_vreg_regunit(VRegOrUnit); 2030 if (LaneMask.any()) 2031 report_context_lanemask(LaneMask); 2032 report_context(*VNI); 2033 report_context(DefIdx); 2034 } 2035 } else { 2036 report("No live segment at def", MO, MONum); 2037 report_context_liverange(LR); 2038 report_context_vreg_regunit(VRegOrUnit); 2039 if (LaneMask.any()) 2040 report_context_lanemask(LaneMask); 2041 report_context(DefIdx); 2042 } 2043 // Check that, if the dead def flag is present, LiveInts agree. 2044 if (MO->isDead()) { 2045 LiveQueryResult LRQ = LR.Query(DefIdx); 2046 if (!LRQ.isDeadDef()) { 2047 assert(Register::isVirtualRegister(VRegOrUnit) && 2048 "Expecting a virtual register."); 2049 // A dead subreg def only tells us that the specific subreg is dead. There 2050 // could be other non-dead defs of other subregs, or we could have other 2051 // parts of the register being live through the instruction. So unless we 2052 // are checking liveness for a subrange it is ok for the live range to 2053 // continue, given that we have a dead def of a subregister. 2054 if (SubRangeCheck || MO->getSubReg() == 0) { 2055 report("Live range continues after dead def flag", MO, MONum); 2056 report_context_liverange(LR); 2057 report_context_vreg_regunit(VRegOrUnit); 2058 if (LaneMask.any()) 2059 report_context_lanemask(LaneMask); 2060 } 2061 } 2062 } 2063 } 2064 2065 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) { 2066 const MachineInstr *MI = MO->getParent(); 2067 const Register Reg = MO->getReg(); 2068 2069 // Both use and def operands can read a register. 2070 if (MO->readsReg()) { 2071 if (MO->isKill()) 2072 addRegWithSubRegs(regsKilled, Reg); 2073 2074 // Check that LiveVars knows this kill. 2075 if (LiveVars && Register::isVirtualRegister(Reg) && MO->isKill()) { 2076 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 2077 if (!is_contained(VI.Kills, MI)) 2078 report("Kill missing from LiveVariables", MO, MONum); 2079 } 2080 2081 // Check LiveInts liveness and kill. 2082 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 2083 SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI); 2084 // Check the cached regunit intervals. 2085 if (Reg.isPhysical() && !isReserved(Reg)) { 2086 for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid(); 2087 ++Units) { 2088 if (MRI->isReservedRegUnit(*Units)) 2089 continue; 2090 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) 2091 checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units); 2092 } 2093 } 2094 2095 if (Register::isVirtualRegister(Reg)) { 2096 if (LiveInts->hasInterval(Reg)) { 2097 // This is a virtual register interval. 2098 const LiveInterval &LI = LiveInts->getInterval(Reg); 2099 checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg); 2100 2101 if (LI.hasSubRanges() && !MO->isDef()) { 2102 unsigned SubRegIdx = MO->getSubReg(); 2103 LaneBitmask MOMask = SubRegIdx != 0 2104 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 2105 : MRI->getMaxLaneMaskForVReg(Reg); 2106 LaneBitmask LiveInMask; 2107 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2108 if ((MOMask & SR.LaneMask).none()) 2109 continue; 2110 checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask); 2111 LiveQueryResult LRQ = SR.Query(UseIdx); 2112 if (LRQ.valueIn()) 2113 LiveInMask |= SR.LaneMask; 2114 } 2115 // At least parts of the register has to be live at the use. 2116 if ((LiveInMask & MOMask).none()) { 2117 report("No live subrange at use", MO, MONum); 2118 report_context(LI); 2119 report_context(UseIdx); 2120 } 2121 } 2122 } else { 2123 report("Virtual register has no live interval", MO, MONum); 2124 } 2125 } 2126 } 2127 2128 // Use of a dead register. 2129 if (!regsLive.count(Reg)) { 2130 if (Register::isPhysicalRegister(Reg)) { 2131 // Reserved registers may be used even when 'dead'. 2132 bool Bad = !isReserved(Reg); 2133 // We are fine if just any subregister has a defined value. 2134 if (Bad) { 2135 2136 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) { 2137 if (regsLive.count(SubReg)) { 2138 Bad = false; 2139 break; 2140 } 2141 } 2142 } 2143 // If there is an additional implicit-use of a super register we stop 2144 // here. By definition we are fine if the super register is not 2145 // (completely) dead, if the complete super register is dead we will 2146 // get a report for its operand. 2147 if (Bad) { 2148 for (const MachineOperand &MOP : MI->uses()) { 2149 if (!MOP.isReg() || !MOP.isImplicit()) 2150 continue; 2151 2152 if (!Register::isPhysicalRegister(MOP.getReg())) 2153 continue; 2154 2155 for (const MCPhysReg &SubReg : TRI->subregs(MOP.getReg())) { 2156 if (SubReg == Reg) { 2157 Bad = false; 2158 break; 2159 } 2160 } 2161 } 2162 } 2163 if (Bad) 2164 report("Using an undefined physical register", MO, MONum); 2165 } else if (MRI->def_empty(Reg)) { 2166 report("Reading virtual register without a def", MO, MONum); 2167 } else { 2168 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 2169 // We don't know which virtual registers are live in, so only complain 2170 // if vreg was killed in this MBB. Otherwise keep track of vregs that 2171 // must be live in. PHI instructions are handled separately. 2172 if (MInfo.regsKilled.count(Reg)) 2173 report("Using a killed virtual register", MO, MONum); 2174 else if (!MI->isPHI()) 2175 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI)); 2176 } 2177 } 2178 } 2179 2180 if (MO->isDef()) { 2181 // Register defined. 2182 // TODO: verify that earlyclobber ops are not used. 2183 if (MO->isDead()) 2184 addRegWithSubRegs(regsDead, Reg); 2185 else 2186 addRegWithSubRegs(regsDefined, Reg); 2187 2188 // Verify SSA form. 2189 if (MRI->isSSA() && Register::isVirtualRegister(Reg) && 2190 std::next(MRI->def_begin(Reg)) != MRI->def_end()) 2191 report("Multiple virtual register defs in SSA form", MO, MONum); 2192 2193 // Check LiveInts for a live segment, but only for virtual registers. 2194 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 2195 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI); 2196 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber()); 2197 2198 if (Register::isVirtualRegister(Reg)) { 2199 if (LiveInts->hasInterval(Reg)) { 2200 const LiveInterval &LI = LiveInts->getInterval(Reg); 2201 checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg); 2202 2203 if (LI.hasSubRanges()) { 2204 unsigned SubRegIdx = MO->getSubReg(); 2205 LaneBitmask MOMask = SubRegIdx != 0 2206 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 2207 : MRI->getMaxLaneMaskForVReg(Reg); 2208 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2209 if ((SR.LaneMask & MOMask).none()) 2210 continue; 2211 checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask); 2212 } 2213 } 2214 } else { 2215 report("Virtual register has no Live interval", MO, MONum); 2216 } 2217 } 2218 } 2219 } 2220 } 2221 2222 // This function gets called after visiting all instructions in a bundle. The 2223 // argument points to the bundle header. 2224 // Normal stand-alone instructions are also considered 'bundles', and this 2225 // function is called for all of them. 2226 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) { 2227 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 2228 set_union(MInfo.regsKilled, regsKilled); 2229 set_subtract(regsLive, regsKilled); regsKilled.clear(); 2230 // Kill any masked registers. 2231 while (!regMasks.empty()) { 2232 const uint32_t *Mask = regMasks.pop_back_val(); 2233 for (Register Reg : regsLive) 2234 if (Reg.isPhysical() && 2235 MachineOperand::clobbersPhysReg(Mask, Reg.asMCReg())) 2236 regsDead.push_back(Reg); 2237 } 2238 set_subtract(regsLive, regsDead); regsDead.clear(); 2239 set_union(regsLive, regsDefined); regsDefined.clear(); 2240 } 2241 2242 void 2243 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) { 2244 MBBInfoMap[MBB].regsLiveOut = regsLive; 2245 regsLive.clear(); 2246 2247 if (Indexes) { 2248 SlotIndex stop = Indexes->getMBBEndIdx(MBB); 2249 if (!(stop > lastIndex)) { 2250 report("Block ends before last instruction index", MBB); 2251 errs() << "Block ends at " << stop 2252 << " last instruction was at " << lastIndex << '\n'; 2253 } 2254 lastIndex = stop; 2255 } 2256 } 2257 2258 namespace { 2259 // This implements a set of registers that serves as a filter: can filter other 2260 // sets by passing through elements not in the filter and blocking those that 2261 // are. Any filter implicitly includes the full set of physical registers upon 2262 // creation, thus filtering them all out. The filter itself as a set only grows, 2263 // and needs to be as efficient as possible. 2264 struct VRegFilter { 2265 // Add elements to the filter itself. \pre Input set \p FromRegSet must have 2266 // no duplicates. Both virtual and physical registers are fine. 2267 template <typename RegSetT> void add(const RegSetT &FromRegSet) { 2268 SmallVector<Register, 0> VRegsBuffer; 2269 filterAndAdd(FromRegSet, VRegsBuffer); 2270 } 2271 // Filter \p FromRegSet through the filter and append passed elements into \p 2272 // ToVRegs. All elements appended are then added to the filter itself. 2273 // \returns true if anything changed. 2274 template <typename RegSetT> 2275 bool filterAndAdd(const RegSetT &FromRegSet, 2276 SmallVectorImpl<Register> &ToVRegs) { 2277 unsigned SparseUniverse = Sparse.size(); 2278 unsigned NewSparseUniverse = SparseUniverse; 2279 unsigned NewDenseSize = Dense.size(); 2280 size_t Begin = ToVRegs.size(); 2281 for (Register Reg : FromRegSet) { 2282 if (!Reg.isVirtual()) 2283 continue; 2284 unsigned Index = Register::virtReg2Index(Reg); 2285 if (Index < SparseUniverseMax) { 2286 if (Index < SparseUniverse && Sparse.test(Index)) 2287 continue; 2288 NewSparseUniverse = std::max(NewSparseUniverse, Index + 1); 2289 } else { 2290 if (Dense.count(Reg)) 2291 continue; 2292 ++NewDenseSize; 2293 } 2294 ToVRegs.push_back(Reg); 2295 } 2296 size_t End = ToVRegs.size(); 2297 if (Begin == End) 2298 return false; 2299 // Reserving space in sets once performs better than doing so continuously 2300 // and pays easily for double look-ups (even in Dense with SparseUniverseMax 2301 // tuned all the way down) and double iteration (the second one is over a 2302 // SmallVector, which is a lot cheaper compared to DenseSet or BitVector). 2303 Sparse.resize(NewSparseUniverse); 2304 Dense.reserve(NewDenseSize); 2305 for (unsigned I = Begin; I < End; ++I) { 2306 Register Reg = ToVRegs[I]; 2307 unsigned Index = Register::virtReg2Index(Reg); 2308 if (Index < SparseUniverseMax) 2309 Sparse.set(Index); 2310 else 2311 Dense.insert(Reg); 2312 } 2313 return true; 2314 } 2315 2316 private: 2317 static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8; 2318 // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound 2319 // are tracked by Dense. The only purpose of the threashold and the Dense set 2320 // is to have a reasonably growing memory usage in pathological cases (large 2321 // number of very sparse VRegFilter instances live at the same time). In 2322 // practice even in the worst-by-execution time cases having all elements 2323 // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more 2324 // space efficient than if tracked by Dense. The threashold is set to keep the 2325 // worst-case memory usage within 2x of figures determined empirically for 2326 // "all Dense" scenario in such worst-by-execution-time cases. 2327 BitVector Sparse; 2328 DenseSet<unsigned> Dense; 2329 }; 2330 2331 // Implements both a transfer function and a (binary, in-place) join operator 2332 // for a dataflow over register sets with set union join and filtering transfer 2333 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time. 2334 // Maintains out_b as its state, allowing for O(n) iteration over it at any 2335 // time, where n is the size of the set (as opposed to O(U) where U is the 2336 // universe). filter_b implicitly contains all physical registers at all times. 2337 class FilteringVRegSet { 2338 VRegFilter Filter; 2339 SmallVector<Register, 0> VRegs; 2340 2341 public: 2342 // Set-up the filter_b. \pre Input register set \p RS must have no duplicates. 2343 // Both virtual and physical registers are fine. 2344 template <typename RegSetT> void addToFilter(const RegSetT &RS) { 2345 Filter.add(RS); 2346 } 2347 // Passes \p RS through the filter_b (transfer function) and adds what's left 2348 // to itself (out_b). 2349 template <typename RegSetT> bool add(const RegSetT &RS) { 2350 // Double-duty the Filter: to maintain VRegs a set (and the join operation 2351 // a set union) just add everything being added here to the Filter as well. 2352 return Filter.filterAndAdd(RS, VRegs); 2353 } 2354 using const_iterator = decltype(VRegs)::const_iterator; 2355 const_iterator begin() const { return VRegs.begin(); } 2356 const_iterator end() const { return VRegs.end(); } 2357 size_t size() const { return VRegs.size(); } 2358 }; 2359 } // namespace 2360 2361 // Calculate the largest possible vregsPassed sets. These are the registers that 2362 // can pass through an MBB live, but may not be live every time. It is assumed 2363 // that all vregsPassed sets are empty before the call. 2364 void MachineVerifier::calcRegsPassed() { 2365 if (MF->empty()) 2366 // ReversePostOrderTraversal doesn't handle empty functions. 2367 return; 2368 2369 for (const MachineBasicBlock *MB : 2370 ReversePostOrderTraversal<const MachineFunction *>(MF)) { 2371 FilteringVRegSet VRegs; 2372 BBInfo &Info = MBBInfoMap[MB]; 2373 assert(Info.reachable); 2374 2375 VRegs.addToFilter(Info.regsKilled); 2376 VRegs.addToFilter(Info.regsLiveOut); 2377 for (const MachineBasicBlock *Pred : MB->predecessors()) { 2378 const BBInfo &PredInfo = MBBInfoMap[Pred]; 2379 if (!PredInfo.reachable) 2380 continue; 2381 2382 VRegs.add(PredInfo.regsLiveOut); 2383 VRegs.add(PredInfo.vregsPassed); 2384 } 2385 Info.vregsPassed.reserve(VRegs.size()); 2386 Info.vregsPassed.insert(VRegs.begin(), VRegs.end()); 2387 } 2388 } 2389 2390 // Calculate the set of virtual registers that must be passed through each basic 2391 // block in order to satisfy the requirements of successor blocks. This is very 2392 // similar to calcRegsPassed, only backwards. 2393 void MachineVerifier::calcRegsRequired() { 2394 // First push live-in regs to predecessors' vregsRequired. 2395 SmallPtrSet<const MachineBasicBlock*, 8> todo; 2396 for (const auto &MBB : *MF) { 2397 BBInfo &MInfo = MBBInfoMap[&MBB]; 2398 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 2399 BBInfo &PInfo = MBBInfoMap[Pred]; 2400 if (PInfo.addRequired(MInfo.vregsLiveIn)) 2401 todo.insert(Pred); 2402 } 2403 2404 // Handle the PHI node. 2405 for (const MachineInstr &MI : MBB.phis()) { 2406 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 2407 // Skip those Operands which are undef regs or not regs. 2408 if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg()) 2409 continue; 2410 2411 // Get register and predecessor for one PHI edge. 2412 Register Reg = MI.getOperand(i).getReg(); 2413 const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB(); 2414 2415 BBInfo &PInfo = MBBInfoMap[Pred]; 2416 if (PInfo.addRequired(Reg)) 2417 todo.insert(Pred); 2418 } 2419 } 2420 } 2421 2422 // Iteratively push vregsRequired to predecessors. This will converge to the 2423 // same final state regardless of DenseSet iteration order. 2424 while (!todo.empty()) { 2425 const MachineBasicBlock *MBB = *todo.begin(); 2426 todo.erase(MBB); 2427 BBInfo &MInfo = MBBInfoMap[MBB]; 2428 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 2429 if (Pred == MBB) 2430 continue; 2431 BBInfo &SInfo = MBBInfoMap[Pred]; 2432 if (SInfo.addRequired(MInfo.vregsRequired)) 2433 todo.insert(Pred); 2434 } 2435 } 2436 } 2437 2438 // Check PHI instructions at the beginning of MBB. It is assumed that 2439 // calcRegsPassed has been run so BBInfo::isLiveOut is valid. 2440 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) { 2441 BBInfo &MInfo = MBBInfoMap[&MBB]; 2442 2443 SmallPtrSet<const MachineBasicBlock*, 8> seen; 2444 for (const MachineInstr &Phi : MBB) { 2445 if (!Phi.isPHI()) 2446 break; 2447 seen.clear(); 2448 2449 const MachineOperand &MODef = Phi.getOperand(0); 2450 if (!MODef.isReg() || !MODef.isDef()) { 2451 report("Expected first PHI operand to be a register def", &MODef, 0); 2452 continue; 2453 } 2454 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() || 2455 MODef.isEarlyClobber() || MODef.isDebug()) 2456 report("Unexpected flag on PHI operand", &MODef, 0); 2457 Register DefReg = MODef.getReg(); 2458 if (!Register::isVirtualRegister(DefReg)) 2459 report("Expected first PHI operand to be a virtual register", &MODef, 0); 2460 2461 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) { 2462 const MachineOperand &MO0 = Phi.getOperand(I); 2463 if (!MO0.isReg()) { 2464 report("Expected PHI operand to be a register", &MO0, I); 2465 continue; 2466 } 2467 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() || 2468 MO0.isDebug() || MO0.isTied()) 2469 report("Unexpected flag on PHI operand", &MO0, I); 2470 2471 const MachineOperand &MO1 = Phi.getOperand(I + 1); 2472 if (!MO1.isMBB()) { 2473 report("Expected PHI operand to be a basic block", &MO1, I + 1); 2474 continue; 2475 } 2476 2477 const MachineBasicBlock &Pre = *MO1.getMBB(); 2478 if (!Pre.isSuccessor(&MBB)) { 2479 report("PHI input is not a predecessor block", &MO1, I + 1); 2480 continue; 2481 } 2482 2483 if (MInfo.reachable) { 2484 seen.insert(&Pre); 2485 BBInfo &PrInfo = MBBInfoMap[&Pre]; 2486 if (!MO0.isUndef() && PrInfo.reachable && 2487 !PrInfo.isLiveOut(MO0.getReg())) 2488 report("PHI operand is not live-out from predecessor", &MO0, I); 2489 } 2490 } 2491 2492 // Did we see all predecessors? 2493 if (MInfo.reachable) { 2494 for (MachineBasicBlock *Pred : MBB.predecessors()) { 2495 if (!seen.count(Pred)) { 2496 report("Missing PHI operand", &Phi); 2497 errs() << printMBBReference(*Pred) 2498 << " is a predecessor according to the CFG.\n"; 2499 } 2500 } 2501 } 2502 } 2503 } 2504 2505 void MachineVerifier::visitMachineFunctionAfter() { 2506 calcRegsPassed(); 2507 2508 for (const MachineBasicBlock &MBB : *MF) 2509 checkPHIOps(MBB); 2510 2511 // Now check liveness info if available 2512 calcRegsRequired(); 2513 2514 // Check for killed virtual registers that should be live out. 2515 for (const auto &MBB : *MF) { 2516 BBInfo &MInfo = MBBInfoMap[&MBB]; 2517 for (Register VReg : MInfo.vregsRequired) 2518 if (MInfo.regsKilled.count(VReg)) { 2519 report("Virtual register killed in block, but needed live out.", &MBB); 2520 errs() << "Virtual register " << printReg(VReg) 2521 << " is used after the block.\n"; 2522 } 2523 } 2524 2525 if (!MF->empty()) { 2526 BBInfo &MInfo = MBBInfoMap[&MF->front()]; 2527 for (Register VReg : MInfo.vregsRequired) { 2528 report("Virtual register defs don't dominate all uses.", MF); 2529 report_context_vreg(VReg); 2530 } 2531 } 2532 2533 if (LiveVars) 2534 verifyLiveVariables(); 2535 if (LiveInts) 2536 verifyLiveIntervals(); 2537 2538 // Check live-in list of each MBB. If a register is live into MBB, check 2539 // that the register is in regsLiveOut of each predecessor block. Since 2540 // this must come from a definition in the predecesssor or its live-in 2541 // list, this will catch a live-through case where the predecessor does not 2542 // have the register in its live-in list. This currently only checks 2543 // registers that have no aliases, are not allocatable and are not 2544 // reserved, which could mean a condition code register for instance. 2545 if (MRI->tracksLiveness()) 2546 for (const auto &MBB : *MF) 2547 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) { 2548 MCPhysReg LiveInReg = P.PhysReg; 2549 bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid(); 2550 if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg)) 2551 continue; 2552 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 2553 BBInfo &PInfo = MBBInfoMap[Pred]; 2554 if (!PInfo.regsLiveOut.count(LiveInReg)) { 2555 report("Live in register not found to be live out from predecessor.", 2556 &MBB); 2557 errs() << TRI->getName(LiveInReg) 2558 << " not found to be live out from " 2559 << printMBBReference(*Pred) << "\n"; 2560 } 2561 } 2562 } 2563 2564 for (auto CSInfo : MF->getCallSitesInfo()) 2565 if (!CSInfo.first->isCall()) 2566 report("Call site info referencing instruction that is not call", MF); 2567 2568 // If there's debug-info, check that we don't have any duplicate value 2569 // tracking numbers. 2570 if (MF->getFunction().getSubprogram()) { 2571 DenseSet<unsigned> SeenNumbers; 2572 for (auto &MBB : *MF) { 2573 for (auto &MI : MBB) { 2574 if (auto Num = MI.peekDebugInstrNum()) { 2575 auto Result = SeenNumbers.insert((unsigned)Num); 2576 if (!Result.second) 2577 report("Instruction has a duplicated value tracking number", &MI); 2578 } 2579 } 2580 } 2581 } 2582 } 2583 2584 void MachineVerifier::verifyLiveVariables() { 2585 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars"); 2586 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) { 2587 Register Reg = Register::index2VirtReg(I); 2588 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 2589 for (const auto &MBB : *MF) { 2590 BBInfo &MInfo = MBBInfoMap[&MBB]; 2591 2592 // Our vregsRequired should be identical to LiveVariables' AliveBlocks 2593 if (MInfo.vregsRequired.count(Reg)) { 2594 if (!VI.AliveBlocks.test(MBB.getNumber())) { 2595 report("LiveVariables: Block missing from AliveBlocks", &MBB); 2596 errs() << "Virtual register " << printReg(Reg) 2597 << " must be live through the block.\n"; 2598 } 2599 } else { 2600 if (VI.AliveBlocks.test(MBB.getNumber())) { 2601 report("LiveVariables: Block should not be in AliveBlocks", &MBB); 2602 errs() << "Virtual register " << printReg(Reg) 2603 << " is not needed live through the block.\n"; 2604 } 2605 } 2606 } 2607 } 2608 } 2609 2610 void MachineVerifier::verifyLiveIntervals() { 2611 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts"); 2612 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) { 2613 Register Reg = Register::index2VirtReg(I); 2614 2615 // Spilling and splitting may leave unused registers around. Skip them. 2616 if (MRI->reg_nodbg_empty(Reg)) 2617 continue; 2618 2619 if (!LiveInts->hasInterval(Reg)) { 2620 report("Missing live interval for virtual register", MF); 2621 errs() << printReg(Reg, TRI) << " still has defs or uses\n"; 2622 continue; 2623 } 2624 2625 const LiveInterval &LI = LiveInts->getInterval(Reg); 2626 assert(Reg == LI.reg() && "Invalid reg to interval mapping"); 2627 verifyLiveInterval(LI); 2628 } 2629 2630 // Verify all the cached regunit intervals. 2631 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 2632 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i)) 2633 verifyLiveRange(*LR, i); 2634 } 2635 2636 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR, 2637 const VNInfo *VNI, Register Reg, 2638 LaneBitmask LaneMask) { 2639 if (VNI->isUnused()) 2640 return; 2641 2642 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def); 2643 2644 if (!DefVNI) { 2645 report("Value not live at VNInfo def and not marked unused", MF); 2646 report_context(LR, Reg, LaneMask); 2647 report_context(*VNI); 2648 return; 2649 } 2650 2651 if (DefVNI != VNI) { 2652 report("Live segment at def has different VNInfo", MF); 2653 report_context(LR, Reg, LaneMask); 2654 report_context(*VNI); 2655 return; 2656 } 2657 2658 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def); 2659 if (!MBB) { 2660 report("Invalid VNInfo definition index", MF); 2661 report_context(LR, Reg, LaneMask); 2662 report_context(*VNI); 2663 return; 2664 } 2665 2666 if (VNI->isPHIDef()) { 2667 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) { 2668 report("PHIDef VNInfo is not defined at MBB start", MBB); 2669 report_context(LR, Reg, LaneMask); 2670 report_context(*VNI); 2671 } 2672 return; 2673 } 2674 2675 // Non-PHI def. 2676 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def); 2677 if (!MI) { 2678 report("No instruction at VNInfo def index", MBB); 2679 report_context(LR, Reg, LaneMask); 2680 report_context(*VNI); 2681 return; 2682 } 2683 2684 if (Reg != 0) { 2685 bool hasDef = false; 2686 bool isEarlyClobber = false; 2687 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 2688 if (!MOI->isReg() || !MOI->isDef()) 2689 continue; 2690 if (Register::isVirtualRegister(Reg)) { 2691 if (MOI->getReg() != Reg) 2692 continue; 2693 } else { 2694 if (!Register::isPhysicalRegister(MOI->getReg()) || 2695 !TRI->hasRegUnit(MOI->getReg(), Reg)) 2696 continue; 2697 } 2698 if (LaneMask.any() && 2699 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none()) 2700 continue; 2701 hasDef = true; 2702 if (MOI->isEarlyClobber()) 2703 isEarlyClobber = true; 2704 } 2705 2706 if (!hasDef) { 2707 report("Defining instruction does not modify register", MI); 2708 report_context(LR, Reg, LaneMask); 2709 report_context(*VNI); 2710 } 2711 2712 // Early clobber defs begin at USE slots, but other defs must begin at 2713 // DEF slots. 2714 if (isEarlyClobber) { 2715 if (!VNI->def.isEarlyClobber()) { 2716 report("Early clobber def must be at an early-clobber slot", MBB); 2717 report_context(LR, Reg, LaneMask); 2718 report_context(*VNI); 2719 } 2720 } else if (!VNI->def.isRegister()) { 2721 report("Non-PHI, non-early clobber def must be at a register slot", MBB); 2722 report_context(LR, Reg, LaneMask); 2723 report_context(*VNI); 2724 } 2725 } 2726 } 2727 2728 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR, 2729 const LiveRange::const_iterator I, 2730 Register Reg, 2731 LaneBitmask LaneMask) { 2732 const LiveRange::Segment &S = *I; 2733 const VNInfo *VNI = S.valno; 2734 assert(VNI && "Live segment has no valno"); 2735 2736 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) { 2737 report("Foreign valno in live segment", MF); 2738 report_context(LR, Reg, LaneMask); 2739 report_context(S); 2740 report_context(*VNI); 2741 } 2742 2743 if (VNI->isUnused()) { 2744 report("Live segment valno is marked unused", MF); 2745 report_context(LR, Reg, LaneMask); 2746 report_context(S); 2747 } 2748 2749 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start); 2750 if (!MBB) { 2751 report("Bad start of live segment, no basic block", MF); 2752 report_context(LR, Reg, LaneMask); 2753 report_context(S); 2754 return; 2755 } 2756 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB); 2757 if (S.start != MBBStartIdx && S.start != VNI->def) { 2758 report("Live segment must begin at MBB entry or valno def", MBB); 2759 report_context(LR, Reg, LaneMask); 2760 report_context(S); 2761 } 2762 2763 const MachineBasicBlock *EndMBB = 2764 LiveInts->getMBBFromIndex(S.end.getPrevSlot()); 2765 if (!EndMBB) { 2766 report("Bad end of live segment, no basic block", MF); 2767 report_context(LR, Reg, LaneMask); 2768 report_context(S); 2769 return; 2770 } 2771 2772 // No more checks for live-out segments. 2773 if (S.end == LiveInts->getMBBEndIdx(EndMBB)) 2774 return; 2775 2776 // RegUnit intervals are allowed dead phis. 2777 if (!Register::isVirtualRegister(Reg) && VNI->isPHIDef() && 2778 S.start == VNI->def && S.end == VNI->def.getDeadSlot()) 2779 return; 2780 2781 // The live segment is ending inside EndMBB 2782 const MachineInstr *MI = 2783 LiveInts->getInstructionFromIndex(S.end.getPrevSlot()); 2784 if (!MI) { 2785 report("Live segment doesn't end at a valid instruction", EndMBB); 2786 report_context(LR, Reg, LaneMask); 2787 report_context(S); 2788 return; 2789 } 2790 2791 // The block slot must refer to a basic block boundary. 2792 if (S.end.isBlock()) { 2793 report("Live segment ends at B slot of an instruction", EndMBB); 2794 report_context(LR, Reg, LaneMask); 2795 report_context(S); 2796 } 2797 2798 if (S.end.isDead()) { 2799 // Segment ends on the dead slot. 2800 // That means there must be a dead def. 2801 if (!SlotIndex::isSameInstr(S.start, S.end)) { 2802 report("Live segment ending at dead slot spans instructions", EndMBB); 2803 report_context(LR, Reg, LaneMask); 2804 report_context(S); 2805 } 2806 } 2807 2808 // A live segment can only end at an early-clobber slot if it is being 2809 // redefined by an early-clobber def. 2810 if (S.end.isEarlyClobber()) { 2811 if (I+1 == LR.end() || (I+1)->start != S.end) { 2812 report("Live segment ending at early clobber slot must be " 2813 "redefined by an EC def in the same instruction", EndMBB); 2814 report_context(LR, Reg, LaneMask); 2815 report_context(S); 2816 } 2817 } 2818 2819 // The following checks only apply to virtual registers. Physreg liveness 2820 // is too weird to check. 2821 if (Register::isVirtualRegister(Reg)) { 2822 // A live segment can end with either a redefinition, a kill flag on a 2823 // use, or a dead flag on a def. 2824 bool hasRead = false; 2825 bool hasSubRegDef = false; 2826 bool hasDeadDef = false; 2827 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 2828 if (!MOI->isReg() || MOI->getReg() != Reg) 2829 continue; 2830 unsigned Sub = MOI->getSubReg(); 2831 LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) 2832 : LaneBitmask::getAll(); 2833 if (MOI->isDef()) { 2834 if (Sub != 0) { 2835 hasSubRegDef = true; 2836 // An operand %0:sub0 reads %0:sub1..n. Invert the lane 2837 // mask for subregister defs. Read-undef defs will be handled by 2838 // readsReg below. 2839 SLM = ~SLM; 2840 } 2841 if (MOI->isDead()) 2842 hasDeadDef = true; 2843 } 2844 if (LaneMask.any() && (LaneMask & SLM).none()) 2845 continue; 2846 if (MOI->readsReg()) 2847 hasRead = true; 2848 } 2849 if (S.end.isDead()) { 2850 // Make sure that the corresponding machine operand for a "dead" live 2851 // range has the dead flag. We cannot perform this check for subregister 2852 // liveranges as partially dead values are allowed. 2853 if (LaneMask.none() && !hasDeadDef) { 2854 report("Instruction ending live segment on dead slot has no dead flag", 2855 MI); 2856 report_context(LR, Reg, LaneMask); 2857 report_context(S); 2858 } 2859 } else { 2860 if (!hasRead) { 2861 // When tracking subregister liveness, the main range must start new 2862 // values on partial register writes, even if there is no read. 2863 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() || 2864 !hasSubRegDef) { 2865 report("Instruction ending live segment doesn't read the register", 2866 MI); 2867 report_context(LR, Reg, LaneMask); 2868 report_context(S); 2869 } 2870 } 2871 } 2872 } 2873 2874 // Now check all the basic blocks in this live segment. 2875 MachineFunction::const_iterator MFI = MBB->getIterator(); 2876 // Is this live segment the beginning of a non-PHIDef VN? 2877 if (S.start == VNI->def && !VNI->isPHIDef()) { 2878 // Not live-in to any blocks. 2879 if (MBB == EndMBB) 2880 return; 2881 // Skip this block. 2882 ++MFI; 2883 } 2884 2885 SmallVector<SlotIndex, 4> Undefs; 2886 if (LaneMask.any()) { 2887 LiveInterval &OwnerLI = LiveInts->getInterval(Reg); 2888 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes); 2889 } 2890 2891 while (true) { 2892 assert(LiveInts->isLiveInToMBB(LR, &*MFI)); 2893 // We don't know how to track physregs into a landing pad. 2894 if (!Register::isVirtualRegister(Reg) && MFI->isEHPad()) { 2895 if (&*MFI == EndMBB) 2896 break; 2897 ++MFI; 2898 continue; 2899 } 2900 2901 // Is VNI a PHI-def in the current block? 2902 bool IsPHI = VNI->isPHIDef() && 2903 VNI->def == LiveInts->getMBBStartIdx(&*MFI); 2904 2905 // Check that VNI is live-out of all predecessors. 2906 for (const MachineBasicBlock *Pred : MFI->predecessors()) { 2907 SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred); 2908 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd); 2909 2910 // All predecessors must have a live-out value. However for a phi 2911 // instruction with subregister intervals 2912 // only one of the subregisters (not necessarily the current one) needs to 2913 // be defined. 2914 if (!PVNI && (LaneMask.none() || !IsPHI)) { 2915 if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes)) 2916 continue; 2917 report("Register not marked live out of predecessor", Pred); 2918 report_context(LR, Reg, LaneMask); 2919 report_context(*VNI); 2920 errs() << " live into " << printMBBReference(*MFI) << '@' 2921 << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " 2922 << PEnd << '\n'; 2923 continue; 2924 } 2925 2926 // Only PHI-defs can take different predecessor values. 2927 if (!IsPHI && PVNI != VNI) { 2928 report("Different value live out of predecessor", Pred); 2929 report_context(LR, Reg, LaneMask); 2930 errs() << "Valno #" << PVNI->id << " live out of " 2931 << printMBBReference(*Pred) << '@' << PEnd << "\nValno #" 2932 << VNI->id << " live into " << printMBBReference(*MFI) << '@' 2933 << LiveInts->getMBBStartIdx(&*MFI) << '\n'; 2934 } 2935 } 2936 if (&*MFI == EndMBB) 2937 break; 2938 ++MFI; 2939 } 2940 } 2941 2942 void MachineVerifier::verifyLiveRange(const LiveRange &LR, Register Reg, 2943 LaneBitmask LaneMask) { 2944 for (const VNInfo *VNI : LR.valnos) 2945 verifyLiveRangeValue(LR, VNI, Reg, LaneMask); 2946 2947 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I) 2948 verifyLiveRangeSegment(LR, I, Reg, LaneMask); 2949 } 2950 2951 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) { 2952 Register Reg = LI.reg(); 2953 assert(Register::isVirtualRegister(Reg)); 2954 verifyLiveRange(LI, Reg); 2955 2956 LaneBitmask Mask; 2957 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 2958 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2959 if ((Mask & SR.LaneMask).any()) { 2960 report("Lane masks of sub ranges overlap in live interval", MF); 2961 report_context(LI); 2962 } 2963 if ((SR.LaneMask & ~MaxMask).any()) { 2964 report("Subrange lanemask is invalid", MF); 2965 report_context(LI); 2966 } 2967 if (SR.empty()) { 2968 report("Subrange must not be empty", MF); 2969 report_context(SR, LI.reg(), SR.LaneMask); 2970 } 2971 Mask |= SR.LaneMask; 2972 verifyLiveRange(SR, LI.reg(), SR.LaneMask); 2973 if (!LI.covers(SR)) { 2974 report("A Subrange is not covered by the main range", MF); 2975 report_context(LI); 2976 } 2977 } 2978 2979 // Check the LI only has one connected component. 2980 ConnectedVNInfoEqClasses ConEQ(*LiveInts); 2981 unsigned NumComp = ConEQ.Classify(LI); 2982 if (NumComp > 1) { 2983 report("Multiple connected components in live interval", MF); 2984 report_context(LI); 2985 for (unsigned comp = 0; comp != NumComp; ++comp) { 2986 errs() << comp << ": valnos"; 2987 for (const VNInfo *I : LI.valnos) 2988 if (comp == ConEQ.getEqClass(I)) 2989 errs() << ' ' << I->id; 2990 errs() << '\n'; 2991 } 2992 } 2993 } 2994 2995 namespace { 2996 2997 // FrameSetup and FrameDestroy can have zero adjustment, so using a single 2998 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the 2999 // value is zero. 3000 // We use a bool plus an integer to capture the stack state. 3001 struct StackStateOfBB { 3002 StackStateOfBB() = default; 3003 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) : 3004 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup), 3005 ExitIsSetup(ExitSetup) {} 3006 3007 // Can be negative, which means we are setting up a frame. 3008 int EntryValue = 0; 3009 int ExitValue = 0; 3010 bool EntryIsSetup = false; 3011 bool ExitIsSetup = false; 3012 }; 3013 3014 } // end anonymous namespace 3015 3016 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed 3017 /// by a FrameDestroy <n>, stack adjustments are identical on all 3018 /// CFG edges to a merge point, and frame is destroyed at end of a return block. 3019 void MachineVerifier::verifyStackFrame() { 3020 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 3021 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 3022 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u) 3023 return; 3024 3025 SmallVector<StackStateOfBB, 8> SPState; 3026 SPState.resize(MF->getNumBlockIDs()); 3027 df_iterator_default_set<const MachineBasicBlock*> Reachable; 3028 3029 // Visit the MBBs in DFS order. 3030 for (df_ext_iterator<const MachineFunction *, 3031 df_iterator_default_set<const MachineBasicBlock *>> 3032 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable); 3033 DFI != DFE; ++DFI) { 3034 const MachineBasicBlock *MBB = *DFI; 3035 3036 StackStateOfBB BBState; 3037 // Check the exit state of the DFS stack predecessor. 3038 if (DFI.getPathLength() >= 2) { 3039 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 3040 assert(Reachable.count(StackPred) && 3041 "DFS stack predecessor is already visited.\n"); 3042 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue; 3043 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup; 3044 BBState.ExitValue = BBState.EntryValue; 3045 BBState.ExitIsSetup = BBState.EntryIsSetup; 3046 } 3047 3048 // Update stack state by checking contents of MBB. 3049 for (const auto &I : *MBB) { 3050 if (I.getOpcode() == FrameSetupOpcode) { 3051 if (BBState.ExitIsSetup) 3052 report("FrameSetup is after another FrameSetup", &I); 3053 BBState.ExitValue -= TII->getFrameTotalSize(I); 3054 BBState.ExitIsSetup = true; 3055 } 3056 3057 if (I.getOpcode() == FrameDestroyOpcode) { 3058 int Size = TII->getFrameTotalSize(I); 3059 if (!BBState.ExitIsSetup) 3060 report("FrameDestroy is not after a FrameSetup", &I); 3061 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue : 3062 BBState.ExitValue; 3063 if (BBState.ExitIsSetup && AbsSPAdj != Size) { 3064 report("FrameDestroy <n> is after FrameSetup <m>", &I); 3065 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <" 3066 << AbsSPAdj << ">.\n"; 3067 } 3068 BBState.ExitValue += Size; 3069 BBState.ExitIsSetup = false; 3070 } 3071 } 3072 SPState[MBB->getNumber()] = BBState; 3073 3074 // Make sure the exit state of any predecessor is consistent with the entry 3075 // state. 3076 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 3077 if (Reachable.count(Pred) && 3078 (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue || 3079 SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) { 3080 report("The exit stack state of a predecessor is inconsistent.", MBB); 3081 errs() << "Predecessor " << printMBBReference(*Pred) 3082 << " has exit state (" << SPState[Pred->getNumber()].ExitValue 3083 << ", " << SPState[Pred->getNumber()].ExitIsSetup << "), while " 3084 << printMBBReference(*MBB) << " has entry state (" 3085 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n"; 3086 } 3087 } 3088 3089 // Make sure the entry state of any successor is consistent with the exit 3090 // state. 3091 for (const MachineBasicBlock *Succ : MBB->successors()) { 3092 if (Reachable.count(Succ) && 3093 (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue || 3094 SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) { 3095 report("The entry stack state of a successor is inconsistent.", MBB); 3096 errs() << "Successor " << printMBBReference(*Succ) 3097 << " has entry state (" << SPState[Succ->getNumber()].EntryValue 3098 << ", " << SPState[Succ->getNumber()].EntryIsSetup << "), while " 3099 << printMBBReference(*MBB) << " has exit state (" 3100 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n"; 3101 } 3102 } 3103 3104 // Make sure a basic block with return ends with zero stack adjustment. 3105 if (!MBB->empty() && MBB->back().isReturn()) { 3106 if (BBState.ExitIsSetup) 3107 report("A return block ends with a FrameSetup.", MBB); 3108 if (BBState.ExitValue) 3109 report("A return block ends with a nonzero stack adjustment.", MBB); 3110 } 3111 } 3112 } 3113