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_ASSERT_SEXT: 971 case TargetOpcode::G_ASSERT_ZEXT: { 972 std::string OpcName = 973 Opc == TargetOpcode::G_ASSERT_ZEXT ? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT"; 974 if (!MI->getOperand(2).isImm()) { 975 report(Twine(OpcName, " expects an immediate operand #2"), MI); 976 break; 977 } 978 979 Register Dst = MI->getOperand(0).getReg(); 980 Register Src = MI->getOperand(1).getReg(); 981 LLT SrcTy = MRI->getType(Src); 982 int64_t Imm = MI->getOperand(2).getImm(); 983 if (Imm <= 0) { 984 report(Twine(OpcName, " size must be >= 1"), MI); 985 break; 986 } 987 988 if (Imm >= SrcTy.getScalarSizeInBits()) { 989 report(Twine(OpcName, " size must be less than source bit width"), MI); 990 break; 991 } 992 993 if (MRI->getRegBankOrNull(Src) != MRI->getRegBankOrNull(Dst)) { 994 report( 995 Twine(OpcName, " source and destination register banks must match"), 996 MI); 997 break; 998 } 999 1000 if (MRI->getRegClassOrNull(Src) != MRI->getRegClassOrNull(Dst)) 1001 report( 1002 Twine(OpcName, " source and destination register classes must match"), 1003 MI); 1004 1005 break; 1006 } 1007 1008 case TargetOpcode::G_CONSTANT: 1009 case TargetOpcode::G_FCONSTANT: { 1010 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1011 if (DstTy.isVector()) 1012 report("Instruction cannot use a vector result type", MI); 1013 1014 if (MI->getOpcode() == TargetOpcode::G_CONSTANT) { 1015 if (!MI->getOperand(1).isCImm()) { 1016 report("G_CONSTANT operand must be cimm", MI); 1017 break; 1018 } 1019 1020 const ConstantInt *CI = MI->getOperand(1).getCImm(); 1021 if (CI->getBitWidth() != DstTy.getSizeInBits()) 1022 report("inconsistent constant size", MI); 1023 } else { 1024 if (!MI->getOperand(1).isFPImm()) { 1025 report("G_FCONSTANT operand must be fpimm", MI); 1026 break; 1027 } 1028 const ConstantFP *CF = MI->getOperand(1).getFPImm(); 1029 1030 if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) != 1031 DstTy.getSizeInBits()) { 1032 report("inconsistent constant size", MI); 1033 } 1034 } 1035 1036 break; 1037 } 1038 case TargetOpcode::G_LOAD: 1039 case TargetOpcode::G_STORE: 1040 case TargetOpcode::G_ZEXTLOAD: 1041 case TargetOpcode::G_SEXTLOAD: { 1042 LLT ValTy = MRI->getType(MI->getOperand(0).getReg()); 1043 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg()); 1044 if (!PtrTy.isPointer()) 1045 report("Generic memory instruction must access a pointer", MI); 1046 1047 // Generic loads and stores must have a single MachineMemOperand 1048 // describing that access. 1049 if (!MI->hasOneMemOperand()) { 1050 report("Generic instruction accessing memory must have one mem operand", 1051 MI); 1052 } else { 1053 const MachineMemOperand &MMO = **MI->memoperands_begin(); 1054 if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD || 1055 MI->getOpcode() == TargetOpcode::G_SEXTLOAD) { 1056 if (MMO.getSizeInBits() >= ValTy.getSizeInBits()) 1057 report("Generic extload must have a narrower memory type", MI); 1058 } else if (MI->getOpcode() == TargetOpcode::G_LOAD) { 1059 if (MMO.getSize() > ValTy.getSizeInBytes()) 1060 report("load memory size cannot exceed result size", MI); 1061 } else if (MI->getOpcode() == TargetOpcode::G_STORE) { 1062 if (ValTy.getSizeInBytes() < MMO.getSize()) 1063 report("store memory size cannot exceed value size", MI); 1064 } 1065 } 1066 1067 break; 1068 } 1069 case TargetOpcode::G_PHI: { 1070 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1071 if (!DstTy.isValid() || !all_of(drop_begin(MI->operands()), 1072 [this, &DstTy](const MachineOperand &MO) { 1073 if (!MO.isReg()) 1074 return true; 1075 LLT Ty = MRI->getType(MO.getReg()); 1076 if (!Ty.isValid() || (Ty != DstTy)) 1077 return false; 1078 return true; 1079 })) 1080 report("Generic Instruction G_PHI has operands with incompatible/missing " 1081 "types", 1082 MI); 1083 break; 1084 } 1085 case TargetOpcode::G_BITCAST: { 1086 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1087 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1088 if (!DstTy.isValid() || !SrcTy.isValid()) 1089 break; 1090 1091 if (SrcTy.isPointer() != DstTy.isPointer()) 1092 report("bitcast cannot convert between pointers and other types", MI); 1093 1094 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits()) 1095 report("bitcast sizes must match", MI); 1096 1097 if (SrcTy == DstTy) 1098 report("bitcast must change the type", MI); 1099 1100 break; 1101 } 1102 case TargetOpcode::G_INTTOPTR: 1103 case TargetOpcode::G_PTRTOINT: 1104 case TargetOpcode::G_ADDRSPACE_CAST: { 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 verifyVectorElementMatch(DstTy, SrcTy, MI); 1111 1112 DstTy = DstTy.getScalarType(); 1113 SrcTy = SrcTy.getScalarType(); 1114 1115 if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) { 1116 if (!DstTy.isPointer()) 1117 report("inttoptr result type must be a pointer", MI); 1118 if (SrcTy.isPointer()) 1119 report("inttoptr source type must not be a pointer", MI); 1120 } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) { 1121 if (!SrcTy.isPointer()) 1122 report("ptrtoint source type must be a pointer", MI); 1123 if (DstTy.isPointer()) 1124 report("ptrtoint result type must not be a pointer", MI); 1125 } else { 1126 assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST); 1127 if (!SrcTy.isPointer() || !DstTy.isPointer()) 1128 report("addrspacecast types must be pointers", MI); 1129 else { 1130 if (SrcTy.getAddressSpace() == DstTy.getAddressSpace()) 1131 report("addrspacecast must convert different address spaces", MI); 1132 } 1133 } 1134 1135 break; 1136 } 1137 case TargetOpcode::G_PTR_ADD: { 1138 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1139 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg()); 1140 LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg()); 1141 if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid()) 1142 break; 1143 1144 if (!PtrTy.getScalarType().isPointer()) 1145 report("gep first operand must be a pointer", MI); 1146 1147 if (OffsetTy.getScalarType().isPointer()) 1148 report("gep offset operand must not be a pointer", MI); 1149 1150 // TODO: Is the offset allowed to be a scalar with a vector? 1151 break; 1152 } 1153 case TargetOpcode::G_PTRMASK: { 1154 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1155 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1156 LLT MaskTy = MRI->getType(MI->getOperand(2).getReg()); 1157 if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid()) 1158 break; 1159 1160 if (!DstTy.getScalarType().isPointer()) 1161 report("ptrmask result type must be a pointer", MI); 1162 1163 if (!MaskTy.getScalarType().isScalar()) 1164 report("ptrmask mask type must be an integer", MI); 1165 1166 verifyVectorElementMatch(DstTy, MaskTy, MI); 1167 break; 1168 } 1169 case TargetOpcode::G_SEXT: 1170 case TargetOpcode::G_ZEXT: 1171 case TargetOpcode::G_ANYEXT: 1172 case TargetOpcode::G_TRUNC: 1173 case TargetOpcode::G_FPEXT: 1174 case TargetOpcode::G_FPTRUNC: { 1175 // Number of operands and presense of types is already checked (and 1176 // reported in case of any issues), so no need to report them again. As 1177 // we're trying to report as many issues as possible at once, however, the 1178 // instructions aren't guaranteed to have the right number of operands or 1179 // types attached to them at this point 1180 assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}"); 1181 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1182 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1183 if (!DstTy.isValid() || !SrcTy.isValid()) 1184 break; 1185 1186 LLT DstElTy = DstTy.getScalarType(); 1187 LLT SrcElTy = SrcTy.getScalarType(); 1188 if (DstElTy.isPointer() || SrcElTy.isPointer()) 1189 report("Generic extend/truncate can not operate on pointers", MI); 1190 1191 verifyVectorElementMatch(DstTy, SrcTy, MI); 1192 1193 unsigned DstSize = DstElTy.getSizeInBits(); 1194 unsigned SrcSize = SrcElTy.getSizeInBits(); 1195 switch (MI->getOpcode()) { 1196 default: 1197 if (DstSize <= SrcSize) 1198 report("Generic extend has destination type no larger than source", MI); 1199 break; 1200 case TargetOpcode::G_TRUNC: 1201 case TargetOpcode::G_FPTRUNC: 1202 if (DstSize >= SrcSize) 1203 report("Generic truncate has destination type no smaller than source", 1204 MI); 1205 break; 1206 } 1207 break; 1208 } 1209 case TargetOpcode::G_SELECT: { 1210 LLT SelTy = MRI->getType(MI->getOperand(0).getReg()); 1211 LLT CondTy = MRI->getType(MI->getOperand(1).getReg()); 1212 if (!SelTy.isValid() || !CondTy.isValid()) 1213 break; 1214 1215 // Scalar condition select on a vector is valid. 1216 if (CondTy.isVector()) 1217 verifyVectorElementMatch(SelTy, CondTy, MI); 1218 break; 1219 } 1220 case TargetOpcode::G_MERGE_VALUES: { 1221 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar, 1222 // e.g. s2N = MERGE sN, sN 1223 // Merging multiple scalars into a vector is not allowed, should use 1224 // G_BUILD_VECTOR for that. 1225 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1226 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1227 if (DstTy.isVector() || SrcTy.isVector()) 1228 report("G_MERGE_VALUES cannot operate on vectors", MI); 1229 1230 const unsigned NumOps = MI->getNumOperands(); 1231 if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1)) 1232 report("G_MERGE_VALUES result size is inconsistent", MI); 1233 1234 for (unsigned I = 2; I != NumOps; ++I) { 1235 if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy) 1236 report("G_MERGE_VALUES source types do not match", MI); 1237 } 1238 1239 break; 1240 } 1241 case TargetOpcode::G_UNMERGE_VALUES: { 1242 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1243 LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg()); 1244 // For now G_UNMERGE can split vectors. 1245 for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) { 1246 if (MRI->getType(MI->getOperand(i).getReg()) != DstTy) 1247 report("G_UNMERGE_VALUES destination types do not match", MI); 1248 } 1249 if (SrcTy.getSizeInBits() != 1250 (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) { 1251 report("G_UNMERGE_VALUES source operand does not cover dest operands", 1252 MI); 1253 } 1254 break; 1255 } 1256 case TargetOpcode::G_BUILD_VECTOR: { 1257 // Source types must be scalars, dest type a vector. Total size of scalars 1258 // must match the dest vector size. 1259 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1260 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg()); 1261 if (!DstTy.isVector() || SrcEltTy.isVector()) { 1262 report("G_BUILD_VECTOR must produce a vector from scalar operands", MI); 1263 break; 1264 } 1265 1266 if (DstTy.getElementType() != SrcEltTy) 1267 report("G_BUILD_VECTOR result element type must match source type", MI); 1268 1269 if (DstTy.getNumElements() != MI->getNumOperands() - 1) 1270 report("G_BUILD_VECTOR must have an operand for each elemement", MI); 1271 1272 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1273 if (MRI->getType(MI->getOperand(1).getReg()) != 1274 MRI->getType(MI->getOperand(i).getReg())) 1275 report("G_BUILD_VECTOR source operand types are not homogeneous", MI); 1276 } 1277 1278 break; 1279 } 1280 case TargetOpcode::G_BUILD_VECTOR_TRUNC: { 1281 // Source types must be scalars, dest type a vector. Scalar types must be 1282 // larger than the dest vector elt type, as this is a truncating operation. 1283 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1284 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg()); 1285 if (!DstTy.isVector() || SrcEltTy.isVector()) 1286 report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands", 1287 MI); 1288 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1289 if (MRI->getType(MI->getOperand(1).getReg()) != 1290 MRI->getType(MI->getOperand(i).getReg())) 1291 report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous", 1292 MI); 1293 } 1294 if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits()) 1295 report("G_BUILD_VECTOR_TRUNC source operand types are not larger than " 1296 "dest elt type", 1297 MI); 1298 break; 1299 } 1300 case TargetOpcode::G_CONCAT_VECTORS: { 1301 // Source types should be vectors, and total size should match the dest 1302 // vector size. 1303 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1304 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1305 if (!DstTy.isVector() || !SrcTy.isVector()) 1306 report("G_CONCAT_VECTOR requires vector source and destination operands", 1307 MI); 1308 1309 if (MI->getNumOperands() < 3) 1310 report("G_CONCAT_VECTOR requires at least 2 source operands", MI); 1311 1312 for (unsigned i = 2; i < MI->getNumOperands(); ++i) { 1313 if (MRI->getType(MI->getOperand(1).getReg()) != 1314 MRI->getType(MI->getOperand(i).getReg())) 1315 report("G_CONCAT_VECTOR source operand types are not homogeneous", MI); 1316 } 1317 if (DstTy.getNumElements() != 1318 SrcTy.getNumElements() * (MI->getNumOperands() - 1)) 1319 report("G_CONCAT_VECTOR num dest and source elements should match", MI); 1320 break; 1321 } 1322 case TargetOpcode::G_ICMP: 1323 case TargetOpcode::G_FCMP: { 1324 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1325 LLT SrcTy = MRI->getType(MI->getOperand(2).getReg()); 1326 1327 if ((DstTy.isVector() != SrcTy.isVector()) || 1328 (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements())) 1329 report("Generic vector icmp/fcmp must preserve number of lanes", MI); 1330 1331 break; 1332 } 1333 case TargetOpcode::G_EXTRACT: { 1334 const MachineOperand &SrcOp = MI->getOperand(1); 1335 if (!SrcOp.isReg()) { 1336 report("extract source must be a register", MI); 1337 break; 1338 } 1339 1340 const MachineOperand &OffsetOp = MI->getOperand(2); 1341 if (!OffsetOp.isImm()) { 1342 report("extract offset must be a constant", MI); 1343 break; 1344 } 1345 1346 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits(); 1347 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits(); 1348 if (SrcSize == DstSize) 1349 report("extract source must be larger than result", MI); 1350 1351 if (DstSize + OffsetOp.getImm() > SrcSize) 1352 report("extract reads past end of register", MI); 1353 break; 1354 } 1355 case TargetOpcode::G_INSERT: { 1356 const MachineOperand &SrcOp = MI->getOperand(2); 1357 if (!SrcOp.isReg()) { 1358 report("insert source must be a register", MI); 1359 break; 1360 } 1361 1362 const MachineOperand &OffsetOp = MI->getOperand(3); 1363 if (!OffsetOp.isImm()) { 1364 report("insert offset must be a constant", MI); 1365 break; 1366 } 1367 1368 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits(); 1369 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits(); 1370 1371 if (DstSize <= SrcSize) 1372 report("inserted size must be smaller than total register", MI); 1373 1374 if (SrcSize + OffsetOp.getImm() > DstSize) 1375 report("insert writes past end of register", MI); 1376 1377 break; 1378 } 1379 case TargetOpcode::G_JUMP_TABLE: { 1380 if (!MI->getOperand(1).isJTI()) 1381 report("G_JUMP_TABLE source operand must be a jump table index", MI); 1382 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1383 if (!DstTy.isPointer()) 1384 report("G_JUMP_TABLE dest operand must have a pointer type", MI); 1385 break; 1386 } 1387 case TargetOpcode::G_BRJT: { 1388 if (!MRI->getType(MI->getOperand(0).getReg()).isPointer()) 1389 report("G_BRJT src operand 0 must be a pointer type", MI); 1390 1391 if (!MI->getOperand(1).isJTI()) 1392 report("G_BRJT src operand 1 must be a jump table index", MI); 1393 1394 const auto &IdxOp = MI->getOperand(2); 1395 if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer()) 1396 report("G_BRJT src operand 2 must be a scalar reg type", MI); 1397 break; 1398 } 1399 case TargetOpcode::G_INTRINSIC: 1400 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS: { 1401 // TODO: Should verify number of def and use operands, but the current 1402 // interface requires passing in IR types for mangling. 1403 const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs()); 1404 if (!IntrIDOp.isIntrinsicID()) { 1405 report("G_INTRINSIC first src operand must be an intrinsic ID", MI); 1406 break; 1407 } 1408 1409 bool NoSideEffects = MI->getOpcode() == TargetOpcode::G_INTRINSIC; 1410 unsigned IntrID = IntrIDOp.getIntrinsicID(); 1411 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) { 1412 AttributeList Attrs 1413 = Intrinsic::getAttributes(MF->getFunction().getContext(), 1414 static_cast<Intrinsic::ID>(IntrID)); 1415 bool DeclHasSideEffects = !Attrs.hasFnAttr(Attribute::ReadNone); 1416 if (NoSideEffects && DeclHasSideEffects) { 1417 report("G_INTRINSIC used with intrinsic that accesses memory", MI); 1418 break; 1419 } 1420 if (!NoSideEffects && !DeclHasSideEffects) { 1421 report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI); 1422 break; 1423 } 1424 } 1425 1426 break; 1427 } 1428 case TargetOpcode::G_SEXT_INREG: { 1429 if (!MI->getOperand(2).isImm()) { 1430 report("G_SEXT_INREG expects an immediate operand #2", MI); 1431 break; 1432 } 1433 1434 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg()); 1435 int64_t Imm = MI->getOperand(2).getImm(); 1436 if (Imm <= 0) 1437 report("G_SEXT_INREG size must be >= 1", MI); 1438 if (Imm >= SrcTy.getScalarSizeInBits()) 1439 report("G_SEXT_INREG size must be less than source bit width", MI); 1440 break; 1441 } 1442 case TargetOpcode::G_SHUFFLE_VECTOR: { 1443 const MachineOperand &MaskOp = MI->getOperand(3); 1444 if (!MaskOp.isShuffleMask()) { 1445 report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI); 1446 break; 1447 } 1448 1449 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1450 LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg()); 1451 LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg()); 1452 1453 if (Src0Ty != Src1Ty) 1454 report("Source operands must be the same type", MI); 1455 1456 if (Src0Ty.getScalarType() != DstTy.getScalarType()) 1457 report("G_SHUFFLE_VECTOR cannot change element type", MI); 1458 1459 // Don't check that all operands are vector because scalars are used in 1460 // place of 1 element vectors. 1461 int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1; 1462 int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1; 1463 1464 ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask(); 1465 1466 if (static_cast<int>(MaskIdxes.size()) != DstNumElts) 1467 report("Wrong result type for shufflemask", MI); 1468 1469 for (int Idx : MaskIdxes) { 1470 if (Idx < 0) 1471 continue; 1472 1473 if (Idx >= 2 * SrcNumElts) 1474 report("Out of bounds shuffle index", MI); 1475 } 1476 1477 break; 1478 } 1479 case TargetOpcode::G_DYN_STACKALLOC: { 1480 const MachineOperand &DstOp = MI->getOperand(0); 1481 const MachineOperand &AllocOp = MI->getOperand(1); 1482 const MachineOperand &AlignOp = MI->getOperand(2); 1483 1484 if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) { 1485 report("dst operand 0 must be a pointer type", MI); 1486 break; 1487 } 1488 1489 if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) { 1490 report("src operand 1 must be a scalar reg type", MI); 1491 break; 1492 } 1493 1494 if (!AlignOp.isImm()) { 1495 report("src operand 2 must be an immediate type", MI); 1496 break; 1497 } 1498 break; 1499 } 1500 case TargetOpcode::G_MEMCPY_INLINE: 1501 case TargetOpcode::G_MEMCPY: 1502 case TargetOpcode::G_MEMMOVE: { 1503 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands(); 1504 if (MMOs.size() != 2) { 1505 report("memcpy/memmove must have 2 memory operands", MI); 1506 break; 1507 } 1508 1509 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) || 1510 (MMOs[1]->isStore() || !MMOs[1]->isLoad())) { 1511 report("wrong memory operand types", MI); 1512 break; 1513 } 1514 1515 if (MMOs[0]->getSize() != MMOs[1]->getSize()) 1516 report("inconsistent memory operand sizes", MI); 1517 1518 LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg()); 1519 LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg()); 1520 1521 if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) { 1522 report("memory instruction operand must be a pointer", MI); 1523 break; 1524 } 1525 1526 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace()) 1527 report("inconsistent store address space", MI); 1528 if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace()) 1529 report("inconsistent load address space", MI); 1530 1531 if (Opc != TargetOpcode::G_MEMCPY_INLINE) 1532 if (!MI->getOperand(3).isImm() || (MI->getOperand(3).getImm() & ~1LL)) 1533 report("'tail' flag (operand 3) must be an immediate 0 or 1", MI); 1534 1535 break; 1536 } 1537 case TargetOpcode::G_BZERO: 1538 case TargetOpcode::G_MEMSET: { 1539 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands(); 1540 std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset" : "bzero"; 1541 if (MMOs.size() != 1) { 1542 report(Twine(Name, " must have 1 memory operand"), MI); 1543 break; 1544 } 1545 1546 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) { 1547 report(Twine(Name, " memory operand must be a store"), MI); 1548 break; 1549 } 1550 1551 LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg()); 1552 if (!DstPtrTy.isPointer()) { 1553 report(Twine(Name, " operand must be a pointer"), MI); 1554 break; 1555 } 1556 1557 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace()) 1558 report("inconsistent " + Twine(Name, " address space"), MI); 1559 1560 if (!MI->getOperand(MI->getNumOperands() - 1).isImm() || 1561 (MI->getOperand(MI->getNumOperands() - 1).getImm() & ~1LL)) 1562 report("'tail' flag (last operand) must be an immediate 0 or 1", MI); 1563 1564 break; 1565 } 1566 case TargetOpcode::G_VECREDUCE_SEQ_FADD: 1567 case TargetOpcode::G_VECREDUCE_SEQ_FMUL: { 1568 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1569 LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg()); 1570 LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg()); 1571 if (!DstTy.isScalar()) 1572 report("Vector reduction requires a scalar destination type", MI); 1573 if (!Src1Ty.isScalar()) 1574 report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI); 1575 if (!Src2Ty.isVector()) 1576 report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI); 1577 break; 1578 } 1579 case TargetOpcode::G_VECREDUCE_FADD: 1580 case TargetOpcode::G_VECREDUCE_FMUL: 1581 case TargetOpcode::G_VECREDUCE_FMAX: 1582 case TargetOpcode::G_VECREDUCE_FMIN: 1583 case TargetOpcode::G_VECREDUCE_ADD: 1584 case TargetOpcode::G_VECREDUCE_MUL: 1585 case TargetOpcode::G_VECREDUCE_AND: 1586 case TargetOpcode::G_VECREDUCE_OR: 1587 case TargetOpcode::G_VECREDUCE_XOR: 1588 case TargetOpcode::G_VECREDUCE_SMAX: 1589 case TargetOpcode::G_VECREDUCE_SMIN: 1590 case TargetOpcode::G_VECREDUCE_UMAX: 1591 case TargetOpcode::G_VECREDUCE_UMIN: { 1592 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1593 if (!DstTy.isScalar()) 1594 report("Vector reduction requires a scalar destination type", MI); 1595 break; 1596 } 1597 1598 case TargetOpcode::G_SBFX: 1599 case TargetOpcode::G_UBFX: { 1600 LLT DstTy = MRI->getType(MI->getOperand(0).getReg()); 1601 if (DstTy.isVector()) { 1602 report("Bitfield extraction is not supported on vectors", MI); 1603 break; 1604 } 1605 break; 1606 } 1607 case TargetOpcode::G_ROTR: 1608 case TargetOpcode::G_ROTL: { 1609 LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg()); 1610 LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg()); 1611 if (Src1Ty.isVector() != Src2Ty.isVector()) { 1612 report("Rotate requires operands to be either all scalars or all vectors", 1613 MI); 1614 break; 1615 } 1616 break; 1617 } 1618 case TargetOpcode::G_LLROUND: 1619 case TargetOpcode::G_LROUND: { 1620 verifyAllRegOpsScalar(*MI, *MRI); 1621 break; 1622 } 1623 default: 1624 break; 1625 } 1626 } 1627 1628 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) { 1629 const MCInstrDesc &MCID = MI->getDesc(); 1630 if (MI->getNumOperands() < MCID.getNumOperands()) { 1631 report("Too few operands", MI); 1632 errs() << MCID.getNumOperands() << " operands expected, but " 1633 << MI->getNumOperands() << " given.\n"; 1634 } 1635 1636 if (MI->isPHI()) { 1637 if (MF->getProperties().hasProperty( 1638 MachineFunctionProperties::Property::NoPHIs)) 1639 report("Found PHI instruction with NoPHIs property set", MI); 1640 1641 if (FirstNonPHI) 1642 report("Found PHI instruction after non-PHI", MI); 1643 } else if (FirstNonPHI == nullptr) 1644 FirstNonPHI = MI; 1645 1646 // Check the tied operands. 1647 if (MI->isInlineAsm()) 1648 verifyInlineAsm(MI); 1649 1650 // Check that unspillable terminators define a reg and have at most one use. 1651 if (TII->isUnspillableTerminator(MI)) { 1652 if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef()) 1653 report("Unspillable Terminator does not define a reg", MI); 1654 Register Def = MI->getOperand(0).getReg(); 1655 if (Def.isVirtual() && 1656 !MF->getProperties().hasProperty( 1657 MachineFunctionProperties::Property::NoPHIs) && 1658 std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1) 1659 report("Unspillable Terminator expected to have at most one use!", MI); 1660 } 1661 1662 // A fully-formed DBG_VALUE must have a location. Ignore partially formed 1663 // DBG_VALUEs: these are convenient to use in tests, but should never get 1664 // generated. 1665 if (MI->isDebugValue() && MI->getNumOperands() == 4) 1666 if (!MI->getDebugLoc()) 1667 report("Missing DebugLoc for debug instruction", MI); 1668 1669 // Meta instructions should never be the subject of debug value tracking, 1670 // they don't create a value in the output program at all. 1671 if (MI->isMetaInstruction() && MI->peekDebugInstrNum()) 1672 report("Metadata instruction should not have a value tracking number", MI); 1673 1674 // Check the MachineMemOperands for basic consistency. 1675 for (MachineMemOperand *Op : MI->memoperands()) { 1676 if (Op->isLoad() && !MI->mayLoad()) 1677 report("Missing mayLoad flag", MI); 1678 if (Op->isStore() && !MI->mayStore()) 1679 report("Missing mayStore flag", MI); 1680 } 1681 1682 // Debug values must not have a slot index. 1683 // Other instructions must have one, unless they are inside a bundle. 1684 if (LiveInts) { 1685 bool mapped = !LiveInts->isNotInMIMap(*MI); 1686 if (MI->isDebugOrPseudoInstr()) { 1687 if (mapped) 1688 report("Debug instruction has a slot index", MI); 1689 } else if (MI->isInsideBundle()) { 1690 if (mapped) 1691 report("Instruction inside bundle has a slot index", MI); 1692 } else { 1693 if (!mapped) 1694 report("Missing slot index", MI); 1695 } 1696 } 1697 1698 unsigned Opc = MCID.getOpcode(); 1699 if (isPreISelGenericOpcode(Opc) || isPreISelGenericOptimizationHint(Opc)) { 1700 verifyPreISelGenericInstruction(MI); 1701 return; 1702 } 1703 1704 StringRef ErrorInfo; 1705 if (!TII->verifyInstruction(*MI, ErrorInfo)) 1706 report(ErrorInfo.data(), MI); 1707 1708 // Verify properties of various specific instruction types 1709 switch (MI->getOpcode()) { 1710 case TargetOpcode::COPY: { 1711 const MachineOperand &DstOp = MI->getOperand(0); 1712 const MachineOperand &SrcOp = MI->getOperand(1); 1713 const Register SrcReg = SrcOp.getReg(); 1714 const Register DstReg = DstOp.getReg(); 1715 1716 LLT DstTy = MRI->getType(DstReg); 1717 LLT SrcTy = MRI->getType(SrcReg); 1718 if (SrcTy.isValid() && DstTy.isValid()) { 1719 // If both types are valid, check that the types are the same. 1720 if (SrcTy != DstTy) { 1721 report("Copy Instruction is illegal with mismatching types", MI); 1722 errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n"; 1723 } 1724 1725 break; 1726 } 1727 1728 if (!SrcTy.isValid() && !DstTy.isValid()) 1729 break; 1730 1731 // If we have only one valid type, this is likely a copy between a virtual 1732 // and physical register. 1733 unsigned SrcSize = 0; 1734 unsigned DstSize = 0; 1735 if (SrcReg.isPhysical() && DstTy.isValid()) { 1736 const TargetRegisterClass *SrcRC = 1737 TRI->getMinimalPhysRegClassLLT(SrcReg, DstTy); 1738 if (SrcRC) 1739 SrcSize = TRI->getRegSizeInBits(*SrcRC); 1740 } 1741 1742 if (SrcSize == 0) 1743 SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI); 1744 1745 if (DstReg.isPhysical() && SrcTy.isValid()) { 1746 const TargetRegisterClass *DstRC = 1747 TRI->getMinimalPhysRegClassLLT(DstReg, SrcTy); 1748 if (DstRC) 1749 DstSize = TRI->getRegSizeInBits(*DstRC); 1750 } 1751 1752 if (DstSize == 0) 1753 DstSize = TRI->getRegSizeInBits(DstReg, *MRI); 1754 1755 if (SrcSize != 0 && DstSize != 0 && SrcSize != DstSize) { 1756 if (!DstOp.getSubReg() && !SrcOp.getSubReg()) { 1757 report("Copy Instruction is illegal with mismatching sizes", MI); 1758 errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize 1759 << "\n"; 1760 } 1761 } 1762 break; 1763 } 1764 case TargetOpcode::STATEPOINT: { 1765 StatepointOpers SO(MI); 1766 if (!MI->getOperand(SO.getIDPos()).isImm() || 1767 !MI->getOperand(SO.getNBytesPos()).isImm() || 1768 !MI->getOperand(SO.getNCallArgsPos()).isImm()) { 1769 report("meta operands to STATEPOINT not constant!", MI); 1770 break; 1771 } 1772 1773 auto VerifyStackMapConstant = [&](unsigned Offset) { 1774 if (Offset >= MI->getNumOperands()) { 1775 report("stack map constant to STATEPOINT is out of range!", MI); 1776 return; 1777 } 1778 if (!MI->getOperand(Offset - 1).isImm() || 1779 MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp || 1780 !MI->getOperand(Offset).isImm()) 1781 report("stack map constant to STATEPOINT not well formed!", MI); 1782 }; 1783 VerifyStackMapConstant(SO.getCCIdx()); 1784 VerifyStackMapConstant(SO.getFlagsIdx()); 1785 VerifyStackMapConstant(SO.getNumDeoptArgsIdx()); 1786 VerifyStackMapConstant(SO.getNumGCPtrIdx()); 1787 VerifyStackMapConstant(SO.getNumAllocaIdx()); 1788 VerifyStackMapConstant(SO.getNumGcMapEntriesIdx()); 1789 1790 // Verify that all explicit statepoint defs are tied to gc operands as 1791 // they are expected to be a relocation of gc operands. 1792 unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx(); 1793 unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2; 1794 for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) { 1795 unsigned UseOpIdx; 1796 if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) { 1797 report("STATEPOINT defs expected to be tied", MI); 1798 break; 1799 } 1800 if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) { 1801 report("STATEPOINT def tied to non-gc operand", MI); 1802 break; 1803 } 1804 } 1805 1806 // TODO: verify we have properly encoded deopt arguments 1807 } break; 1808 case TargetOpcode::INSERT_SUBREG: { 1809 unsigned InsertedSize; 1810 if (unsigned SubIdx = MI->getOperand(2).getSubReg()) 1811 InsertedSize = TRI->getSubRegIdxSize(SubIdx); 1812 else 1813 InsertedSize = TRI->getRegSizeInBits(MI->getOperand(2).getReg(), *MRI); 1814 unsigned SubRegSize = TRI->getSubRegIdxSize(MI->getOperand(3).getImm()); 1815 if (SubRegSize < InsertedSize) { 1816 report("INSERT_SUBREG expected inserted value to have equal or lesser " 1817 "size than the subreg it was inserted into", MI); 1818 break; 1819 } 1820 } break; 1821 } 1822 } 1823 1824 void 1825 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) { 1826 const MachineInstr *MI = MO->getParent(); 1827 const MCInstrDesc &MCID = MI->getDesc(); 1828 unsigned NumDefs = MCID.getNumDefs(); 1829 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT) 1830 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0; 1831 1832 // The first MCID.NumDefs operands must be explicit register defines 1833 if (MONum < NumDefs) { 1834 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 1835 if (!MO->isReg()) 1836 report("Explicit definition must be a register", MO, MONum); 1837 else if (!MO->isDef() && !MCOI.isOptionalDef()) 1838 report("Explicit definition marked as use", MO, MONum); 1839 else if (MO->isImplicit()) 1840 report("Explicit definition marked as implicit", MO, MONum); 1841 } else if (MONum < MCID.getNumOperands()) { 1842 const MCOperandInfo &MCOI = MCID.OpInfo[MONum]; 1843 // Don't check if it's the last operand in a variadic instruction. See, 1844 // e.g., LDM_RET in the arm back end. Check non-variadic operands only. 1845 bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1; 1846 if (!IsOptional) { 1847 if (MO->isReg()) { 1848 if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs()) 1849 report("Explicit operand marked as def", MO, MONum); 1850 if (MO->isImplicit()) 1851 report("Explicit operand marked as implicit", MO, MONum); 1852 } 1853 1854 // Check that an instruction has register operands only as expected. 1855 if (MCOI.OperandType == MCOI::OPERAND_REGISTER && 1856 !MO->isReg() && !MO->isFI()) 1857 report("Expected a register operand.", MO, MONum); 1858 if (MO->isReg()) { 1859 if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE || 1860 (MCOI.OperandType == MCOI::OPERAND_PCREL && 1861 !TII->isPCRelRegisterOperandLegal(*MO))) 1862 report("Expected a non-register operand.", MO, MONum); 1863 } 1864 } 1865 1866 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO); 1867 if (TiedTo != -1) { 1868 if (!MO->isReg()) 1869 report("Tied use must be a register", MO, MONum); 1870 else if (!MO->isTied()) 1871 report("Operand should be tied", MO, MONum); 1872 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum)) 1873 report("Tied def doesn't match MCInstrDesc", MO, MONum); 1874 else if (Register::isPhysicalRegister(MO->getReg())) { 1875 const MachineOperand &MOTied = MI->getOperand(TiedTo); 1876 if (!MOTied.isReg()) 1877 report("Tied counterpart must be a register", &MOTied, TiedTo); 1878 else if (Register::isPhysicalRegister(MOTied.getReg()) && 1879 MO->getReg() != MOTied.getReg()) 1880 report("Tied physical registers must match.", &MOTied, TiedTo); 1881 } 1882 } else if (MO->isReg() && MO->isTied()) 1883 report("Explicit operand should not be tied", MO, MONum); 1884 } else { 1885 // ARM adds %reg0 operands to indicate predicates. We'll allow that. 1886 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg()) 1887 report("Extra explicit operand on non-variadic instruction", MO, MONum); 1888 } 1889 1890 switch (MO->getType()) { 1891 case MachineOperand::MO_Register: { 1892 const Register Reg = MO->getReg(); 1893 if (!Reg) 1894 return; 1895 if (MRI->tracksLiveness() && !MI->isDebugValue()) 1896 checkLiveness(MO, MONum); 1897 1898 // Verify the consistency of tied operands. 1899 if (MO->isTied()) { 1900 unsigned OtherIdx = MI->findTiedOperandIdx(MONum); 1901 const MachineOperand &OtherMO = MI->getOperand(OtherIdx); 1902 if (!OtherMO.isReg()) 1903 report("Must be tied to a register", MO, MONum); 1904 if (!OtherMO.isTied()) 1905 report("Missing tie flags on tied operand", MO, MONum); 1906 if (MI->findTiedOperandIdx(OtherIdx) != MONum) 1907 report("Inconsistent tie links", MO, MONum); 1908 if (MONum < MCID.getNumDefs()) { 1909 if (OtherIdx < MCID.getNumOperands()) { 1910 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO)) 1911 report("Explicit def tied to explicit use without tie constraint", 1912 MO, MONum); 1913 } else { 1914 if (!OtherMO.isImplicit()) 1915 report("Explicit def should be tied to implicit use", MO, MONum); 1916 } 1917 } 1918 } 1919 1920 // Verify two-address constraints after the twoaddressinstruction pass. 1921 // Both twoaddressinstruction pass and phi-node-elimination pass call 1922 // MRI->leaveSSA() to set MF as NoSSA, we should do the verification after 1923 // twoaddressinstruction pass not after phi-node-elimination pass. So we 1924 // shouldn't use the NoSSA as the condition, we should based on 1925 // TiedOpsRewritten property to verify two-address constraints, this 1926 // property will be set in twoaddressinstruction pass. 1927 unsigned DefIdx; 1928 if (MF->getProperties().hasProperty( 1929 MachineFunctionProperties::Property::TiedOpsRewritten) && 1930 MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) && 1931 Reg != MI->getOperand(DefIdx).getReg()) 1932 report("Two-address instruction operands must be identical", MO, MONum); 1933 1934 // Check register classes. 1935 unsigned SubIdx = MO->getSubReg(); 1936 1937 if (Register::isPhysicalRegister(Reg)) { 1938 if (SubIdx) { 1939 report("Illegal subregister index for physical register", MO, MONum); 1940 return; 1941 } 1942 if (MONum < MCID.getNumOperands()) { 1943 if (const TargetRegisterClass *DRC = 1944 TII->getRegClass(MCID, MONum, TRI, *MF)) { 1945 if (!DRC->contains(Reg)) { 1946 report("Illegal physical register for instruction", MO, MONum); 1947 errs() << printReg(Reg, TRI) << " is not a " 1948 << TRI->getRegClassName(DRC) << " register.\n"; 1949 } 1950 } 1951 } 1952 if (MO->isRenamable()) { 1953 if (MRI->isReserved(Reg)) { 1954 report("isRenamable set on reserved register", MO, MONum); 1955 return; 1956 } 1957 } 1958 if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) { 1959 report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum); 1960 return; 1961 } 1962 } else { 1963 // Virtual register. 1964 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg); 1965 if (!RC) { 1966 // This is a generic virtual register. 1967 1968 // Do not allow undef uses for generic virtual registers. This ensures 1969 // getVRegDef can never fail and return null on a generic register. 1970 // 1971 // FIXME: This restriction should probably be broadened to all SSA 1972 // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still 1973 // run on the SSA function just before phi elimination. 1974 if (MO->isUndef()) 1975 report("Generic virtual register use cannot be undef", MO, MONum); 1976 1977 // If we're post-Select, we can't have gvregs anymore. 1978 if (isFunctionSelected) { 1979 report("Generic virtual register invalid in a Selected function", 1980 MO, MONum); 1981 return; 1982 } 1983 1984 // The gvreg must have a type and it must not have a SubIdx. 1985 LLT Ty = MRI->getType(Reg); 1986 if (!Ty.isValid()) { 1987 report("Generic virtual register must have a valid type", MO, 1988 MONum); 1989 return; 1990 } 1991 1992 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg); 1993 1994 // If we're post-RegBankSelect, the gvreg must have a bank. 1995 if (!RegBank && isFunctionRegBankSelected) { 1996 report("Generic virtual register must have a bank in a " 1997 "RegBankSelected function", 1998 MO, MONum); 1999 return; 2000 } 2001 2002 // Make sure the register fits into its register bank if any. 2003 if (RegBank && Ty.isValid() && 2004 RegBank->getSize() < Ty.getSizeInBits()) { 2005 report("Register bank is too small for virtual register", MO, 2006 MONum); 2007 errs() << "Register bank " << RegBank->getName() << " too small(" 2008 << RegBank->getSize() << ") to fit " << Ty.getSizeInBits() 2009 << "-bits\n"; 2010 return; 2011 } 2012 if (SubIdx) { 2013 report("Generic virtual register does not allow subregister index", MO, 2014 MONum); 2015 return; 2016 } 2017 2018 // If this is a target specific instruction and this operand 2019 // has register class constraint, the virtual register must 2020 // comply to it. 2021 if (!isPreISelGenericOpcode(MCID.getOpcode()) && 2022 MONum < MCID.getNumOperands() && 2023 TII->getRegClass(MCID, MONum, TRI, *MF)) { 2024 report("Virtual register does not match instruction constraint", MO, 2025 MONum); 2026 errs() << "Expect register class " 2027 << TRI->getRegClassName( 2028 TII->getRegClass(MCID, MONum, TRI, *MF)) 2029 << " but got nothing\n"; 2030 return; 2031 } 2032 2033 break; 2034 } 2035 if (SubIdx) { 2036 const TargetRegisterClass *SRC = 2037 TRI->getSubClassWithSubReg(RC, SubIdx); 2038 if (!SRC) { 2039 report("Invalid subregister index for virtual register", MO, MONum); 2040 errs() << "Register class " << TRI->getRegClassName(RC) 2041 << " does not support subreg index " << SubIdx << "\n"; 2042 return; 2043 } 2044 if (RC != SRC) { 2045 report("Invalid register class for subregister index", MO, MONum); 2046 errs() << "Register class " << TRI->getRegClassName(RC) 2047 << " does not fully support subreg index " << SubIdx << "\n"; 2048 return; 2049 } 2050 } 2051 if (MONum < MCID.getNumOperands()) { 2052 if (const TargetRegisterClass *DRC = 2053 TII->getRegClass(MCID, MONum, TRI, *MF)) { 2054 if (SubIdx) { 2055 const TargetRegisterClass *SuperRC = 2056 TRI->getLargestLegalSuperClass(RC, *MF); 2057 if (!SuperRC) { 2058 report("No largest legal super class exists.", MO, MONum); 2059 return; 2060 } 2061 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx); 2062 if (!DRC) { 2063 report("No matching super-reg register class.", MO, MONum); 2064 return; 2065 } 2066 } 2067 if (!RC->hasSuperClassEq(DRC)) { 2068 report("Illegal virtual register for instruction", MO, MONum); 2069 errs() << "Expected a " << TRI->getRegClassName(DRC) 2070 << " register, but got a " << TRI->getRegClassName(RC) 2071 << " register\n"; 2072 } 2073 } 2074 } 2075 } 2076 break; 2077 } 2078 2079 case MachineOperand::MO_RegisterMask: 2080 regMasks.push_back(MO->getRegMask()); 2081 break; 2082 2083 case MachineOperand::MO_MachineBasicBlock: 2084 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent())) 2085 report("PHI operand is not in the CFG", MO, MONum); 2086 break; 2087 2088 case MachineOperand::MO_FrameIndex: 2089 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) && 2090 LiveInts && !LiveInts->isNotInMIMap(*MI)) { 2091 int FI = MO->getIndex(); 2092 LiveInterval &LI = LiveStks->getInterval(FI); 2093 SlotIndex Idx = LiveInts->getInstructionIndex(*MI); 2094 2095 bool stores = MI->mayStore(); 2096 bool loads = MI->mayLoad(); 2097 // For a memory-to-memory move, we need to check if the frame 2098 // index is used for storing or loading, by inspecting the 2099 // memory operands. 2100 if (stores && loads) { 2101 for (auto *MMO : MI->memoperands()) { 2102 const PseudoSourceValue *PSV = MMO->getPseudoValue(); 2103 if (PSV == nullptr) continue; 2104 const FixedStackPseudoSourceValue *Value = 2105 dyn_cast<FixedStackPseudoSourceValue>(PSV); 2106 if (Value == nullptr) continue; 2107 if (Value->getFrameIndex() != FI) continue; 2108 2109 if (MMO->isStore()) 2110 loads = false; 2111 else 2112 stores = false; 2113 break; 2114 } 2115 if (loads == stores) 2116 report("Missing fixed stack memoperand.", MI); 2117 } 2118 if (loads && !LI.liveAt(Idx.getRegSlot(true))) { 2119 report("Instruction loads from dead spill slot", MO, MONum); 2120 errs() << "Live stack: " << LI << '\n'; 2121 } 2122 if (stores && !LI.liveAt(Idx.getRegSlot())) { 2123 report("Instruction stores to dead spill slot", MO, MONum); 2124 errs() << "Live stack: " << LI << '\n'; 2125 } 2126 } 2127 break; 2128 2129 default: 2130 break; 2131 } 2132 } 2133 2134 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO, 2135 unsigned MONum, SlotIndex UseIdx, 2136 const LiveRange &LR, 2137 Register VRegOrUnit, 2138 LaneBitmask LaneMask) { 2139 LiveQueryResult LRQ = LR.Query(UseIdx); 2140 // Check if we have a segment at the use, note however that we only need one 2141 // live subregister range, the others may be dead. 2142 if (!LRQ.valueIn() && LaneMask.none()) { 2143 report("No live segment at use", MO, MONum); 2144 report_context_liverange(LR); 2145 report_context_vreg_regunit(VRegOrUnit); 2146 report_context(UseIdx); 2147 } 2148 if (MO->isKill() && !LRQ.isKill()) { 2149 report("Live range continues after kill flag", MO, MONum); 2150 report_context_liverange(LR); 2151 report_context_vreg_regunit(VRegOrUnit); 2152 if (LaneMask.any()) 2153 report_context_lanemask(LaneMask); 2154 report_context(UseIdx); 2155 } 2156 } 2157 2158 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO, 2159 unsigned MONum, SlotIndex DefIdx, 2160 const LiveRange &LR, 2161 Register VRegOrUnit, 2162 bool SubRangeCheck, 2163 LaneBitmask LaneMask) { 2164 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) { 2165 assert(VNI && "NULL valno is not allowed"); 2166 if (VNI->def != DefIdx) { 2167 report("Inconsistent valno->def", MO, MONum); 2168 report_context_liverange(LR); 2169 report_context_vreg_regunit(VRegOrUnit); 2170 if (LaneMask.any()) 2171 report_context_lanemask(LaneMask); 2172 report_context(*VNI); 2173 report_context(DefIdx); 2174 } 2175 } else { 2176 report("No live segment at def", MO, MONum); 2177 report_context_liverange(LR); 2178 report_context_vreg_regunit(VRegOrUnit); 2179 if (LaneMask.any()) 2180 report_context_lanemask(LaneMask); 2181 report_context(DefIdx); 2182 } 2183 // Check that, if the dead def flag is present, LiveInts agree. 2184 if (MO->isDead()) { 2185 LiveQueryResult LRQ = LR.Query(DefIdx); 2186 if (!LRQ.isDeadDef()) { 2187 assert(Register::isVirtualRegister(VRegOrUnit) && 2188 "Expecting a virtual register."); 2189 // A dead subreg def only tells us that the specific subreg is dead. There 2190 // could be other non-dead defs of other subregs, or we could have other 2191 // parts of the register being live through the instruction. So unless we 2192 // are checking liveness for a subrange it is ok for the live range to 2193 // continue, given that we have a dead def of a subregister. 2194 if (SubRangeCheck || MO->getSubReg() == 0) { 2195 report("Live range continues after dead def flag", MO, MONum); 2196 report_context_liverange(LR); 2197 report_context_vreg_regunit(VRegOrUnit); 2198 if (LaneMask.any()) 2199 report_context_lanemask(LaneMask); 2200 } 2201 } 2202 } 2203 } 2204 2205 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) { 2206 const MachineInstr *MI = MO->getParent(); 2207 const Register Reg = MO->getReg(); 2208 2209 // Both use and def operands can read a register. 2210 if (MO->readsReg()) { 2211 if (MO->isKill()) 2212 addRegWithSubRegs(regsKilled, Reg); 2213 2214 // Check that LiveVars knows this kill (unless we are inside a bundle, in 2215 // which case we have already checked that LiveVars knows any kills on the 2216 // bundle header instead). 2217 if (LiveVars && Register::isVirtualRegister(Reg) && MO->isKill() && 2218 !MI->isBundledWithPred()) { 2219 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 2220 if (!is_contained(VI.Kills, MI)) 2221 report("Kill missing from LiveVariables", MO, MONum); 2222 } 2223 2224 // Check LiveInts liveness and kill. 2225 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 2226 SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI); 2227 // Check the cached regunit intervals. 2228 if (Reg.isPhysical() && !isReserved(Reg)) { 2229 for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid(); 2230 ++Units) { 2231 if (MRI->isReservedRegUnit(*Units)) 2232 continue; 2233 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) 2234 checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units); 2235 } 2236 } 2237 2238 if (Register::isVirtualRegister(Reg)) { 2239 if (LiveInts->hasInterval(Reg)) { 2240 // This is a virtual register interval. 2241 const LiveInterval &LI = LiveInts->getInterval(Reg); 2242 checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg); 2243 2244 if (LI.hasSubRanges() && !MO->isDef()) { 2245 unsigned SubRegIdx = MO->getSubReg(); 2246 LaneBitmask MOMask = SubRegIdx != 0 2247 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 2248 : MRI->getMaxLaneMaskForVReg(Reg); 2249 LaneBitmask LiveInMask; 2250 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2251 if ((MOMask & SR.LaneMask).none()) 2252 continue; 2253 checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask); 2254 LiveQueryResult LRQ = SR.Query(UseIdx); 2255 if (LRQ.valueIn()) 2256 LiveInMask |= SR.LaneMask; 2257 } 2258 // At least parts of the register has to be live at the use. 2259 if ((LiveInMask & MOMask).none()) { 2260 report("No live subrange at use", MO, MONum); 2261 report_context(LI); 2262 report_context(UseIdx); 2263 } 2264 } 2265 } else { 2266 report("Virtual register has no live interval", MO, MONum); 2267 } 2268 } 2269 } 2270 2271 // Use of a dead register. 2272 if (!regsLive.count(Reg)) { 2273 if (Register::isPhysicalRegister(Reg)) { 2274 // Reserved registers may be used even when 'dead'. 2275 bool Bad = !isReserved(Reg); 2276 // We are fine if just any subregister has a defined value. 2277 if (Bad) { 2278 2279 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) { 2280 if (regsLive.count(SubReg)) { 2281 Bad = false; 2282 break; 2283 } 2284 } 2285 } 2286 // If there is an additional implicit-use of a super register we stop 2287 // here. By definition we are fine if the super register is not 2288 // (completely) dead, if the complete super register is dead we will 2289 // get a report for its operand. 2290 if (Bad) { 2291 for (const MachineOperand &MOP : MI->uses()) { 2292 if (!MOP.isReg() || !MOP.isImplicit()) 2293 continue; 2294 2295 if (!Register::isPhysicalRegister(MOP.getReg())) 2296 continue; 2297 2298 if (llvm::is_contained(TRI->subregs(MOP.getReg()), Reg)) 2299 Bad = false; 2300 } 2301 } 2302 if (Bad) 2303 report("Using an undefined physical register", MO, MONum); 2304 } else if (MRI->def_empty(Reg)) { 2305 report("Reading virtual register without a def", MO, MONum); 2306 } else { 2307 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 2308 // We don't know which virtual registers are live in, so only complain 2309 // if vreg was killed in this MBB. Otherwise keep track of vregs that 2310 // must be live in. PHI instructions are handled separately. 2311 if (MInfo.regsKilled.count(Reg)) 2312 report("Using a killed virtual register", MO, MONum); 2313 else if (!MI->isPHI()) 2314 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI)); 2315 } 2316 } 2317 } 2318 2319 if (MO->isDef()) { 2320 // Register defined. 2321 // TODO: verify that earlyclobber ops are not used. 2322 if (MO->isDead()) 2323 addRegWithSubRegs(regsDead, Reg); 2324 else 2325 addRegWithSubRegs(regsDefined, Reg); 2326 2327 // Verify SSA form. 2328 if (MRI->isSSA() && Register::isVirtualRegister(Reg) && 2329 std::next(MRI->def_begin(Reg)) != MRI->def_end()) 2330 report("Multiple virtual register defs in SSA form", MO, MONum); 2331 2332 // Check LiveInts for a live segment, but only for virtual registers. 2333 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) { 2334 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI); 2335 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber()); 2336 2337 if (Register::isVirtualRegister(Reg)) { 2338 if (LiveInts->hasInterval(Reg)) { 2339 const LiveInterval &LI = LiveInts->getInterval(Reg); 2340 checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg); 2341 2342 if (LI.hasSubRanges()) { 2343 unsigned SubRegIdx = MO->getSubReg(); 2344 LaneBitmask MOMask = SubRegIdx != 0 2345 ? TRI->getSubRegIndexLaneMask(SubRegIdx) 2346 : MRI->getMaxLaneMaskForVReg(Reg); 2347 for (const LiveInterval::SubRange &SR : LI.subranges()) { 2348 if ((SR.LaneMask & MOMask).none()) 2349 continue; 2350 checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask); 2351 } 2352 } 2353 } else { 2354 report("Virtual register has no Live interval", MO, MONum); 2355 } 2356 } 2357 } 2358 } 2359 } 2360 2361 // This function gets called after visiting all instructions in a bundle. The 2362 // argument points to the bundle header. 2363 // Normal stand-alone instructions are also considered 'bundles', and this 2364 // function is called for all of them. 2365 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) { 2366 BBInfo &MInfo = MBBInfoMap[MI->getParent()]; 2367 set_union(MInfo.regsKilled, regsKilled); 2368 set_subtract(regsLive, regsKilled); regsKilled.clear(); 2369 // Kill any masked registers. 2370 while (!regMasks.empty()) { 2371 const uint32_t *Mask = regMasks.pop_back_val(); 2372 for (Register Reg : regsLive) 2373 if (Reg.isPhysical() && 2374 MachineOperand::clobbersPhysReg(Mask, Reg.asMCReg())) 2375 regsDead.push_back(Reg); 2376 } 2377 set_subtract(regsLive, regsDead); regsDead.clear(); 2378 set_union(regsLive, regsDefined); regsDefined.clear(); 2379 } 2380 2381 void 2382 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) { 2383 MBBInfoMap[MBB].regsLiveOut = regsLive; 2384 regsLive.clear(); 2385 2386 if (Indexes) { 2387 SlotIndex stop = Indexes->getMBBEndIdx(MBB); 2388 if (!(stop > lastIndex)) { 2389 report("Block ends before last instruction index", MBB); 2390 errs() << "Block ends at " << stop 2391 << " last instruction was at " << lastIndex << '\n'; 2392 } 2393 lastIndex = stop; 2394 } 2395 } 2396 2397 namespace { 2398 // This implements a set of registers that serves as a filter: can filter other 2399 // sets by passing through elements not in the filter and blocking those that 2400 // are. Any filter implicitly includes the full set of physical registers upon 2401 // creation, thus filtering them all out. The filter itself as a set only grows, 2402 // and needs to be as efficient as possible. 2403 struct VRegFilter { 2404 // Add elements to the filter itself. \pre Input set \p FromRegSet must have 2405 // no duplicates. Both virtual and physical registers are fine. 2406 template <typename RegSetT> void add(const RegSetT &FromRegSet) { 2407 SmallVector<Register, 0> VRegsBuffer; 2408 filterAndAdd(FromRegSet, VRegsBuffer); 2409 } 2410 // Filter \p FromRegSet through the filter and append passed elements into \p 2411 // ToVRegs. All elements appended are then added to the filter itself. 2412 // \returns true if anything changed. 2413 template <typename RegSetT> 2414 bool filterAndAdd(const RegSetT &FromRegSet, 2415 SmallVectorImpl<Register> &ToVRegs) { 2416 unsigned SparseUniverse = Sparse.size(); 2417 unsigned NewSparseUniverse = SparseUniverse; 2418 unsigned NewDenseSize = Dense.size(); 2419 size_t Begin = ToVRegs.size(); 2420 for (Register Reg : FromRegSet) { 2421 if (!Reg.isVirtual()) 2422 continue; 2423 unsigned Index = Register::virtReg2Index(Reg); 2424 if (Index < SparseUniverseMax) { 2425 if (Index < SparseUniverse && Sparse.test(Index)) 2426 continue; 2427 NewSparseUniverse = std::max(NewSparseUniverse, Index + 1); 2428 } else { 2429 if (Dense.count(Reg)) 2430 continue; 2431 ++NewDenseSize; 2432 } 2433 ToVRegs.push_back(Reg); 2434 } 2435 size_t End = ToVRegs.size(); 2436 if (Begin == End) 2437 return false; 2438 // Reserving space in sets once performs better than doing so continuously 2439 // and pays easily for double look-ups (even in Dense with SparseUniverseMax 2440 // tuned all the way down) and double iteration (the second one is over a 2441 // SmallVector, which is a lot cheaper compared to DenseSet or BitVector). 2442 Sparse.resize(NewSparseUniverse); 2443 Dense.reserve(NewDenseSize); 2444 for (unsigned I = Begin; I < End; ++I) { 2445 Register Reg = ToVRegs[I]; 2446 unsigned Index = Register::virtReg2Index(Reg); 2447 if (Index < SparseUniverseMax) 2448 Sparse.set(Index); 2449 else 2450 Dense.insert(Reg); 2451 } 2452 return true; 2453 } 2454 2455 private: 2456 static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8; 2457 // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound 2458 // are tracked by Dense. The only purpose of the threashold and the Dense set 2459 // is to have a reasonably growing memory usage in pathological cases (large 2460 // number of very sparse VRegFilter instances live at the same time). In 2461 // practice even in the worst-by-execution time cases having all elements 2462 // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more 2463 // space efficient than if tracked by Dense. The threashold is set to keep the 2464 // worst-case memory usage within 2x of figures determined empirically for 2465 // "all Dense" scenario in such worst-by-execution-time cases. 2466 BitVector Sparse; 2467 DenseSet<unsigned> Dense; 2468 }; 2469 2470 // Implements both a transfer function and a (binary, in-place) join operator 2471 // for a dataflow over register sets with set union join and filtering transfer 2472 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time. 2473 // Maintains out_b as its state, allowing for O(n) iteration over it at any 2474 // time, where n is the size of the set (as opposed to O(U) where U is the 2475 // universe). filter_b implicitly contains all physical registers at all times. 2476 class FilteringVRegSet { 2477 VRegFilter Filter; 2478 SmallVector<Register, 0> VRegs; 2479 2480 public: 2481 // Set-up the filter_b. \pre Input register set \p RS must have no duplicates. 2482 // Both virtual and physical registers are fine. 2483 template <typename RegSetT> void addToFilter(const RegSetT &RS) { 2484 Filter.add(RS); 2485 } 2486 // Passes \p RS through the filter_b (transfer function) and adds what's left 2487 // to itself (out_b). 2488 template <typename RegSetT> bool add(const RegSetT &RS) { 2489 // Double-duty the Filter: to maintain VRegs a set (and the join operation 2490 // a set union) just add everything being added here to the Filter as well. 2491 return Filter.filterAndAdd(RS, VRegs); 2492 } 2493 using const_iterator = decltype(VRegs)::const_iterator; 2494 const_iterator begin() const { return VRegs.begin(); } 2495 const_iterator end() const { return VRegs.end(); } 2496 size_t size() const { return VRegs.size(); } 2497 }; 2498 } // namespace 2499 2500 // Calculate the largest possible vregsPassed sets. These are the registers that 2501 // can pass through an MBB live, but may not be live every time. It is assumed 2502 // that all vregsPassed sets are empty before the call. 2503 void MachineVerifier::calcRegsPassed() { 2504 if (MF->empty()) 2505 // ReversePostOrderTraversal doesn't handle empty functions. 2506 return; 2507 2508 for (const MachineBasicBlock *MB : 2509 ReversePostOrderTraversal<const MachineFunction *>(MF)) { 2510 FilteringVRegSet VRegs; 2511 BBInfo &Info = MBBInfoMap[MB]; 2512 assert(Info.reachable); 2513 2514 VRegs.addToFilter(Info.regsKilled); 2515 VRegs.addToFilter(Info.regsLiveOut); 2516 for (const MachineBasicBlock *Pred : MB->predecessors()) { 2517 const BBInfo &PredInfo = MBBInfoMap[Pred]; 2518 if (!PredInfo.reachable) 2519 continue; 2520 2521 VRegs.add(PredInfo.regsLiveOut); 2522 VRegs.add(PredInfo.vregsPassed); 2523 } 2524 Info.vregsPassed.reserve(VRegs.size()); 2525 Info.vregsPassed.insert(VRegs.begin(), VRegs.end()); 2526 } 2527 } 2528 2529 // Calculate the set of virtual registers that must be passed through each basic 2530 // block in order to satisfy the requirements of successor blocks. This is very 2531 // similar to calcRegsPassed, only backwards. 2532 void MachineVerifier::calcRegsRequired() { 2533 // First push live-in regs to predecessors' vregsRequired. 2534 SmallPtrSet<const MachineBasicBlock*, 8> todo; 2535 for (const auto &MBB : *MF) { 2536 BBInfo &MInfo = MBBInfoMap[&MBB]; 2537 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 2538 BBInfo &PInfo = MBBInfoMap[Pred]; 2539 if (PInfo.addRequired(MInfo.vregsLiveIn)) 2540 todo.insert(Pred); 2541 } 2542 2543 // Handle the PHI node. 2544 for (const MachineInstr &MI : MBB.phis()) { 2545 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 2546 // Skip those Operands which are undef regs or not regs. 2547 if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg()) 2548 continue; 2549 2550 // Get register and predecessor for one PHI edge. 2551 Register Reg = MI.getOperand(i).getReg(); 2552 const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB(); 2553 2554 BBInfo &PInfo = MBBInfoMap[Pred]; 2555 if (PInfo.addRequired(Reg)) 2556 todo.insert(Pred); 2557 } 2558 } 2559 } 2560 2561 // Iteratively push vregsRequired to predecessors. This will converge to the 2562 // same final state regardless of DenseSet iteration order. 2563 while (!todo.empty()) { 2564 const MachineBasicBlock *MBB = *todo.begin(); 2565 todo.erase(MBB); 2566 BBInfo &MInfo = MBBInfoMap[MBB]; 2567 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 2568 if (Pred == MBB) 2569 continue; 2570 BBInfo &SInfo = MBBInfoMap[Pred]; 2571 if (SInfo.addRequired(MInfo.vregsRequired)) 2572 todo.insert(Pred); 2573 } 2574 } 2575 } 2576 2577 // Check PHI instructions at the beginning of MBB. It is assumed that 2578 // calcRegsPassed has been run so BBInfo::isLiveOut is valid. 2579 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) { 2580 BBInfo &MInfo = MBBInfoMap[&MBB]; 2581 2582 SmallPtrSet<const MachineBasicBlock*, 8> seen; 2583 for (const MachineInstr &Phi : MBB) { 2584 if (!Phi.isPHI()) 2585 break; 2586 seen.clear(); 2587 2588 const MachineOperand &MODef = Phi.getOperand(0); 2589 if (!MODef.isReg() || !MODef.isDef()) { 2590 report("Expected first PHI operand to be a register def", &MODef, 0); 2591 continue; 2592 } 2593 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() || 2594 MODef.isEarlyClobber() || MODef.isDebug()) 2595 report("Unexpected flag on PHI operand", &MODef, 0); 2596 Register DefReg = MODef.getReg(); 2597 if (!Register::isVirtualRegister(DefReg)) 2598 report("Expected first PHI operand to be a virtual register", &MODef, 0); 2599 2600 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) { 2601 const MachineOperand &MO0 = Phi.getOperand(I); 2602 if (!MO0.isReg()) { 2603 report("Expected PHI operand to be a register", &MO0, I); 2604 continue; 2605 } 2606 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() || 2607 MO0.isDebug() || MO0.isTied()) 2608 report("Unexpected flag on PHI operand", &MO0, I); 2609 2610 const MachineOperand &MO1 = Phi.getOperand(I + 1); 2611 if (!MO1.isMBB()) { 2612 report("Expected PHI operand to be a basic block", &MO1, I + 1); 2613 continue; 2614 } 2615 2616 const MachineBasicBlock &Pre = *MO1.getMBB(); 2617 if (!Pre.isSuccessor(&MBB)) { 2618 report("PHI input is not a predecessor block", &MO1, I + 1); 2619 continue; 2620 } 2621 2622 if (MInfo.reachable) { 2623 seen.insert(&Pre); 2624 BBInfo &PrInfo = MBBInfoMap[&Pre]; 2625 if (!MO0.isUndef() && PrInfo.reachable && 2626 !PrInfo.isLiveOut(MO0.getReg())) 2627 report("PHI operand is not live-out from predecessor", &MO0, I); 2628 } 2629 } 2630 2631 // Did we see all predecessors? 2632 if (MInfo.reachable) { 2633 for (MachineBasicBlock *Pred : MBB.predecessors()) { 2634 if (!seen.count(Pred)) { 2635 report("Missing PHI operand", &Phi); 2636 errs() << printMBBReference(*Pred) 2637 << " is a predecessor according to the CFG.\n"; 2638 } 2639 } 2640 } 2641 } 2642 } 2643 2644 void MachineVerifier::visitMachineFunctionAfter() { 2645 calcRegsPassed(); 2646 2647 for (const MachineBasicBlock &MBB : *MF) 2648 checkPHIOps(MBB); 2649 2650 // Now check liveness info if available 2651 calcRegsRequired(); 2652 2653 // Check for killed virtual registers that should be live out. 2654 for (const auto &MBB : *MF) { 2655 BBInfo &MInfo = MBBInfoMap[&MBB]; 2656 for (Register VReg : MInfo.vregsRequired) 2657 if (MInfo.regsKilled.count(VReg)) { 2658 report("Virtual register killed in block, but needed live out.", &MBB); 2659 errs() << "Virtual register " << printReg(VReg) 2660 << " is used after the block.\n"; 2661 } 2662 } 2663 2664 if (!MF->empty()) { 2665 BBInfo &MInfo = MBBInfoMap[&MF->front()]; 2666 for (Register VReg : MInfo.vregsRequired) { 2667 report("Virtual register defs don't dominate all uses.", MF); 2668 report_context_vreg(VReg); 2669 } 2670 } 2671 2672 if (LiveVars) 2673 verifyLiveVariables(); 2674 if (LiveInts) 2675 verifyLiveIntervals(); 2676 2677 // Check live-in list of each MBB. If a register is live into MBB, check 2678 // that the register is in regsLiveOut of each predecessor block. Since 2679 // this must come from a definition in the predecesssor or its live-in 2680 // list, this will catch a live-through case where the predecessor does not 2681 // have the register in its live-in list. This currently only checks 2682 // registers that have no aliases, are not allocatable and are not 2683 // reserved, which could mean a condition code register for instance. 2684 if (MRI->tracksLiveness()) 2685 for (const auto &MBB : *MF) 2686 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) { 2687 MCPhysReg LiveInReg = P.PhysReg; 2688 bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid(); 2689 if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg)) 2690 continue; 2691 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 2692 BBInfo &PInfo = MBBInfoMap[Pred]; 2693 if (!PInfo.regsLiveOut.count(LiveInReg)) { 2694 report("Live in register not found to be live out from predecessor.", 2695 &MBB); 2696 errs() << TRI->getName(LiveInReg) 2697 << " not found to be live out from " 2698 << printMBBReference(*Pred) << "\n"; 2699 } 2700 } 2701 } 2702 2703 for (auto CSInfo : MF->getCallSitesInfo()) 2704 if (!CSInfo.first->isCall()) 2705 report("Call site info referencing instruction that is not call", MF); 2706 2707 // If there's debug-info, check that we don't have any duplicate value 2708 // tracking numbers. 2709 if (MF->getFunction().getSubprogram()) { 2710 DenseSet<unsigned> SeenNumbers; 2711 for (auto &MBB : *MF) { 2712 for (auto &MI : MBB) { 2713 if (auto Num = MI.peekDebugInstrNum()) { 2714 auto Result = SeenNumbers.insert((unsigned)Num); 2715 if (!Result.second) 2716 report("Instruction has a duplicated value tracking number", &MI); 2717 } 2718 } 2719 } 2720 } 2721 } 2722 2723 void MachineVerifier::verifyLiveVariables() { 2724 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars"); 2725 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) { 2726 Register Reg = Register::index2VirtReg(I); 2727 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg); 2728 for (const auto &MBB : *MF) { 2729 BBInfo &MInfo = MBBInfoMap[&MBB]; 2730 2731 // Our vregsRequired should be identical to LiveVariables' AliveBlocks 2732 if (MInfo.vregsRequired.count(Reg)) { 2733 if (!VI.AliveBlocks.test(MBB.getNumber())) { 2734 report("LiveVariables: Block missing from AliveBlocks", &MBB); 2735 errs() << "Virtual register " << printReg(Reg) 2736 << " must be live through the block.\n"; 2737 } 2738 } else { 2739 if (VI.AliveBlocks.test(MBB.getNumber())) { 2740 report("LiveVariables: Block should not be in AliveBlocks", &MBB); 2741 errs() << "Virtual register " << printReg(Reg) 2742 << " is not needed live through the block.\n"; 2743 } 2744 } 2745 } 2746 } 2747 } 2748 2749 void MachineVerifier::verifyLiveIntervals() { 2750 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts"); 2751 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) { 2752 Register Reg = Register::index2VirtReg(I); 2753 2754 // Spilling and splitting may leave unused registers around. Skip them. 2755 if (MRI->reg_nodbg_empty(Reg)) 2756 continue; 2757 2758 if (!LiveInts->hasInterval(Reg)) { 2759 report("Missing live interval for virtual register", MF); 2760 errs() << printReg(Reg, TRI) << " still has defs or uses\n"; 2761 continue; 2762 } 2763 2764 const LiveInterval &LI = LiveInts->getInterval(Reg); 2765 assert(Reg == LI.reg() && "Invalid reg to interval mapping"); 2766 verifyLiveInterval(LI); 2767 } 2768 2769 // Verify all the cached regunit intervals. 2770 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 2771 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i)) 2772 verifyLiveRange(*LR, i); 2773 } 2774 2775 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR, 2776 const VNInfo *VNI, Register Reg, 2777 LaneBitmask LaneMask) { 2778 if (VNI->isUnused()) 2779 return; 2780 2781 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def); 2782 2783 if (!DefVNI) { 2784 report("Value not live at VNInfo def and not marked unused", MF); 2785 report_context(LR, Reg, LaneMask); 2786 report_context(*VNI); 2787 return; 2788 } 2789 2790 if (DefVNI != VNI) { 2791 report("Live segment at def has different VNInfo", MF); 2792 report_context(LR, Reg, LaneMask); 2793 report_context(*VNI); 2794 return; 2795 } 2796 2797 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def); 2798 if (!MBB) { 2799 report("Invalid VNInfo definition index", MF); 2800 report_context(LR, Reg, LaneMask); 2801 report_context(*VNI); 2802 return; 2803 } 2804 2805 if (VNI->isPHIDef()) { 2806 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) { 2807 report("PHIDef VNInfo is not defined at MBB start", MBB); 2808 report_context(LR, Reg, LaneMask); 2809 report_context(*VNI); 2810 } 2811 return; 2812 } 2813 2814 // Non-PHI def. 2815 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def); 2816 if (!MI) { 2817 report("No instruction at VNInfo def index", MBB); 2818 report_context(LR, Reg, LaneMask); 2819 report_context(*VNI); 2820 return; 2821 } 2822 2823 if (Reg != 0) { 2824 bool hasDef = false; 2825 bool isEarlyClobber = false; 2826 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 2827 if (!MOI->isReg() || !MOI->isDef()) 2828 continue; 2829 if (Register::isVirtualRegister(Reg)) { 2830 if (MOI->getReg() != Reg) 2831 continue; 2832 } else { 2833 if (!Register::isPhysicalRegister(MOI->getReg()) || 2834 !TRI->hasRegUnit(MOI->getReg(), Reg)) 2835 continue; 2836 } 2837 if (LaneMask.any() && 2838 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none()) 2839 continue; 2840 hasDef = true; 2841 if (MOI->isEarlyClobber()) 2842 isEarlyClobber = true; 2843 } 2844 2845 if (!hasDef) { 2846 report("Defining instruction does not modify register", MI); 2847 report_context(LR, Reg, LaneMask); 2848 report_context(*VNI); 2849 } 2850 2851 // Early clobber defs begin at USE slots, but other defs must begin at 2852 // DEF slots. 2853 if (isEarlyClobber) { 2854 if (!VNI->def.isEarlyClobber()) { 2855 report("Early clobber def must be at an early-clobber slot", MBB); 2856 report_context(LR, Reg, LaneMask); 2857 report_context(*VNI); 2858 } 2859 } else if (!VNI->def.isRegister()) { 2860 report("Non-PHI, non-early clobber def must be at a register slot", MBB); 2861 report_context(LR, Reg, LaneMask); 2862 report_context(*VNI); 2863 } 2864 } 2865 } 2866 2867 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR, 2868 const LiveRange::const_iterator I, 2869 Register Reg, 2870 LaneBitmask LaneMask) { 2871 const LiveRange::Segment &S = *I; 2872 const VNInfo *VNI = S.valno; 2873 assert(VNI && "Live segment has no valno"); 2874 2875 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) { 2876 report("Foreign valno in live segment", MF); 2877 report_context(LR, Reg, LaneMask); 2878 report_context(S); 2879 report_context(*VNI); 2880 } 2881 2882 if (VNI->isUnused()) { 2883 report("Live segment valno is marked unused", MF); 2884 report_context(LR, Reg, LaneMask); 2885 report_context(S); 2886 } 2887 2888 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start); 2889 if (!MBB) { 2890 report("Bad start of live segment, no basic block", MF); 2891 report_context(LR, Reg, LaneMask); 2892 report_context(S); 2893 return; 2894 } 2895 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB); 2896 if (S.start != MBBStartIdx && S.start != VNI->def) { 2897 report("Live segment must begin at MBB entry or valno def", MBB); 2898 report_context(LR, Reg, LaneMask); 2899 report_context(S); 2900 } 2901 2902 const MachineBasicBlock *EndMBB = 2903 LiveInts->getMBBFromIndex(S.end.getPrevSlot()); 2904 if (!EndMBB) { 2905 report("Bad end of live segment, no basic block", MF); 2906 report_context(LR, Reg, LaneMask); 2907 report_context(S); 2908 return; 2909 } 2910 2911 // No more checks for live-out segments. 2912 if (S.end == LiveInts->getMBBEndIdx(EndMBB)) 2913 return; 2914 2915 // RegUnit intervals are allowed dead phis. 2916 if (!Register::isVirtualRegister(Reg) && VNI->isPHIDef() && 2917 S.start == VNI->def && S.end == VNI->def.getDeadSlot()) 2918 return; 2919 2920 // The live segment is ending inside EndMBB 2921 const MachineInstr *MI = 2922 LiveInts->getInstructionFromIndex(S.end.getPrevSlot()); 2923 if (!MI) { 2924 report("Live segment doesn't end at a valid instruction", EndMBB); 2925 report_context(LR, Reg, LaneMask); 2926 report_context(S); 2927 return; 2928 } 2929 2930 // The block slot must refer to a basic block boundary. 2931 if (S.end.isBlock()) { 2932 report("Live segment ends at B slot of an instruction", EndMBB); 2933 report_context(LR, Reg, LaneMask); 2934 report_context(S); 2935 } 2936 2937 if (S.end.isDead()) { 2938 // Segment ends on the dead slot. 2939 // That means there must be a dead def. 2940 if (!SlotIndex::isSameInstr(S.start, S.end)) { 2941 report("Live segment ending at dead slot spans instructions", EndMBB); 2942 report_context(LR, Reg, LaneMask); 2943 report_context(S); 2944 } 2945 } 2946 2947 // After tied operands are rewritten, a live segment can only end at an 2948 // early-clobber slot if it is being redefined by an early-clobber def. 2949 // TODO: Before tied operands are rewritten, a live segment can only end at an 2950 // early-clobber slot if the last use is tied to an early-clobber def. 2951 if (MF->getProperties().hasProperty( 2952 MachineFunctionProperties::Property::TiedOpsRewritten) && 2953 S.end.isEarlyClobber()) { 2954 if (I+1 == LR.end() || (I+1)->start != S.end) { 2955 report("Live segment ending at early clobber slot must be " 2956 "redefined by an EC def in the same instruction", EndMBB); 2957 report_context(LR, Reg, LaneMask); 2958 report_context(S); 2959 } 2960 } 2961 2962 // The following checks only apply to virtual registers. Physreg liveness 2963 // is too weird to check. 2964 if (Register::isVirtualRegister(Reg)) { 2965 // A live segment can end with either a redefinition, a kill flag on a 2966 // use, or a dead flag on a def. 2967 bool hasRead = false; 2968 bool hasSubRegDef = false; 2969 bool hasDeadDef = false; 2970 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 2971 if (!MOI->isReg() || MOI->getReg() != Reg) 2972 continue; 2973 unsigned Sub = MOI->getSubReg(); 2974 LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) 2975 : LaneBitmask::getAll(); 2976 if (MOI->isDef()) { 2977 if (Sub != 0) { 2978 hasSubRegDef = true; 2979 // An operand %0:sub0 reads %0:sub1..n. Invert the lane 2980 // mask for subregister defs. Read-undef defs will be handled by 2981 // readsReg below. 2982 SLM = ~SLM; 2983 } 2984 if (MOI->isDead()) 2985 hasDeadDef = true; 2986 } 2987 if (LaneMask.any() && (LaneMask & SLM).none()) 2988 continue; 2989 if (MOI->readsReg()) 2990 hasRead = true; 2991 } 2992 if (S.end.isDead()) { 2993 // Make sure that the corresponding machine operand for a "dead" live 2994 // range has the dead flag. We cannot perform this check for subregister 2995 // liveranges as partially dead values are allowed. 2996 if (LaneMask.none() && !hasDeadDef) { 2997 report("Instruction ending live segment on dead slot has no dead flag", 2998 MI); 2999 report_context(LR, Reg, LaneMask); 3000 report_context(S); 3001 } 3002 } else { 3003 if (!hasRead) { 3004 // When tracking subregister liveness, the main range must start new 3005 // values on partial register writes, even if there is no read. 3006 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() || 3007 !hasSubRegDef) { 3008 report("Instruction ending live segment doesn't read the register", 3009 MI); 3010 report_context(LR, Reg, LaneMask); 3011 report_context(S); 3012 } 3013 } 3014 } 3015 } 3016 3017 // Now check all the basic blocks in this live segment. 3018 MachineFunction::const_iterator MFI = MBB->getIterator(); 3019 // Is this live segment the beginning of a non-PHIDef VN? 3020 if (S.start == VNI->def && !VNI->isPHIDef()) { 3021 // Not live-in to any blocks. 3022 if (MBB == EndMBB) 3023 return; 3024 // Skip this block. 3025 ++MFI; 3026 } 3027 3028 SmallVector<SlotIndex, 4> Undefs; 3029 if (LaneMask.any()) { 3030 LiveInterval &OwnerLI = LiveInts->getInterval(Reg); 3031 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes); 3032 } 3033 3034 while (true) { 3035 assert(LiveInts->isLiveInToMBB(LR, &*MFI)); 3036 // We don't know how to track physregs into a landing pad. 3037 if (!Register::isVirtualRegister(Reg) && MFI->isEHPad()) { 3038 if (&*MFI == EndMBB) 3039 break; 3040 ++MFI; 3041 continue; 3042 } 3043 3044 // Is VNI a PHI-def in the current block? 3045 bool IsPHI = VNI->isPHIDef() && 3046 VNI->def == LiveInts->getMBBStartIdx(&*MFI); 3047 3048 // Check that VNI is live-out of all predecessors. 3049 for (const MachineBasicBlock *Pred : MFI->predecessors()) { 3050 SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred); 3051 // Predecessor of landing pad live-out on last call. 3052 if (MFI->isEHPad()) { 3053 for (auto I = Pred->rbegin(), E = Pred->rend(); I != E; ++I) { 3054 if (I->isCall()) { 3055 PEnd = Indexes->getInstructionIndex(*I).getBoundaryIndex(); 3056 break; 3057 } 3058 } 3059 } 3060 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd); 3061 3062 // All predecessors must have a live-out value. However for a phi 3063 // instruction with subregister intervals 3064 // only one of the subregisters (not necessarily the current one) needs to 3065 // be defined. 3066 if (!PVNI && (LaneMask.none() || !IsPHI)) { 3067 if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes)) 3068 continue; 3069 report("Register not marked live out of predecessor", Pred); 3070 report_context(LR, Reg, LaneMask); 3071 report_context(*VNI); 3072 errs() << " live into " << printMBBReference(*MFI) << '@' 3073 << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " 3074 << PEnd << '\n'; 3075 continue; 3076 } 3077 3078 // Only PHI-defs can take different predecessor values. 3079 if (!IsPHI && PVNI != VNI) { 3080 report("Different value live out of predecessor", Pred); 3081 report_context(LR, Reg, LaneMask); 3082 errs() << "Valno #" << PVNI->id << " live out of " 3083 << printMBBReference(*Pred) << '@' << PEnd << "\nValno #" 3084 << VNI->id << " live into " << printMBBReference(*MFI) << '@' 3085 << LiveInts->getMBBStartIdx(&*MFI) << '\n'; 3086 } 3087 } 3088 if (&*MFI == EndMBB) 3089 break; 3090 ++MFI; 3091 } 3092 } 3093 3094 void MachineVerifier::verifyLiveRange(const LiveRange &LR, Register Reg, 3095 LaneBitmask LaneMask) { 3096 for (const VNInfo *VNI : LR.valnos) 3097 verifyLiveRangeValue(LR, VNI, Reg, LaneMask); 3098 3099 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I) 3100 verifyLiveRangeSegment(LR, I, Reg, LaneMask); 3101 } 3102 3103 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) { 3104 Register Reg = LI.reg(); 3105 assert(Register::isVirtualRegister(Reg)); 3106 verifyLiveRange(LI, Reg); 3107 3108 LaneBitmask Mask; 3109 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg); 3110 for (const LiveInterval::SubRange &SR : LI.subranges()) { 3111 if ((Mask & SR.LaneMask).any()) { 3112 report("Lane masks of sub ranges overlap in live interval", MF); 3113 report_context(LI); 3114 } 3115 if ((SR.LaneMask & ~MaxMask).any()) { 3116 report("Subrange lanemask is invalid", MF); 3117 report_context(LI); 3118 } 3119 if (SR.empty()) { 3120 report("Subrange must not be empty", MF); 3121 report_context(SR, LI.reg(), SR.LaneMask); 3122 } 3123 Mask |= SR.LaneMask; 3124 verifyLiveRange(SR, LI.reg(), SR.LaneMask); 3125 if (!LI.covers(SR)) { 3126 report("A Subrange is not covered by the main range", MF); 3127 report_context(LI); 3128 } 3129 } 3130 3131 // Check the LI only has one connected component. 3132 ConnectedVNInfoEqClasses ConEQ(*LiveInts); 3133 unsigned NumComp = ConEQ.Classify(LI); 3134 if (NumComp > 1) { 3135 report("Multiple connected components in live interval", MF); 3136 report_context(LI); 3137 for (unsigned comp = 0; comp != NumComp; ++comp) { 3138 errs() << comp << ": valnos"; 3139 for (const VNInfo *I : LI.valnos) 3140 if (comp == ConEQ.getEqClass(I)) 3141 errs() << ' ' << I->id; 3142 errs() << '\n'; 3143 } 3144 } 3145 } 3146 3147 namespace { 3148 3149 // FrameSetup and FrameDestroy can have zero adjustment, so using a single 3150 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the 3151 // value is zero. 3152 // We use a bool plus an integer to capture the stack state. 3153 struct StackStateOfBB { 3154 StackStateOfBB() = default; 3155 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) : 3156 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup), 3157 ExitIsSetup(ExitSetup) {} 3158 3159 // Can be negative, which means we are setting up a frame. 3160 int EntryValue = 0; 3161 int ExitValue = 0; 3162 bool EntryIsSetup = false; 3163 bool ExitIsSetup = false; 3164 }; 3165 3166 } // end anonymous namespace 3167 3168 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed 3169 /// by a FrameDestroy <n>, stack adjustments are identical on all 3170 /// CFG edges to a merge point, and frame is destroyed at end of a return block. 3171 void MachineVerifier::verifyStackFrame() { 3172 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 3173 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 3174 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u) 3175 return; 3176 3177 SmallVector<StackStateOfBB, 8> SPState; 3178 SPState.resize(MF->getNumBlockIDs()); 3179 df_iterator_default_set<const MachineBasicBlock*> Reachable; 3180 3181 // Visit the MBBs in DFS order. 3182 for (df_ext_iterator<const MachineFunction *, 3183 df_iterator_default_set<const MachineBasicBlock *>> 3184 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable); 3185 DFI != DFE; ++DFI) { 3186 const MachineBasicBlock *MBB = *DFI; 3187 3188 StackStateOfBB BBState; 3189 // Check the exit state of the DFS stack predecessor. 3190 if (DFI.getPathLength() >= 2) { 3191 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 3192 assert(Reachable.count(StackPred) && 3193 "DFS stack predecessor is already visited.\n"); 3194 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue; 3195 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup; 3196 BBState.ExitValue = BBState.EntryValue; 3197 BBState.ExitIsSetup = BBState.EntryIsSetup; 3198 } 3199 3200 // Update stack state by checking contents of MBB. 3201 for (const auto &I : *MBB) { 3202 if (I.getOpcode() == FrameSetupOpcode) { 3203 if (BBState.ExitIsSetup) 3204 report("FrameSetup is after another FrameSetup", &I); 3205 BBState.ExitValue -= TII->getFrameTotalSize(I); 3206 BBState.ExitIsSetup = true; 3207 } 3208 3209 if (I.getOpcode() == FrameDestroyOpcode) { 3210 int Size = TII->getFrameTotalSize(I); 3211 if (!BBState.ExitIsSetup) 3212 report("FrameDestroy is not after a FrameSetup", &I); 3213 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue : 3214 BBState.ExitValue; 3215 if (BBState.ExitIsSetup && AbsSPAdj != Size) { 3216 report("FrameDestroy <n> is after FrameSetup <m>", &I); 3217 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <" 3218 << AbsSPAdj << ">.\n"; 3219 } 3220 BBState.ExitValue += Size; 3221 BBState.ExitIsSetup = false; 3222 } 3223 } 3224 SPState[MBB->getNumber()] = BBState; 3225 3226 // Make sure the exit state of any predecessor is consistent with the entry 3227 // state. 3228 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 3229 if (Reachable.count(Pred) && 3230 (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue || 3231 SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) { 3232 report("The exit stack state of a predecessor is inconsistent.", MBB); 3233 errs() << "Predecessor " << printMBBReference(*Pred) 3234 << " has exit state (" << SPState[Pred->getNumber()].ExitValue 3235 << ", " << SPState[Pred->getNumber()].ExitIsSetup << "), while " 3236 << printMBBReference(*MBB) << " has entry state (" 3237 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n"; 3238 } 3239 } 3240 3241 // Make sure the entry state of any successor is consistent with the exit 3242 // state. 3243 for (const MachineBasicBlock *Succ : MBB->successors()) { 3244 if (Reachable.count(Succ) && 3245 (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue || 3246 SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) { 3247 report("The entry stack state of a successor is inconsistent.", MBB); 3248 errs() << "Successor " << printMBBReference(*Succ) 3249 << " has entry state (" << SPState[Succ->getNumber()].EntryValue 3250 << ", " << SPState[Succ->getNumber()].EntryIsSetup << "), while " 3251 << printMBBReference(*MBB) << " has exit state (" 3252 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n"; 3253 } 3254 } 3255 3256 // Make sure a basic block with return ends with zero stack adjustment. 3257 if (!MBB->empty() && MBB->back().isReturn()) { 3258 if (BBState.ExitIsSetup) 3259 report("A return block ends with a FrameSetup.", MBB); 3260 if (BBState.ExitValue) 3261 report("A return block ends with a nonzero stack adjustment.", MBB); 3262 } 3263 } 3264 } 3265