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