1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Pass to verify generated machine code. The following is checked:
12 // Operand counts: All explicit operands must be present.
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/InlineAsm.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
53 struct MachineVerifier {
55 MachineVerifier(Pass *pass, const char *b) :
60 bool runOnMachineFunction(MachineFunction &MF);
64 const MachineFunction *MF;
65 const TargetMachine *TM;
66 const TargetInstrInfo *TII;
67 const TargetRegisterInfo *TRI;
68 const MachineRegisterInfo *MRI;
72 typedef SmallVector<unsigned, 16> RegVector;
73 typedef SmallVector<const uint32_t*, 4> RegMaskVector;
74 typedef DenseSet<unsigned> RegSet;
75 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
76 typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
78 const MachineInstr *FirstTerminator;
79 BlockSet FunctionBlocks;
81 BitVector regsReserved;
83 RegVector regsDefined, regsDead, regsKilled;
84 RegMaskVector regMasks;
85 RegSet regsLiveInButUnused;
89 // Add Reg and any sub-registers to RV
90 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
92 if (TargetRegisterInfo::isPhysicalRegister(Reg))
93 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
94 RV.push_back(*SubRegs);
98 // Is this MBB reachable from the MF entry point?
101 // Vregs that must be live in because they are used without being
102 // defined. Map value is the user.
105 // Regs killed in MBB. They may be defined again, and will then be in both
106 // regsKilled and regsLiveOut.
109 // Regs defined in MBB and live out. Note that vregs passing through may
110 // be live out without being mentioned here.
113 // Vregs that pass through MBB untouched. This set is disjoint from
114 // regsKilled and regsLiveOut.
117 // Vregs that must pass through MBB because they are needed by a successor
118 // block. This set is disjoint from regsLiveOut.
119 RegSet vregsRequired;
121 // Set versions of block's predecessor and successor lists.
122 BlockSet Preds, Succs;
124 BBInfo() : reachable(false) {}
126 // Add register to vregsPassed if it belongs there. Return true if
128 bool addPassed(unsigned Reg) {
129 if (!TargetRegisterInfo::isVirtualRegister(Reg))
131 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
133 return vregsPassed.insert(Reg).second;
136 // Same for a full set.
137 bool addPassed(const RegSet &RS) {
138 bool changed = false;
139 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
145 // Add register to vregsRequired if it belongs there. Return true if
147 bool addRequired(unsigned Reg) {
148 if (!TargetRegisterInfo::isVirtualRegister(Reg))
150 if (regsLiveOut.count(Reg))
152 return vregsRequired.insert(Reg).second;
155 // Same for a full set.
156 bool addRequired(const RegSet &RS) {
157 bool changed = false;
158 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
164 // Same for a full map.
165 bool addRequired(const RegMap &RM) {
166 bool changed = false;
167 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
168 if (addRequired(I->first))
173 // Live-out registers are either in regsLiveOut or vregsPassed.
174 bool isLiveOut(unsigned Reg) const {
175 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
179 // Extra register info per MBB.
180 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
182 bool isReserved(unsigned Reg) {
183 return Reg < regsReserved.size() && regsReserved.test(Reg);
186 bool isAllocatable(unsigned Reg) {
187 return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
190 // Analysis information if available
191 LiveVariables *LiveVars;
192 LiveIntervals *LiveInts;
193 LiveStacks *LiveStks;
194 SlotIndexes *Indexes;
196 void visitMachineFunctionBefore();
197 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
198 void visitMachineBundleBefore(const MachineInstr *MI);
199 void visitMachineInstrBefore(const MachineInstr *MI);
200 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
201 void visitMachineInstrAfter(const MachineInstr *MI);
202 void visitMachineBundleAfter(const MachineInstr *MI);
203 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
204 void visitMachineFunctionAfter();
206 void report(const char *msg, const MachineFunction *MF);
207 void report(const char *msg, const MachineBasicBlock *MBB);
208 void report(const char *msg, const MachineInstr *MI);
209 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
210 void report(const char *msg, const MachineFunction *MF,
211 const LiveInterval &LI);
212 void report(const char *msg, const MachineBasicBlock *MBB,
213 const LiveInterval &LI);
214 void report(const char *msg, const MachineFunction *MF,
215 const LiveRange &LR, unsigned Reg, LaneBitmask LaneMask);
216 void report(const char *msg, const MachineBasicBlock *MBB,
217 const LiveRange &LR, unsigned Reg, LaneBitmask LaneMask);
219 void verifyInlineAsm(const MachineInstr *MI);
221 void checkLiveness(const MachineOperand *MO, unsigned MONum);
222 void markReachable(const MachineBasicBlock *MBB);
223 void calcRegsPassed();
224 void checkPHIOps(const MachineBasicBlock *MBB);
226 void calcRegsRequired();
227 void verifyLiveVariables();
228 void verifyLiveIntervals();
229 void verifyLiveInterval(const LiveInterval&);
230 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
232 void verifyLiveRangeSegment(const LiveRange&,
233 const LiveRange::const_iterator I, unsigned,
235 void verifyLiveRange(const LiveRange&, unsigned, LaneBitmask LaneMask = 0);
237 void verifyStackFrame();
239 void verifySlotIndexes() const;
242 struct MachineVerifierPass : public MachineFunctionPass {
243 static char ID; // Pass ID, replacement for typeid
244 const std::string Banner;
246 MachineVerifierPass(const std::string &banner = nullptr)
247 : MachineFunctionPass(ID), Banner(banner) {
248 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
251 void getAnalysisUsage(AnalysisUsage &AU) const override {
252 AU.setPreservesAll();
253 MachineFunctionPass::getAnalysisUsage(AU);
256 bool runOnMachineFunction(MachineFunction &MF) override {
257 MF.verify(this, Banner.c_str());
264 char MachineVerifierPass::ID = 0;
265 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
266 "Verify generated machine code", false, false)
268 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
269 return new MachineVerifierPass(Banner);
272 void MachineFunction::verify(Pass *p, const char *Banner) const {
273 MachineVerifier(p, Banner)
274 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
277 void MachineVerifier::verifySlotIndexes() const {
278 if (Indexes == nullptr)
281 // Ensure the IdxMBB list is sorted by slot indexes.
283 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
284 E = Indexes->MBBIndexEnd(); I != E; ++I) {
285 assert(!Last.isValid() || I->first > Last);
290 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
294 TM = &MF.getTarget();
295 TII = MF.getSubtarget().getInstrInfo();
296 TRI = MF.getSubtarget().getRegisterInfo();
297 MRI = &MF.getRegInfo();
304 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
305 // We don't want to verify LiveVariables if LiveIntervals is available.
307 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
308 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
309 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
314 visitMachineFunctionBefore();
315 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
317 visitMachineBasicBlockBefore(MFI);
318 // Keep track of the current bundle header.
319 const MachineInstr *CurBundle = nullptr;
320 // Do we expect the next instruction to be part of the same bundle?
321 bool InBundle = false;
323 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
324 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
325 if (MBBI->getParent() != MFI) {
326 report("Bad instruction parent pointer", MFI);
327 errs() << "Instruction: " << *MBBI;
331 // Check for consistent bundle flags.
332 if (InBundle && !MBBI->isBundledWithPred())
333 report("Missing BundledPred flag, "
334 "BundledSucc was set on predecessor", MBBI);
335 if (!InBundle && MBBI->isBundledWithPred())
336 report("BundledPred flag is set, "
337 "but BundledSucc not set on predecessor", MBBI);
339 // Is this a bundle header?
340 if (!MBBI->isInsideBundle()) {
342 visitMachineBundleAfter(CurBundle);
344 visitMachineBundleBefore(CurBundle);
345 } else if (!CurBundle)
346 report("No bundle header", MBBI);
347 visitMachineInstrBefore(MBBI);
348 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
349 const MachineInstr &MI = *MBBI;
350 const MachineOperand &Op = MI.getOperand(I);
351 if (Op.getParent() != &MI) {
352 // Make sure to use correct addOperand / RemoveOperand / ChangeTo
353 // functions when replacing operands of a MachineInstr.
354 report("Instruction has operand with wrong parent set", &MI);
357 visitMachineOperand(&Op, I);
360 visitMachineInstrAfter(MBBI);
362 // Was this the last bundled instruction?
363 InBundle = MBBI->isBundledWithSucc();
366 visitMachineBundleAfter(CurBundle);
368 report("BundledSucc flag set on last instruction in block", &MFI->back());
369 visitMachineBasicBlockAfter(MFI);
371 visitMachineFunctionAfter();
374 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
382 regsLiveInButUnused.clear();
385 return false; // no changes
388 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
391 if (!foundErrors++) {
393 errs() << "# " << Banner << '\n';
394 MF->print(errs(), Indexes);
396 errs() << "*** Bad machine code: " << msg << " ***\n"
397 << "- function: " << MF->getName() << "\n";
400 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
402 report(msg, MBB->getParent());
403 errs() << "- basic block: BB#" << MBB->getNumber()
404 << ' ' << MBB->getName()
405 << " (" << (const void*)MBB << ')';
407 errs() << " [" << Indexes->getMBBStartIdx(MBB)
408 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
412 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
414 report(msg, MI->getParent());
415 errs() << "- instruction: ";
416 if (Indexes && Indexes->hasIndex(MI))
417 errs() << Indexes->getInstructionIndex(MI) << '\t';
418 MI->print(errs(), TM);
421 void MachineVerifier::report(const char *msg,
422 const MachineOperand *MO, unsigned MONum) {
424 report(msg, MO->getParent());
425 errs() << "- operand " << MONum << ": ";
426 MO->print(errs(), TRI);
430 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
431 const LiveInterval &LI) {
433 errs() << "- interval: " << LI << '\n';
436 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
437 const LiveInterval &LI) {
439 errs() << "- interval: " << LI << '\n';
442 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
443 const LiveRange &LR, unsigned Reg,
444 LaneBitmask LaneMask) {
446 errs() << "- liverange: " << LR << '\n';
447 errs() << "- register: " << PrintReg(Reg, TRI) << '\n';
449 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
452 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
453 const LiveRange &LR, unsigned Reg,
454 LaneBitmask LaneMask) {
456 errs() << "- liverange: " << LR << '\n';
457 errs() << "- register: " << PrintReg(Reg, TRI) << '\n';
459 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
462 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
463 BBInfo &MInfo = MBBInfoMap[MBB];
464 if (!MInfo.reachable) {
465 MInfo.reachable = true;
466 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
467 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
472 void MachineVerifier::visitMachineFunctionBefore() {
473 lastIndex = SlotIndex();
474 regsReserved = MRI->getReservedRegs();
476 // A sub-register of a reserved register is also reserved
477 for (int Reg = regsReserved.find_first(); Reg>=0;
478 Reg = regsReserved.find_next(Reg)) {
479 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
480 // FIXME: This should probably be:
481 // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
482 regsReserved.set(*SubRegs);
486 markReachable(&MF->front());
488 // Build a set of the basic blocks in the function.
489 FunctionBlocks.clear();
490 for (const auto &MBB : *MF) {
491 FunctionBlocks.insert(&MBB);
492 BBInfo &MInfo = MBBInfoMap[&MBB];
494 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
495 if (MInfo.Preds.size() != MBB.pred_size())
496 report("MBB has duplicate entries in its predecessor list.", &MBB);
498 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
499 if (MInfo.Succs.size() != MBB.succ_size())
500 report("MBB has duplicate entries in its successor list.", &MBB);
503 // Check that the register use lists are sane.
504 MRI->verifyUseLists();
509 // Does iterator point to a and b as the first two elements?
510 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
511 const MachineBasicBlock *a, const MachineBasicBlock *b) {
520 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
521 FirstTerminator = nullptr;
524 // If this block has allocatable physical registers live-in, check that
525 // it is an entry block or landing pad.
526 for (const auto &LI : MBB->liveins()) {
527 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
528 MBB != MBB->getParent()->begin()) {
529 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
534 // Count the number of landing pad successors.
535 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
536 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
537 E = MBB->succ_end(); I != E; ++I) {
539 LandingPadSuccs.insert(*I);
540 if (!FunctionBlocks.count(*I))
541 report("MBB has successor that isn't part of the function.", MBB);
542 if (!MBBInfoMap[*I].Preds.count(MBB)) {
543 report("Inconsistent CFG", MBB);
544 errs() << "MBB is not in the predecessor list of the successor BB#"
545 << (*I)->getNumber() << ".\n";
549 // Check the predecessor list.
550 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
551 E = MBB->pred_end(); I != E; ++I) {
552 if (!FunctionBlocks.count(*I))
553 report("MBB has predecessor that isn't part of the function.", MBB);
554 if (!MBBInfoMap[*I].Succs.count(MBB)) {
555 report("Inconsistent CFG", MBB);
556 errs() << "MBB is not in the successor list of the predecessor BB#"
557 << (*I)->getNumber() << ".\n";
561 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
562 const BasicBlock *BB = MBB->getBasicBlock();
563 if (LandingPadSuccs.size() > 1 &&
565 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
566 BB && isa<SwitchInst>(BB->getTerminator())))
567 report("MBB has more than one landing pad successor", MBB);
569 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
570 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
571 SmallVector<MachineOperand, 4> Cond;
572 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
574 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
575 // check whether its answers match up with reality.
577 // Block falls through to its successor.
578 MachineFunction::const_iterator MBBI = MBB;
580 if (MBBI == MF->end()) {
581 // It's possible that the block legitimately ends with a noreturn
582 // call or an unreachable, in which case it won't actually fall
583 // out the bottom of the function.
584 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
585 // It's possible that the block legitimately ends with a noreturn
586 // call or an unreachable, in which case it won't actuall fall
588 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
589 report("MBB exits via unconditional fall-through but doesn't have "
590 "exactly one CFG successor!", MBB);
591 } else if (!MBB->isSuccessor(MBBI)) {
592 report("MBB exits via unconditional fall-through but its successor "
593 "differs from its CFG successor!", MBB);
595 if (!MBB->empty() && MBB->back().isBarrier() &&
596 !TII->isPredicated(&MBB->back())) {
597 report("MBB exits via unconditional fall-through but ends with a "
598 "barrier instruction!", MBB);
601 report("MBB exits via unconditional fall-through but has a condition!",
604 } else if (TBB && !FBB && Cond.empty()) {
605 // Block unconditionally branches somewhere.
606 // If the block has exactly one successor, that happens to be a
607 // landingpad, accept it as valid control flow.
608 if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
609 (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
610 *MBB->succ_begin() != *LandingPadSuccs.begin())) {
611 report("MBB exits via unconditional branch but doesn't have "
612 "exactly one CFG successor!", MBB);
613 } else if (!MBB->isSuccessor(TBB)) {
614 report("MBB exits via unconditional branch but the CFG "
615 "successor doesn't match the actual successor!", MBB);
618 report("MBB exits via unconditional branch but doesn't contain "
619 "any instructions!", MBB);
620 } else if (!MBB->back().isBarrier()) {
621 report("MBB exits via unconditional branch but doesn't end with a "
622 "barrier instruction!", MBB);
623 } else if (!MBB->back().isTerminator()) {
624 report("MBB exits via unconditional branch but the branch isn't a "
625 "terminator instruction!", MBB);
627 } else if (TBB && !FBB && !Cond.empty()) {
628 // Block conditionally branches somewhere, otherwise falls through.
629 MachineFunction::const_iterator MBBI = MBB;
631 if (MBBI == MF->end()) {
632 report("MBB conditionally falls through out of function!", MBB);
633 } else if (MBB->succ_size() == 1) {
634 // A conditional branch with only one successor is weird, but allowed.
636 report("MBB exits via conditional branch/fall-through but only has "
637 "one CFG successor!", MBB);
638 else if (TBB != *MBB->succ_begin())
639 report("MBB exits via conditional branch/fall-through but the CFG "
640 "successor don't match the actual successor!", MBB);
641 } else if (MBB->succ_size() != 2) {
642 report("MBB exits via conditional branch/fall-through but doesn't have "
643 "exactly two CFG successors!", MBB);
644 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
645 report("MBB exits via conditional branch/fall-through but the CFG "
646 "successors don't match the actual successors!", MBB);
649 report("MBB exits via conditional branch/fall-through but doesn't "
650 "contain any instructions!", MBB);
651 } else if (MBB->back().isBarrier()) {
652 report("MBB exits via conditional branch/fall-through but ends with a "
653 "barrier instruction!", MBB);
654 } else if (!MBB->back().isTerminator()) {
655 report("MBB exits via conditional branch/fall-through but the branch "
656 "isn't a terminator instruction!", MBB);
658 } else if (TBB && FBB) {
659 // Block conditionally branches somewhere, otherwise branches
661 if (MBB->succ_size() == 1) {
662 // A conditional branch with only one successor is weird, but allowed.
664 report("MBB exits via conditional branch/branch through but only has "
665 "one CFG successor!", MBB);
666 else if (TBB != *MBB->succ_begin())
667 report("MBB exits via conditional branch/branch through but the CFG "
668 "successor don't match the actual successor!", MBB);
669 } else if (MBB->succ_size() != 2) {
670 report("MBB exits via conditional branch/branch but doesn't have "
671 "exactly two CFG successors!", MBB);
672 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
673 report("MBB exits via conditional branch/branch but the CFG "
674 "successors don't match the actual successors!", MBB);
677 report("MBB exits via conditional branch/branch but doesn't "
678 "contain any instructions!", MBB);
679 } else if (!MBB->back().isBarrier()) {
680 report("MBB exits via conditional branch/branch but doesn't end with a "
681 "barrier instruction!", MBB);
682 } else if (!MBB->back().isTerminator()) {
683 report("MBB exits via conditional branch/branch but the branch "
684 "isn't a terminator instruction!", MBB);
687 report("MBB exits via conditinal branch/branch but there's no "
691 report("AnalyzeBranch returned invalid data!", MBB);
696 for (const auto &LI : MBB->liveins()) {
697 if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
698 report("MBB live-in list contains non-physical register", MBB);
701 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
702 SubRegs.isValid(); ++SubRegs)
703 regsLive.insert(*SubRegs);
705 regsLiveInButUnused = regsLive;
707 const MachineFrameInfo *MFI = MF->getFrameInfo();
708 assert(MFI && "Function has no frame info");
709 BitVector PR = MFI->getPristineRegs(*MF);
710 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
711 for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
712 SubRegs.isValid(); ++SubRegs)
713 regsLive.insert(*SubRegs);
720 lastIndex = Indexes->getMBBStartIdx(MBB);
723 // This function gets called for all bundle headers, including normal
724 // stand-alone unbundled instructions.
725 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
726 if (Indexes && Indexes->hasIndex(MI)) {
727 SlotIndex idx = Indexes->getInstructionIndex(MI);
728 if (!(idx > lastIndex)) {
729 report("Instruction index out of order", MI);
730 errs() << "Last instruction was at " << lastIndex << '\n';
735 // Ensure non-terminators don't follow terminators.
736 // Ignore predicated terminators formed by if conversion.
737 // FIXME: If conversion shouldn't need to violate this rule.
738 if (MI->isTerminator() && !TII->isPredicated(MI)) {
739 if (!FirstTerminator)
740 FirstTerminator = MI;
741 } else if (FirstTerminator) {
742 report("Non-terminator instruction after the first terminator", MI);
743 errs() << "First terminator was:\t" << *FirstTerminator;
747 // The operands on an INLINEASM instruction must follow a template.
748 // Verify that the flag operands make sense.
749 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
750 // The first two operands on INLINEASM are the asm string and global flags.
751 if (MI->getNumOperands() < 2) {
752 report("Too few operands on inline asm", MI);
755 if (!MI->getOperand(0).isSymbol())
756 report("Asm string must be an external symbol", MI);
757 if (!MI->getOperand(1).isImm())
758 report("Asm flags must be an immediate", MI);
759 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
760 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
761 if (!isUInt<5>(MI->getOperand(1).getImm()))
762 report("Unknown asm flags", &MI->getOperand(1), 1);
764 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
766 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
768 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
769 const MachineOperand &MO = MI->getOperand(OpNo);
770 // There may be implicit ops after the fixed operands.
773 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
776 if (OpNo > MI->getNumOperands())
777 report("Missing operands in last group", MI);
779 // An optional MDNode follows the groups.
780 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
783 // All trailing operands must be implicit registers.
784 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
785 const MachineOperand &MO = MI->getOperand(OpNo);
786 if (!MO.isReg() || !MO.isImplicit())
787 report("Expected implicit register after groups", &MO, OpNo);
791 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
792 const MCInstrDesc &MCID = MI->getDesc();
793 if (MI->getNumOperands() < MCID.getNumOperands()) {
794 report("Too few operands", MI);
795 errs() << MCID.getNumOperands() << " operands expected, but "
796 << MI->getNumOperands() << " given.\n";
799 // Check the tied operands.
800 if (MI->isInlineAsm())
803 // Check the MachineMemOperands for basic consistency.
804 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
805 E = MI->memoperands_end(); I != E; ++I) {
806 if ((*I)->isLoad() && !MI->mayLoad())
807 report("Missing mayLoad flag", MI);
808 if ((*I)->isStore() && !MI->mayStore())
809 report("Missing mayStore flag", MI);
812 // Debug values must not have a slot index.
813 // Other instructions must have one, unless they are inside a bundle.
815 bool mapped = !LiveInts->isNotInMIMap(MI);
816 if (MI->isDebugValue()) {
818 report("Debug instruction has a slot index", MI);
819 } else if (MI->isInsideBundle()) {
821 report("Instruction inside bundle has a slot index", MI);
824 report("Missing slot index", MI);
829 if (!TII->verifyInstruction(MI, ErrorInfo))
830 report(ErrorInfo.data(), MI);
834 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
835 const MachineInstr *MI = MO->getParent();
836 const MCInstrDesc &MCID = MI->getDesc();
837 unsigned NumDefs = MCID.getNumDefs();
838 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
839 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
841 // The first MCID.NumDefs operands must be explicit register defines
842 if (MONum < NumDefs) {
843 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
845 report("Explicit definition must be a register", MO, MONum);
846 else if (!MO->isDef() && !MCOI.isOptionalDef())
847 report("Explicit definition marked as use", MO, MONum);
848 else if (MO->isImplicit())
849 report("Explicit definition marked as implicit", MO, MONum);
850 } else if (MONum < MCID.getNumOperands()) {
851 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
852 // Don't check if it's the last operand in a variadic instruction. See,
853 // e.g., LDM_RET in the arm back end.
855 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
856 if (MO->isDef() && !MCOI.isOptionalDef())
857 report("Explicit operand marked as def", MO, MONum);
858 if (MO->isImplicit())
859 report("Explicit operand marked as implicit", MO, MONum);
862 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
865 report("Tied use must be a register", MO, MONum);
866 else if (!MO->isTied())
867 report("Operand should be tied", MO, MONum);
868 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
869 report("Tied def doesn't match MCInstrDesc", MO, MONum);
870 } else if (MO->isReg() && MO->isTied())
871 report("Explicit operand should not be tied", MO, MONum);
873 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
874 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
875 report("Extra explicit operand on non-variadic instruction", MO, MONum);
878 switch (MO->getType()) {
879 case MachineOperand::MO_Register: {
880 const unsigned Reg = MO->getReg();
883 if (MRI->tracksLiveness() && !MI->isDebugValue())
884 checkLiveness(MO, MONum);
886 // Verify the consistency of tied operands.
888 unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
889 const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
890 if (!OtherMO.isReg())
891 report("Must be tied to a register", MO, MONum);
892 if (!OtherMO.isTied())
893 report("Missing tie flags on tied operand", MO, MONum);
894 if (MI->findTiedOperandIdx(OtherIdx) != MONum)
895 report("Inconsistent tie links", MO, MONum);
896 if (MONum < MCID.getNumDefs()) {
897 if (OtherIdx < MCID.getNumOperands()) {
898 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
899 report("Explicit def tied to explicit use without tie constraint",
902 if (!OtherMO.isImplicit())
903 report("Explicit def should be tied to implicit use", MO, MONum);
908 // Verify two-address constraints after leaving SSA form.
910 if (!MRI->isSSA() && MO->isUse() &&
911 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
912 Reg != MI->getOperand(DefIdx).getReg())
913 report("Two-address instruction operands must be identical", MO, MONum);
915 // Check register classes.
916 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
917 unsigned SubIdx = MO->getSubReg();
919 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
921 report("Illegal subregister index for physical register", MO, MONum);
924 if (const TargetRegisterClass *DRC =
925 TII->getRegClass(MCID, MONum, TRI, *MF)) {
926 if (!DRC->contains(Reg)) {
927 report("Illegal physical register for instruction", MO, MONum);
928 errs() << TRI->getName(Reg) << " is not a "
929 << TRI->getRegClassName(DRC) << " register.\n";
934 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
936 const TargetRegisterClass *SRC =
937 TRI->getSubClassWithSubReg(RC, SubIdx);
939 report("Invalid subregister index for virtual register", MO, MONum);
940 errs() << "Register class " << TRI->getRegClassName(RC)
941 << " does not support subreg index " << SubIdx << "\n";
945 report("Invalid register class for subregister index", MO, MONum);
946 errs() << "Register class " << TRI->getRegClassName(RC)
947 << " does not fully support subreg index " << SubIdx << "\n";
951 if (const TargetRegisterClass *DRC =
952 TII->getRegClass(MCID, MONum, TRI, *MF)) {
954 const TargetRegisterClass *SuperRC =
955 TRI->getLargestLegalSuperClass(RC, *MF);
957 report("No largest legal super class exists.", MO, MONum);
960 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
962 report("No matching super-reg register class.", MO, MONum);
966 if (!RC->hasSuperClassEq(DRC)) {
967 report("Illegal virtual register for instruction", MO, MONum);
968 errs() << "Expected a " << TRI->getRegClassName(DRC)
969 << " register, but got a " << TRI->getRegClassName(RC)
978 case MachineOperand::MO_RegisterMask:
979 regMasks.push_back(MO->getRegMask());
982 case MachineOperand::MO_MachineBasicBlock:
983 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
984 report("PHI operand is not in the CFG", MO, MONum);
987 case MachineOperand::MO_FrameIndex:
988 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
989 LiveInts && !LiveInts->isNotInMIMap(MI)) {
990 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
991 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
992 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
993 report("Instruction loads from dead spill slot", MO, MONum);
994 errs() << "Live stack: " << LI << '\n';
996 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
997 report("Instruction stores to dead spill slot", MO, MONum);
998 errs() << "Live stack: " << LI << '\n';
1008 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1009 const MachineInstr *MI = MO->getParent();
1010 const unsigned Reg = MO->getReg();
1012 // Both use and def operands can read a register.
1013 if (MO->readsReg()) {
1014 regsLiveInButUnused.erase(Reg);
1017 addRegWithSubRegs(regsKilled, Reg);
1019 // Check that LiveVars knows this kill.
1020 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1022 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1023 if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1024 report("Kill missing from LiveVariables", MO, MONum);
1027 // Check LiveInts liveness and kill.
1028 if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1029 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1030 // Check the cached regunit intervals.
1031 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1032 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1033 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) {
1034 LiveQueryResult LRQ = LR->Query(UseIdx);
1035 if (!LRQ.valueIn()) {
1036 report("No live segment at use", MO, MONum);
1037 errs() << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1038 << ' ' << *LR << '\n';
1040 if (MO->isKill() && !LRQ.isKill()) {
1041 report("Live range continues after kill flag", MO, MONum);
1042 errs() << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n';
1048 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1049 if (LiveInts->hasInterval(Reg)) {
1050 // This is a virtual register interval.
1051 const LiveInterval &LI = LiveInts->getInterval(Reg);
1052 LiveQueryResult LRQ = LI.Query(UseIdx);
1053 if (!LRQ.valueIn()) {
1054 report("No live segment at use", MO, MONum);
1055 errs() << UseIdx << " is not live in " << LI << '\n';
1057 // Check for extra kill flags.
1058 // Note that we allow missing kill flags for now.
1059 if (MO->isKill() && !LRQ.isKill()) {
1060 report("Live range continues after kill flag", MO, MONum);
1061 errs() << "Live range: " << LI << '\n';
1064 report("Virtual register has no live interval", MO, MONum);
1069 // Use of a dead register.
1070 if (!regsLive.count(Reg)) {
1071 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1072 // Reserved registers may be used even when 'dead'.
1073 bool Bad = !isReserved(Reg);
1074 // We are fine if just any subregister has a defined value.
1076 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
1078 if (regsLive.count(*SubRegs)) {
1084 // If there is an additional implicit-use of a super register we stop
1085 // here. By definition we are fine if the super register is not
1086 // (completely) dead, if the complete super register is dead we will
1087 // get a report for its operand.
1089 for (const MachineOperand &MOP : MI->uses()) {
1092 if (!MOP.isImplicit())
1094 for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1096 if (*SubRegs == Reg) {
1104 report("Using an undefined physical register", MO, MONum);
1105 } else if (MRI->def_empty(Reg)) {
1106 report("Reading virtual register without a def", MO, MONum);
1108 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1109 // We don't know which virtual registers are live in, so only complain
1110 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1111 // must be live in. PHI instructions are handled separately.
1112 if (MInfo.regsKilled.count(Reg))
1113 report("Using a killed virtual register", MO, MONum);
1114 else if (!MI->isPHI())
1115 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1121 // Register defined.
1122 // TODO: verify that earlyclobber ops are not used.
1124 addRegWithSubRegs(regsDead, Reg);
1126 addRegWithSubRegs(regsDefined, Reg);
1129 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1130 std::next(MRI->def_begin(Reg)) != MRI->def_end())
1131 report("Multiple virtual register defs in SSA form", MO, MONum);
1133 // Check LiveInts for a live segment, but only for virtual registers.
1134 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1135 !LiveInts->isNotInMIMap(MI)) {
1136 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1137 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1138 if (LiveInts->hasInterval(Reg)) {
1139 const LiveInterval &LI = LiveInts->getInterval(Reg);
1140 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1141 assert(VNI && "NULL valno is not allowed");
1142 if (VNI->def != DefIdx) {
1143 report("Inconsistent valno->def", MO, MONum);
1144 errs() << "Valno " << VNI->id << " is not defined at "
1145 << DefIdx << " in " << LI << '\n';
1148 report("No live segment at def", MO, MONum);
1149 errs() << DefIdx << " is not live in " << LI << '\n';
1151 // Check that, if the dead def flag is present, LiveInts agree.
1153 LiveQueryResult LRQ = LI.Query(DefIdx);
1154 if (!LRQ.isDeadDef()) {
1155 report("Live range continues after dead def flag", MO, MONum);
1156 errs() << "Live range: " << LI << '\n';
1160 report("Virtual register has no Live interval", MO, MONum);
1166 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1169 // This function gets called after visiting all instructions in a bundle. The
1170 // argument points to the bundle header.
1171 // Normal stand-alone instructions are also considered 'bundles', and this
1172 // function is called for all of them.
1173 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1174 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1175 set_union(MInfo.regsKilled, regsKilled);
1176 set_subtract(regsLive, regsKilled); regsKilled.clear();
1177 // Kill any masked registers.
1178 while (!regMasks.empty()) {
1179 const uint32_t *Mask = regMasks.pop_back_val();
1180 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1181 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1182 MachineOperand::clobbersPhysReg(Mask, *I))
1183 regsDead.push_back(*I);
1185 set_subtract(regsLive, regsDead); regsDead.clear();
1186 set_union(regsLive, regsDefined); regsDefined.clear();
1190 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1191 MBBInfoMap[MBB].regsLiveOut = regsLive;
1195 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1196 if (!(stop > lastIndex)) {
1197 report("Block ends before last instruction index", MBB);
1198 errs() << "Block ends at " << stop
1199 << " last instruction was at " << lastIndex << '\n';
1205 // Calculate the largest possible vregsPassed sets. These are the registers that
1206 // can pass through an MBB live, but may not be live every time. It is assumed
1207 // that all vregsPassed sets are empty before the call.
1208 void MachineVerifier::calcRegsPassed() {
1209 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1210 // have any vregsPassed.
1211 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1212 for (const auto &MBB : *MF) {
1213 BBInfo &MInfo = MBBInfoMap[&MBB];
1214 if (!MInfo.reachable)
1216 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1217 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1218 BBInfo &SInfo = MBBInfoMap[*SuI];
1219 if (SInfo.addPassed(MInfo.regsLiveOut))
1224 // Iteratively push vregsPassed to successors. This will converge to the same
1225 // final state regardless of DenseSet iteration order.
1226 while (!todo.empty()) {
1227 const MachineBasicBlock *MBB = *todo.begin();
1229 BBInfo &MInfo = MBBInfoMap[MBB];
1230 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1231 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1234 BBInfo &SInfo = MBBInfoMap[*SuI];
1235 if (SInfo.addPassed(MInfo.vregsPassed))
1241 // Calculate the set of virtual registers that must be passed through each basic
1242 // block in order to satisfy the requirements of successor blocks. This is very
1243 // similar to calcRegsPassed, only backwards.
1244 void MachineVerifier::calcRegsRequired() {
1245 // First push live-in regs to predecessors' vregsRequired.
1246 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1247 for (const auto &MBB : *MF) {
1248 BBInfo &MInfo = MBBInfoMap[&MBB];
1249 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1250 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1251 BBInfo &PInfo = MBBInfoMap[*PrI];
1252 if (PInfo.addRequired(MInfo.vregsLiveIn))
1257 // Iteratively push vregsRequired to predecessors. This will converge to the
1258 // same final state regardless of DenseSet iteration order.
1259 while (!todo.empty()) {
1260 const MachineBasicBlock *MBB = *todo.begin();
1262 BBInfo &MInfo = MBBInfoMap[MBB];
1263 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1264 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1267 BBInfo &SInfo = MBBInfoMap[*PrI];
1268 if (SInfo.addRequired(MInfo.vregsRequired))
1274 // Check PHI instructions at the beginning of MBB. It is assumed that
1275 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1276 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1277 SmallPtrSet<const MachineBasicBlock*, 8> seen;
1278 for (const auto &BBI : *MBB) {
1283 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
1284 unsigned Reg = BBI.getOperand(i).getReg();
1285 const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB();
1286 if (!Pre->isSuccessor(MBB))
1289 BBInfo &PrInfo = MBBInfoMap[Pre];
1290 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1291 report("PHI operand is not live-out from predecessor",
1292 &BBI.getOperand(i), i);
1295 // Did we see all predecessors?
1296 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1297 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1298 if (!seen.count(*PrI)) {
1299 report("Missing PHI operand", &BBI);
1300 errs() << "BB#" << (*PrI)->getNumber()
1301 << " is a predecessor according to the CFG.\n";
1307 void MachineVerifier::visitMachineFunctionAfter() {
1310 for (const auto &MBB : *MF) {
1311 BBInfo &MInfo = MBBInfoMap[&MBB];
1313 // Skip unreachable MBBs.
1314 if (!MInfo.reachable)
1320 // Now check liveness info if available
1323 // Check for killed virtual registers that should be live out.
1324 for (const auto &MBB : *MF) {
1325 BBInfo &MInfo = MBBInfoMap[&MBB];
1326 for (RegSet::iterator
1327 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1329 if (MInfo.regsKilled.count(*I)) {
1330 report("Virtual register killed in block, but needed live out.", &MBB);
1331 errs() << "Virtual register " << PrintReg(*I)
1332 << " is used after the block.\n";
1337 BBInfo &MInfo = MBBInfoMap[&MF->front()];
1338 for (RegSet::iterator
1339 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1341 report("Virtual register def doesn't dominate all uses.",
1342 MRI->getVRegDef(*I));
1346 verifyLiveVariables();
1348 verifyLiveIntervals();
1351 void MachineVerifier::verifyLiveVariables() {
1352 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1353 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1354 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1355 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1356 for (const auto &MBB : *MF) {
1357 BBInfo &MInfo = MBBInfoMap[&MBB];
1359 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1360 if (MInfo.vregsRequired.count(Reg)) {
1361 if (!VI.AliveBlocks.test(MBB.getNumber())) {
1362 report("LiveVariables: Block missing from AliveBlocks", &MBB);
1363 errs() << "Virtual register " << PrintReg(Reg)
1364 << " must be live through the block.\n";
1367 if (VI.AliveBlocks.test(MBB.getNumber())) {
1368 report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1369 errs() << "Virtual register " << PrintReg(Reg)
1370 << " is not needed live through the block.\n";
1377 void MachineVerifier::verifyLiveIntervals() {
1378 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1379 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1380 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1382 // Spilling and splitting may leave unused registers around. Skip them.
1383 if (MRI->reg_nodbg_empty(Reg))
1386 if (!LiveInts->hasInterval(Reg)) {
1387 report("Missing live interval for virtual register", MF);
1388 errs() << PrintReg(Reg, TRI) << " still has defs or uses\n";
1392 const LiveInterval &LI = LiveInts->getInterval(Reg);
1393 assert(Reg == LI.reg && "Invalid reg to interval mapping");
1394 verifyLiveInterval(LI);
1397 // Verify all the cached regunit intervals.
1398 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1399 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1400 verifyLiveRange(*LR, i);
1403 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1404 const VNInfo *VNI, unsigned Reg,
1405 LaneBitmask LaneMask) {
1406 if (VNI->isUnused())
1409 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1412 report("Valno not live at def and not marked unused", MF, LR, Reg,
1414 errs() << "Valno #" << VNI->id << '\n';
1418 if (DefVNI != VNI) {
1419 report("Live segment at def has different valno", MF, LR, Reg, LaneMask);
1420 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1421 << " where valno #" << DefVNI->id << " is live\n";
1425 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1427 report("Invalid definition index", MF, LR, Reg, LaneMask);
1428 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1429 << " in " << LR << '\n';
1433 if (VNI->isPHIDef()) {
1434 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1435 report("PHIDef value is not defined at MBB start", MBB, LR, Reg,
1437 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1438 << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1444 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1446 report("No instruction at def index", MBB, LR, Reg, LaneMask);
1447 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1452 bool hasDef = false;
1453 bool isEarlyClobber = false;
1454 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1455 if (!MOI->isReg() || !MOI->isDef())
1457 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1458 if (MOI->getReg() != Reg)
1461 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1462 !TRI->hasRegUnit(MOI->getReg(), Reg))
1465 if (LaneMask != 0 &&
1466 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask) == 0)
1469 if (MOI->isEarlyClobber())
1470 isEarlyClobber = true;
1474 report("Defining instruction does not modify register", MI);
1475 errs() << "Valno #" << VNI->id << " in " << LR << '\n';
1478 // Early clobber defs begin at USE slots, but other defs must begin at
1480 if (isEarlyClobber) {
1481 if (!VNI->def.isEarlyClobber()) {
1482 report("Early clobber def must be at an early-clobber slot", MBB, LR,
1484 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1486 } else if (!VNI->def.isRegister()) {
1487 report("Non-PHI, non-early clobber def must be at a register slot",
1488 MBB, LR, Reg, LaneMask);
1489 errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1494 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1495 const LiveRange::const_iterator I,
1496 unsigned Reg, LaneBitmask LaneMask)
1498 const LiveRange::Segment &S = *I;
1499 const VNInfo *VNI = S.valno;
1500 assert(VNI && "Live segment has no valno");
1502 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1503 report("Foreign valno in live segment", MF, LR, Reg, LaneMask);
1504 errs() << S << " has a bad valno\n";
1507 if (VNI->isUnused()) {
1508 report("Live segment valno is marked unused", MF, LR, Reg, LaneMask);
1509 errs() << S << '\n';
1512 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1514 report("Bad start of live segment, no basic block", MF, LR, Reg, LaneMask);
1515 errs() << S << '\n';
1518 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1519 if (S.start != MBBStartIdx && S.start != VNI->def) {
1520 report("Live segment must begin at MBB entry or valno def", MBB, LR, Reg,
1522 errs() << S << '\n';
1525 const MachineBasicBlock *EndMBB =
1526 LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1528 report("Bad end of live segment, no basic block", MF, LR, Reg, LaneMask);
1529 errs() << S << '\n';
1533 // No more checks for live-out segments.
1534 if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1537 // RegUnit intervals are allowed dead phis.
1538 if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1539 S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1542 // The live segment is ending inside EndMBB
1543 const MachineInstr *MI =
1544 LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1546 report("Live segment doesn't end at a valid instruction", EndMBB, LR, Reg,
1548 errs() << S << '\n';
1552 // The block slot must refer to a basic block boundary.
1553 if (S.end.isBlock()) {
1554 report("Live segment ends at B slot of an instruction", EndMBB, LR, Reg,
1556 errs() << S << '\n';
1559 if (S.end.isDead()) {
1560 // Segment ends on the dead slot.
1561 // That means there must be a dead def.
1562 if (!SlotIndex::isSameInstr(S.start, S.end)) {
1563 report("Live segment ending at dead slot spans instructions", EndMBB, LR,
1565 errs() << S << '\n';
1569 // A live segment can only end at an early-clobber slot if it is being
1570 // redefined by an early-clobber def.
1571 if (S.end.isEarlyClobber()) {
1572 if (I+1 == LR.end() || (I+1)->start != S.end) {
1573 report("Live segment ending at early clobber slot must be "
1574 "redefined by an EC def in the same instruction", EndMBB, LR, Reg,
1576 errs() << S << '\n';
1580 // The following checks only apply to virtual registers. Physreg liveness
1581 // is too weird to check.
1582 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1583 // A live segment can end with either a redefinition, a kill flag on a
1584 // use, or a dead flag on a def.
1585 bool hasRead = false;
1586 bool hasSubRegDef = false;
1587 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1588 if (!MOI->isReg() || MOI->getReg() != Reg)
1590 if (LaneMask != 0 &&
1591 (LaneMask & TRI->getSubRegIndexLaneMask(MOI->getSubReg())) == 0)
1593 if (MOI->isDef() && MOI->getSubReg() != 0)
1594 hasSubRegDef = true;
1595 if (MOI->readsReg())
1598 if (!S.end.isDead()) {
1600 // When tracking subregister liveness, the main range must start new
1601 // values on partial register writes, even if there is no read.
1602 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask != 0 ||
1604 report("Instruction ending live segment doesn't read the register",
1606 errs() << S << " in " << LR << '\n';
1612 // Now check all the basic blocks in this live segment.
1613 MachineFunction::const_iterator MFI = MBB;
1614 // Is this live segment the beginning of a non-PHIDef VN?
1615 if (S.start == VNI->def && !VNI->isPHIDef()) {
1616 // Not live-in to any blocks.
1623 assert(LiveInts->isLiveInToMBB(LR, MFI));
1624 // We don't know how to track physregs into a landing pad.
1625 if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1627 if (&*MFI == EndMBB)
1633 // Is VNI a PHI-def in the current block?
1634 bool IsPHI = VNI->isPHIDef() &&
1635 VNI->def == LiveInts->getMBBStartIdx(MFI);
1637 // Check that VNI is live-out of all predecessors.
1638 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1639 PE = MFI->pred_end(); PI != PE; ++PI) {
1640 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1641 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1643 // All predecessors must have a live-out value.
1645 report("Register not marked live out of predecessor", *PI, LR, Reg,
1647 errs() << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1648 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1653 // Only PHI-defs can take different predecessor values.
1654 if (!IsPHI && PVNI != VNI) {
1655 report("Different value live out of predecessor", *PI, LR, Reg,
1657 errs() << "Valno #" << PVNI->id << " live out of BB#"
1658 << (*PI)->getNumber() << '@' << PEnd
1659 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1660 << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
1663 if (&*MFI == EndMBB)
1669 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
1670 LaneBitmask LaneMask) {
1671 for (const VNInfo *VNI : LR.valnos)
1672 verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
1674 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1675 verifyLiveRangeSegment(LR, I, Reg, LaneMask);
1678 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1679 unsigned Reg = LI.reg;
1680 assert(TargetRegisterInfo::isVirtualRegister(Reg));
1681 verifyLiveRange(LI, Reg);
1683 LaneBitmask Mask = 0;
1684 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
1685 for (const LiveInterval::SubRange &SR : LI.subranges()) {
1686 if ((Mask & SR.LaneMask) != 0)
1687 report("Lane masks of sub ranges overlap in live interval", MF, LI);
1688 if ((SR.LaneMask & ~MaxMask) != 0)
1689 report("Subrange lanemask is invalid", MF, LI);
1691 report("Subrange must not be empty", MF, SR, LI.reg, SR.LaneMask);
1692 Mask |= SR.LaneMask;
1693 verifyLiveRange(SR, LI.reg, SR.LaneMask);
1695 report("A Subrange is not covered by the main range", MF, LI);
1698 // Check the LI only has one connected component.
1699 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1700 unsigned NumComp = ConEQ.Classify(&LI);
1702 report("Multiple connected components in live interval", MF, LI);
1703 for (unsigned comp = 0; comp != NumComp; ++comp) {
1704 errs() << comp << ": valnos";
1705 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1706 E = LI.vni_end(); I!=E; ++I)
1707 if (comp == ConEQ.getEqClass(*I))
1708 errs() << ' ' << (*I)->id;
1715 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1716 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1718 // We use a bool plus an integer to capture the stack state.
1719 struct StackStateOfBB {
1720 StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1721 ExitIsSetup(false) { }
1722 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1723 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1724 ExitIsSetup(ExitSetup) { }
1725 // Can be negative, which means we are setting up a frame.
1733 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1734 /// by a FrameDestroy <n>, stack adjustments are identical on all
1735 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1736 void MachineVerifier::verifyStackFrame() {
1737 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
1738 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1740 SmallVector<StackStateOfBB, 8> SPState;
1741 SPState.resize(MF->getNumBlockIDs());
1742 SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1744 // Visit the MBBs in DFS order.
1745 for (df_ext_iterator<const MachineFunction*,
1746 SmallPtrSet<const MachineBasicBlock*, 8> >
1747 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1748 DFI != DFE; ++DFI) {
1749 const MachineBasicBlock *MBB = *DFI;
1751 StackStateOfBB BBState;
1752 // Check the exit state of the DFS stack predecessor.
1753 if (DFI.getPathLength() >= 2) {
1754 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1755 assert(Reachable.count(StackPred) &&
1756 "DFS stack predecessor is already visited.\n");
1757 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1758 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1759 BBState.ExitValue = BBState.EntryValue;
1760 BBState.ExitIsSetup = BBState.EntryIsSetup;
1763 // Update stack state by checking contents of MBB.
1764 for (const auto &I : *MBB) {
1765 if (I.getOpcode() == FrameSetupOpcode) {
1766 // The first operand of a FrameOpcode should be i32.
1767 int Size = I.getOperand(0).getImm();
1769 "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1771 if (BBState.ExitIsSetup)
1772 report("FrameSetup is after another FrameSetup", &I);
1773 BBState.ExitValue -= Size;
1774 BBState.ExitIsSetup = true;
1777 if (I.getOpcode() == FrameDestroyOpcode) {
1778 // The first operand of a FrameOpcode should be i32.
1779 int Size = I.getOperand(0).getImm();
1781 "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1783 if (!BBState.ExitIsSetup)
1784 report("FrameDestroy is not after a FrameSetup", &I);
1785 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1787 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1788 report("FrameDestroy <n> is after FrameSetup <m>", &I);
1789 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
1790 << AbsSPAdj << ">.\n";
1792 BBState.ExitValue += Size;
1793 BBState.ExitIsSetup = false;
1796 SPState[MBB->getNumber()] = BBState;
1798 // Make sure the exit state of any predecessor is consistent with the entry
1800 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1801 E = MBB->pred_end(); I != E; ++I) {
1802 if (Reachable.count(*I) &&
1803 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1804 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1805 report("The exit stack state of a predecessor is inconsistent.", MBB);
1806 errs() << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1807 << SPState[(*I)->getNumber()].ExitValue << ", "
1808 << SPState[(*I)->getNumber()].ExitIsSetup
1809 << "), while BB#" << MBB->getNumber() << " has entry state ("
1810 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1814 // Make sure the entry state of any successor is consistent with the exit
1816 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1817 E = MBB->succ_end(); I != E; ++I) {
1818 if (Reachable.count(*I) &&
1819 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1820 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1821 report("The entry stack state of a successor is inconsistent.", MBB);
1822 errs() << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1823 << SPState[(*I)->getNumber()].EntryValue << ", "
1824 << SPState[(*I)->getNumber()].EntryIsSetup
1825 << "), while BB#" << MBB->getNumber() << " has exit state ("
1826 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1830 // Make sure a basic block with return ends with zero stack adjustment.
1831 if (!MBB->empty() && MBB->back().isReturn()) {
1832 if (BBState.ExitIsSetup)
1833 report("A return block ends with a FrameSetup.", MBB);
1834 if (BBState.ExitValue)
1835 report("A return block ends with a nonzero stack adjustment.", MBB);