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