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