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