1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Pass to verify generated machine code. The following is checked: 11 // 12 // Operand counts: All explicit operands must be present. 13 // 14 // Register classes: All physical and virtual register operands must be 15 // compatible with the register class required by the instruction descriptor. 16 // 17 // Register live intervals: Registers must be defined only once, and must be 18 // defined before use. 19 // 20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the 21 // command-line option -verify-machineinstrs, or by defining the environment 22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive 23 // the verifier errors. 24 //===----------------------------------------------------------------------===// 25 26 #include "llvm/CodeGen/Passes.h" 27 #include "llvm/ADT/DenseSet.h" 28 #include "llvm/ADT/DepthFirstIterator.h" 29 #include "llvm/ADT/SetOperations.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/Analysis/EHPersonalities.h" 32 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 33 #include "llvm/CodeGen/LiveStackAnalysis.h" 34 #include "llvm/CodeGen/LiveVariables.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunctionPass.h" 37 #include "llvm/CodeGen/MachineMemOperand.h" 38 #include "llvm/CodeGen/MachineRegisterInfo.h" 39 #include "llvm/IR/BasicBlock.h" 40 #include "llvm/IR/InlineAsm.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/MC/MCAsmInfo.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/FileSystem.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetInstrInfo.h" 48 #include "llvm/Target/TargetMachine.h" 49 #include "llvm/Target/TargetRegisterInfo.h" 50 #include "llvm/Target/TargetSubtargetInfo.h" 51 using namespace llvm; 52 53 namespace { 54 struct MachineVerifier { 55 56 MachineVerifier(Pass *pass, const char *b) : 57 PASS(pass), 58 Banner(b) 59 {} 60 61 unsigned verify(MachineFunction &MF); 62 63 Pass *const PASS; 64 const char *Banner; 65 const MachineFunction *MF; 66 const TargetMachine *TM; 67 const TargetInstrInfo *TII; 68 const TargetRegisterInfo *TRI; 69 const MachineRegisterInfo *MRI; 70 71 unsigned foundErrors; 72 73 // Avoid querying the MachineFunctionProperties for each operand. 74 bool isFunctionRegBankSelected; 75 bool isFunctionSelected; 76 77 typedef SmallVector<unsigned, 16> RegVector; 78 typedef SmallVector<const uint32_t*, 4> RegMaskVector; 79 typedef DenseSet<unsigned> RegSet; 80 typedef DenseMap<unsigned, const MachineInstr*> RegMap; 81 typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet; 82 83 const MachineInstr *FirstTerminator; 84 BlockSet FunctionBlocks; 85 86 BitVector regsReserved; 87 RegSet regsLive; 88 RegVector regsDefined, regsDead, regsKilled; 89 RegMaskVector regMasks; 90 RegSet regsLiveInButUnused; 91 92 SlotIndex lastIndex; 93 94 // Add Reg and any sub-registers to RV 95 void addRegWithSubRegs(RegVector &RV, unsigned Reg) { 96 RV.push_back(Reg); 97 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 98 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) 99 RV.push_back(*SubRegs); 100 } 101 102 struct BBInfo { 103 // Is this MBB reachable from the MF entry point? 104 bool reachable; 105 106 // Vregs that must be live in because they are used without being 107 // defined. Map value is the user. 108 RegMap vregsLiveIn; 109 110 // Regs killed in MBB. They may be defined again, and will then be in both 111 // regsKilled and regsLiveOut. 112 RegSet regsKilled; 113 114 // Regs defined in MBB and live out. Note that vregs passing through may 115 // be live out without being mentioned here. 116 RegSet regsLiveOut; 117 118 // Vregs that pass through MBB untouched. This set is disjoint from 119 // regsKilled and regsLiveOut. 120 RegSet vregsPassed; 121 122 // Vregs that must pass through MBB because they are needed by a successor 123 // block. This set is disjoint from regsLiveOut. 124 RegSet vregsRequired; 125 126 // Set versions of block's predecessor and successor lists. 127 BlockSet Preds, Succs; 128 129 BBInfo() : reachable(false) {} 130 131 // Add register to vregsPassed if it belongs there. Return true if 132 // anything changed. 133 bool addPassed(unsigned Reg) { 134 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 135 return false; 136 if (regsKilled.count(Reg) || regsLiveOut.count(Reg)) 137 return false; 138 return vregsPassed.insert(Reg).second; 139 } 140 141 // Same for a full set. 142 bool addPassed(const RegSet &RS) { 143 bool changed = false; 144 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I) 145 if (addPassed(*I)) 146 changed = true; 147 return changed; 148 } 149 150 // Add register to vregsRequired if it belongs there. Return true if 151 // anything changed. 152 bool addRequired(unsigned Reg) { 153 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 154 return false; 155 if (regsLiveOut.count(Reg)) 156 return false; 157 return vregsRequired.insert(Reg).second; 158 } 159 160 // Same for a full set. 161 bool addRequired(const RegSet &RS) { 162 bool changed = false; 163 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I) 164 if (addRequired(*I)) 165 changed = true; 166 return changed; 167 } 168 169 // Same for a full map. 170 bool addRequired(const RegMap &RM) { 171 bool changed = false; 172 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I) 173 if (addRequired(I->first)) 174 changed = true; 175 return changed; 176 } 177 178 // Live-out registers are either in regsLiveOut or vregsPassed. 179 bool isLiveOut(unsigned Reg) const { 180 return regsLiveOut.count(Reg) || vregsPassed.count(Reg); 181 } 182 }; 183 184 // Extra register info per MBB. 185 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap; 186 187 bool isReserved(unsigned Reg) { 188 return Reg < regsReserved.size() && regsReserved.test(Reg); 189 } 190 191 bool isAllocatable(unsigned Reg) { 192 return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg); 193 } 194 195 // Analysis information if available 196 LiveVariables *LiveVars; 197 LiveIntervals *LiveInts; 198 LiveStacks *LiveStks; 199 SlotIndexes *Indexes; 200 201 void visitMachineFunctionBefore(); 202 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB); 203 void visitMachineBundleBefore(const MachineInstr *MI); 204 void visitMachineInstrBefore(const MachineInstr *MI); 205 void visitMachineOperand(const MachineOperand *MO, unsigned MONum); 206 void visitMachineInstrAfter(const MachineInstr *MI); 207 void visitMachineBundleAfter(const MachineInstr *MI); 208 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB); 209 void visitMachineFunctionAfter(); 210 211 template <typename T> void report(const char *msg, ilist_iterator<T> I) { 212 report(msg, &*I); 213 } 214 void report(const char *msg, const MachineFunction *MF); 215 void report(const char *msg, const MachineBasicBlock *MBB); 216 void report(const char *msg, const MachineInstr *MI); 217 void report(const char *msg, const MachineOperand *MO, unsigned MONum); 218 219 void report_context(const LiveInterval &LI) const; 220 void report_context(const LiveRange &LR, unsigned VRegUnit, 221 LaneBitmask LaneMask) const; 222 void report_context(const LiveRange::Segment &S) const; 223 void report_context(const VNInfo &VNI) const; 224 void report_context(SlotIndex Pos) const; 225 void report_context_liverange(const LiveRange &LR) const; 226 void report_context_lanemask(LaneBitmask LaneMask) const; 227 void report_context_vreg(unsigned VReg) const; 228 void report_context_vreg_regunit(unsigned VRegOrRegUnit) const; 229 230 void verifyInlineAsm(const MachineInstr *MI); 231 232 void checkLiveness(const MachineOperand *MO, unsigned MONum); 233 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum, 234 SlotIndex UseIdx, const LiveRange &LR, unsigned Reg, 235 LaneBitmask LaneMask = 0); 236 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum, 237 SlotIndex DefIdx, const LiveRange &LR, unsigned Reg, 238 LaneBitmask LaneMask = 0); 239 240 void markReachable(const MachineBasicBlock *MBB); 241 void calcRegsPassed(); 242 void checkPHIOps(const MachineBasicBlock *MBB); 243 244 void calcRegsRequired(); 245 void verifyLiveVariables(); 246 void verifyLiveIntervals(); 247 void verifyLiveInterval(const LiveInterval&); 248 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned, 249 unsigned); 250 void verifyLiveRangeSegment(const LiveRange&, 251 const LiveRange::const_iterator I, unsigned, 252 unsigned); 253 void verifyLiveRange(const LiveRange&, unsigned, LaneBitmask LaneMask = 0); 254 255 void verifyStackFrame(); 256 257 void verifySlotIndexes() const; 258 void verifyProperties(const MachineFunction &MF); 259 }; 260 261 struct MachineVerifierPass : public MachineFunctionPass { 262 static char ID; // Pass ID, replacement for typeid 263 const std::string Banner; 264 265 MachineVerifierPass(const std::string &banner = nullptr) 266 : MachineFunctionPass(ID), Banner(banner) { 267 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry()); 268 } 269 270 void getAnalysisUsage(AnalysisUsage &AU) const override { 271 AU.setPreservesAll(); 272 MachineFunctionPass::getAnalysisUsage(AU); 273 } 274 275 bool runOnMachineFunction(MachineFunction &MF) override { 276 unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF); 277 if (FoundErrors) 278 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors."); 279 return false; 280 } 281 }; 282 283 } 284 285 char MachineVerifierPass::ID = 0; 286 INITIALIZE_PASS(MachineVerifierPass, "machineverifier", 287 "Verify generated machine code", false, false) 288 289 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) { 290 return new MachineVerifierPass(Banner); 291 } 292 293 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors) 294 const { 295 MachineFunction &MF = const_cast<MachineFunction&>(*this); 296 unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF); 297 if (AbortOnErrors && FoundErrors) 298 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors."); 299 return FoundErrors == 0; 300 } 301 302 void MachineVerifier::verifySlotIndexes() const { 303 if (Indexes == nullptr) 304 return; 305 306 // Ensure the IdxMBB list is sorted by slot indexes. 307 SlotIndex Last; 308 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(), 309 E = Indexes->MBBIndexEnd(); I != E; ++I) { 310 assert(!Last.isValid() || I->first > Last); 311 Last = I->first; 312 } 313 } 314 315 void MachineVerifier::verifyProperties(const MachineFunction &MF) { 316 // If a pass has introduced virtual registers without clearing the 317 // AllVRegsAllocated property (or set it without allocating the vregs) 318 // then report an error. 319 if (MF.getProperties().hasProperty( 320 MachineFunctionProperties::Property::AllVRegsAllocated) && 321 MRI->getNumVirtRegs()) { 322 report( 323 "Function has AllVRegsAllocated property but there are VReg operands", 324 &MF); 325 } 326 } 327 328 unsigned MachineVerifier::verify(MachineFunction &MF) { 329 foundErrors = 0; 330 331 this->MF = &MF; 332 TM = &MF.getTarget(); 333 TII = MF.getSubtarget().getInstrInfo(); 334 TRI = MF.getSubtarget().getRegisterInfo(); 335 MRI = &MF.getRegInfo(); 336 337 isFunctionRegBankSelected = MF.getProperties().hasProperty( 338 MachineFunctionProperties::Property::RegBankSelected); 339 isFunctionSelected = MF.getProperties().hasProperty( 340 MachineFunctionProperties::Property::Selected); 341 342 LiveVars = nullptr; 343 LiveInts = nullptr; 344 LiveStks = nullptr; 345 Indexes = nullptr; 346 if (PASS) { 347 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>(); 348 // We don't want to verify LiveVariables if LiveIntervals is available. 349 if (!LiveInts) 350 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>(); 351 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>(); 352 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>(); 353 } 354 355 verifySlotIndexes(); 356 357 verifyProperties(MF); 358 359 visitMachineFunctionBefore(); 360 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end(); 361 MFI!=MFE; ++MFI) { 362 visitMachineBasicBlockBefore(&*MFI); 363 // Keep track of the current bundle header. 364 const MachineInstr *CurBundle = nullptr; 365 // Do we expect the next instruction to be part of the same bundle? 366 bool InBundle = false; 367 368 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(), 369 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) { 370 if (MBBI->getParent() != &*MFI) { 371 report("Bad instruction parent pointer", MFI); 372 errs() << "Instruction: " << *MBBI; 373 continue; 374 } 375 376 // Check for consistent bundle flags. 377 if (InBundle && !MBBI->isBundledWithPred()) 378 report("Missing BundledPred flag, " 379 "BundledSucc was set on predecessor", 380 &*MBBI); 381 if (!InBundle && MBBI->isBundledWithPred()) 382 report("BundledPred flag is set, " 383 "but BundledSucc not set on predecessor", 384 &*MBBI); 385 386 // Is this a bundle header? 387 if (!MBBI->isInsideBundle()) { 388 if (CurBundle) 389 visitMachineBundleAfter(CurBundle); 390 CurBundle = &*MBBI; 391 visitMachineBundleBefore(CurBundle); 392 } else if (!CurBundle) 393 report("No bundle header", MBBI); 394 visitMachineInstrBefore(&*MBBI); 395 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) { 396 const MachineInstr &MI = *MBBI; 397 const MachineOperand &Op = MI.getOperand(I); 398 if (Op.getParent() != &MI) { 399 // Make sure to use correct addOperand / RemoveOperand / ChangeTo 400 // functions when replacing operands of a MachineInstr. 401 report("Instruction has operand with wrong parent set", &MI); 402 } 403 404 visitMachineOperand(&Op, I); 405 } 406 407 visitMachineInstrAfter(&*MBBI); 408 409 // Was this the last bundled instruction? 410 InBundle = MBBI->isBundledWithSucc(); 411 } 412 if (CurBundle) 413 visitMachineBundleAfter(CurBundle); 414 if (InBundle) 415 report("BundledSucc flag set on last instruction in block", &MFI->back()); 416 visitMachineBasicBlockAfter(&*MFI); 417 } 418 visitMachineFunctionAfter(); 419 420 // Clean up. 421 regsLive.clear(); 422 regsDefined.clear(); 423 regsDead.clear(); 424 regsKilled.clear(); 425 regMasks.clear(); 426 regsLiveInButUnused.clear(); 427 MBBInfoMap.clear(); 428 429 return foundErrors; 430 } 431 432 void MachineVerifier::report(const char *msg, const MachineFunction *MF) { 433 assert(MF); 434 errs() << '\n'; 435 if (!foundErrors++) { 436 if (Banner) 437 errs() << "# " << Banner << '\n'; 438 if (LiveInts != nullptr) 439 LiveInts->print(errs()); 440 else 441 MF->print(errs(), Indexes); 442 } 443 errs() << "*** Bad machine code: " << msg << " ***\n" 444 << "- function: " << MF->getName() << "\n"; 445 } 446 447 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) { 448 assert(MBB); 449 report(msg, MBB->getParent()); 450 errs() << "- basic block: BB#" << MBB->getNumber() 451 << ' ' << MBB->getName() 452 << " (" << (const void*)MBB << ')'; 453 if (Indexes) 454 errs() << " [" << Indexes->getMBBStartIdx(MBB) 455 << ';' << Indexes->getMBBEndIdx(MBB) << ')'; 456 errs() << '\n'; 457 } 458 459 void MachineVerifier::report(const char *msg, const MachineInstr *MI) { 460 assert(MI); 461 report(msg, MI->getParent()); 462 errs() << "- instruction: "; 463 if (Indexes && Indexes->hasIndex(*MI)) 464 errs() << Indexes->getInstructionIndex(*MI) << '\t'; 465 MI->print(errs(), /*SkipOpers=*/true); 466 errs() << '\n'; 467 } 468 469 void MachineVerifier::report(const char *msg, 470 const MachineOperand *MO, unsigned MONum) { 471 assert(MO); 472 report(msg, MO->getParent()); 473 errs() << "- operand " << MONum << ": "; 474 MO->print(errs(), TRI); 475 errs() << "\n"; 476 } 477 478 void MachineVerifier::report_context(SlotIndex Pos) const { 479 errs() << "- at: " << Pos << '\n'; 480 } 481 482 void MachineVerifier::report_context(const LiveInterval &LI) const { 483 errs() << "- interval: " << LI << '\n'; 484 } 485 486 void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit, 487 LaneBitmask LaneMask) const { 488 report_context_liverange(LR); 489 report_context_vreg_regunit(VRegUnit); 490 if (LaneMask != 0) 491 report_context_lanemask(LaneMask); 492 } 493 494 void MachineVerifier::report_context(const LiveRange::Segment &S) const { 495 errs() << "- segment: " << S << '\n'; 496 } 497 498 void MachineVerifier::report_context(const VNInfo &VNI) const { 499 errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n"; 500 } 501 502 void MachineVerifier::report_context_liverange(const LiveRange &LR) const { 503 errs() << "- liverange: " << LR << '\n'; 504 } 505 506 void MachineVerifier::report_context_vreg(unsigned VReg) const { 507 errs() << "- v. register: " << PrintReg(VReg, TRI) << '\n'; 508 } 509 510 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const { 511 if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) { 512 report_context_vreg(VRegOrUnit); 513 } else { 514 errs() << "- regunit: " << PrintRegUnit(VRegOrUnit, TRI) << '\n'; 515 } 516 } 517 518 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const { 519 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n'; 520 } 521 522 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) { 523 BBInfo &MInfo = MBBInfoMap[MBB]; 524 if (!MInfo.reachable) { 525 MInfo.reachable = true; 526 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(), 527 SuE = MBB->succ_end(); SuI != SuE; ++SuI) 528 markReachable(*SuI); 529 } 530 } 531 532 void MachineVerifier::visitMachineFunctionBefore() { 533 lastIndex = SlotIndex(); 534 regsReserved = MRI->getReservedRegs(); 535 536 // A sub-register of a reserved register is also reserved 537 for (int Reg = regsReserved.find_first(); Reg>=0; 538 Reg = regsReserved.find_next(Reg)) { 539 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) { 540 // FIXME: This should probably be: 541 // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register"); 542 regsReserved.set(*SubRegs); 543 } 544 } 545 546 markReachable(&MF->front()); 547 548 // Build a set of the basic blocks in the function. 549 FunctionBlocks.clear(); 550 for (const auto &MBB : *MF) { 551 FunctionBlocks.insert(&MBB); 552 BBInfo &MInfo = MBBInfoMap[&MBB]; 553 554 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end()); 555 if (MInfo.Preds.size() != MBB.pred_size()) 556 report("MBB has duplicate entries in its predecessor list.", &MBB); 557 558 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end()); 559 if (MInfo.Succs.size() != MBB.succ_size()) 560 report("MBB has duplicate entries in its successor list.", &MBB); 561 } 562 563 // Check that the register use lists are sane. 564 MRI->verifyUseLists(); 565 566 verifyStackFrame(); 567 } 568 569 // Does iterator point to a and b as the first two elements? 570 static bool matchPair(MachineBasicBlock::const_succ_iterator i, 571 const MachineBasicBlock *a, const MachineBasicBlock *b) { 572 if (*i == a) 573 return *++i == b; 574 if (*i == b) 575 return *++i == a; 576 return false; 577 } 578 579 void 580 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) { 581 FirstTerminator = nullptr; 582 583 if (!MF->getProperties().hasProperty( 584 MachineFunctionProperties::Property::NoPHIs)) { 585 // If this block has allocatable physical registers live-in, check that 586 // it is an entry block or landing pad. 587 for (const auto &LI : MBB->liveins()) { 588 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() && 589 MBB->getIterator() != MBB->getParent()->begin()) { 590 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB); 591 } 592 } 593 } 594 595 // Count the number of landing pad successors. 596 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs; 597 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(), 598 E = MBB->succ_end(); I != E; ++I) { 599 if ((*I)->isEHPad()) 600 LandingPadSuccs.insert(*I); 601 if (!FunctionBlocks.count(*I)) 602 report("MBB has successor that isn't part of the function.", MBB); 603 if (!MBBInfoMap[*I].Preds.count(MBB)) { 604 report("Inconsistent CFG", MBB); 605 errs() << "MBB is not in the predecessor list of the successor BB#" 606 << (*I)->getNumber() << ".\n"; 607 } 608 } 609 610 // Check the predecessor list. 611 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(), 612 E = MBB->pred_end(); I != E; ++I) { 613 if (!FunctionBlocks.count(*I)) 614 report("MBB has predecessor that isn't part of the function.", MBB); 615 if (!MBBInfoMap[*I].Succs.count(MBB)) { 616 report("Inconsistent CFG", MBB); 617 errs() << "MBB is not in the successor list of the predecessor BB#" 618 << (*I)->getNumber() << ".\n"; 619 } 620 } 621 622 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo(); 623 const BasicBlock *BB = MBB->getBasicBlock(); 624 const Function *Fn = MF->getFunction(); 625 if (LandingPadSuccs.size() > 1 && 626 !(AsmInfo && 627 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj && 628 BB && isa<SwitchInst>(BB->getTerminator())) && 629 !isFuncletEHPersonality(classifyEHPersonality(Fn->getPersonalityFn()))) 630 report("MBB has more than one landing pad successor", MBB); 631 632 // Call AnalyzeBranch. If it succeeds, there several more conditions to check. 633 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 634 SmallVector<MachineOperand, 4> Cond; 635 if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB, 636 Cond)) { 637 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's 638 // check whether its answers match up with reality. 639 if (!TBB && !FBB) { 640 // Block falls through to its successor. 641 MachineFunction::const_iterator MBBI = MBB->getIterator(); 642 ++MBBI; 643 if (MBBI == MF->end()) { 644 // It's possible that the block legitimately ends with a noreturn 645 // call or an unreachable, in which case it won't actually fall 646 // out the bottom of the function. 647 } else if (MBB->succ_size() == LandingPadSuccs.size()) { 648 // It's possible that the block legitimately ends with a noreturn 649 // call or an unreachable, in which case it won't actuall fall 650 // out of the block. 651 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) { 652 report("MBB exits via unconditional fall-through but doesn't have " 653 "exactly one CFG successor!", MBB); 654 } else if (!MBB->isSuccessor(&*MBBI)) { 655 report("MBB exits via unconditional fall-through but its successor " 656 "differs from its CFG successor!", MBB); 657 } 658 if (!MBB->empty() && MBB->back().isBarrier() && 659 !TII->isPredicated(MBB->back())) { 660 report("MBB exits via unconditional fall-through but ends with a " 661 "barrier instruction!", MBB); 662 } 663 if (!Cond.empty()) { 664 report("MBB exits via unconditional fall-through but has a condition!", 665 MBB); 666 } 667 } else if (TBB && !FBB && Cond.empty()) { 668 // Block unconditionally branches somewhere. 669 // If the block has exactly one successor, that happens to be a 670 // landingpad, accept it as valid control flow. 671 if (MBB->succ_size() != 1+LandingPadSuccs.size() && 672 (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 || 673 *MBB->succ_begin() != *LandingPadSuccs.begin())) { 674 report("MBB exits via unconditional branch but doesn't have " 675 "exactly one CFG successor!", MBB); 676 } else if (!MBB->isSuccessor(TBB)) { 677 report("MBB exits via unconditional branch but the CFG " 678 "successor doesn't match the actual successor!", MBB); 679 } 680 if (MBB->empty()) { 681 report("MBB exits via unconditional branch but doesn't contain " 682 "any instructions!", MBB); 683 } else if (!MBB->back().isBarrier()) { 684 report("MBB exits via unconditional branch but doesn't end with a " 685 "barrier instruction!", MBB); 686 } else if (!MBB->back().isTerminator()) { 687 report("MBB exits via unconditional branch but the branch isn't a " 688 "terminator instruction!", MBB); 689 } 690 } else if (TBB && !FBB && !Cond.empty()) { 691 // Block conditionally branches somewhere, otherwise falls through. 692 MachineFunction::const_iterator MBBI = MBB->getIterator(); 693 ++MBBI; 694 if (MBBI == MF->end()) { 695 report("MBB conditionally falls through out of function!", MBB); 696 } else if (MBB->succ_size() == 1) { 697 // A conditional branch with only one successor is weird, but allowed. 698 if (&*MBBI != TBB) 699 report("MBB exits via conditional branch/fall-through but only has " 700 "one CFG successor!", MBB); 701 else if (TBB != *MBB->succ_begin()) 702 report("MBB exits via conditional branch/fall-through but the CFG " 703 "successor don't match the actual successor!", MBB); 704 } else if (MBB->succ_size() != 2) { 705 report("MBB exits via conditional branch/fall-through but doesn't have " 706 "exactly two CFG successors!", MBB); 707 } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) { 708 report("MBB exits via conditional branch/fall-through but the CFG " 709 "successors don't match the actual successors!", MBB); 710 } 711 if (MBB->empty()) { 712 report("MBB exits via conditional branch/fall-through but doesn't " 713 "contain any instructions!", MBB); 714 } else if (MBB->back().isBarrier()) { 715 report("MBB exits via conditional branch/fall-through but ends with a " 716 "barrier instruction!", MBB); 717 } else if (!MBB->back().isTerminator()) { 718 report("MBB exits via conditional branch/fall-through but the branch " 719 "isn't a terminator instruction!", MBB); 720 } 721 } else if (TBB && FBB) { 722 // Block conditionally branches somewhere, otherwise branches 723 // somewhere else. 724 if (MBB->succ_size() == 1) { 725 // A conditional branch with only one successor is weird, but allowed. 726 if (FBB != TBB) 727 report("MBB exits via conditional branch/branch through but only has " 728 "one CFG successor!", MBB); 729 else if (TBB != *MBB->succ_begin()) 730 report("MBB exits via conditional branch/branch through but the CFG " 731 "successor don't match the actual successor!", MBB); 732 } else if (MBB->succ_size() != 2) { 733 report("MBB exits via conditional branch/branch but doesn't have " 734 "exactly two CFG successors!", MBB); 735 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) { 736 report("MBB exits via conditional branch/branch but the CFG " 737 "successors don't match the actual successors!", MBB); 738 } 739 if (MBB->empty()) { 740 report("MBB exits via conditional branch/branch but doesn't " 741 "contain any instructions!", MBB); 742 } else if (!MBB->back().isBarrier()) { 743 report("MBB exits via conditional branch/branch but doesn't end with a " 744 "barrier instruction!", MBB); 745 } else if (!MBB->back().isTerminator()) { 746 report("MBB exits via conditional branch/branch but the branch " 747 "isn't a terminator instruction!", MBB); 748 } 749 if (Cond.empty()) { 750 report("MBB exits via conditinal branch/branch but there's no " 751 "condition!", MBB); 752 } 753 } else { 754 report("AnalyzeBranch returned invalid data!", MBB); 755 } 756 } 757 758 regsLive.clear(); 759 for (const auto &LI : MBB->liveins()) { 760 if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) { 761 report("MBB live-in list contains non-physical register", MBB); 762 continue; 763 } 764 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true); 765 SubRegs.isValid(); ++SubRegs) 766 regsLive.insert(*SubRegs); 767 } 768 regsLiveInButUnused = regsLive; 769 770 const MachineFrameInfo &MFI = MF->getFrameInfo(); 771 BitVector PR = MFI.getPristineRegs(*MF); 772 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) { 773 for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true); 774 SubRegs.isValid(); ++SubRegs) 775 regsLive.insert(*SubRegs); 776 } 777 778 regsKilled.clear(); 779 regsDefined.clear(); 780 781 if (Indexes) 782 lastIndex = Indexes->getMBBStartIdx(MBB); 783 } 784 785 // This function gets called for all bundle headers, including normal 786 // stand-alone unbundled instructions. 787 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) { 788 if (Indexes && Indexes->hasIndex(*MI)) { 789 SlotIndex idx = Indexes->getInstructionIndex(*MI); 790 if (!(idx > lastIndex)) { 791 report("Instruction index out of order", MI); 792 errs() << "Last instruction was at " << lastIndex << '\n'; 793 } 794 lastIndex = idx; 795 } 796 797 // Ensure non-terminators don't follow terminators. 798 // Ignore predicated terminators formed by if conversion. 799 // FIXME: If conversion shouldn't need to violate this rule. 800 if (MI->isTerminator() && !TII->isPredicated(*MI)) { 801 if (!FirstTerminator) 802 FirstTerminator = MI; 803 } else if (FirstTerminator) { 804 report("Non-terminator instruction after the first terminator", MI); 805 errs() << "First terminator was:\t" << *FirstTerminator; 806 } 807 } 808 809 // The operands on an INLINEASM instruction must follow a template. 810 // Verify that the flag operands make sense. 811 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) { 812 // The first two operands on INLINEASM are the asm string and global flags. 813 if (MI->getNumOperands() < 2) { 814 report("Too few operands on inline asm", MI); 815 return; 816 } 817 if (!MI->getOperand(0).isSymbol()) 818 report("Asm string must be an external symbol", MI); 819 if (!MI->getOperand(1).isImm()) 820 report("Asm flags must be an immediate", MI); 821 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2, 822 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16, 823 // and Extra_IsConvergent = 32. 824 if (!isUInt<6>(MI->getOperand(1).getImm())) 825 report("Unknown asm flags", &MI->getOperand(1), 1); 826 827 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed"); 828 829 unsigned OpNo = InlineAsm::MIOp_FirstOperand; 830 unsigned NumOps; 831 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) { 832 const MachineOperand &MO = MI->getOperand(OpNo); 833 // There may be implicit ops after the fixed operands. 834 if (!MO.isImm()) 835 break; 836 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm()); 837 } 838 839 if (OpNo > MI->getNumOperands()) 840 report("Missing operands in last group", MI); 841 842 // An optional MDNode follows the groups. 843 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata()) 844 ++OpNo; 845 846 // All trailing operands must be implicit registers. 847 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) { 848 const MachineOperand &MO = MI->getOperand(OpNo); 849 if (!MO.isReg() || !MO.isImplicit()) 850 report("Expected implicit register after groups", &MO, OpNo); 851 } 852 } 853 854 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) { 855 const MCInstrDesc &MCID = MI->getDesc(); 856 if (MI->getNumOperands() < MCID.getNumOperands()) { 857 report("Too few operands", MI); 858 errs() << MCID.getNumOperands() << " operands expected, but " 859 << MI->getNumOperands() << " given.\n"; 860 } 861 862 if (MI->isPHI() && MF->getProperties().hasProperty( 863 MachineFunctionProperties::Property::NoPHIs)) 864 report("Found PHI instruction with NoPHIs property set", MI); 865 866 // Check the tied operands. 867 if (MI->isInlineAsm()) 868 verifyInlineAsm(MI); 869 870 // Check the MachineMemOperands for basic consistency. 871 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(), 872 E = MI->memoperands_end(); I != E; ++I) { 873 if ((*I)->isLoad() && !MI->mayLoad()) 874 report("Missing mayLoad flag", MI); 875 if ((*I)->isStore() && !MI->mayStore()) 876 report("Missing mayStore flag", MI); 877 } 878 879 // Debug values must not have a slot index. 880 // Other instructions must have one, unless they are inside a bundle. 881 if (LiveInts) { 882 bool mapped = !LiveInts->isNotInMIMap(*MI); 883 if (MI->isDebugValue()) { 884 if (mapped) 885 report("Debug instruction has a slot index", MI); 886 } else if (MI->isInsideBundle()) { 887 if (mapped) 888 report("Instruction inside bundle has a slot index", MI); 889 } else { 890 if (!mapped) 891 report("Missing slot index", MI); 892 } 893 } 894 895 // Check types. 896 const unsigned NumTypes = MI->getNumTypes(); 897 if (isPreISelGenericOpcode(MCID.getOpcode())) { 898 if (isFunctionSelected) 899 report("Unexpected generic instruction in a Selected function", MI); 900 901 if (NumTypes == 0) 902 report("Generic instruction must have a type", MI); 903 } else { 904 if (NumTypes != 0) 905 report("Non-generic instruction cannot have a type", MI); 906 } 907 908 StringRef ErrorInfo; 909 if (!TII->verifyInstruction(*MI, ErrorInfo)) 910 report(ErrorInfo.data(), MI); 911 } 912 913 void 914 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) { 915 const MachineInstr *MI = MO->getParent(); 916 const MCInstrDesc &MCID = MI->getDesc(); 917 unsigned NumDefs = MCID.getNumDefs(); 918 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT) 919 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0; 920 921 // The first MCID.NumDefs operands must be explicit register defines 922 if (MONum < NumDefs) { 923 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 924 if (!MO->isReg()) 925 report("Explicit definition must be a register", MO, MONum); 926 else if (!MO->isDef() && !MCOI.isOptionalDef()) 927 report("Explicit definition marked as use", MO, MONum); 928 else if (MO->isImplicit()) 929 report("Explicit definition marked as implicit", MO, MONum); 930 } else if (MONum < MCID.getNumOperands()) { 931 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 932 // Don't check if it's the last operand in a variadic instruction. See, 933 // e.g., LDM_RET in the arm back end. 934 if (MO->isReg() && 935 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) { 936 if (MO->isDef() && !MCOI.isOptionalDef()) 937 report("Explicit operand marked as def", MO, MONum); 938 if (MO->isImplicit()) 939 report("Explicit operand marked as implicit", MO, MONum); 940 } 941 942 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO); 943 if (TiedTo != -1) { 944 if (!MO->isReg()) 945 report("Tied use must be a register", MO, MONum); 946 else if (!MO->isTied()) 947 report("Operand should be tied", MO, MONum); 948 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum)) 949 report("Tied def doesn't match MCInstrDesc", MO, MONum); 950 } else if (MO->isReg() && MO->isTied()) 951 report("Explicit operand should not be tied", MO, MONum); 952 } else { 953 // ARM adds %reg0 operands to indicate predicates. We'll allow that. 954 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg()) 955 report("Extra explicit operand on non-variadic instruction", MO, MONum); 956 } 957 958 switch (MO->getType()) { 959 case MachineOperand::MO_Register: { 960 const unsigned Reg = MO->getReg(); 961 if (!Reg) 962 return; 963 if (MRI->tracksLiveness() && !MI->isDebugValue()) 964 checkLiveness(MO, MONum); 965 966 // Verify the consistency of tied operands. 967 if (MO->isTied()) { 968 unsigned OtherIdx = MI->findTiedOperandIdx(MONum); 969 const MachineOperand &OtherMO = MI->getOperand(OtherIdx); 970 if (!OtherMO.isReg()) 971 report("Must be tied to a register", MO, MONum); 972 if (!OtherMO.isTied()) 973 report("Missing tie flags on tied operand", MO, MONum); 974 if (MI->findTiedOperandIdx(OtherIdx) != MONum) 975 report("Inconsistent tie links", MO, MONum); 976 if (MONum < MCID.getNumDefs()) { 977 if (OtherIdx < MCID.getNumOperands()) { 978 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO)) 979 report("Explicit def tied to explicit use without tie constraint", 980 MO, MONum); 981 } else { 982 if (!OtherMO.isImplicit()) 983 report("Explicit def should be tied to implicit use", MO, MONum); 984 } 985 } 986 } 987 988 // Verify two-address constraints after leaving SSA form. 989 unsigned DefIdx; 990 if (!MRI->isSSA() && MO->isUse() && 991 MI->isRegTiedToDefOperand(MONum, &DefIdx) && 992 Reg != MI->getOperand(DefIdx).getReg()) 993 report("Two-address instruction operands must be identical", MO, MONum); 994 995 // Check register classes. 996 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) { 997 unsigned SubIdx = MO->getSubReg(); 998 999 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1000 if (SubIdx) { 1001 report("Illegal subregister index for physical register", MO, MONum); 1002 return; 1003 } 1004 if (const TargetRegisterClass *DRC = 1005 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1006 if (!DRC->contains(Reg)) { 1007 report("Illegal physical register for instruction", MO, MONum); 1008 errs() << TRI->getName(Reg) << " is not a " 1009 << TRI->getRegClassName(DRC) << " register.\n"; 1010 } 1011 } 1012 } else { 1013 // Virtual register. 1014 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg); 1015 if (!RC) { 1016 // This is a generic virtual register. 1017 1018 // If we're post-Select, we can't have gvregs anymore. 1019 if (isFunctionSelected) { 1020 report("Generic virtual register invalid in a Selected function", 1021 MO, MONum); 1022 return; 1023 } 1024 1025 // The gvreg must have a size and it must not have a SubIdx. 1026 unsigned Size = MRI->getSize(Reg); 1027 if (!Size) { 1028 report("Generic virtual register must have a size", MO, MONum); 1029 return; 1030 } 1031 1032 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg); 1033 1034 // If we're post-RegBankSelect, the gvreg must have a bank. 1035 if (!RegBank && isFunctionRegBankSelected) { 1036 report("Generic virtual register must have a bank in a " 1037 "RegBankSelected function", 1038 MO, MONum); 1039 return; 1040 } 1041 1042 // Make sure the register fits into its register bank if any. 1043 if (RegBank && RegBank->getSize() < Size) { 1044 report("Register bank is too small for virtual register", MO, 1045 MONum); 1046 errs() << "Register bank " << RegBank->getName() << " too small(" 1047 << RegBank->getSize() << ") to fit " << Size << "-bits\n"; 1048 return; 1049 } 1050 if (SubIdx) { 1051 report("Generic virtual register does not subregister index", MO, MONum); 1052 return; 1053 } 1054 break; 1055 } 1056 if (SubIdx) { 1057 const TargetRegisterClass *SRC = 1058 TRI->getSubClassWithSubReg(RC, SubIdx); 1059 if (!SRC) { 1060 report("Invalid subregister index for virtual register", MO, MONum); 1061 errs() << "Register class " << TRI->getRegClassName(RC) 1062 << " does not support subreg index " << SubIdx << "\n"; 1063 return; 1064 } 1065 if (RC != SRC) { 1066 report("Invalid register class for subregister index", MO, MONum); 1067 errs() << "Register class " << TRI->getRegClassName(RC) 1068 << " does not fully support subreg index " << SubIdx << "\n"; 1069 return; 1070 } 1071 } 1072 if (const TargetRegisterClass *DRC = 1073 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1074 if (SubIdx) { 1075 const TargetRegisterClass *SuperRC = 1076 TRI->getLargestLegalSuperClass(RC, *MF); 1077 if (!SuperRC) { 1078 report("No largest legal super class exists.", MO, MONum); 1079 return; 1080 } 1081 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx); 1082 if (!DRC) { 1083 report("No matching super-reg register class.", MO, MONum); 1084 return; 1085 } 1086 } 1087 if (!RC->hasSuperClassEq(DRC)) { 1088 report("Illegal virtual register for instruction", MO, MONum); 1089 errs() << "Expected a " << TRI->getRegClassName(DRC) 1090 << " register, but got a " << TRI->getRegClassName(RC) 1091 << " register\n"; 1092 } 1093 } 1094 } 1095 } 1096 break; 1097 } 1098 1099 case MachineOperand::MO_RegisterMask: 1100 regMasks.push_back(MO->getRegMask()); 1101 break; 1102 1103 case MachineOperand::MO_MachineBasicBlock: 1104 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent())) 1105 report("PHI operand is not in the CFG", MO, MONum); 1106 break; 1107 1108 case MachineOperand::MO_FrameIndex: 1109 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) && 1110 LiveInts && !LiveInts->isNotInMIMap(*MI)) { 1111 int FI = MO->getIndex(); 1112 LiveInterval &LI = LiveStks->getInterval(FI); 1113 SlotIndex Idx = LiveInts->getInstructionIndex(*MI); 1114 1115 bool stores = MI->mayStore(); 1116 bool loads = MI->mayLoad(); 1117 // For a memory-to-memory move, we need to check if the frame 1118 // index is used for storing or loading, by inspecting the 1119 // memory operands. 1120 if (stores && loads) { 1121 for (auto *MMO : MI->memoperands()) { 1122 const PseudoSourceValue *PSV = MMO->getPseudoValue(); 1123 if (PSV == nullptr) continue; 1124 const FixedStackPseudoSourceValue *Value = 1125 dyn_cast<FixedStackPseudoSourceValue>(PSV); 1126 if (Value == nullptr) continue; 1127 if (Value->getFrameIndex() != FI) continue; 1128 1129 if (MMO->isStore()) 1130 loads = false; 1131 else 1132 stores = false; 1133 break; 1134 } 1135 if (loads == stores) 1136 report("Missing fixed stack memoperand.", MI); 1137 } 1138 if (loads && !LI.liveAt(Idx.getRegSlot(true))) { 1139 report("Instruction loads from dead spill slot", MO, MONum); 1140 errs() << "Live stack: " << LI << '\n'; 1141 } 1142 if (stores && !LI.liveAt(Idx.getRegSlot())) { 1143 report("Instruction stores to dead spill slot", MO, MONum); 1144 errs() << "Live stack: " << LI << '\n'; 1145 } 1146 } 1147 break; 1148 1149 default: 1150 break; 1151 } 1152 } 1153 1154 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO, 1155 unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit, 1156 LaneBitmask LaneMask) { 1157 LiveQueryResult LRQ = LR.Query(UseIdx); 1158 // Check if we have a segment at the use, note however that we only need one 1159 // live subregister range, the others may be dead. 1160 if (!LRQ.valueIn() && LaneMask == 0) { 1161 report("No live segment at use", MO, MONum); 1162 report_context_liverange(LR); 1163 report_context_vreg_regunit(VRegOrUnit); 1164 report_context(UseIdx); 1165 } 1166 if (MO->isKill() && !LRQ.isKill()) { 1167 report("Live range continues after kill flag", MO, MONum); 1168 report_context_liverange(LR); 1169 report_context_vreg_regunit(VRegOrUnit); 1170 if (LaneMask != 0) 1171 report_context_lanemask(LaneMask); 1172 report_context(UseIdx); 1173 } 1174 } 1175 1176 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO, 1177 unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit, 1178 LaneBitmask LaneMask) { 1179 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) { 1180 assert(VNI && "NULL valno is not allowed"); 1181 if (VNI->def != DefIdx) { 1182 report("Inconsistent valno->def", MO, MONum); 1183 report_context_liverange(LR); 1184 report_context_vreg_regunit(VRegOrUnit); 1185 if (LaneMask != 0) 1186 report_context_lanemask(LaneMask); 1187 report_context(*VNI); 1188 report_context(DefIdx); 1189 } 1190 } else { 1191 report("No live segment at def", MO, MONum); 1192 report_context_liverange(LR); 1193 report_context_vreg_regunit(VRegOrUnit); 1194 if (LaneMask != 0) 1195 report_context_lanemask(LaneMask); 1196 report_context(DefIdx); 1197 } 1198 // Check that, if the dead def flag is present, LiveInts agree. 1199 if (MO->isDead()) { 1200 LiveQueryResult LRQ = LR.Query(DefIdx); 1201 if (!LRQ.isDeadDef()) { 1202 // In case of physregs we can have a non-dead definition on another 1203 // operand. 1204 bool otherDef = false; 1205 if (!TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) { 1206 const MachineInstr &MI = *MO->getParent(); 1207 for (const MachineOperand &MO : MI.operands()) { 1208 if (!MO.isReg() || !MO.isDef() || MO.isDead()) 1209 continue; 1210 unsigned Reg = MO.getReg(); 1211 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 1212 if (*Units == VRegOrUnit) { 1213 otherDef = true; 1214 break; 1215 } 1216 } 1217 } 1218 } 1219 1220 if (!otherDef) { 1221 report("Live range continues after dead def flag", MO, MONum); 1222 report_context_liverange(LR); 1223 report_context_vreg_regunit(VRegOrUnit); 1224 if (LaneMask != 0) 1225 report_context_lanemask(LaneMask); 1226 } 1227 } 1228 } 1229 } 1230 1231 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) { 1232 const MachineInstr *MI = MO->getParent(); 1233 const unsigned Reg = MO->getReg(); 1234 1235 // Both use and def operands can read a register. 1236 if (MO->readsReg()) { 1237 regsLiveInButUnused.erase(Reg); 1238 1239 if (MO->isKill()) 1240 addRegWithSubRegs(regsKilled, Reg); 1241 1242 // Check that LiveVars knows this kill. 1243 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) && 1244 MO->isKill()) { 1245 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 1246 if (!is_contained(VI.Kills, MI)) 1247 report("Kill missing from LiveVariables", MO, MONum); 1248 } 1249 1250 // Check LiveInts liveness and kill. 1251 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 1252 SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI); 1253 // Check the cached regunit intervals. 1254 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) { 1255 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 1256 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) 1257 checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units); 1258 } 1259 } 1260 1261 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1262 if (LiveInts->hasInterval(Reg)) { 1263 // This is a virtual register interval. 1264 const LiveInterval &LI = LiveInts->getInterval(Reg); 1265 checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg); 1266 1267 if (LI.hasSubRanges() && !MO->isDef()) { 1268 unsigned SubRegIdx = MO->getSubReg(); 1269 LaneBitmask MOMask = SubRegIdx != 0 1270 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 1271 : MRI->getMaxLaneMaskForVReg(Reg); 1272 LaneBitmask LiveInMask = 0; 1273 for (const LiveInterval::SubRange &SR : LI.subranges()) { 1274 if ((MOMask & SR.LaneMask) == 0) 1275 continue; 1276 checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask); 1277 LiveQueryResult LRQ = SR.Query(UseIdx); 1278 if (LRQ.valueIn()) 1279 LiveInMask |= SR.LaneMask; 1280 } 1281 // At least parts of the register has to be live at the use. 1282 if ((LiveInMask & MOMask) == 0) { 1283 report("No live subrange at use", MO, MONum); 1284 report_context(LI); 1285 report_context(UseIdx); 1286 } 1287 } 1288 } else { 1289 report("Virtual register has no live interval", MO, MONum); 1290 } 1291 } 1292 } 1293 1294 // Use of a dead register. 1295 if (!regsLive.count(Reg)) { 1296 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1297 // Reserved registers may be used even when 'dead'. 1298 bool Bad = !isReserved(Reg); 1299 // We are fine if just any subregister has a defined value. 1300 if (Bad) { 1301 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); 1302 ++SubRegs) { 1303 if (regsLive.count(*SubRegs)) { 1304 Bad = false; 1305 break; 1306 } 1307 } 1308 } 1309 // If there is an additional implicit-use of a super register we stop 1310 // here. By definition we are fine if the super register is not 1311 // (completely) dead, if the complete super register is dead we will 1312 // get a report for its operand. 1313 if (Bad) { 1314 for (const MachineOperand &MOP : MI->uses()) { 1315 if (!MOP.isReg()) 1316 continue; 1317 if (!MOP.isImplicit()) 1318 continue; 1319 for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid(); 1320 ++SubRegs) { 1321 if (*SubRegs == Reg) { 1322 Bad = false; 1323 break; 1324 } 1325 } 1326 } 1327 } 1328 if (Bad) 1329 report("Using an undefined physical register", MO, MONum); 1330 } else if (MRI->def_empty(Reg)) { 1331 report("Reading virtual register without a def", MO, MONum); 1332 } else { 1333 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 1334 // We don't know which virtual registers are live in, so only complain 1335 // if vreg was killed in this MBB. Otherwise keep track of vregs that 1336 // must be live in. PHI instructions are handled separately. 1337 if (MInfo.regsKilled.count(Reg)) 1338 report("Using a killed virtual register", MO, MONum); 1339 else if (!MI->isPHI()) 1340 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI)); 1341 } 1342 } 1343 } 1344 1345 if (MO->isDef()) { 1346 // Register defined. 1347 // TODO: verify that earlyclobber ops are not used. 1348 if (MO->isDead()) 1349 addRegWithSubRegs(regsDead, Reg); 1350 else 1351 addRegWithSubRegs(regsDefined, Reg); 1352 1353 // Verify SSA form. 1354 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) && 1355 std::next(MRI->def_begin(Reg)) != MRI->def_end()) 1356 report("Multiple virtual register defs in SSA form", MO, MONum); 1357 1358 // Check LiveInts for a live segment, but only for virtual registers. 1359 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 1360 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI); 1361 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber()); 1362 1363 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1364 if (LiveInts->hasInterval(Reg)) { 1365 const LiveInterval &LI = LiveInts->getInterval(Reg); 1366 checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg); 1367 1368 if (LI.hasSubRanges()) { 1369 unsigned SubRegIdx = MO->getSubReg(); 1370 LaneBitmask MOMask = SubRegIdx != 0 1371 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 1372 : MRI->getMaxLaneMaskForVReg(Reg); 1373 for (const LiveInterval::SubRange &SR : LI.subranges()) { 1374 if ((SR.LaneMask & MOMask) == 0) 1375 continue; 1376 checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, SR.LaneMask); 1377 } 1378 } 1379 } else { 1380 report("Virtual register has no Live interval", MO, MONum); 1381 } 1382 } 1383 } 1384 } 1385 } 1386 1387 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) { 1388 } 1389 1390 // This function gets called after visiting all instructions in a bundle. The 1391 // argument points to the bundle header. 1392 // Normal stand-alone instructions are also considered 'bundles', and this 1393 // function is called for all of them. 1394 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) { 1395 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 1396 set_union(MInfo.regsKilled, regsKilled); 1397 set_subtract(regsLive, regsKilled); regsKilled.clear(); 1398 // Kill any masked registers. 1399 while (!regMasks.empty()) { 1400 const uint32_t *Mask = regMasks.pop_back_val(); 1401 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I) 1402 if (TargetRegisterInfo::isPhysicalRegister(*I) && 1403 MachineOperand::clobbersPhysReg(Mask, *I)) 1404 regsDead.push_back(*I); 1405 } 1406 set_subtract(regsLive, regsDead); regsDead.clear(); 1407 set_union(regsLive, regsDefined); regsDefined.clear(); 1408 } 1409 1410 void 1411 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) { 1412 MBBInfoMap[MBB].regsLiveOut = regsLive; 1413 regsLive.clear(); 1414 1415 if (Indexes) { 1416 SlotIndex stop = Indexes->getMBBEndIdx(MBB); 1417 if (!(stop > lastIndex)) { 1418 report("Block ends before last instruction index", MBB); 1419 errs() << "Block ends at " << stop 1420 << " last instruction was at " << lastIndex << '\n'; 1421 } 1422 lastIndex = stop; 1423 } 1424 } 1425 1426 // Calculate the largest possible vregsPassed sets. These are the registers that 1427 // can pass through an MBB live, but may not be live every time. It is assumed 1428 // that all vregsPassed sets are empty before the call. 1429 void MachineVerifier::calcRegsPassed() { 1430 // First push live-out regs to successors' vregsPassed. Remember the MBBs that 1431 // have any vregsPassed. 1432 SmallPtrSet<const MachineBasicBlock*, 8> todo; 1433 for (const auto &MBB : *MF) { 1434 BBInfo &MInfo = MBBInfoMap[&MBB]; 1435 if (!MInfo.reachable) 1436 continue; 1437 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(), 1438 SuE = MBB.succ_end(); SuI != SuE; ++SuI) { 1439 BBInfo &SInfo = MBBInfoMap[*SuI]; 1440 if (SInfo.addPassed(MInfo.regsLiveOut)) 1441 todo.insert(*SuI); 1442 } 1443 } 1444 1445 // Iteratively push vregsPassed to successors. This will converge to the same 1446 // final state regardless of DenseSet iteration order. 1447 while (!todo.empty()) { 1448 const MachineBasicBlock *MBB = *todo.begin(); 1449 todo.erase(MBB); 1450 BBInfo &MInfo = MBBInfoMap[MBB]; 1451 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(), 1452 SuE = MBB->succ_end(); SuI != SuE; ++SuI) { 1453 if (*SuI == MBB) 1454 continue; 1455 BBInfo &SInfo = MBBInfoMap[*SuI]; 1456 if (SInfo.addPassed(MInfo.vregsPassed)) 1457 todo.insert(*SuI); 1458 } 1459 } 1460 } 1461 1462 // Calculate the set of virtual registers that must be passed through each basic 1463 // block in order to satisfy the requirements of successor blocks. This is very 1464 // similar to calcRegsPassed, only backwards. 1465 void MachineVerifier::calcRegsRequired() { 1466 // First push live-in regs to predecessors' vregsRequired. 1467 SmallPtrSet<const MachineBasicBlock*, 8> todo; 1468 for (const auto &MBB : *MF) { 1469 BBInfo &MInfo = MBBInfoMap[&MBB]; 1470 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(), 1471 PrE = MBB.pred_end(); PrI != PrE; ++PrI) { 1472 BBInfo &PInfo = MBBInfoMap[*PrI]; 1473 if (PInfo.addRequired(MInfo.vregsLiveIn)) 1474 todo.insert(*PrI); 1475 } 1476 } 1477 1478 // Iteratively push vregsRequired to predecessors. This will converge to the 1479 // same final state regardless of DenseSet iteration order. 1480 while (!todo.empty()) { 1481 const MachineBasicBlock *MBB = *todo.begin(); 1482 todo.erase(MBB); 1483 BBInfo &MInfo = MBBInfoMap[MBB]; 1484 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(), 1485 PrE = MBB->pred_end(); PrI != PrE; ++PrI) { 1486 if (*PrI == MBB) 1487 continue; 1488 BBInfo &SInfo = MBBInfoMap[*PrI]; 1489 if (SInfo.addRequired(MInfo.vregsRequired)) 1490 todo.insert(*PrI); 1491 } 1492 } 1493 } 1494 1495 // Check PHI instructions at the beginning of MBB. It is assumed that 1496 // calcRegsPassed has been run so BBInfo::isLiveOut is valid. 1497 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) { 1498 SmallPtrSet<const MachineBasicBlock*, 8> seen; 1499 for (const auto &BBI : *MBB) { 1500 if (!BBI.isPHI()) 1501 break; 1502 seen.clear(); 1503 1504 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) { 1505 unsigned Reg = BBI.getOperand(i).getReg(); 1506 const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB(); 1507 if (!Pre->isSuccessor(MBB)) 1508 continue; 1509 seen.insert(Pre); 1510 BBInfo &PrInfo = MBBInfoMap[Pre]; 1511 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg)) 1512 report("PHI operand is not live-out from predecessor", 1513 &BBI.getOperand(i), i); 1514 } 1515 1516 // Did we see all predecessors? 1517 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(), 1518 PrE = MBB->pred_end(); PrI != PrE; ++PrI) { 1519 if (!seen.count(*PrI)) { 1520 report("Missing PHI operand", &BBI); 1521 errs() << "BB#" << (*PrI)->getNumber() 1522 << " is a predecessor according to the CFG.\n"; 1523 } 1524 } 1525 } 1526 } 1527 1528 void MachineVerifier::visitMachineFunctionAfter() { 1529 calcRegsPassed(); 1530 1531 for (const auto &MBB : *MF) { 1532 BBInfo &MInfo = MBBInfoMap[&MBB]; 1533 1534 // Skip unreachable MBBs. 1535 if (!MInfo.reachable) 1536 continue; 1537 1538 checkPHIOps(&MBB); 1539 } 1540 1541 // Now check liveness info if available 1542 calcRegsRequired(); 1543 1544 // Check for killed virtual registers that should be live out. 1545 for (const auto &MBB : *MF) { 1546 BBInfo &MInfo = MBBInfoMap[&MBB]; 1547 for (RegSet::iterator 1548 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E; 1549 ++I) 1550 if (MInfo.regsKilled.count(*I)) { 1551 report("Virtual register killed in block, but needed live out.", &MBB); 1552 errs() << "Virtual register " << PrintReg(*I) 1553 << " is used after the block.\n"; 1554 } 1555 } 1556 1557 if (!MF->empty()) { 1558 BBInfo &MInfo = MBBInfoMap[&MF->front()]; 1559 for (RegSet::iterator 1560 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E; 1561 ++I) { 1562 report("Virtual register defs don't dominate all uses.", MF); 1563 report_context_vreg(*I); 1564 } 1565 } 1566 1567 if (LiveVars) 1568 verifyLiveVariables(); 1569 if (LiveInts) 1570 verifyLiveIntervals(); 1571 } 1572 1573 void MachineVerifier::verifyLiveVariables() { 1574 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars"); 1575 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1576 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 1577 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 1578 for (const auto &MBB : *MF) { 1579 BBInfo &MInfo = MBBInfoMap[&MBB]; 1580 1581 // Our vregsRequired should be identical to LiveVariables' AliveBlocks 1582 if (MInfo.vregsRequired.count(Reg)) { 1583 if (!VI.AliveBlocks.test(MBB.getNumber())) { 1584 report("LiveVariables: Block missing from AliveBlocks", &MBB); 1585 errs() << "Virtual register " << PrintReg(Reg) 1586 << " must be live through the block.\n"; 1587 } 1588 } else { 1589 if (VI.AliveBlocks.test(MBB.getNumber())) { 1590 report("LiveVariables: Block should not be in AliveBlocks", &MBB); 1591 errs() << "Virtual register " << PrintReg(Reg) 1592 << " is not needed live through the block.\n"; 1593 } 1594 } 1595 } 1596 } 1597 } 1598 1599 void MachineVerifier::verifyLiveIntervals() { 1600 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts"); 1601 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1602 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 1603 1604 // Spilling and splitting may leave unused registers around. Skip them. 1605 if (MRI->reg_nodbg_empty(Reg)) 1606 continue; 1607 1608 if (!LiveInts->hasInterval(Reg)) { 1609 report("Missing live interval for virtual register", MF); 1610 errs() << PrintReg(Reg, TRI) << " still has defs or uses\n"; 1611 continue; 1612 } 1613 1614 const LiveInterval &LI = LiveInts->getInterval(Reg); 1615 assert(Reg == LI.reg && "Invalid reg to interval mapping"); 1616 verifyLiveInterval(LI); 1617 } 1618 1619 // Verify all the cached regunit intervals. 1620 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 1621 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i)) 1622 verifyLiveRange(*LR, i); 1623 } 1624 1625 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR, 1626 const VNInfo *VNI, unsigned Reg, 1627 LaneBitmask LaneMask) { 1628 if (VNI->isUnused()) 1629 return; 1630 1631 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def); 1632 1633 if (!DefVNI) { 1634 report("Value not live at VNInfo def and not marked unused", MF); 1635 report_context(LR, Reg, LaneMask); 1636 report_context(*VNI); 1637 return; 1638 } 1639 1640 if (DefVNI != VNI) { 1641 report("Live segment at def has different VNInfo", MF); 1642 report_context(LR, Reg, LaneMask); 1643 report_context(*VNI); 1644 return; 1645 } 1646 1647 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def); 1648 if (!MBB) { 1649 report("Invalid VNInfo definition index", MF); 1650 report_context(LR, Reg, LaneMask); 1651 report_context(*VNI); 1652 return; 1653 } 1654 1655 if (VNI->isPHIDef()) { 1656 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) { 1657 report("PHIDef VNInfo is not defined at MBB start", MBB); 1658 report_context(LR, Reg, LaneMask); 1659 report_context(*VNI); 1660 } 1661 return; 1662 } 1663 1664 // Non-PHI def. 1665 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def); 1666 if (!MI) { 1667 report("No instruction at VNInfo def index", MBB); 1668 report_context(LR, Reg, LaneMask); 1669 report_context(*VNI); 1670 return; 1671 } 1672 1673 if (Reg != 0) { 1674 bool hasDef = false; 1675 bool isEarlyClobber = false; 1676 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 1677 if (!MOI->isReg() || !MOI->isDef()) 1678 continue; 1679 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1680 if (MOI->getReg() != Reg) 1681 continue; 1682 } else { 1683 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) || 1684 !TRI->hasRegUnit(MOI->getReg(), Reg)) 1685 continue; 1686 } 1687 if (LaneMask != 0 && 1688 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask) == 0) 1689 continue; 1690 hasDef = true; 1691 if (MOI->isEarlyClobber()) 1692 isEarlyClobber = true; 1693 } 1694 1695 if (!hasDef) { 1696 report("Defining instruction does not modify register", MI); 1697 report_context(LR, Reg, LaneMask); 1698 report_context(*VNI); 1699 } 1700 1701 // Early clobber defs begin at USE slots, but other defs must begin at 1702 // DEF slots. 1703 if (isEarlyClobber) { 1704 if (!VNI->def.isEarlyClobber()) { 1705 report("Early clobber def must be at an early-clobber slot", MBB); 1706 report_context(LR, Reg, LaneMask); 1707 report_context(*VNI); 1708 } 1709 } else if (!VNI->def.isRegister()) { 1710 report("Non-PHI, non-early clobber def must be at a register slot", MBB); 1711 report_context(LR, Reg, LaneMask); 1712 report_context(*VNI); 1713 } 1714 } 1715 } 1716 1717 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR, 1718 const LiveRange::const_iterator I, 1719 unsigned Reg, LaneBitmask LaneMask) 1720 { 1721 const LiveRange::Segment &S = *I; 1722 const VNInfo *VNI = S.valno; 1723 assert(VNI && "Live segment has no valno"); 1724 1725 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) { 1726 report("Foreign valno in live segment", MF); 1727 report_context(LR, Reg, LaneMask); 1728 report_context(S); 1729 report_context(*VNI); 1730 } 1731 1732 if (VNI->isUnused()) { 1733 report("Live segment valno is marked unused", MF); 1734 report_context(LR, Reg, LaneMask); 1735 report_context(S); 1736 } 1737 1738 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start); 1739 if (!MBB) { 1740 report("Bad start of live segment, no basic block", MF); 1741 report_context(LR, Reg, LaneMask); 1742 report_context(S); 1743 return; 1744 } 1745 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB); 1746 if (S.start != MBBStartIdx && S.start != VNI->def) { 1747 report("Live segment must begin at MBB entry or valno def", MBB); 1748 report_context(LR, Reg, LaneMask); 1749 report_context(S); 1750 } 1751 1752 const MachineBasicBlock *EndMBB = 1753 LiveInts->getMBBFromIndex(S.end.getPrevSlot()); 1754 if (!EndMBB) { 1755 report("Bad end of live segment, no basic block", MF); 1756 report_context(LR, Reg, LaneMask); 1757 report_context(S); 1758 return; 1759 } 1760 1761 // No more checks for live-out segments. 1762 if (S.end == LiveInts->getMBBEndIdx(EndMBB)) 1763 return; 1764 1765 // RegUnit intervals are allowed dead phis. 1766 if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() && 1767 S.start == VNI->def && S.end == VNI->def.getDeadSlot()) 1768 return; 1769 1770 // The live segment is ending inside EndMBB 1771 const MachineInstr *MI = 1772 LiveInts->getInstructionFromIndex(S.end.getPrevSlot()); 1773 if (!MI) { 1774 report("Live segment doesn't end at a valid instruction", EndMBB); 1775 report_context(LR, Reg, LaneMask); 1776 report_context(S); 1777 return; 1778 } 1779 1780 // The block slot must refer to a basic block boundary. 1781 if (S.end.isBlock()) { 1782 report("Live segment ends at B slot of an instruction", EndMBB); 1783 report_context(LR, Reg, LaneMask); 1784 report_context(S); 1785 } 1786 1787 if (S.end.isDead()) { 1788 // Segment ends on the dead slot. 1789 // That means there must be a dead def. 1790 if (!SlotIndex::isSameInstr(S.start, S.end)) { 1791 report("Live segment ending at dead slot spans instructions", EndMBB); 1792 report_context(LR, Reg, LaneMask); 1793 report_context(S); 1794 } 1795 } 1796 1797 // A live segment can only end at an early-clobber slot if it is being 1798 // redefined by an early-clobber def. 1799 if (S.end.isEarlyClobber()) { 1800 if (I+1 == LR.end() || (I+1)->start != S.end) { 1801 report("Live segment ending at early clobber slot must be " 1802 "redefined by an EC def in the same instruction", EndMBB); 1803 report_context(LR, Reg, LaneMask); 1804 report_context(S); 1805 } 1806 } 1807 1808 // The following checks only apply to virtual registers. Physreg liveness 1809 // is too weird to check. 1810 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1811 // A live segment can end with either a redefinition, a kill flag on a 1812 // use, or a dead flag on a def. 1813 bool hasRead = false; 1814 bool hasSubRegDef = false; 1815 bool hasDeadDef = false; 1816 LaneBitmask RLM = MRI->getMaxLaneMaskForVReg(Reg); 1817 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 1818 if (!MOI->isReg() || MOI->getReg() != Reg) 1819 continue; 1820 unsigned Sub = MOI->getSubReg(); 1821 LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) : RLM; 1822 if (MOI->isDef()) { 1823 if (Sub != 0) { 1824 hasSubRegDef = true; 1825 // An operand vreg0:sub0<def> reads vreg0:sub1..n. Invert the lane 1826 // mask for subregister defs. Read-undef defs will be handled by 1827 // readsReg below. 1828 SLM = ~SLM & RLM; 1829 } 1830 if (MOI->isDead()) 1831 hasDeadDef = true; 1832 } 1833 if (LaneMask != 0 && !(LaneMask & SLM)) 1834 continue; 1835 if (MOI->readsReg()) 1836 hasRead = true; 1837 } 1838 if (S.end.isDead()) { 1839 // Make sure that the corresponding machine operand for a "dead" live 1840 // range has the dead flag. We cannot perform this check for subregister 1841 // liveranges as partially dead values are allowed. 1842 if (LaneMask == 0 && !hasDeadDef) { 1843 report("Instruction ending live segment on dead slot has no dead flag", 1844 MI); 1845 report_context(LR, Reg, LaneMask); 1846 report_context(S); 1847 } 1848 } else { 1849 if (!hasRead) { 1850 // When tracking subregister liveness, the main range must start new 1851 // values on partial register writes, even if there is no read. 1852 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask != 0 || 1853 !hasSubRegDef) { 1854 report("Instruction ending live segment doesn't read the register", 1855 MI); 1856 report_context(LR, Reg, LaneMask); 1857 report_context(S); 1858 } 1859 } 1860 } 1861 } 1862 1863 // Now check all the basic blocks in this live segment. 1864 MachineFunction::const_iterator MFI = MBB->getIterator(); 1865 // Is this live segment the beginning of a non-PHIDef VN? 1866 if (S.start == VNI->def && !VNI->isPHIDef()) { 1867 // Not live-in to any blocks. 1868 if (MBB == EndMBB) 1869 return; 1870 // Skip this block. 1871 ++MFI; 1872 } 1873 for (;;) { 1874 assert(LiveInts->isLiveInToMBB(LR, &*MFI)); 1875 // We don't know how to track physregs into a landing pad. 1876 if (!TargetRegisterInfo::isVirtualRegister(Reg) && 1877 MFI->isEHPad()) { 1878 if (&*MFI == EndMBB) 1879 break; 1880 ++MFI; 1881 continue; 1882 } 1883 1884 // Is VNI a PHI-def in the current block? 1885 bool IsPHI = VNI->isPHIDef() && 1886 VNI->def == LiveInts->getMBBStartIdx(&*MFI); 1887 1888 // Check that VNI is live-out of all predecessors. 1889 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(), 1890 PE = MFI->pred_end(); PI != PE; ++PI) { 1891 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI); 1892 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd); 1893 1894 // All predecessors must have a live-out value if this is not a 1895 // subregister liverange. 1896 if (!PVNI && LaneMask == 0) { 1897 report("Register not marked live out of predecessor", *PI); 1898 report_context(LR, Reg, LaneMask); 1899 report_context(*VNI); 1900 errs() << " live into BB#" << MFI->getNumber() 1901 << '@' << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " 1902 << PEnd << '\n'; 1903 continue; 1904 } 1905 1906 // Only PHI-defs can take different predecessor values. 1907 if (!IsPHI && PVNI != VNI) { 1908 report("Different value live out of predecessor", *PI); 1909 report_context(LR, Reg, LaneMask); 1910 errs() << "Valno #" << PVNI->id << " live out of BB#" 1911 << (*PI)->getNumber() << '@' << PEnd << "\nValno #" << VNI->id 1912 << " live into BB#" << MFI->getNumber() << '@' 1913 << LiveInts->getMBBStartIdx(&*MFI) << '\n'; 1914 } 1915 } 1916 if (&*MFI == EndMBB) 1917 break; 1918 ++MFI; 1919 } 1920 } 1921 1922 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg, 1923 LaneBitmask LaneMask) { 1924 for (const VNInfo *VNI : LR.valnos) 1925 verifyLiveRangeValue(LR, VNI, Reg, LaneMask); 1926 1927 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I) 1928 verifyLiveRangeSegment(LR, I, Reg, LaneMask); 1929 } 1930 1931 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) { 1932 unsigned Reg = LI.reg; 1933 assert(TargetRegisterInfo::isVirtualRegister(Reg)); 1934 verifyLiveRange(LI, Reg); 1935 1936 LaneBitmask Mask = 0; 1937 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 1938 for (const LiveInterval::SubRange &SR : LI.subranges()) { 1939 if ((Mask & SR.LaneMask) != 0) { 1940 report("Lane masks of sub ranges overlap in live interval", MF); 1941 report_context(LI); 1942 } 1943 if ((SR.LaneMask & ~MaxMask) != 0) { 1944 report("Subrange lanemask is invalid", MF); 1945 report_context(LI); 1946 } 1947 if (SR.empty()) { 1948 report("Subrange must not be empty", MF); 1949 report_context(SR, LI.reg, SR.LaneMask); 1950 } 1951 Mask |= SR.LaneMask; 1952 verifyLiveRange(SR, LI.reg, SR.LaneMask); 1953 if (!LI.covers(SR)) { 1954 report("A Subrange is not covered by the main range", MF); 1955 report_context(LI); 1956 } 1957 } 1958 1959 // Check the LI only has one connected component. 1960 ConnectedVNInfoEqClasses ConEQ(*LiveInts); 1961 unsigned NumComp = ConEQ.Classify(LI); 1962 if (NumComp > 1) { 1963 report("Multiple connected components in live interval", MF); 1964 report_context(LI); 1965 for (unsigned comp = 0; comp != NumComp; ++comp) { 1966 errs() << comp << ": valnos"; 1967 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), 1968 E = LI.vni_end(); I!=E; ++I) 1969 if (comp == ConEQ.getEqClass(*I)) 1970 errs() << ' ' << (*I)->id; 1971 errs() << '\n'; 1972 } 1973 } 1974 } 1975 1976 namespace { 1977 // FrameSetup and FrameDestroy can have zero adjustment, so using a single 1978 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the 1979 // value is zero. 1980 // We use a bool plus an integer to capture the stack state. 1981 struct StackStateOfBB { 1982 StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false), 1983 ExitIsSetup(false) { } 1984 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) : 1985 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup), 1986 ExitIsSetup(ExitSetup) { } 1987 // Can be negative, which means we are setting up a frame. 1988 int EntryValue; 1989 int ExitValue; 1990 bool EntryIsSetup; 1991 bool ExitIsSetup; 1992 }; 1993 } 1994 1995 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed 1996 /// by a FrameDestroy <n>, stack adjustments are identical on all 1997 /// CFG edges to a merge point, and frame is destroyed at end of a return block. 1998 void MachineVerifier::verifyStackFrame() { 1999 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 2000 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 2001 2002 SmallVector<StackStateOfBB, 8> SPState; 2003 SPState.resize(MF->getNumBlockIDs()); 2004 SmallPtrSet<const MachineBasicBlock*, 8> Reachable; 2005 2006 // Visit the MBBs in DFS order. 2007 for (df_ext_iterator<const MachineFunction*, 2008 SmallPtrSet<const MachineBasicBlock*, 8> > 2009 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable); 2010 DFI != DFE; ++DFI) { 2011 const MachineBasicBlock *MBB = *DFI; 2012 2013 StackStateOfBB BBState; 2014 // Check the exit state of the DFS stack predecessor. 2015 if (DFI.getPathLength() >= 2) { 2016 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 2017 assert(Reachable.count(StackPred) && 2018 "DFS stack predecessor is already visited.\n"); 2019 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue; 2020 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup; 2021 BBState.ExitValue = BBState.EntryValue; 2022 BBState.ExitIsSetup = BBState.EntryIsSetup; 2023 } 2024 2025 // Update stack state by checking contents of MBB. 2026 for (const auto &I : *MBB) { 2027 if (I.getOpcode() == FrameSetupOpcode) { 2028 // The first operand of a FrameOpcode should be i32. 2029 int Size = I.getOperand(0).getImm(); 2030 assert(Size >= 0 && 2031 "Value should be non-negative in FrameSetup and FrameDestroy.\n"); 2032 2033 if (BBState.ExitIsSetup) 2034 report("FrameSetup is after another FrameSetup", &I); 2035 BBState.ExitValue -= Size; 2036 BBState.ExitIsSetup = true; 2037 } 2038 2039 if (I.getOpcode() == FrameDestroyOpcode) { 2040 // The first operand of a FrameOpcode should be i32. 2041 int Size = I.getOperand(0).getImm(); 2042 assert(Size >= 0 && 2043 "Value should be non-negative in FrameSetup and FrameDestroy.\n"); 2044 2045 if (!BBState.ExitIsSetup) 2046 report("FrameDestroy is not after a FrameSetup", &I); 2047 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue : 2048 BBState.ExitValue; 2049 if (BBState.ExitIsSetup && AbsSPAdj != Size) { 2050 report("FrameDestroy <n> is after FrameSetup <m>", &I); 2051 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <" 2052 << AbsSPAdj << ">.\n"; 2053 } 2054 BBState.ExitValue += Size; 2055 BBState.ExitIsSetup = false; 2056 } 2057 } 2058 SPState[MBB->getNumber()] = BBState; 2059 2060 // Make sure the exit state of any predecessor is consistent with the entry 2061 // state. 2062 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(), 2063 E = MBB->pred_end(); I != E; ++I) { 2064 if (Reachable.count(*I) && 2065 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue || 2066 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) { 2067 report("The exit stack state of a predecessor is inconsistent.", MBB); 2068 errs() << "Predecessor BB#" << (*I)->getNumber() << " has exit state (" 2069 << SPState[(*I)->getNumber()].ExitValue << ", " 2070 << SPState[(*I)->getNumber()].ExitIsSetup 2071 << "), while BB#" << MBB->getNumber() << " has entry state (" 2072 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n"; 2073 } 2074 } 2075 2076 // Make sure the entry state of any successor is consistent with the exit 2077 // state. 2078 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(), 2079 E = MBB->succ_end(); I != E; ++I) { 2080 if (Reachable.count(*I) && 2081 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue || 2082 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) { 2083 report("The entry stack state of a successor is inconsistent.", MBB); 2084 errs() << "Successor BB#" << (*I)->getNumber() << " has entry state (" 2085 << SPState[(*I)->getNumber()].EntryValue << ", " 2086 << SPState[(*I)->getNumber()].EntryIsSetup 2087 << "), while BB#" << MBB->getNumber() << " has exit state (" 2088 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n"; 2089 } 2090 } 2091 2092 // Make sure a basic block with return ends with zero stack adjustment. 2093 if (!MBB->empty() && MBB->back().isReturn()) { 2094 if (BBState.ExitIsSetup) 2095 report("A return block ends with a FrameSetup.", MBB); 2096 if (BBState.ExitValue) 2097 report("A return block ends with a nonzero stack adjustment.", MBB); 2098 } 2099 } 2100 } 2101