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/ADT/BitVector.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/DepthFirstIterator.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetOperations.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/Analysis/EHPersonalities.h"
37 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
38 #include "llvm/CodeGen/LiveInterval.h"
39 #include "llvm/CodeGen/LiveIntervals.h"
40 #include "llvm/CodeGen/LiveStacks.h"
41 #include "llvm/CodeGen/LiveVariables.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineFunctionPass.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBundle.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineOperand.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/CodeGen/PseudoSourceValue.h"
52 #include "llvm/CodeGen/SlotIndexes.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/TargetInstrInfo.h"
55 #include "llvm/CodeGen/TargetOpcodes.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/TargetSubtargetInfo.h"
58 #include "llvm/IR/BasicBlock.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/InlineAsm.h"
61 #include "llvm/IR/Instructions.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"
86 struct MachineVerifier {
87 MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
89 unsigned verify(MachineFunction &MF);
93 const MachineFunction *MF;
94 const TargetMachine *TM;
95 const TargetInstrInfo *TII;
96 const TargetRegisterInfo *TRI;
97 const MachineRegisterInfo *MRI;
101 // Avoid querying the MachineFunctionProperties for each operand.
102 bool isFunctionRegBankSelected;
103 bool isFunctionSelected;
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>;
111 const MachineInstr *FirstTerminator;
112 BlockSet FunctionBlocks;
114 BitVector regsReserved;
116 RegVector regsDefined, regsDead, regsKilled;
117 RegMaskVector regMasks;
121 // Add Reg and any sub-registers to RV
122 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
124 if (TargetRegisterInfo::isPhysicalRegister(Reg))
125 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
126 RV.push_back(*SubRegs);
130 // Is this MBB reachable from the MF entry point?
131 bool reachable = false;
133 // Vregs that must be live in because they are used without being
134 // defined. Map value is the user.
137 // Regs killed in MBB. They may be defined again, and will then be in both
138 // regsKilled and regsLiveOut.
141 // Regs defined in MBB and live out. Note that vregs passing through may
142 // be live out without being mentioned here.
145 // Vregs that pass through MBB untouched. This set is disjoint from
146 // regsKilled and regsLiveOut.
149 // Vregs that must pass through MBB because they are needed by a successor
150 // block. This set is disjoint from regsLiveOut.
151 RegSet vregsRequired;
153 // Set versions of block's predecessor and successor lists.
154 BlockSet Preds, Succs;
158 // Add register to vregsPassed if it belongs there. Return true if
160 bool addPassed(unsigned Reg) {
161 if (!TargetRegisterInfo::isVirtualRegister(Reg))
163 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
165 return vregsPassed.insert(Reg).second;
168 // Same for a full set.
169 bool addPassed(const RegSet &RS) {
170 bool changed = false;
171 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
177 // Add register to vregsRequired if it belongs there. Return true if
179 bool addRequired(unsigned Reg) {
180 if (!TargetRegisterInfo::isVirtualRegister(Reg))
182 if (regsLiveOut.count(Reg))
184 return vregsRequired.insert(Reg).second;
187 // Same for a full set.
188 bool addRequired(const RegSet &RS) {
189 bool changed = false;
190 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
196 // Same for a full map.
197 bool addRequired(const RegMap &RM) {
198 bool changed = false;
199 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
200 if (addRequired(I->first))
205 // Live-out registers are either in regsLiveOut or vregsPassed.
206 bool isLiveOut(unsigned Reg) const {
207 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
211 // Extra register info per MBB.
212 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
214 bool isReserved(unsigned Reg) {
215 return Reg < regsReserved.size() && regsReserved.test(Reg);
218 bool isAllocatable(unsigned Reg) const {
219 return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
220 !regsReserved.test(Reg);
223 // Analysis information if available
224 LiveVariables *LiveVars;
225 LiveIntervals *LiveInts;
226 LiveStacks *LiveStks;
227 SlotIndexes *Indexes;
229 void visitMachineFunctionBefore();
230 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
231 void visitMachineBundleBefore(const MachineInstr *MI);
232 void visitMachineInstrBefore(const MachineInstr *MI);
233 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
234 void visitMachineInstrAfter(const MachineInstr *MI);
235 void visitMachineBundleAfter(const MachineInstr *MI);
236 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
237 void visitMachineFunctionAfter();
239 void report(const char *msg, const MachineFunction *MF);
240 void report(const char *msg, const MachineBasicBlock *MBB);
241 void report(const char *msg, const MachineInstr *MI);
242 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
244 void report_context(const LiveInterval &LI) const;
245 void report_context(const LiveRange &LR, unsigned VRegUnit,
246 LaneBitmask LaneMask) const;
247 void report_context(const LiveRange::Segment &S) const;
248 void report_context(const VNInfo &VNI) const;
249 void report_context(SlotIndex Pos) const;
250 void report_context_liverange(const LiveRange &LR) const;
251 void report_context_lanemask(LaneBitmask LaneMask) const;
252 void report_context_vreg(unsigned VReg) const;
253 void report_context_vreg_regunit(unsigned VRegOrRegUnit) const;
255 void verifyInlineAsm(const MachineInstr *MI);
257 void checkLiveness(const MachineOperand *MO, unsigned MONum);
258 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
259 SlotIndex UseIdx, const LiveRange &LR, unsigned Reg,
260 LaneBitmask LaneMask = LaneBitmask::getNone());
261 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
262 SlotIndex DefIdx, const LiveRange &LR, unsigned Reg,
263 LaneBitmask LaneMask = LaneBitmask::getNone());
265 void markReachable(const MachineBasicBlock *MBB);
266 void calcRegsPassed();
267 void checkPHIOps(const MachineBasicBlock &MBB);
269 void calcRegsRequired();
270 void verifyLiveVariables();
271 void verifyLiveIntervals();
272 void verifyLiveInterval(const LiveInterval&);
273 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
275 void verifyLiveRangeSegment(const LiveRange&,
276 const LiveRange::const_iterator I, unsigned,
278 void verifyLiveRange(const LiveRange&, unsigned,
279 LaneBitmask LaneMask = LaneBitmask::getNone());
281 void verifyStackFrame();
283 void verifySlotIndexes() const;
284 void verifyProperties(const MachineFunction &MF);
287 struct MachineVerifierPass : public MachineFunctionPass {
288 static char ID; // Pass ID, replacement for typeid
290 const std::string Banner;
292 MachineVerifierPass(std::string banner = std::string())
293 : MachineFunctionPass(ID), Banner(std::move(banner)) {
294 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
297 void getAnalysisUsage(AnalysisUsage &AU) const override {
298 AU.setPreservesAll();
299 MachineFunctionPass::getAnalysisUsage(AU);
302 bool runOnMachineFunction(MachineFunction &MF) override {
303 unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
305 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
310 } // end anonymous namespace
312 char MachineVerifierPass::ID = 0;
314 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
315 "Verify generated machine code", false, false)
317 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
318 return new MachineVerifierPass(Banner);
321 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
323 MachineFunction &MF = const_cast<MachineFunction&>(*this);
324 unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
325 if (AbortOnErrors && FoundErrors)
326 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
327 return FoundErrors == 0;
330 void MachineVerifier::verifySlotIndexes() const {
331 if (Indexes == nullptr)
334 // Ensure the IdxMBB list is sorted by slot indexes.
336 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
337 E = Indexes->MBBIndexEnd(); I != E; ++I) {
338 assert(!Last.isValid() || I->first > Last);
343 void MachineVerifier::verifyProperties(const MachineFunction &MF) {
344 // If a pass has introduced virtual registers without clearing the
345 // NoVRegs property (or set it without allocating the vregs)
346 // then report an error.
347 if (MF.getProperties().hasProperty(
348 MachineFunctionProperties::Property::NoVRegs) &&
349 MRI->getNumVirtRegs())
350 report("Function has NoVRegs property but there are VReg operands", &MF);
353 unsigned MachineVerifier::verify(MachineFunction &MF) {
357 TM = &MF.getTarget();
358 TII = MF.getSubtarget().getInstrInfo();
359 TRI = MF.getSubtarget().getRegisterInfo();
360 MRI = &MF.getRegInfo();
362 isFunctionRegBankSelected = MF.getProperties().hasProperty(
363 MachineFunctionProperties::Property::RegBankSelected);
364 isFunctionSelected = MF.getProperties().hasProperty(
365 MachineFunctionProperties::Property::Selected);
372 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
373 // We don't want to verify LiveVariables if LiveIntervals is available.
375 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
376 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
377 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
382 verifyProperties(MF);
384 visitMachineFunctionBefore();
385 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
387 visitMachineBasicBlockBefore(&*MFI);
388 // Keep track of the current bundle header.
389 const MachineInstr *CurBundle = nullptr;
390 // Do we expect the next instruction to be part of the same bundle?
391 bool InBundle = false;
393 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
394 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
395 if (MBBI->getParent() != &*MFI) {
396 report("Bad instruction parent pointer", &*MFI);
397 errs() << "Instruction: " << *MBBI;
401 // Check for consistent bundle flags.
402 if (InBundle && !MBBI->isBundledWithPred())
403 report("Missing BundledPred flag, "
404 "BundledSucc was set on predecessor",
406 if (!InBundle && MBBI->isBundledWithPred())
407 report("BundledPred flag is set, "
408 "but BundledSucc not set on predecessor",
411 // Is this a bundle header?
412 if (!MBBI->isInsideBundle()) {
414 visitMachineBundleAfter(CurBundle);
416 visitMachineBundleBefore(CurBundle);
417 } else if (!CurBundle)
418 report("No bundle header", &*MBBI);
419 visitMachineInstrBefore(&*MBBI);
420 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
421 const MachineInstr &MI = *MBBI;
422 const MachineOperand &Op = MI.getOperand(I);
423 if (Op.getParent() != &MI) {
424 // Make sure to use correct addOperand / RemoveOperand / ChangeTo
425 // functions when replacing operands of a MachineInstr.
426 report("Instruction has operand with wrong parent set", &MI);
429 visitMachineOperand(&Op, I);
432 visitMachineInstrAfter(&*MBBI);
434 // Was this the last bundled instruction?
435 InBundle = MBBI->isBundledWithSucc();
438 visitMachineBundleAfter(CurBundle);
440 report("BundledSucc flag set on last instruction in block", &MFI->back());
441 visitMachineBasicBlockAfter(&*MFI);
443 visitMachineFunctionAfter();
456 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
459 if (!foundErrors++) {
461 errs() << "# " << Banner << '\n';
462 if (LiveInts != nullptr)
463 LiveInts->print(errs());
465 MF->print(errs(), Indexes);
467 errs() << "*** Bad machine code: " << msg << " ***\n"
468 << "- function: " << MF->getName() << "\n";
471 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
473 report(msg, MBB->getParent());
474 errs() << "- basic block: " << printMBBReference(*MBB) << ' '
475 << MBB->getName() << " (" << (const void *)MBB << ')';
477 errs() << " [" << Indexes->getMBBStartIdx(MBB)
478 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
482 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
484 report(msg, MI->getParent());
485 errs() << "- instruction: ";
486 if (Indexes && Indexes->hasIndex(*MI))
487 errs() << Indexes->getInstructionIndex(*MI) << '\t';
488 MI->print(errs(), /*SkipOpers=*/true);
492 void MachineVerifier::report(const char *msg,
493 const MachineOperand *MO, unsigned MONum) {
495 report(msg, MO->getParent());
496 errs() << "- operand " << MONum << ": ";
497 MO->print(errs(), TRI);
501 void MachineVerifier::report_context(SlotIndex Pos) const {
502 errs() << "- at: " << Pos << '\n';
505 void MachineVerifier::report_context(const LiveInterval &LI) const {
506 errs() << "- interval: " << LI << '\n';
509 void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit,
510 LaneBitmask LaneMask) const {
511 report_context_liverange(LR);
512 report_context_vreg_regunit(VRegUnit);
514 report_context_lanemask(LaneMask);
517 void MachineVerifier::report_context(const LiveRange::Segment &S) const {
518 errs() << "- segment: " << S << '\n';
521 void MachineVerifier::report_context(const VNInfo &VNI) const {
522 errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n";
525 void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
526 errs() << "- liverange: " << LR << '\n';
529 void MachineVerifier::report_context_vreg(unsigned VReg) const {
530 errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
533 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const {
534 if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) {
535 report_context_vreg(VRegOrUnit);
537 errs() << "- regunit: " << printRegUnit(VRegOrUnit, TRI) << '\n';
541 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
542 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
545 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
546 BBInfo &MInfo = MBBInfoMap[MBB];
547 if (!MInfo.reachable) {
548 MInfo.reachable = true;
549 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
550 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
555 void MachineVerifier::visitMachineFunctionBefore() {
556 lastIndex = SlotIndex();
557 regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
558 : TRI->getReservedRegs(*MF);
561 markReachable(&MF->front());
563 // Build a set of the basic blocks in the function.
564 FunctionBlocks.clear();
565 for (const auto &MBB : *MF) {
566 FunctionBlocks.insert(&MBB);
567 BBInfo &MInfo = MBBInfoMap[&MBB];
569 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
570 if (MInfo.Preds.size() != MBB.pred_size())
571 report("MBB has duplicate entries in its predecessor list.", &MBB);
573 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
574 if (MInfo.Succs.size() != MBB.succ_size())
575 report("MBB has duplicate entries in its successor list.", &MBB);
578 // Check that the register use lists are sane.
579 MRI->verifyUseLists();
585 // Does iterator point to a and b as the first two elements?
586 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
587 const MachineBasicBlock *a, const MachineBasicBlock *b) {
596 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
597 FirstTerminator = nullptr;
599 if (!MF->getProperties().hasProperty(
600 MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
601 // If this block has allocatable physical registers live-in, check that
602 // it is an entry block or landing pad.
603 for (const auto &LI : MBB->liveins()) {
604 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
605 MBB->getIterator() != MBB->getParent()->begin()) {
606 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
611 // Count the number of landing pad successors.
612 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
613 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
614 E = MBB->succ_end(); I != E; ++I) {
616 LandingPadSuccs.insert(*I);
617 if (!FunctionBlocks.count(*I))
618 report("MBB has successor that isn't part of the function.", MBB);
619 if (!MBBInfoMap[*I].Preds.count(MBB)) {
620 report("Inconsistent CFG", MBB);
621 errs() << "MBB is not in the predecessor list of the successor "
622 << printMBBReference(*(*I)) << ".\n";
626 // Check the predecessor list.
627 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
628 E = MBB->pred_end(); I != E; ++I) {
629 if (!FunctionBlocks.count(*I))
630 report("MBB has predecessor that isn't part of the function.", MBB);
631 if (!MBBInfoMap[*I].Succs.count(MBB)) {
632 report("Inconsistent CFG", MBB);
633 errs() << "MBB is not in the successor list of the predecessor "
634 << printMBBReference(*(*I)) << ".\n";
638 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
639 const BasicBlock *BB = MBB->getBasicBlock();
640 const Function &F = MF->getFunction();
641 if (LandingPadSuccs.size() > 1 &&
643 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
644 BB && isa<SwitchInst>(BB->getTerminator())) &&
645 !isFuncletEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
646 report("MBB has more than one landing pad successor", MBB);
648 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
649 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
650 SmallVector<MachineOperand, 4> Cond;
651 if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
653 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
654 // check whether its answers match up with reality.
656 // Block falls through to its successor.
657 MachineFunction::const_iterator MBBI = MBB->getIterator();
659 if (MBBI == MF->end()) {
660 // It's possible that the block legitimately ends with a noreturn
661 // call or an unreachable, in which case it won't actually fall
662 // out the bottom of the function.
663 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
664 // It's possible that the block legitimately ends with a noreturn
665 // call or an unreachable, in which case it won't actuall fall
667 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
668 report("MBB exits via unconditional fall-through but doesn't have "
669 "exactly one CFG successor!", MBB);
670 } else if (!MBB->isSuccessor(&*MBBI)) {
671 report("MBB exits via unconditional fall-through but its successor "
672 "differs from its CFG successor!", MBB);
674 if (!MBB->empty() && MBB->back().isBarrier() &&
675 !TII->isPredicated(MBB->back())) {
676 report("MBB exits via unconditional fall-through but ends with a "
677 "barrier instruction!", MBB);
680 report("MBB exits via unconditional fall-through but has a condition!",
683 } else if (TBB && !FBB && Cond.empty()) {
684 // Block unconditionally branches somewhere.
685 // If the block has exactly one successor, that happens to be a
686 // landingpad, accept it as valid control flow.
687 if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
688 (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
689 *MBB->succ_begin() != *LandingPadSuccs.begin())) {
690 report("MBB exits via unconditional branch but doesn't have "
691 "exactly one CFG successor!", MBB);
692 } else if (!MBB->isSuccessor(TBB)) {
693 report("MBB exits via unconditional branch but the CFG "
694 "successor doesn't match the actual successor!", MBB);
697 report("MBB exits via unconditional branch but doesn't contain "
698 "any instructions!", MBB);
699 } else if (!MBB->back().isBarrier()) {
700 report("MBB exits via unconditional branch but doesn't end with a "
701 "barrier instruction!", MBB);
702 } else if (!MBB->back().isTerminator()) {
703 report("MBB exits via unconditional branch but the branch isn't a "
704 "terminator instruction!", MBB);
706 } else if (TBB && !FBB && !Cond.empty()) {
707 // Block conditionally branches somewhere, otherwise falls through.
708 MachineFunction::const_iterator MBBI = MBB->getIterator();
710 if (MBBI == MF->end()) {
711 report("MBB conditionally falls through out of function!", MBB);
712 } else if (MBB->succ_size() == 1) {
713 // A conditional branch with only one successor is weird, but allowed.
715 report("MBB exits via conditional branch/fall-through but only has "
716 "one CFG successor!", MBB);
717 else if (TBB != *MBB->succ_begin())
718 report("MBB exits via conditional branch/fall-through but the CFG "
719 "successor don't match the actual successor!", MBB);
720 } else if (MBB->succ_size() != 2) {
721 report("MBB exits via conditional branch/fall-through but doesn't have "
722 "exactly two CFG successors!", MBB);
723 } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
724 report("MBB exits via conditional branch/fall-through but the CFG "
725 "successors don't match the actual successors!", MBB);
728 report("MBB exits via conditional branch/fall-through but doesn't "
729 "contain any instructions!", MBB);
730 } else if (MBB->back().isBarrier()) {
731 report("MBB exits via conditional branch/fall-through but ends with a "
732 "barrier instruction!", MBB);
733 } else if (!MBB->back().isTerminator()) {
734 report("MBB exits via conditional branch/fall-through but the branch "
735 "isn't a terminator instruction!", MBB);
737 } else if (TBB && FBB) {
738 // Block conditionally branches somewhere, otherwise branches
740 if (MBB->succ_size() == 1) {
741 // A conditional branch with only one successor is weird, but allowed.
743 report("MBB exits via conditional branch/branch through but only has "
744 "one CFG successor!", MBB);
745 else if (TBB != *MBB->succ_begin())
746 report("MBB exits via conditional branch/branch through but the CFG "
747 "successor don't match the actual successor!", MBB);
748 } else if (MBB->succ_size() != 2) {
749 report("MBB exits via conditional branch/branch but doesn't have "
750 "exactly two CFG successors!", MBB);
751 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
752 report("MBB exits via conditional branch/branch but the CFG "
753 "successors don't match the actual successors!", MBB);
756 report("MBB exits via conditional branch/branch but doesn't "
757 "contain any instructions!", MBB);
758 } else if (!MBB->back().isBarrier()) {
759 report("MBB exits via conditional branch/branch but doesn't end with a "
760 "barrier instruction!", MBB);
761 } else if (!MBB->back().isTerminator()) {
762 report("MBB exits via conditional branch/branch but the branch "
763 "isn't a terminator instruction!", MBB);
766 report("MBB exits via conditinal branch/branch but there's no "
770 report("AnalyzeBranch returned invalid data!", MBB);
775 if (MRI->tracksLiveness()) {
776 for (const auto &LI : MBB->liveins()) {
777 if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
778 report("MBB live-in list contains non-physical register", MBB);
781 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
782 SubRegs.isValid(); ++SubRegs)
783 regsLive.insert(*SubRegs);
787 const MachineFrameInfo &MFI = MF->getFrameInfo();
788 BitVector PR = MFI.getPristineRegs(*MF);
789 for (unsigned I : PR.set_bits()) {
790 for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
791 SubRegs.isValid(); ++SubRegs)
792 regsLive.insert(*SubRegs);
799 lastIndex = Indexes->getMBBStartIdx(MBB);
802 // This function gets called for all bundle headers, including normal
803 // stand-alone unbundled instructions.
804 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
805 if (Indexes && Indexes->hasIndex(*MI)) {
806 SlotIndex idx = Indexes->getInstructionIndex(*MI);
807 if (!(idx > lastIndex)) {
808 report("Instruction index out of order", MI);
809 errs() << "Last instruction was at " << lastIndex << '\n';
814 // Ensure non-terminators don't follow terminators.
815 // Ignore predicated terminators formed by if conversion.
816 // FIXME: If conversion shouldn't need to violate this rule.
817 if (MI->isTerminator() && !TII->isPredicated(*MI)) {
818 if (!FirstTerminator)
819 FirstTerminator = MI;
820 } else if (FirstTerminator) {
821 report("Non-terminator instruction after the first terminator", MI);
822 errs() << "First terminator was:\t" << *FirstTerminator;
826 // The operands on an INLINEASM instruction must follow a template.
827 // Verify that the flag operands make sense.
828 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
829 // The first two operands on INLINEASM are the asm string and global flags.
830 if (MI->getNumOperands() < 2) {
831 report("Too few operands on inline asm", MI);
834 if (!MI->getOperand(0).isSymbol())
835 report("Asm string must be an external symbol", MI);
836 if (!MI->getOperand(1).isImm())
837 report("Asm flags must be an immediate", MI);
838 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
839 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
840 // and Extra_IsConvergent = 32.
841 if (!isUInt<6>(MI->getOperand(1).getImm()))
842 report("Unknown asm flags", &MI->getOperand(1), 1);
844 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
846 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
848 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
849 const MachineOperand &MO = MI->getOperand(OpNo);
850 // There may be implicit ops after the fixed operands.
853 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
856 if (OpNo > MI->getNumOperands())
857 report("Missing operands in last group", MI);
859 // An optional MDNode follows the groups.
860 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
863 // All trailing operands must be implicit registers.
864 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
865 const MachineOperand &MO = MI->getOperand(OpNo);
866 if (!MO.isReg() || !MO.isImplicit())
867 report("Expected implicit register after groups", &MO, OpNo);
871 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
872 const MCInstrDesc &MCID = MI->getDesc();
873 if (MI->getNumOperands() < MCID.getNumOperands()) {
874 report("Too few operands", MI);
875 errs() << MCID.getNumOperands() << " operands expected, but "
876 << MI->getNumOperands() << " given.\n";
879 if (MI->isPHI() && MF->getProperties().hasProperty(
880 MachineFunctionProperties::Property::NoPHIs))
881 report("Found PHI instruction with NoPHIs property set", MI);
883 // Check the tied operands.
884 if (MI->isInlineAsm())
887 // Check the MachineMemOperands for basic consistency.
888 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
889 E = MI->memoperands_end(); I != E; ++I) {
890 if ((*I)->isLoad() && !MI->mayLoad())
891 report("Missing mayLoad flag", MI);
892 if ((*I)->isStore() && !MI->mayStore())
893 report("Missing mayStore flag", MI);
896 // Debug values must not have a slot index.
897 // Other instructions must have one, unless they are inside a bundle.
899 bool mapped = !LiveInts->isNotInMIMap(*MI);
900 if (MI->isDebugValue()) {
902 report("Debug instruction has a slot index", MI);
903 } else if (MI->isInsideBundle()) {
905 report("Instruction inside bundle has a slot index", MI);
908 report("Missing slot index", MI);
913 if (isPreISelGenericOpcode(MCID.getOpcode())) {
914 if (isFunctionSelected)
915 report("Unexpected generic instruction in a Selected function", MI);
917 // Generic instructions specify equality constraints between some
918 // of their operands. Make sure these are consistent.
919 SmallVector<LLT, 4> Types;
920 for (unsigned i = 0; i < MCID.getNumOperands(); ++i) {
921 if (!MCID.OpInfo[i].isGenericType())
923 size_t TypeIdx = MCID.OpInfo[i].getGenericTypeIndex();
924 Types.resize(std::max(TypeIdx + 1, Types.size()));
926 LLT OpTy = MRI->getType(MI->getOperand(i).getReg());
927 if (Types[TypeIdx].isValid() && Types[TypeIdx] != OpTy)
928 report("type mismatch in generic instruction", MI);
929 Types[TypeIdx] = OpTy;
933 // Generic opcodes must not have physical register operands.
934 if (isPreISelGenericOpcode(MCID.getOpcode())) {
935 for (auto &Op : MI->operands()) {
936 if (Op.isReg() && TargetRegisterInfo::isPhysicalRegister(Op.getReg()))
937 report("Generic instruction cannot have physical register", MI);
942 if (!TII->verifyInstruction(*MI, ErrorInfo))
943 report(ErrorInfo.data(), MI);
945 // Verify properties of various specific instruction types
946 switch(MI->getOpcode()) {
949 case TargetOpcode::G_LOAD:
950 case TargetOpcode::G_STORE:
951 // Generic loads and stores must have a single MachineMemOperand
952 // describing that access.
953 if (!MI->hasOneMemOperand())
954 report("Generic instruction accessing memory must have one mem operand",
957 case TargetOpcode::G_PHI: {
958 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
959 if (!DstTy.isValid() ||
960 !std::all_of(MI->operands_begin() + 1, MI->operands_end(),
961 [this, &DstTy](const MachineOperand &MO) {
964 LLT Ty = MRI->getType(MO.getReg());
965 if (!Ty.isValid() || (Ty != DstTy))
969 report("Generic Instruction G_PHI has operands with incompatible/missing "
974 case TargetOpcode::STATEPOINT:
975 if (!MI->getOperand(StatepointOpers::IDPos).isImm() ||
976 !MI->getOperand(StatepointOpers::NBytesPos).isImm() ||
977 !MI->getOperand(StatepointOpers::NCallArgsPos).isImm())
978 report("meta operands to STATEPOINT not constant!", MI);
981 auto VerifyStackMapConstant = [&](unsigned Offset) {
982 if (!MI->getOperand(Offset).isImm() ||
983 MI->getOperand(Offset).getImm() != StackMaps::ConstantOp ||
984 !MI->getOperand(Offset + 1).isImm())
985 report("stack map constant to STATEPOINT not well formed!", MI);
987 const unsigned VarStart = StatepointOpers(MI).getVarIdx();
988 VerifyStackMapConstant(VarStart + StatepointOpers::CCOffset);
989 VerifyStackMapConstant(VarStart + StatepointOpers::FlagsOffset);
990 VerifyStackMapConstant(VarStart + StatepointOpers::NumDeoptOperandsOffset);
992 // TODO: verify we have properly encoded deopt arguments
997 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
998 const MachineInstr *MI = MO->getParent();
999 const MCInstrDesc &MCID = MI->getDesc();
1000 unsigned NumDefs = MCID.getNumDefs();
1001 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
1002 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
1004 // The first MCID.NumDefs operands must be explicit register defines
1005 if (MONum < NumDefs) {
1006 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1008 report("Explicit definition must be a register", MO, MONum);
1009 else if (!MO->isDef() && !MCOI.isOptionalDef())
1010 report("Explicit definition marked as use", MO, MONum);
1011 else if (MO->isImplicit())
1012 report("Explicit definition marked as implicit", MO, MONum);
1013 } else if (MONum < MCID.getNumOperands()) {
1014 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1015 // Don't check if it's the last operand in a variadic instruction. See,
1016 // e.g., LDM_RET in the arm back end.
1018 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
1019 if (MO->isDef() && !MCOI.isOptionalDef())
1020 report("Explicit operand marked as def", MO, MONum);
1021 if (MO->isImplicit())
1022 report("Explicit operand marked as implicit", MO, MONum);
1025 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
1028 report("Tied use must be a register", MO, MONum);
1029 else if (!MO->isTied())
1030 report("Operand should be tied", MO, MONum);
1031 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
1032 report("Tied def doesn't match MCInstrDesc", MO, MONum);
1033 else if (TargetRegisterInfo::isPhysicalRegister(MO->getReg())) {
1034 const MachineOperand &MOTied = MI->getOperand(TiedTo);
1035 if (!MOTied.isReg())
1036 report("Tied counterpart must be a register", &MOTied, TiedTo);
1037 else if (TargetRegisterInfo::isPhysicalRegister(MOTied.getReg()) &&
1038 MO->getReg() != MOTied.getReg())
1039 report("Tied physical registers must match.", &MOTied, TiedTo);
1041 } else if (MO->isReg() && MO->isTied())
1042 report("Explicit operand should not be tied", MO, MONum);
1044 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1045 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
1046 report("Extra explicit operand on non-variadic instruction", MO, MONum);
1049 switch (MO->getType()) {
1050 case MachineOperand::MO_Register: {
1051 const unsigned Reg = MO->getReg();
1054 if (MRI->tracksLiveness() && !MI->isDebugValue())
1055 checkLiveness(MO, MONum);
1057 // Verify the consistency of tied operands.
1059 unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
1060 const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
1061 if (!OtherMO.isReg())
1062 report("Must be tied to a register", MO, MONum);
1063 if (!OtherMO.isTied())
1064 report("Missing tie flags on tied operand", MO, MONum);
1065 if (MI->findTiedOperandIdx(OtherIdx) != MONum)
1066 report("Inconsistent tie links", MO, MONum);
1067 if (MONum < MCID.getNumDefs()) {
1068 if (OtherIdx < MCID.getNumOperands()) {
1069 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
1070 report("Explicit def tied to explicit use without tie constraint",
1073 if (!OtherMO.isImplicit())
1074 report("Explicit def should be tied to implicit use", MO, MONum);
1079 // Verify two-address constraints after leaving SSA form.
1081 if (!MRI->isSSA() && MO->isUse() &&
1082 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
1083 Reg != MI->getOperand(DefIdx).getReg())
1084 report("Two-address instruction operands must be identical", MO, MONum);
1086 // Check register classes.
1087 unsigned SubIdx = MO->getSubReg();
1089 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1091 report("Illegal subregister index for physical register", MO, MONum);
1094 if (MONum < MCID.getNumOperands()) {
1095 if (const TargetRegisterClass *DRC =
1096 TII->getRegClass(MCID, MONum, TRI, *MF)) {
1097 if (!DRC->contains(Reg)) {
1098 report("Illegal physical register for instruction", MO, MONum);
1099 errs() << printReg(Reg, TRI) << " is not a "
1100 << TRI->getRegClassName(DRC) << " register.\n";
1104 if (MO->isRenamable() &&
1105 ((MO->isDef() && MI->hasExtraDefRegAllocReq()) ||
1106 (MO->isUse() && MI->hasExtraSrcRegAllocReq()))) {
1107 report("Illegal isRenamable setting for opcode with extra regalloc "
1113 // Virtual register.
1114 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
1116 // This is a generic virtual register.
1118 // If we're post-Select, we can't have gvregs anymore.
1119 if (isFunctionSelected) {
1120 report("Generic virtual register invalid in a Selected function",
1125 // The gvreg must have a type and it must not have a SubIdx.
1126 LLT Ty = MRI->getType(Reg);
1127 if (!Ty.isValid()) {
1128 report("Generic virtual register must have a valid type", MO,
1133 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
1135 // If we're post-RegBankSelect, the gvreg must have a bank.
1136 if (!RegBank && isFunctionRegBankSelected) {
1137 report("Generic virtual register must have a bank in a "
1138 "RegBankSelected function",
1143 // Make sure the register fits into its register bank if any.
1144 if (RegBank && Ty.isValid() &&
1145 RegBank->getSize() < Ty.getSizeInBits()) {
1146 report("Register bank is too small for virtual register", MO,
1148 errs() << "Register bank " << RegBank->getName() << " too small("
1149 << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
1154 report("Generic virtual register does not subregister index", MO,
1159 // If this is a target specific instruction and this operand
1160 // has register class constraint, the virtual register must
1162 if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
1163 MONum < MCID.getNumOperands() &&
1164 TII->getRegClass(MCID, MONum, TRI, *MF)) {
1165 report("Virtual register does not match instruction constraint", MO,
1167 errs() << "Expect register class "
1168 << TRI->getRegClassName(
1169 TII->getRegClass(MCID, MONum, TRI, *MF))
1170 << " but got nothing\n";
1177 const TargetRegisterClass *SRC =
1178 TRI->getSubClassWithSubReg(RC, SubIdx);
1180 report("Invalid subregister index for virtual register", MO, MONum);
1181 errs() << "Register class " << TRI->getRegClassName(RC)
1182 << " does not support subreg index " << SubIdx << "\n";
1186 report("Invalid register class for subregister index", MO, MONum);
1187 errs() << "Register class " << TRI->getRegClassName(RC)
1188 << " does not fully support subreg index " << SubIdx << "\n";
1192 if (MONum < MCID.getNumOperands()) {
1193 if (const TargetRegisterClass *DRC =
1194 TII->getRegClass(MCID, MONum, TRI, *MF)) {
1196 const TargetRegisterClass *SuperRC =
1197 TRI->getLargestLegalSuperClass(RC, *MF);
1199 report("No largest legal super class exists.", MO, MONum);
1202 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
1204 report("No matching super-reg register class.", MO, MONum);
1208 if (!RC->hasSuperClassEq(DRC)) {
1209 report("Illegal virtual register for instruction", MO, MONum);
1210 errs() << "Expected a " << TRI->getRegClassName(DRC)
1211 << " register, but got a " << TRI->getRegClassName(RC)
1220 case MachineOperand::MO_RegisterMask:
1221 regMasks.push_back(MO->getRegMask());
1224 case MachineOperand::MO_MachineBasicBlock:
1225 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
1226 report("PHI operand is not in the CFG", MO, MONum);
1229 case MachineOperand::MO_FrameIndex:
1230 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
1231 LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1232 int FI = MO->getIndex();
1233 LiveInterval &LI = LiveStks->getInterval(FI);
1234 SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
1236 bool stores = MI->mayStore();
1237 bool loads = MI->mayLoad();
1238 // For a memory-to-memory move, we need to check if the frame
1239 // index is used for storing or loading, by inspecting the
1241 if (stores && loads) {
1242 for (auto *MMO : MI->memoperands()) {
1243 const PseudoSourceValue *PSV = MMO->getPseudoValue();
1244 if (PSV == nullptr) continue;
1245 const FixedStackPseudoSourceValue *Value =
1246 dyn_cast<FixedStackPseudoSourceValue>(PSV);
1247 if (Value == nullptr) continue;
1248 if (Value->getFrameIndex() != FI) continue;
1256 if (loads == stores)
1257 report("Missing fixed stack memoperand.", MI);
1259 if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
1260 report("Instruction loads from dead spill slot", MO, MONum);
1261 errs() << "Live stack: " << LI << '\n';
1263 if (stores && !LI.liveAt(Idx.getRegSlot())) {
1264 report("Instruction stores to dead spill slot", MO, MONum);
1265 errs() << "Live stack: " << LI << '\n';
1275 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
1276 unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
1277 LaneBitmask LaneMask) {
1278 LiveQueryResult LRQ = LR.Query(UseIdx);
1279 // Check if we have a segment at the use, note however that we only need one
1280 // live subregister range, the others may be dead.
1281 if (!LRQ.valueIn() && LaneMask.none()) {
1282 report("No live segment at use", MO, MONum);
1283 report_context_liverange(LR);
1284 report_context_vreg_regunit(VRegOrUnit);
1285 report_context(UseIdx);
1287 if (MO->isKill() && !LRQ.isKill()) {
1288 report("Live range continues after kill flag", MO, MONum);
1289 report_context_liverange(LR);
1290 report_context_vreg_regunit(VRegOrUnit);
1292 report_context_lanemask(LaneMask);
1293 report_context(UseIdx);
1297 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
1298 unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
1299 LaneBitmask LaneMask) {
1300 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
1301 assert(VNI && "NULL valno is not allowed");
1302 if (VNI->def != DefIdx) {
1303 report("Inconsistent valno->def", MO, MONum);
1304 report_context_liverange(LR);
1305 report_context_vreg_regunit(VRegOrUnit);
1307 report_context_lanemask(LaneMask);
1308 report_context(*VNI);
1309 report_context(DefIdx);
1312 report("No live segment at def", MO, MONum);
1313 report_context_liverange(LR);
1314 report_context_vreg_regunit(VRegOrUnit);
1316 report_context_lanemask(LaneMask);
1317 report_context(DefIdx);
1319 // Check that, if the dead def flag is present, LiveInts agree.
1321 LiveQueryResult LRQ = LR.Query(DefIdx);
1322 if (!LRQ.isDeadDef()) {
1323 // In case of physregs we can have a non-dead definition on another
1325 bool otherDef = false;
1326 if (!TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) {
1327 const MachineInstr &MI = *MO->getParent();
1328 for (const MachineOperand &MO : MI.operands()) {
1329 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1331 unsigned Reg = MO.getReg();
1332 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1333 if (*Units == VRegOrUnit) {
1342 report("Live range continues after dead def flag", MO, MONum);
1343 report_context_liverange(LR);
1344 report_context_vreg_regunit(VRegOrUnit);
1346 report_context_lanemask(LaneMask);
1352 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1353 const MachineInstr *MI = MO->getParent();
1354 const unsigned Reg = MO->getReg();
1356 // Both use and def operands can read a register.
1357 if (MO->readsReg()) {
1359 addRegWithSubRegs(regsKilled, Reg);
1361 // Check that LiveVars knows this kill.
1362 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1364 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1365 if (!is_contained(VI.Kills, MI))
1366 report("Kill missing from LiveVariables", MO, MONum);
1369 // Check LiveInts liveness and kill.
1370 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1371 SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
1372 // Check the cached regunit intervals.
1373 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1374 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1375 if (MRI->isReservedRegUnit(*Units))
1377 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
1378 checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
1382 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1383 if (LiveInts->hasInterval(Reg)) {
1384 // This is a virtual register interval.
1385 const LiveInterval &LI = LiveInts->getInterval(Reg);
1386 checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg);
1388 if (LI.hasSubRanges() && !MO->isDef()) {
1389 unsigned SubRegIdx = MO->getSubReg();
1390 LaneBitmask MOMask = SubRegIdx != 0
1391 ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1392 : MRI->getMaxLaneMaskForVReg(Reg);
1393 LaneBitmask LiveInMask;
1394 for (const LiveInterval::SubRange &SR : LI.subranges()) {
1395 if ((MOMask & SR.LaneMask).none())
1397 checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
1398 LiveQueryResult LRQ = SR.Query(UseIdx);
1400 LiveInMask |= SR.LaneMask;
1402 // At least parts of the register has to be live at the use.
1403 if ((LiveInMask & MOMask).none()) {
1404 report("No live subrange at use", MO, MONum);
1406 report_context(UseIdx);
1410 report("Virtual register has no live interval", MO, MONum);
1415 // Use of a dead register.
1416 if (!regsLive.count(Reg)) {
1417 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1418 // Reserved registers may be used even when 'dead'.
1419 bool Bad = !isReserved(Reg);
1420 // We are fine if just any subregister has a defined value.
1422 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
1424 if (regsLive.count(*SubRegs)) {
1430 // If there is an additional implicit-use of a super register we stop
1431 // here. By definition we are fine if the super register is not
1432 // (completely) dead, if the complete super register is dead we will
1433 // get a report for its operand.
1435 for (const MachineOperand &MOP : MI->uses()) {
1438 if (!MOP.isImplicit())
1440 for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1442 if (*SubRegs == Reg) {
1450 report("Using an undefined physical register", MO, MONum);
1451 } else if (MRI->def_empty(Reg)) {
1452 report("Reading virtual register without a def", MO, MONum);
1454 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1455 // We don't know which virtual registers are live in, so only complain
1456 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1457 // must be live in. PHI instructions are handled separately.
1458 if (MInfo.regsKilled.count(Reg))
1459 report("Using a killed virtual register", MO, MONum);
1460 else if (!MI->isPHI())
1461 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1467 // Register defined.
1468 // TODO: verify that earlyclobber ops are not used.
1470 addRegWithSubRegs(regsDead, Reg);
1472 addRegWithSubRegs(regsDefined, Reg);
1475 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1476 std::next(MRI->def_begin(Reg)) != MRI->def_end())
1477 report("Multiple virtual register defs in SSA form", MO, MONum);
1479 // Check LiveInts for a live segment, but only for virtual registers.
1480 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1481 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
1482 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1484 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1485 if (LiveInts->hasInterval(Reg)) {
1486 const LiveInterval &LI = LiveInts->getInterval(Reg);
1487 checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg);
1489 if (LI.hasSubRanges()) {
1490 unsigned SubRegIdx = MO->getSubReg();
1491 LaneBitmask MOMask = SubRegIdx != 0
1492 ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1493 : MRI->getMaxLaneMaskForVReg(Reg);
1494 for (const LiveInterval::SubRange &SR : LI.subranges()) {
1495 if ((SR.LaneMask & MOMask).none())
1497 checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, SR.LaneMask);
1501 report("Virtual register has no Live interval", MO, MONum);
1508 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {}
1510 // This function gets called after visiting all instructions in a bundle. The
1511 // argument points to the bundle header.
1512 // Normal stand-alone instructions are also considered 'bundles', and this
1513 // function is called for all of them.
1514 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1515 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1516 set_union(MInfo.regsKilled, regsKilled);
1517 set_subtract(regsLive, regsKilled); regsKilled.clear();
1518 // Kill any masked registers.
1519 while (!regMasks.empty()) {
1520 const uint32_t *Mask = regMasks.pop_back_val();
1521 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1522 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1523 MachineOperand::clobbersPhysReg(Mask, *I))
1524 regsDead.push_back(*I);
1526 set_subtract(regsLive, regsDead); regsDead.clear();
1527 set_union(regsLive, regsDefined); regsDefined.clear();
1531 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1532 MBBInfoMap[MBB].regsLiveOut = regsLive;
1536 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1537 if (!(stop > lastIndex)) {
1538 report("Block ends before last instruction index", MBB);
1539 errs() << "Block ends at " << stop
1540 << " last instruction was at " << lastIndex << '\n';
1546 // Calculate the largest possible vregsPassed sets. These are the registers that
1547 // can pass through an MBB live, but may not be live every time. It is assumed
1548 // that all vregsPassed sets are empty before the call.
1549 void MachineVerifier::calcRegsPassed() {
1550 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1551 // have any vregsPassed.
1552 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1553 for (const auto &MBB : *MF) {
1554 BBInfo &MInfo = MBBInfoMap[&MBB];
1555 if (!MInfo.reachable)
1557 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1558 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1559 BBInfo &SInfo = MBBInfoMap[*SuI];
1560 if (SInfo.addPassed(MInfo.regsLiveOut))
1565 // Iteratively push vregsPassed to successors. This will converge to the same
1566 // final state regardless of DenseSet iteration order.
1567 while (!todo.empty()) {
1568 const MachineBasicBlock *MBB = *todo.begin();
1570 BBInfo &MInfo = MBBInfoMap[MBB];
1571 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1572 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1575 BBInfo &SInfo = MBBInfoMap[*SuI];
1576 if (SInfo.addPassed(MInfo.vregsPassed))
1582 // Calculate the set of virtual registers that must be passed through each basic
1583 // block in order to satisfy the requirements of successor blocks. This is very
1584 // similar to calcRegsPassed, only backwards.
1585 void MachineVerifier::calcRegsRequired() {
1586 // First push live-in regs to predecessors' vregsRequired.
1587 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1588 for (const auto &MBB : *MF) {
1589 BBInfo &MInfo = MBBInfoMap[&MBB];
1590 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1591 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1592 BBInfo &PInfo = MBBInfoMap[*PrI];
1593 if (PInfo.addRequired(MInfo.vregsLiveIn))
1598 // Iteratively push vregsRequired to predecessors. This will converge to the
1599 // same final state regardless of DenseSet iteration order.
1600 while (!todo.empty()) {
1601 const MachineBasicBlock *MBB = *todo.begin();
1603 BBInfo &MInfo = MBBInfoMap[MBB];
1604 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1605 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1608 BBInfo &SInfo = MBBInfoMap[*PrI];
1609 if (SInfo.addRequired(MInfo.vregsRequired))
1615 // Check PHI instructions at the beginning of MBB. It is assumed that
1616 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1617 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
1618 BBInfo &MInfo = MBBInfoMap[&MBB];
1620 SmallPtrSet<const MachineBasicBlock*, 8> seen;
1621 for (const MachineInstr &Phi : MBB) {
1626 const MachineOperand &MODef = Phi.getOperand(0);
1627 if (!MODef.isReg() || !MODef.isDef()) {
1628 report("Expected first PHI operand to be a register def", &MODef, 0);
1631 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
1632 MODef.isEarlyClobber() || MODef.isDebug())
1633 report("Unexpected flag on PHI operand", &MODef, 0);
1634 unsigned DefReg = MODef.getReg();
1635 if (!TargetRegisterInfo::isVirtualRegister(DefReg))
1636 report("Expected first PHI operand to be a virtual register", &MODef, 0);
1638 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
1639 const MachineOperand &MO0 = Phi.getOperand(I);
1641 report("Expected PHI operand to be a register", &MO0, I);
1644 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
1645 MO0.isDebug() || MO0.isTied())
1646 report("Unexpected flag on PHI operand", &MO0, I);
1648 const MachineOperand &MO1 = Phi.getOperand(I + 1);
1650 report("Expected PHI operand to be a basic block", &MO1, I + 1);
1654 const MachineBasicBlock &Pre = *MO1.getMBB();
1655 if (!Pre.isSuccessor(&MBB)) {
1656 report("PHI input is not a predecessor block", &MO1, I + 1);
1660 if (MInfo.reachable) {
1662 BBInfo &PrInfo = MBBInfoMap[&Pre];
1663 if (!MO0.isUndef() && PrInfo.reachable &&
1664 !PrInfo.isLiveOut(MO0.getReg()))
1665 report("PHI operand is not live-out from predecessor", &MO0, I);
1669 // Did we see all predecessors?
1670 if (MInfo.reachable) {
1671 for (MachineBasicBlock *Pred : MBB.predecessors()) {
1672 if (!seen.count(Pred)) {
1673 report("Missing PHI operand", &Phi);
1674 errs() << printMBBReference(*Pred)
1675 << " is a predecessor according to the CFG.\n";
1682 void MachineVerifier::visitMachineFunctionAfter() {
1685 for (const MachineBasicBlock &MBB : *MF)
1688 // Now check liveness info if available
1691 // Check for killed virtual registers that should be live out.
1692 for (const auto &MBB : *MF) {
1693 BBInfo &MInfo = MBBInfoMap[&MBB];
1694 for (RegSet::iterator
1695 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1697 if (MInfo.regsKilled.count(*I)) {
1698 report("Virtual register killed in block, but needed live out.", &MBB);
1699 errs() << "Virtual register " << printReg(*I)
1700 << " is used after the block.\n";
1705 BBInfo &MInfo = MBBInfoMap[&MF->front()];
1706 for (RegSet::iterator
1707 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1709 report("Virtual register defs don't dominate all uses.", MF);
1710 report_context_vreg(*I);
1715 verifyLiveVariables();
1717 verifyLiveIntervals();
1720 void MachineVerifier::verifyLiveVariables() {
1721 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1722 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1723 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1724 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1725 for (const auto &MBB : *MF) {
1726 BBInfo &MInfo = MBBInfoMap[&MBB];
1728 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1729 if (MInfo.vregsRequired.count(Reg)) {
1730 if (!VI.AliveBlocks.test(MBB.getNumber())) {
1731 report("LiveVariables: Block missing from AliveBlocks", &MBB);
1732 errs() << "Virtual register " << printReg(Reg)
1733 << " must be live through the block.\n";
1736 if (VI.AliveBlocks.test(MBB.getNumber())) {
1737 report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1738 errs() << "Virtual register " << printReg(Reg)
1739 << " is not needed live through the block.\n";
1746 void MachineVerifier::verifyLiveIntervals() {
1747 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1748 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1749 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1751 // Spilling and splitting may leave unused registers around. Skip them.
1752 if (MRI->reg_nodbg_empty(Reg))
1755 if (!LiveInts->hasInterval(Reg)) {
1756 report("Missing live interval for virtual register", MF);
1757 errs() << printReg(Reg, TRI) << " still has defs or uses\n";
1761 const LiveInterval &LI = LiveInts->getInterval(Reg);
1762 assert(Reg == LI.reg && "Invalid reg to interval mapping");
1763 verifyLiveInterval(LI);
1766 // Verify all the cached regunit intervals.
1767 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1768 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1769 verifyLiveRange(*LR, i);
1772 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1773 const VNInfo *VNI, unsigned Reg,
1774 LaneBitmask LaneMask) {
1775 if (VNI->isUnused())
1778 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1781 report("Value not live at VNInfo def and not marked unused", MF);
1782 report_context(LR, Reg, LaneMask);
1783 report_context(*VNI);
1787 if (DefVNI != VNI) {
1788 report("Live segment at def has different VNInfo", MF);
1789 report_context(LR, Reg, LaneMask);
1790 report_context(*VNI);
1794 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1796 report("Invalid VNInfo definition index", MF);
1797 report_context(LR, Reg, LaneMask);
1798 report_context(*VNI);
1802 if (VNI->isPHIDef()) {
1803 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1804 report("PHIDef VNInfo is not defined at MBB start", MBB);
1805 report_context(LR, Reg, LaneMask);
1806 report_context(*VNI);
1812 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1814 report("No instruction at VNInfo def index", MBB);
1815 report_context(LR, Reg, LaneMask);
1816 report_context(*VNI);
1821 bool hasDef = false;
1822 bool isEarlyClobber = false;
1823 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
1824 if (!MOI->isReg() || !MOI->isDef())
1826 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1827 if (MOI->getReg() != Reg)
1830 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1831 !TRI->hasRegUnit(MOI->getReg(), Reg))
1834 if (LaneMask.any() &&
1835 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
1838 if (MOI->isEarlyClobber())
1839 isEarlyClobber = true;
1843 report("Defining instruction does not modify register", MI);
1844 report_context(LR, Reg, LaneMask);
1845 report_context(*VNI);
1848 // Early clobber defs begin at USE slots, but other defs must begin at
1850 if (isEarlyClobber) {
1851 if (!VNI->def.isEarlyClobber()) {
1852 report("Early clobber def must be at an early-clobber slot", MBB);
1853 report_context(LR, Reg, LaneMask);
1854 report_context(*VNI);
1856 } else if (!VNI->def.isRegister()) {
1857 report("Non-PHI, non-early clobber def must be at a register slot", MBB);
1858 report_context(LR, Reg, LaneMask);
1859 report_context(*VNI);
1864 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1865 const LiveRange::const_iterator I,
1866 unsigned Reg, LaneBitmask LaneMask)
1868 const LiveRange::Segment &S = *I;
1869 const VNInfo *VNI = S.valno;
1870 assert(VNI && "Live segment has no valno");
1872 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1873 report("Foreign valno in live segment", MF);
1874 report_context(LR, Reg, LaneMask);
1876 report_context(*VNI);
1879 if (VNI->isUnused()) {
1880 report("Live segment valno is marked unused", MF);
1881 report_context(LR, Reg, LaneMask);
1885 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1887 report("Bad start of live segment, no basic block", MF);
1888 report_context(LR, Reg, LaneMask);
1892 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1893 if (S.start != MBBStartIdx && S.start != VNI->def) {
1894 report("Live segment must begin at MBB entry or valno def", MBB);
1895 report_context(LR, Reg, LaneMask);
1899 const MachineBasicBlock *EndMBB =
1900 LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1902 report("Bad end of live segment, no basic block", MF);
1903 report_context(LR, Reg, LaneMask);
1908 // No more checks for live-out segments.
1909 if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1912 // RegUnit intervals are allowed dead phis.
1913 if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1914 S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1917 // The live segment is ending inside EndMBB
1918 const MachineInstr *MI =
1919 LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1921 report("Live segment doesn't end at a valid instruction", EndMBB);
1922 report_context(LR, Reg, LaneMask);
1927 // The block slot must refer to a basic block boundary.
1928 if (S.end.isBlock()) {
1929 report("Live segment ends at B slot of an instruction", EndMBB);
1930 report_context(LR, Reg, LaneMask);
1934 if (S.end.isDead()) {
1935 // Segment ends on the dead slot.
1936 // That means there must be a dead def.
1937 if (!SlotIndex::isSameInstr(S.start, S.end)) {
1938 report("Live segment ending at dead slot spans instructions", EndMBB);
1939 report_context(LR, Reg, LaneMask);
1944 // A live segment can only end at an early-clobber slot if it is being
1945 // redefined by an early-clobber def.
1946 if (S.end.isEarlyClobber()) {
1947 if (I+1 == LR.end() || (I+1)->start != S.end) {
1948 report("Live segment ending at early clobber slot must be "
1949 "redefined by an EC def in the same instruction", EndMBB);
1950 report_context(LR, Reg, LaneMask);
1955 // The following checks only apply to virtual registers. Physreg liveness
1956 // is too weird to check.
1957 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1958 // A live segment can end with either a redefinition, a kill flag on a
1959 // use, or a dead flag on a def.
1960 bool hasRead = false;
1961 bool hasSubRegDef = false;
1962 bool hasDeadDef = false;
1963 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
1964 if (!MOI->isReg() || MOI->getReg() != Reg)
1966 unsigned Sub = MOI->getSubReg();
1967 LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
1968 : LaneBitmask::getAll();
1971 hasSubRegDef = true;
1972 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
1973 // mask for subregister defs. Read-undef defs will be handled by
1980 if (LaneMask.any() && (LaneMask & SLM).none())
1982 if (MOI->readsReg())
1985 if (S.end.isDead()) {
1986 // Make sure that the corresponding machine operand for a "dead" live
1987 // range has the dead flag. We cannot perform this check for subregister
1988 // liveranges as partially dead values are allowed.
1989 if (LaneMask.none() && !hasDeadDef) {
1990 report("Instruction ending live segment on dead slot has no dead flag",
1992 report_context(LR, Reg, LaneMask);
1997 // When tracking subregister liveness, the main range must start new
1998 // values on partial register writes, even if there is no read.
1999 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
2001 report("Instruction ending live segment doesn't read the register",
2003 report_context(LR, Reg, LaneMask);
2010 // Now check all the basic blocks in this live segment.
2011 MachineFunction::const_iterator MFI = MBB->getIterator();
2012 // Is this live segment the beginning of a non-PHIDef VN?
2013 if (S.start == VNI->def && !VNI->isPHIDef()) {
2014 // Not live-in to any blocks.
2021 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
2022 // We don't know how to track physregs into a landing pad.
2023 if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
2025 if (&*MFI == EndMBB)
2031 // Is VNI a PHI-def in the current block?
2032 bool IsPHI = VNI->isPHIDef() &&
2033 VNI->def == LiveInts->getMBBStartIdx(&*MFI);
2035 // Check that VNI is live-out of all predecessors.
2036 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
2037 PE = MFI->pred_end(); PI != PE; ++PI) {
2038 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
2039 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
2041 // All predecessors must have a live-out value. However for a phi
2042 // instruction with subregister intervals
2043 // only one of the subregisters (not necessarily the current one) needs to
2045 if (!PVNI && (LaneMask.none() || !IsPHI) ) {
2046 report("Register not marked live out of predecessor", *PI);
2047 report_context(LR, Reg, LaneMask);
2048 report_context(*VNI);
2049 errs() << " live into " << printMBBReference(*MFI) << '@'
2050 << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
2055 // Only PHI-defs can take different predecessor values.
2056 if (!IsPHI && PVNI != VNI) {
2057 report("Different value live out of predecessor", *PI);
2058 report_context(LR, Reg, LaneMask);
2059 errs() << "Valno #" << PVNI->id << " live out of "
2060 << printMBBReference(*(*PI)) << '@' << PEnd << "\nValno #"
2061 << VNI->id << " live into " << printMBBReference(*MFI) << '@'
2062 << LiveInts->getMBBStartIdx(&*MFI) << '\n';
2065 if (&*MFI == EndMBB)
2071 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
2072 LaneBitmask LaneMask) {
2073 for (const VNInfo *VNI : LR.valnos)
2074 verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
2076 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
2077 verifyLiveRangeSegment(LR, I, Reg, LaneMask);
2080 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
2081 unsigned Reg = LI.reg;
2082 assert(TargetRegisterInfo::isVirtualRegister(Reg));
2083 verifyLiveRange(LI, Reg);
2086 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2087 for (const LiveInterval::SubRange &SR : LI.subranges()) {
2088 if ((Mask & SR.LaneMask).any()) {
2089 report("Lane masks of sub ranges overlap in live interval", MF);
2092 if ((SR.LaneMask & ~MaxMask).any()) {
2093 report("Subrange lanemask is invalid", MF);
2097 report("Subrange must not be empty", MF);
2098 report_context(SR, LI.reg, SR.LaneMask);
2100 Mask |= SR.LaneMask;
2101 verifyLiveRange(SR, LI.reg, SR.LaneMask);
2102 if (!LI.covers(SR)) {
2103 report("A Subrange is not covered by the main range", MF);
2108 // Check the LI only has one connected component.
2109 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
2110 unsigned NumComp = ConEQ.Classify(LI);
2112 report("Multiple connected components in live interval", MF);
2114 for (unsigned comp = 0; comp != NumComp; ++comp) {
2115 errs() << comp << ": valnos";
2116 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
2117 E = LI.vni_end(); I!=E; ++I)
2118 if (comp == ConEQ.getEqClass(*I))
2119 errs() << ' ' << (*I)->id;
2127 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2128 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2130 // We use a bool plus an integer to capture the stack state.
2131 struct StackStateOfBB {
2132 StackStateOfBB() = default;
2133 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
2134 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
2135 ExitIsSetup(ExitSetup) {}
2137 // Can be negative, which means we are setting up a frame.
2140 bool EntryIsSetup = false;
2141 bool ExitIsSetup = false;
2144 } // end anonymous namespace
2146 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2147 /// by a FrameDestroy <n>, stack adjustments are identical on all
2148 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
2149 void MachineVerifier::verifyStackFrame() {
2150 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
2151 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
2152 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
2155 SmallVector<StackStateOfBB, 8> SPState;
2156 SPState.resize(MF->getNumBlockIDs());
2157 df_iterator_default_set<const MachineBasicBlock*> Reachable;
2159 // Visit the MBBs in DFS order.
2160 for (df_ext_iterator<const MachineFunction *,
2161 df_iterator_default_set<const MachineBasicBlock *>>
2162 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
2163 DFI != DFE; ++DFI) {
2164 const MachineBasicBlock *MBB = *DFI;
2166 StackStateOfBB BBState;
2167 // Check the exit state of the DFS stack predecessor.
2168 if (DFI.getPathLength() >= 2) {
2169 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
2170 assert(Reachable.count(StackPred) &&
2171 "DFS stack predecessor is already visited.\n");
2172 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
2173 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
2174 BBState.ExitValue = BBState.EntryValue;
2175 BBState.ExitIsSetup = BBState.EntryIsSetup;
2178 // Update stack state by checking contents of MBB.
2179 for (const auto &I : *MBB) {
2180 if (I.getOpcode() == FrameSetupOpcode) {
2181 if (BBState.ExitIsSetup)
2182 report("FrameSetup is after another FrameSetup", &I);
2183 BBState.ExitValue -= TII->getFrameTotalSize(I);
2184 BBState.ExitIsSetup = true;
2187 if (I.getOpcode() == FrameDestroyOpcode) {
2188 int Size = TII->getFrameTotalSize(I);
2189 if (!BBState.ExitIsSetup)
2190 report("FrameDestroy is not after a FrameSetup", &I);
2191 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
2193 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
2194 report("FrameDestroy <n> is after FrameSetup <m>", &I);
2195 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
2196 << AbsSPAdj << ">.\n";
2198 BBState.ExitValue += Size;
2199 BBState.ExitIsSetup = false;
2202 SPState[MBB->getNumber()] = BBState;
2204 // Make sure the exit state of any predecessor is consistent with the entry
2206 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
2207 E = MBB->pred_end(); I != E; ++I) {
2208 if (Reachable.count(*I) &&
2209 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
2210 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
2211 report("The exit stack state of a predecessor is inconsistent.", MBB);
2212 errs() << "Predecessor " << printMBBReference(*(*I))
2213 << " has exit state (" << SPState[(*I)->getNumber()].ExitValue
2214 << ", " << SPState[(*I)->getNumber()].ExitIsSetup << "), while "
2215 << printMBBReference(*MBB) << " has entry state ("
2216 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
2220 // Make sure the entry state of any successor is consistent with the exit
2222 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
2223 E = MBB->succ_end(); I != E; ++I) {
2224 if (Reachable.count(*I) &&
2225 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
2226 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
2227 report("The entry stack state of a successor is inconsistent.", MBB);
2228 errs() << "Successor " << printMBBReference(*(*I))
2229 << " has entry state (" << SPState[(*I)->getNumber()].EntryValue
2230 << ", " << SPState[(*I)->getNumber()].EntryIsSetup << "), while "
2231 << printMBBReference(*MBB) << " has exit state ("
2232 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
2236 // Make sure a basic block with return ends with zero stack adjustment.
2237 if (!MBB->empty() && MBB->back().isReturn()) {
2238 if (BBState.ExitIsSetup)
2239 report("A return block ends with a FrameSetup.", MBB);
2240 if (BBState.ExitValue)
2241 report("A return block ends with a nonzero stack adjustment.", MBB);