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