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