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