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