1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Pass to verify generated machine code. The following is checked:
11 // Operand counts: All explicit operands must be present.
13 // Register classes: All physical and virtual register operands must be
14 // compatible with the register class required by the instruction descriptor.
16 // Register live intervals: Registers must be defined only once, and must be
17 // defined before use.
19 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
20 // command-line option -verify-machineinstrs, or by defining the environment
21 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
22 // the verifier errors.
23 //===----------------------------------------------------------------------===//
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SetOperations.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/Twine.h"
35 #include "llvm/Analysis/EHPersonalities.h"
36 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
37 #include "llvm/CodeGen/LiveInterval.h"
38 #include "llvm/CodeGen/LiveIntervals.h"
39 #include "llvm/CodeGen/LiveRangeCalc.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/InitializePasses.h"
63 #include "llvm/MC/LaneBitmask.h"
64 #include "llvm/MC/MCAsmInfo.h"
65 #include "llvm/MC/MCInstrDesc.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/LowLevelTypeImpl.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetMachine.h"
87 struct MachineVerifier {
88 MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
90 unsigned verify(MachineFunction &MF);
94 const MachineFunction *MF;
95 const TargetMachine *TM;
96 const TargetInstrInfo *TII;
97 const TargetRegisterInfo *TRI;
98 const MachineRegisterInfo *MRI;
100 unsigned foundErrors;
102 // Avoid querying the MachineFunctionProperties for each operand.
103 bool isFunctionRegBankSelected;
104 bool isFunctionSelected;
106 using RegVector = SmallVector<unsigned, 16>;
107 using RegMaskVector = SmallVector<const uint32_t *, 4>;
108 using RegSet = DenseSet<unsigned>;
109 using RegMap = DenseMap<unsigned, const MachineInstr *>;
110 using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
112 const MachineInstr *FirstNonPHI;
113 const MachineInstr *FirstTerminator;
114 BlockSet FunctionBlocks;
116 BitVector regsReserved;
118 RegVector regsDefined, regsDead, regsKilled;
119 RegMaskVector regMasks;
123 // Add Reg and any sub-registers to RV
124 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
126 if (Register::isPhysicalRegister(Reg))
127 for (const MCPhysReg &SubReg : TRI->subregs(Reg))
128 RV.push_back(SubReg);
132 // Is this MBB reachable from the MF entry point?
133 bool reachable = false;
135 // Vregs that must be live in because they are used without being
136 // defined. Map value is the user.
139 // Regs killed in MBB. They may be defined again, and will then be in both
140 // regsKilled and regsLiveOut.
143 // Regs defined in MBB and live out. Note that vregs passing through may
144 // be live out without being mentioned here.
147 // Vregs that pass through MBB untouched. This set is disjoint from
148 // regsKilled and regsLiveOut.
151 // Vregs that must pass through MBB because they are needed by a successor
152 // block. This set is disjoint from regsLiveOut.
153 RegSet vregsRequired;
155 // Set versions of block's predecessor and successor lists.
156 BlockSet Preds, Succs;
160 // Add register to vregsPassed if it belongs there. Return true if
162 bool addPassed(unsigned Reg) {
163 if (!Register::isVirtualRegister(Reg))
165 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
167 return vregsPassed.insert(Reg).second;
170 // Same for a full set.
171 bool addPassed(const RegSet &RS) {
172 bool changed = false;
173 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
179 // Add register to vregsRequired if it belongs there. Return true if
181 bool addRequired(unsigned Reg) {
182 if (!Register::isVirtualRegister(Reg))
184 if (regsLiveOut.count(Reg))
186 return vregsRequired.insert(Reg).second;
189 // Same for a full set.
190 bool addRequired(const RegSet &RS) {
191 bool changed = false;
192 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
198 // Same for a full map.
199 bool addRequired(const RegMap &RM) {
200 bool changed = false;
201 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
202 if (addRequired(I->first))
207 // Live-out registers are either in regsLiveOut or vregsPassed.
208 bool isLiveOut(unsigned Reg) const {
209 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
213 // Extra register info per MBB.
214 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
216 bool isReserved(unsigned Reg) {
217 return Reg < regsReserved.size() && regsReserved.test(Reg);
220 bool isAllocatable(unsigned Reg) const {
221 return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
222 !regsReserved.test(Reg);
225 // Analysis information if available
226 LiveVariables *LiveVars;
227 LiveIntervals *LiveInts;
228 LiveStacks *LiveStks;
229 SlotIndexes *Indexes;
231 void visitMachineFunctionBefore();
232 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
233 void visitMachineBundleBefore(const MachineInstr *MI);
235 bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
236 void verifyPreISelGenericInstruction(const MachineInstr *MI);
237 void visitMachineInstrBefore(const MachineInstr *MI);
238 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
239 void visitMachineInstrAfter(const MachineInstr *MI);
240 void visitMachineBundleAfter(const MachineInstr *MI);
241 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
242 void visitMachineFunctionAfter();
244 void report(const char *msg, const MachineFunction *MF);
245 void report(const char *msg, const MachineBasicBlock *MBB);
246 void report(const char *msg, const MachineInstr *MI);
247 void report(const char *msg, const MachineOperand *MO, unsigned MONum,
248 LLT MOVRegType = LLT{});
250 void report_context(const LiveInterval &LI) const;
251 void report_context(const LiveRange &LR, unsigned VRegUnit,
252 LaneBitmask LaneMask) const;
253 void report_context(const LiveRange::Segment &S) const;
254 void report_context(const VNInfo &VNI) const;
255 void report_context(SlotIndex Pos) const;
256 void report_context(MCPhysReg PhysReg) const;
257 void report_context_liverange(const LiveRange &LR) const;
258 void report_context_lanemask(LaneBitmask LaneMask) const;
259 void report_context_vreg(unsigned VReg) const;
260 void report_context_vreg_regunit(unsigned VRegOrUnit) const;
262 void verifyInlineAsm(const MachineInstr *MI);
264 void checkLiveness(const MachineOperand *MO, unsigned MONum);
265 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
266 SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
267 LaneBitmask LaneMask = LaneBitmask::getNone());
268 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
269 SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
270 bool SubRangeCheck = false,
271 LaneBitmask LaneMask = LaneBitmask::getNone());
273 void markReachable(const MachineBasicBlock *MBB);
274 void calcRegsPassed();
275 void checkPHIOps(const MachineBasicBlock &MBB);
277 void calcRegsRequired();
278 void verifyLiveVariables();
279 void verifyLiveIntervals();
280 void verifyLiveInterval(const LiveInterval&);
281 void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
283 void verifyLiveRangeSegment(const LiveRange&,
284 const LiveRange::const_iterator I, unsigned,
286 void verifyLiveRange(const LiveRange&, unsigned,
287 LaneBitmask LaneMask = LaneBitmask::getNone());
289 void verifyStackFrame();
291 void verifySlotIndexes() const;
292 void verifyProperties(const MachineFunction &MF);
295 struct MachineVerifierPass : public MachineFunctionPass {
296 static char ID; // Pass ID, replacement for typeid
298 const std::string Banner;
300 MachineVerifierPass(std::string banner = std::string())
301 : MachineFunctionPass(ID), Banner(std::move(banner)) {
302 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
305 void getAnalysisUsage(AnalysisUsage &AU) const override {
306 AU.setPreservesAll();
307 MachineFunctionPass::getAnalysisUsage(AU);
310 bool runOnMachineFunction(MachineFunction &MF) override {
311 unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
313 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
318 } // end anonymous namespace
320 char MachineVerifierPass::ID = 0;
322 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
323 "Verify generated machine code", false, false)
325 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
326 return new MachineVerifierPass(Banner);
329 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
331 MachineFunction &MF = const_cast<MachineFunction&>(*this);
332 unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
333 if (AbortOnErrors && FoundErrors)
334 report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
335 return FoundErrors == 0;
338 void MachineVerifier::verifySlotIndexes() const {
339 if (Indexes == nullptr)
342 // Ensure the IdxMBB list is sorted by slot indexes.
344 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
345 E = Indexes->MBBIndexEnd(); I != E; ++I) {
346 assert(!Last.isValid() || I->first > Last);
351 void MachineVerifier::verifyProperties(const MachineFunction &MF) {
352 // If a pass has introduced virtual registers without clearing the
353 // NoVRegs property (or set it without allocating the vregs)
354 // then report an error.
355 if (MF.getProperties().hasProperty(
356 MachineFunctionProperties::Property::NoVRegs) &&
357 MRI->getNumVirtRegs())
358 report("Function has NoVRegs property but there are VReg operands", &MF);
361 unsigned MachineVerifier::verify(MachineFunction &MF) {
365 TM = &MF.getTarget();
366 TII = MF.getSubtarget().getInstrInfo();
367 TRI = MF.getSubtarget().getRegisterInfo();
368 MRI = &MF.getRegInfo();
370 const bool isFunctionFailedISel = MF.getProperties().hasProperty(
371 MachineFunctionProperties::Property::FailedISel);
373 // If we're mid-GlobalISel and we already triggered the fallback path then
374 // it's expected that the MIR is somewhat broken but that's ok since we'll
375 // reset it and clear the FailedISel attribute in ResetMachineFunctions.
376 if (isFunctionFailedISel)
379 isFunctionRegBankSelected =
380 !isFunctionFailedISel &&
381 MF.getProperties().hasProperty(
382 MachineFunctionProperties::Property::RegBankSelected);
383 isFunctionSelected = !isFunctionFailedISel &&
384 MF.getProperties().hasProperty(
385 MachineFunctionProperties::Property::Selected);
391 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
392 // We don't want to verify LiveVariables if LiveIntervals is available.
394 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
395 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
396 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
401 verifyProperties(MF);
403 visitMachineFunctionBefore();
404 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
406 visitMachineBasicBlockBefore(&*MFI);
407 // Keep track of the current bundle header.
408 const MachineInstr *CurBundle = nullptr;
409 // Do we expect the next instruction to be part of the same bundle?
410 bool InBundle = false;
412 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
413 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
414 if (MBBI->getParent() != &*MFI) {
415 report("Bad instruction parent pointer", &*MFI);
416 errs() << "Instruction: " << *MBBI;
420 // Check for consistent bundle flags.
421 if (InBundle && !MBBI->isBundledWithPred())
422 report("Missing BundledPred flag, "
423 "BundledSucc was set on predecessor",
425 if (!InBundle && MBBI->isBundledWithPred())
426 report("BundledPred flag is set, "
427 "but BundledSucc not set on predecessor",
430 // Is this a bundle header?
431 if (!MBBI->isInsideBundle()) {
433 visitMachineBundleAfter(CurBundle);
435 visitMachineBundleBefore(CurBundle);
436 } else if (!CurBundle)
437 report("No bundle header", &*MBBI);
438 visitMachineInstrBefore(&*MBBI);
439 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
440 const MachineInstr &MI = *MBBI;
441 const MachineOperand &Op = MI.getOperand(I);
442 if (Op.getParent() != &MI) {
443 // Make sure to use correct addOperand / RemoveOperand / ChangeTo
444 // functions when replacing operands of a MachineInstr.
445 report("Instruction has operand with wrong parent set", &MI);
448 visitMachineOperand(&Op, I);
451 visitMachineInstrAfter(&*MBBI);
453 // Was this the last bundled instruction?
454 InBundle = MBBI->isBundledWithSucc();
457 visitMachineBundleAfter(CurBundle);
459 report("BundledSucc flag set on last instruction in block", &MFI->back());
460 visitMachineBasicBlockAfter(&*MFI);
462 visitMachineFunctionAfter();
475 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
478 if (!foundErrors++) {
480 errs() << "# " << Banner << '\n';
481 if (LiveInts != nullptr)
482 LiveInts->print(errs());
484 MF->print(errs(), Indexes);
486 errs() << "*** Bad machine code: " << msg << " ***\n"
487 << "- function: " << MF->getName() << "\n";
490 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
492 report(msg, MBB->getParent());
493 errs() << "- basic block: " << printMBBReference(*MBB) << ' '
494 << MBB->getName() << " (" << (const void *)MBB << ')';
496 errs() << " [" << Indexes->getMBBStartIdx(MBB)
497 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
501 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
503 report(msg, MI->getParent());
504 errs() << "- instruction: ";
505 if (Indexes && Indexes->hasIndex(*MI))
506 errs() << Indexes->getInstructionIndex(*MI) << '\t';
507 MI->print(errs(), /*SkipOpers=*/true);
510 void MachineVerifier::report(const char *msg, const MachineOperand *MO,
511 unsigned MONum, LLT MOVRegType) {
513 report(msg, MO->getParent());
514 errs() << "- operand " << MONum << ": ";
515 MO->print(errs(), MOVRegType, TRI);
519 void MachineVerifier::report_context(SlotIndex Pos) const {
520 errs() << "- at: " << Pos << '\n';
523 void MachineVerifier::report_context(const LiveInterval &LI) const {
524 errs() << "- interval: " << LI << '\n';
527 void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit,
528 LaneBitmask LaneMask) const {
529 report_context_liverange(LR);
530 report_context_vreg_regunit(VRegUnit);
532 report_context_lanemask(LaneMask);
535 void MachineVerifier::report_context(const LiveRange::Segment &S) const {
536 errs() << "- segment: " << S << '\n';
539 void MachineVerifier::report_context(const VNInfo &VNI) const {
540 errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n";
543 void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
544 errs() << "- liverange: " << LR << '\n';
547 void MachineVerifier::report_context(MCPhysReg PReg) const {
548 errs() << "- p. register: " << printReg(PReg, TRI) << '\n';
551 void MachineVerifier::report_context_vreg(unsigned VReg) const {
552 errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
555 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const {
556 if (Register::isVirtualRegister(VRegOrUnit)) {
557 report_context_vreg(VRegOrUnit);
559 errs() << "- regunit: " << printRegUnit(VRegOrUnit, TRI) << '\n';
563 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
564 errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
567 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
568 BBInfo &MInfo = MBBInfoMap[MBB];
569 if (!MInfo.reachable) {
570 MInfo.reachable = true;
571 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
572 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
577 void MachineVerifier::visitMachineFunctionBefore() {
578 lastIndex = SlotIndex();
579 regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
580 : TRI->getReservedRegs(*MF);
583 markReachable(&MF->front());
585 // Build a set of the basic blocks in the function.
586 FunctionBlocks.clear();
587 for (const auto &MBB : *MF) {
588 FunctionBlocks.insert(&MBB);
589 BBInfo &MInfo = MBBInfoMap[&MBB];
591 MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
592 if (MInfo.Preds.size() != MBB.pred_size())
593 report("MBB has duplicate entries in its predecessor list.", &MBB);
595 MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
596 if (MInfo.Succs.size() != MBB.succ_size())
597 report("MBB has duplicate entries in its successor list.", &MBB);
600 // Check that the register use lists are sane.
601 MRI->verifyUseLists();
607 // Does iterator point to a and b as the first two elements?
608 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
609 const MachineBasicBlock *a, const MachineBasicBlock *b) {
618 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
619 FirstTerminator = nullptr;
620 FirstNonPHI = nullptr;
622 if (!MF->getProperties().hasProperty(
623 MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
624 // If this block has allocatable physical registers live-in, check that
625 // it is an entry block or landing pad.
626 for (const auto &LI : MBB->liveins()) {
627 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
628 MBB->getIterator() != MBB->getParent()->begin()) {
629 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
630 report_context(LI.PhysReg);
635 // Count the number of landing pad successors.
636 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
637 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
638 E = MBB->succ_end(); I != E; ++I) {
640 LandingPadSuccs.insert(*I);
641 if (!FunctionBlocks.count(*I))
642 report("MBB has successor that isn't part of the function.", MBB);
643 if (!MBBInfoMap[*I].Preds.count(MBB)) {
644 report("Inconsistent CFG", MBB);
645 errs() << "MBB is not in the predecessor list of the successor "
646 << printMBBReference(*(*I)) << ".\n";
650 // Check the predecessor list.
651 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
652 E = MBB->pred_end(); I != E; ++I) {
653 if (!FunctionBlocks.count(*I))
654 report("MBB has predecessor that isn't part of the function.", MBB);
655 if (!MBBInfoMap[*I].Succs.count(MBB)) {
656 report("Inconsistent CFG", MBB);
657 errs() << "MBB is not in the successor list of the predecessor "
658 << printMBBReference(*(*I)) << ".\n";
662 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
663 const BasicBlock *BB = MBB->getBasicBlock();
664 const Function &F = MF->getFunction();
665 if (LandingPadSuccs.size() > 1 &&
667 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
668 BB && isa<SwitchInst>(BB->getTerminator())) &&
669 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
670 report("MBB has more than one landing pad successor", MBB);
672 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
673 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
674 SmallVector<MachineOperand, 4> Cond;
675 if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
677 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
678 // check whether its answers match up with reality.
680 // Block falls through to its successor.
681 MachineFunction::const_iterator MBBI = MBB->getIterator();
683 if (MBBI == MF->end()) {
684 // It's possible that the block legitimately ends with a noreturn
685 // call or an unreachable, in which case it won't actually fall
686 // out the bottom of the function.
687 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
688 // It's possible that the block legitimately ends with a noreturn
689 // call or an unreachable, in which case it won't actually fall
691 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
692 report("MBB exits via unconditional fall-through but doesn't have "
693 "exactly one CFG successor!", MBB);
694 } else if (!MBB->isSuccessor(&*MBBI)) {
695 report("MBB exits via unconditional fall-through but its successor "
696 "differs from its CFG successor!", MBB);
698 if (!MBB->empty() && MBB->back().isBarrier() &&
699 !TII->isPredicated(MBB->back())) {
700 report("MBB exits via unconditional fall-through but ends with a "
701 "barrier instruction!", MBB);
704 report("MBB exits via unconditional fall-through but has a condition!",
707 } else if (TBB && !FBB && Cond.empty()) {
708 // Block unconditionally branches somewhere.
709 // If the block has exactly one successor, that happens to be a
710 // landingpad, accept it as valid control flow.
711 if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
712 (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
713 *MBB->succ_begin() != *LandingPadSuccs.begin())) {
714 report("MBB exits via unconditional branch but doesn't have "
715 "exactly one CFG successor!", MBB);
716 } else if (!MBB->isSuccessor(TBB)) {
717 report("MBB exits via unconditional branch but the CFG "
718 "successor doesn't match the actual successor!", MBB);
721 report("MBB exits via unconditional branch but doesn't contain "
722 "any instructions!", MBB);
723 } else if (!MBB->back().isBarrier()) {
724 report("MBB exits via unconditional branch but doesn't end with a "
725 "barrier instruction!", MBB);
726 } else if (!MBB->back().isTerminator()) {
727 report("MBB exits via unconditional branch but the branch isn't a "
728 "terminator instruction!", MBB);
730 } else if (TBB && !FBB && !Cond.empty()) {
731 // Block conditionally branches somewhere, otherwise falls through.
732 MachineFunction::const_iterator MBBI = MBB->getIterator();
734 if (MBBI == MF->end()) {
735 report("MBB conditionally falls through out of function!", MBB);
736 } else if (MBB->succ_size() == 1) {
737 // A conditional branch with only one successor is weird, but allowed.
739 report("MBB exits via conditional branch/fall-through but only has "
740 "one CFG successor!", MBB);
741 else if (TBB != *MBB->succ_begin())
742 report("MBB exits via conditional branch/fall-through but the CFG "
743 "successor don't match the actual successor!", MBB);
744 } else if (MBB->succ_size() != 2) {
745 report("MBB exits via conditional branch/fall-through but doesn't have "
746 "exactly two CFG successors!", MBB);
747 } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
748 report("MBB exits via conditional branch/fall-through but the CFG "
749 "successors don't match the actual successors!", MBB);
752 report("MBB exits via conditional branch/fall-through but doesn't "
753 "contain any instructions!", MBB);
754 } else if (MBB->back().isBarrier()) {
755 report("MBB exits via conditional branch/fall-through but ends with a "
756 "barrier instruction!", MBB);
757 } else if (!MBB->back().isTerminator()) {
758 report("MBB exits via conditional branch/fall-through but the branch "
759 "isn't a terminator instruction!", MBB);
761 } else if (TBB && FBB) {
762 // Block conditionally branches somewhere, otherwise branches
764 if (MBB->succ_size() == 1) {
765 // A conditional branch with only one successor is weird, but allowed.
767 report("MBB exits via conditional branch/branch through but only has "
768 "one CFG successor!", MBB);
769 else if (TBB != *MBB->succ_begin())
770 report("MBB exits via conditional branch/branch through but the CFG "
771 "successor don't match the actual successor!", MBB);
772 } else if (MBB->succ_size() != 2) {
773 report("MBB exits via conditional branch/branch but doesn't have "
774 "exactly two CFG successors!", MBB);
775 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
776 report("MBB exits via conditional branch/branch but the CFG "
777 "successors don't match the actual successors!", MBB);
780 report("MBB exits via conditional branch/branch but doesn't "
781 "contain any instructions!", MBB);
782 } else if (!MBB->back().isBarrier()) {
783 report("MBB exits via conditional branch/branch but doesn't end with a "
784 "barrier instruction!", MBB);
785 } else if (!MBB->back().isTerminator()) {
786 report("MBB exits via conditional branch/branch but the branch "
787 "isn't a terminator instruction!", MBB);
790 report("MBB exits via conditional branch/branch but there's no "
794 report("AnalyzeBranch returned invalid data!", MBB);
799 if (MRI->tracksLiveness()) {
800 for (const auto &LI : MBB->liveins()) {
801 if (!Register::isPhysicalRegister(LI.PhysReg)) {
802 report("MBB live-in list contains non-physical register", MBB);
805 for (const MCPhysReg &SubReg : TRI->subregs_inclusive(LI.PhysReg))
806 regsLive.insert(SubReg);
810 const MachineFrameInfo &MFI = MF->getFrameInfo();
811 BitVector PR = MFI.getPristineRegs(*MF);
812 for (unsigned I : PR.set_bits()) {
813 for (const MCPhysReg &SubReg : TRI->subregs_inclusive(I))
814 regsLive.insert(SubReg);
821 lastIndex = Indexes->getMBBStartIdx(MBB);
824 // This function gets called for all bundle headers, including normal
825 // stand-alone unbundled instructions.
826 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
827 if (Indexes && Indexes->hasIndex(*MI)) {
828 SlotIndex idx = Indexes->getInstructionIndex(*MI);
829 if (!(idx > lastIndex)) {
830 report("Instruction index out of order", MI);
831 errs() << "Last instruction was at " << lastIndex << '\n';
836 // Ensure non-terminators don't follow terminators.
837 // Ignore predicated terminators formed by if conversion.
838 // FIXME: If conversion shouldn't need to violate this rule.
839 if (MI->isTerminator() && !TII->isPredicated(*MI)) {
840 if (!FirstTerminator)
841 FirstTerminator = MI;
842 } else if (FirstTerminator && !MI->isDebugEntryValue()) {
843 report("Non-terminator instruction after the first terminator", MI);
844 errs() << "First terminator was:\t" << *FirstTerminator;
848 // The operands on an INLINEASM instruction must follow a template.
849 // Verify that the flag operands make sense.
850 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
851 // The first two operands on INLINEASM are the asm string and global flags.
852 if (MI->getNumOperands() < 2) {
853 report("Too few operands on inline asm", MI);
856 if (!MI->getOperand(0).isSymbol())
857 report("Asm string must be an external symbol", MI);
858 if (!MI->getOperand(1).isImm())
859 report("Asm flags must be an immediate", MI);
860 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
861 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
862 // and Extra_IsConvergent = 32.
863 if (!isUInt<6>(MI->getOperand(1).getImm()))
864 report("Unknown asm flags", &MI->getOperand(1), 1);
866 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
868 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
870 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
871 const MachineOperand &MO = MI->getOperand(OpNo);
872 // There may be implicit ops after the fixed operands.
875 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
878 if (OpNo > MI->getNumOperands())
879 report("Missing operands in last group", MI);
881 // An optional MDNode follows the groups.
882 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
885 // All trailing operands must be implicit registers.
886 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
887 const MachineOperand &MO = MI->getOperand(OpNo);
888 if (!MO.isReg() || !MO.isImplicit())
889 report("Expected implicit register after groups", &MO, OpNo);
893 /// Check that types are consistent when two operands need to have the same
894 /// number of vector elements.
895 /// \return true if the types are valid.
896 bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
897 const MachineInstr *MI) {
898 if (Ty0.isVector() != Ty1.isVector()) {
899 report("operand types must be all-vector or all-scalar", MI);
900 // Generally we try to report as many issues as possible at once, but in
901 // this case it's not clear what should we be comparing the size of the
902 // scalar with: the size of the whole vector or its lane. Instead of
903 // making an arbitrary choice and emitting not so helpful message, let's
904 // avoid the extra noise and stop here.
908 if (Ty0.isVector() && Ty0.getNumElements() != Ty1.getNumElements()) {
909 report("operand types must preserve number of vector elements", MI);
916 void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
917 if (isFunctionSelected)
918 report("Unexpected generic instruction in a Selected function", MI);
920 const MCInstrDesc &MCID = MI->getDesc();
921 unsigned NumOps = MI->getNumOperands();
924 SmallVector<LLT, 4> Types;
925 for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps);
927 if (!MCID.OpInfo[I].isGenericType())
929 // Generic instructions specify type equality constraints between some of
930 // their operands. Make sure these are consistent.
931 size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex();
932 Types.resize(std::max(TypeIdx + 1, Types.size()));
934 const MachineOperand *MO = &MI->getOperand(I);
936 report("generic instruction must use register operands", MI);
940 LLT OpTy = MRI->getType(MO->getReg());
941 // Don't report a type mismatch if there is no actual mismatch, only a
942 // type missing, to reduce noise:
943 if (OpTy.isValid()) {
944 // Only the first valid type for a type index will be printed: don't
945 // overwrite it later so it's always clear which type was expected:
946 if (!Types[TypeIdx].isValid())
947 Types[TypeIdx] = OpTy;
948 else if (Types[TypeIdx] != OpTy)
949 report("Type mismatch in generic instruction", MO, I, OpTy);
951 // Generic instructions must have types attached to their operands.
952 report("Generic instruction is missing a virtual register type", MO, I);
956 // Generic opcodes must not have physical register operands.
957 for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
958 const MachineOperand *MO = &MI->getOperand(I);
959 if (MO->isReg() && Register::isPhysicalRegister(MO->getReg()))
960 report("Generic instruction cannot have physical register", MO, I);
963 // Avoid out of bounds in checks below. This was already reported earlier.
964 if (MI->getNumOperands() < MCID.getNumOperands())
968 if (!TII->verifyInstruction(*MI, ErrorInfo))
969 report(ErrorInfo.data(), MI);
971 // Verify properties of various specific instruction types
972 switch (MI->getOpcode()) {
973 case TargetOpcode::G_CONSTANT:
974 case TargetOpcode::G_FCONSTANT: {
975 if (MI->getNumOperands() < MCID.getNumOperands())
978 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
979 if (DstTy.isVector())
980 report("Instruction cannot use a vector result type", MI);
982 if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
983 if (!MI->getOperand(1).isCImm()) {
984 report("G_CONSTANT operand must be cimm", MI);
988 const ConstantInt *CI = MI->getOperand(1).getCImm();
989 if (CI->getBitWidth() != DstTy.getSizeInBits())
990 report("inconsistent constant size", MI);
992 if (!MI->getOperand(1).isFPImm()) {
993 report("G_FCONSTANT operand must be fpimm", MI);
996 const ConstantFP *CF = MI->getOperand(1).getFPImm();
998 if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) !=
999 DstTy.getSizeInBits()) {
1000 report("inconsistent constant size", MI);
1006 case TargetOpcode::G_LOAD:
1007 case TargetOpcode::G_STORE:
1008 case TargetOpcode::G_ZEXTLOAD:
1009 case TargetOpcode::G_SEXTLOAD: {
1010 LLT ValTy = MRI->getType(MI->getOperand(0).getReg());
1011 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1012 if (!PtrTy.isPointer())
1013 report("Generic memory instruction must access a pointer", MI);
1015 // Generic loads and stores must have a single MachineMemOperand
1016 // describing that access.
1017 if (!MI->hasOneMemOperand()) {
1018 report("Generic instruction accessing memory must have one mem operand",
1021 const MachineMemOperand &MMO = **MI->memoperands_begin();
1022 if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD ||
1023 MI->getOpcode() == TargetOpcode::G_SEXTLOAD) {
1024 if (MMO.getSizeInBits() >= ValTy.getSizeInBits())
1025 report("Generic extload must have a narrower memory type", MI);
1026 } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
1027 if (MMO.getSize() > ValTy.getSizeInBytes())
1028 report("load memory size cannot exceed result size", MI);
1029 } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
1030 if (ValTy.getSizeInBytes() < MMO.getSize())
1031 report("store memory size cannot exceed value size", MI);
1037 case TargetOpcode::G_PHI: {
1038 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1039 if (!DstTy.isValid() ||
1040 !std::all_of(MI->operands_begin() + 1, MI->operands_end(),
1041 [this, &DstTy](const MachineOperand &MO) {
1044 LLT Ty = MRI->getType(MO.getReg());
1045 if (!Ty.isValid() || (Ty != DstTy))
1049 report("Generic Instruction G_PHI has operands with incompatible/missing "
1054 case TargetOpcode::G_BITCAST: {
1055 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1056 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1057 if (!DstTy.isValid() || !SrcTy.isValid())
1060 if (SrcTy.isPointer() != DstTy.isPointer())
1061 report("bitcast cannot convert between pointers and other types", MI);
1063 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1064 report("bitcast sizes must match", MI);
1067 case TargetOpcode::G_INTTOPTR:
1068 case TargetOpcode::G_PTRTOINT:
1069 case TargetOpcode::G_ADDRSPACE_CAST: {
1070 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1071 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1072 if (!DstTy.isValid() || !SrcTy.isValid())
1075 verifyVectorElementMatch(DstTy, SrcTy, MI);
1077 DstTy = DstTy.getScalarType();
1078 SrcTy = SrcTy.getScalarType();
1080 if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
1081 if (!DstTy.isPointer())
1082 report("inttoptr result type must be a pointer", MI);
1083 if (SrcTy.isPointer())
1084 report("inttoptr source type must not be a pointer", MI);
1085 } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
1086 if (!SrcTy.isPointer())
1087 report("ptrtoint source type must be a pointer", MI);
1088 if (DstTy.isPointer())
1089 report("ptrtoint result type must not be a pointer", MI);
1091 assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
1092 if (!SrcTy.isPointer() || !DstTy.isPointer())
1093 report("addrspacecast types must be pointers", MI);
1095 if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
1096 report("addrspacecast must convert different address spaces", MI);
1102 case TargetOpcode::G_PTR_ADD: {
1103 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1104 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1105 LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg());
1106 if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
1109 if (!PtrTy.getScalarType().isPointer())
1110 report("gep first operand must be a pointer", MI);
1112 if (OffsetTy.getScalarType().isPointer())
1113 report("gep offset operand must not be a pointer", MI);
1115 // TODO: Is the offset allowed to be a scalar with a vector?
1118 case TargetOpcode::G_SEXT:
1119 case TargetOpcode::G_ZEXT:
1120 case TargetOpcode::G_ANYEXT:
1121 case TargetOpcode::G_TRUNC:
1122 case TargetOpcode::G_FPEXT:
1123 case TargetOpcode::G_FPTRUNC: {
1124 // Number of operands and presense of types is already checked (and
1125 // reported in case of any issues), so no need to report them again. As
1126 // we're trying to report as many issues as possible at once, however, the
1127 // instructions aren't guaranteed to have the right number of operands or
1128 // types attached to them at this point
1129 assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1130 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1131 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1132 if (!DstTy.isValid() || !SrcTy.isValid())
1135 LLT DstElTy = DstTy.getScalarType();
1136 LLT SrcElTy = SrcTy.getScalarType();
1137 if (DstElTy.isPointer() || SrcElTy.isPointer())
1138 report("Generic extend/truncate can not operate on pointers", MI);
1140 verifyVectorElementMatch(DstTy, SrcTy, MI);
1142 unsigned DstSize = DstElTy.getSizeInBits();
1143 unsigned SrcSize = SrcElTy.getSizeInBits();
1144 switch (MI->getOpcode()) {
1146 if (DstSize <= SrcSize)
1147 report("Generic extend has destination type no larger than source", MI);
1149 case TargetOpcode::G_TRUNC:
1150 case TargetOpcode::G_FPTRUNC:
1151 if (DstSize >= SrcSize)
1152 report("Generic truncate has destination type no smaller than source",
1158 case TargetOpcode::G_SELECT: {
1159 LLT SelTy = MRI->getType(MI->getOperand(0).getReg());
1160 LLT CondTy = MRI->getType(MI->getOperand(1).getReg());
1161 if (!SelTy.isValid() || !CondTy.isValid())
1164 // Scalar condition select on a vector is valid.
1165 if (CondTy.isVector())
1166 verifyVectorElementMatch(SelTy, CondTy, MI);
1169 case TargetOpcode::G_MERGE_VALUES: {
1170 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1171 // e.g. s2N = MERGE sN, sN
1172 // Merging multiple scalars into a vector is not allowed, should use
1173 // G_BUILD_VECTOR for that.
1174 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1175 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1176 if (DstTy.isVector() || SrcTy.isVector())
1177 report("G_MERGE_VALUES cannot operate on vectors", MI);
1179 const unsigned NumOps = MI->getNumOperands();
1180 if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
1181 report("G_MERGE_VALUES result size is inconsistent", MI);
1183 for (unsigned I = 2; I != NumOps; ++I) {
1184 if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy)
1185 report("G_MERGE_VALUES source types do not match", MI);
1190 case TargetOpcode::G_UNMERGE_VALUES: {
1191 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1192 LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg());
1193 // For now G_UNMERGE can split vectors.
1194 for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) {
1195 if (MRI->getType(MI->getOperand(i).getReg()) != DstTy)
1196 report("G_UNMERGE_VALUES destination types do not match", MI);
1198 if (SrcTy.getSizeInBits() !=
1199 (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) {
1200 report("G_UNMERGE_VALUES source operand does not cover dest operands",
1205 case TargetOpcode::G_BUILD_VECTOR: {
1206 // Source types must be scalars, dest type a vector. Total size of scalars
1207 // must match the dest vector size.
1208 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1209 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1210 if (!DstTy.isVector() || SrcEltTy.isVector()) {
1211 report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1215 if (DstTy.getElementType() != SrcEltTy)
1216 report("G_BUILD_VECTOR result element type must match source type", MI);
1218 if (DstTy.getNumElements() != MI->getNumOperands() - 1)
1219 report("G_BUILD_VECTOR must have an operand for each elemement", MI);
1221 for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
1222 if (MRI->getType(MI->getOperand(1).getReg()) !=
1223 MRI->getType(MI->getOperand(i).getReg()))
1224 report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
1229 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1230 // Source types must be scalars, dest type a vector. Scalar types must be
1231 // larger than the dest vector elt type, as this is a truncating operation.
1232 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1233 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1234 if (!DstTy.isVector() || SrcEltTy.isVector())
1235 report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1237 for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
1238 if (MRI->getType(MI->getOperand(1).getReg()) !=
1239 MRI->getType(MI->getOperand(i).getReg()))
1240 report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1243 if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1244 report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1249 case TargetOpcode::G_CONCAT_VECTORS: {
1250 // Source types should be vectors, and total size should match the dest
1252 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1253 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1254 if (!DstTy.isVector() || !SrcTy.isVector())
1255 report("G_CONCAT_VECTOR requires vector source and destination operands",
1257 for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
1258 if (MRI->getType(MI->getOperand(1).getReg()) !=
1259 MRI->getType(MI->getOperand(i).getReg()))
1260 report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1262 if (DstTy.getNumElements() !=
1263 SrcTy.getNumElements() * (MI->getNumOperands() - 1))
1264 report("G_CONCAT_VECTOR num dest and source elements should match", MI);
1267 case TargetOpcode::G_ICMP:
1268 case TargetOpcode::G_FCMP: {
1269 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1270 LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
1272 if ((DstTy.isVector() != SrcTy.isVector()) ||
1273 (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements()))
1274 report("Generic vector icmp/fcmp must preserve number of lanes", MI);
1278 case TargetOpcode::G_EXTRACT: {
1279 const MachineOperand &SrcOp = MI->getOperand(1);
1280 if (!SrcOp.isReg()) {
1281 report("extract source must be a register", MI);
1285 const MachineOperand &OffsetOp = MI->getOperand(2);
1286 if (!OffsetOp.isImm()) {
1287 report("extract offset must be a constant", MI);
1291 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1292 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1293 if (SrcSize == DstSize)
1294 report("extract source must be larger than result", MI);
1296 if (DstSize + OffsetOp.getImm() > SrcSize)
1297 report("extract reads past end of register", MI);
1300 case TargetOpcode::G_INSERT: {
1301 const MachineOperand &SrcOp = MI->getOperand(2);
1302 if (!SrcOp.isReg()) {
1303 report("insert source must be a register", MI);
1307 const MachineOperand &OffsetOp = MI->getOperand(3);
1308 if (!OffsetOp.isImm()) {
1309 report("insert offset must be a constant", MI);
1313 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1314 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1316 if (DstSize <= SrcSize)
1317 report("inserted size must be smaller than total register", MI);
1319 if (SrcSize + OffsetOp.getImm() > DstSize)
1320 report("insert writes past end of register", MI);
1324 case TargetOpcode::G_JUMP_TABLE: {
1325 if (!MI->getOperand(1).isJTI())
1326 report("G_JUMP_TABLE source operand must be a jump table index", MI);
1327 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1328 if (!DstTy.isPointer())
1329 report("G_JUMP_TABLE dest operand must have a pointer type", MI);
1332 case TargetOpcode::G_BRJT: {
1333 if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
1334 report("G_BRJT src operand 0 must be a pointer type", MI);
1336 if (!MI->getOperand(1).isJTI())
1337 report("G_BRJT src operand 1 must be a jump table index", MI);
1339 const auto &IdxOp = MI->getOperand(2);
1340 if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
1341 report("G_BRJT src operand 2 must be a scalar reg type", MI);
1344 case TargetOpcode::G_INTRINSIC:
1345 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS: {
1346 // TODO: Should verify number of def and use operands, but the current
1347 // interface requires passing in IR types for mangling.
1348 const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
1349 if (!IntrIDOp.isIntrinsicID()) {
1350 report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
1354 bool NoSideEffects = MI->getOpcode() == TargetOpcode::G_INTRINSIC;
1355 unsigned IntrID = IntrIDOp.getIntrinsicID();
1356 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1358 = Intrinsic::getAttributes(MF->getFunction().getContext(),
1359 static_cast<Intrinsic::ID>(IntrID));
1360 bool DeclHasSideEffects = !Attrs.hasFnAttribute(Attribute::ReadNone);
1361 if (NoSideEffects && DeclHasSideEffects) {
1362 report("G_INTRINSIC used with intrinsic that accesses memory", MI);
1365 if (!NoSideEffects && !DeclHasSideEffects) {
1366 report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI);
1371 case Intrinsic::memcpy:
1372 if (MI->getNumOperands() != 5)
1373 report("Expected memcpy intrinsic to have 5 operands", MI);
1375 case Intrinsic::memmove:
1376 if (MI->getNumOperands() != 5)
1377 report("Expected memmove intrinsic to have 5 operands", MI);
1379 case Intrinsic::memset:
1380 if (MI->getNumOperands() != 5)
1381 report("Expected memset intrinsic to have 5 operands", MI);
1386 case TargetOpcode::G_SEXT_INREG: {
1387 if (!MI->getOperand(2).isImm()) {
1388 report("G_SEXT_INREG expects an immediate operand #2", MI);
1392 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1393 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1394 verifyVectorElementMatch(DstTy, SrcTy, MI);
1396 int64_t Imm = MI->getOperand(2).getImm();
1398 report("G_SEXT_INREG size must be >= 1", MI);
1399 if (Imm >= SrcTy.getScalarSizeInBits())
1400 report("G_SEXT_INREG size must be less than source bit width", MI);
1403 case TargetOpcode::G_SHUFFLE_VECTOR: {
1404 const MachineOperand &MaskOp = MI->getOperand(3);
1405 if (!MaskOp.isShuffleMask()) {
1406 report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
1410 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1411 LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
1412 LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
1414 if (Src0Ty != Src1Ty)
1415 report("Source operands must be the same type", MI);
1417 if (Src0Ty.getScalarType() != DstTy.getScalarType())
1418 report("G_SHUFFLE_VECTOR cannot change element type", MI);
1420 // Don't check that all operands are vector because scalars are used in
1421 // place of 1 element vectors.
1422 int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1;
1423 int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1;
1425 ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
1427 if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
1428 report("Wrong result type for shufflemask", MI);
1430 for (int Idx : MaskIdxes) {
1434 if (Idx >= 2 * SrcNumElts)
1435 report("Out of bounds shuffle index", MI);
1440 case TargetOpcode::G_DYN_STACKALLOC: {
1441 const MachineOperand &DstOp = MI->getOperand(0);
1442 const MachineOperand &AllocOp = MI->getOperand(1);
1443 const MachineOperand &AlignOp = MI->getOperand(2);
1445 if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
1446 report("dst operand 0 must be a pointer type", MI);
1450 if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
1451 report("src operand 1 must be a scalar reg type", MI);
1455 if (!AlignOp.isImm()) {
1456 report("src operand 2 must be an immediate type", MI);
1466 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
1467 const MCInstrDesc &MCID = MI->getDesc();
1468 if (MI->getNumOperands() < MCID.getNumOperands()) {
1469 report("Too few operands", MI);
1470 errs() << MCID.getNumOperands() << " operands expected, but "
1471 << MI->getNumOperands() << " given.\n";
1475 if (MF->getProperties().hasProperty(
1476 MachineFunctionProperties::Property::NoPHIs))
1477 report("Found PHI instruction with NoPHIs property set", MI);
1480 report("Found PHI instruction after non-PHI", MI);
1481 } else if (FirstNonPHI == nullptr)
1484 // Check the tied operands.
1485 if (MI->isInlineAsm())
1486 verifyInlineAsm(MI);
1488 // Check the MachineMemOperands for basic consistency.
1489 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
1490 E = MI->memoperands_end();
1492 if ((*I)->isLoad() && !MI->mayLoad())
1493 report("Missing mayLoad flag", MI);
1494 if ((*I)->isStore() && !MI->mayStore())
1495 report("Missing mayStore flag", MI);
1498 // Debug values must not have a slot index.
1499 // Other instructions must have one, unless they are inside a bundle.
1501 bool mapped = !LiveInts->isNotInMIMap(*MI);
1502 if (MI->isDebugInstr()) {
1504 report("Debug instruction has a slot index", MI);
1505 } else if (MI->isInsideBundle()) {
1507 report("Instruction inside bundle has a slot index", MI);
1510 report("Missing slot index", MI);
1514 if (isPreISelGenericOpcode(MCID.getOpcode())) {
1515 verifyPreISelGenericInstruction(MI);
1519 StringRef ErrorInfo;
1520 if (!TII->verifyInstruction(*MI, ErrorInfo))
1521 report(ErrorInfo.data(), MI);
1523 // Verify properties of various specific instruction types
1524 switch (MI->getOpcode()) {
1525 case TargetOpcode::COPY: {
1528 const MachineOperand &DstOp = MI->getOperand(0);
1529 const MachineOperand &SrcOp = MI->getOperand(1);
1530 LLT DstTy = MRI->getType(DstOp.getReg());
1531 LLT SrcTy = MRI->getType(SrcOp.getReg());
1532 if (SrcTy.isValid() && DstTy.isValid()) {
1533 // If both types are valid, check that the types are the same.
1534 if (SrcTy != DstTy) {
1535 report("Copy Instruction is illegal with mismatching types", MI);
1536 errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
1539 if (SrcTy.isValid() || DstTy.isValid()) {
1540 // If one of them have valid types, let's just check they have the same
1542 unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI);
1543 unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI);
1544 assert(SrcSize && "Expecting size here");
1545 assert(DstSize && "Expecting size here");
1546 if (SrcSize != DstSize)
1547 if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
1548 report("Copy Instruction is illegal with mismatching sizes", MI);
1549 errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
1555 case TargetOpcode::STATEPOINT:
1556 if (!MI->getOperand(StatepointOpers::IDPos).isImm() ||
1557 !MI->getOperand(StatepointOpers::NBytesPos).isImm() ||
1558 !MI->getOperand(StatepointOpers::NCallArgsPos).isImm())
1559 report("meta operands to STATEPOINT not constant!", MI);
1562 auto VerifyStackMapConstant = [&](unsigned Offset) {
1563 if (!MI->getOperand(Offset).isImm() ||
1564 MI->getOperand(Offset).getImm() != StackMaps::ConstantOp ||
1565 !MI->getOperand(Offset + 1).isImm())
1566 report("stack map constant to STATEPOINT not well formed!", MI);
1568 const unsigned VarStart = StatepointOpers(MI).getVarIdx();
1569 VerifyStackMapConstant(VarStart + StatepointOpers::CCOffset);
1570 VerifyStackMapConstant(VarStart + StatepointOpers::FlagsOffset);
1571 VerifyStackMapConstant(VarStart + StatepointOpers::NumDeoptOperandsOffset);
1573 // TODO: verify we have properly encoded deopt arguments
1579 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
1580 const MachineInstr *MI = MO->getParent();
1581 const MCInstrDesc &MCID = MI->getDesc();
1582 unsigned NumDefs = MCID.getNumDefs();
1583 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
1584 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
1586 // The first MCID.NumDefs operands must be explicit register defines
1587 if (MONum < NumDefs) {
1588 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1590 report("Explicit definition must be a register", MO, MONum);
1591 else if (!MO->isDef() && !MCOI.isOptionalDef())
1592 report("Explicit definition marked as use", MO, MONum);
1593 else if (MO->isImplicit())
1594 report("Explicit definition marked as implicit", MO, MONum);
1595 } else if (MONum < MCID.getNumOperands()) {
1596 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1597 // Don't check if it's the last operand in a variadic instruction. See,
1598 // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
1599 bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
1602 if (MO->isDef() && !MCOI.isOptionalDef())
1603 report("Explicit operand marked as def", MO, MONum);
1604 if (MO->isImplicit())
1605 report("Explicit operand marked as implicit", MO, MONum);
1608 // Check that an instruction has register operands only as expected.
1609 if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
1610 !MO->isReg() && !MO->isFI())
1611 report("Expected a register operand.", MO, MONum);
1612 if ((MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
1613 MCOI.OperandType == MCOI::OPERAND_PCREL) && MO->isReg())
1614 report("Expected a non-register operand.", MO, MONum);
1617 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
1620 report("Tied use must be a register", MO, MONum);
1621 else if (!MO->isTied())
1622 report("Operand should be tied", MO, MONum);
1623 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
1624 report("Tied def doesn't match MCInstrDesc", MO, MONum);
1625 else if (Register::isPhysicalRegister(MO->getReg())) {
1626 const MachineOperand &MOTied = MI->getOperand(TiedTo);
1627 if (!MOTied.isReg())
1628 report("Tied counterpart must be a register", &MOTied, TiedTo);
1629 else if (Register::isPhysicalRegister(MOTied.getReg()) &&
1630 MO->getReg() != MOTied.getReg())
1631 report("Tied physical registers must match.", &MOTied, TiedTo);
1633 } else if (MO->isReg() && MO->isTied())
1634 report("Explicit operand should not be tied", MO, MONum);
1636 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1637 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
1638 report("Extra explicit operand on non-variadic instruction", MO, MONum);
1641 switch (MO->getType()) {
1642 case MachineOperand::MO_Register: {
1643 const Register Reg = MO->getReg();
1646 if (MRI->tracksLiveness() && !MI->isDebugValue())
1647 checkLiveness(MO, MONum);
1649 // Verify the consistency of tied operands.
1651 unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
1652 const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
1653 if (!OtherMO.isReg())
1654 report("Must be tied to a register", MO, MONum);
1655 if (!OtherMO.isTied())
1656 report("Missing tie flags on tied operand", MO, MONum);
1657 if (MI->findTiedOperandIdx(OtherIdx) != MONum)
1658 report("Inconsistent tie links", MO, MONum);
1659 if (MONum < MCID.getNumDefs()) {
1660 if (OtherIdx < MCID.getNumOperands()) {
1661 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
1662 report("Explicit def tied to explicit use without tie constraint",
1665 if (!OtherMO.isImplicit())
1666 report("Explicit def should be tied to implicit use", MO, MONum);
1671 // Verify two-address constraints after leaving SSA form.
1673 if (!MRI->isSSA() && MO->isUse() &&
1674 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
1675 Reg != MI->getOperand(DefIdx).getReg())
1676 report("Two-address instruction operands must be identical", MO, MONum);
1678 // Check register classes.
1679 unsigned SubIdx = MO->getSubReg();
1681 if (Register::isPhysicalRegister(Reg)) {
1683 report("Illegal subregister index for physical register", MO, MONum);
1686 if (MONum < MCID.getNumOperands()) {
1687 if (const TargetRegisterClass *DRC =
1688 TII->getRegClass(MCID, MONum, TRI, *MF)) {
1689 if (!DRC->contains(Reg)) {
1690 report("Illegal physical register for instruction", MO, MONum);
1691 errs() << printReg(Reg, TRI) << " is not a "
1692 << TRI->getRegClassName(DRC) << " register.\n";
1696 if (MO->isRenamable()) {
1697 if (MRI->isReserved(Reg)) {
1698 report("isRenamable set on reserved register", MO, MONum);
1702 if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) {
1703 report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum);
1707 // Virtual register.
1708 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
1710 // This is a generic virtual register.
1712 // If we're post-Select, we can't have gvregs anymore.
1713 if (isFunctionSelected) {
1714 report("Generic virtual register invalid in a Selected function",
1719 // The gvreg must have a type and it must not have a SubIdx.
1720 LLT Ty = MRI->getType(Reg);
1721 if (!Ty.isValid()) {
1722 report("Generic virtual register must have a valid type", MO,
1727 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
1729 // If we're post-RegBankSelect, the gvreg must have a bank.
1730 if (!RegBank && isFunctionRegBankSelected) {
1731 report("Generic virtual register must have a bank in a "
1732 "RegBankSelected function",
1737 // Make sure the register fits into its register bank if any.
1738 if (RegBank && Ty.isValid() &&
1739 RegBank->getSize() < Ty.getSizeInBits()) {
1740 report("Register bank is too small for virtual register", MO,
1742 errs() << "Register bank " << RegBank->getName() << " too small("
1743 << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
1748 report("Generic virtual register does not allow subregister index", MO,
1753 // If this is a target specific instruction and this operand
1754 // has register class constraint, the virtual register must
1756 if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
1757 MONum < MCID.getNumOperands() &&
1758 TII->getRegClass(MCID, MONum, TRI, *MF)) {
1759 report("Virtual register does not match instruction constraint", MO,
1761 errs() << "Expect register class "
1762 << TRI->getRegClassName(
1763 TII->getRegClass(MCID, MONum, TRI, *MF))
1764 << " but got nothing\n";
1771 const TargetRegisterClass *SRC =
1772 TRI->getSubClassWithSubReg(RC, SubIdx);
1774 report("Invalid subregister index for virtual register", MO, MONum);
1775 errs() << "Register class " << TRI->getRegClassName(RC)
1776 << " does not support subreg index " << SubIdx << "\n";
1780 report("Invalid register class for subregister index", MO, MONum);
1781 errs() << "Register class " << TRI->getRegClassName(RC)
1782 << " does not fully support subreg index " << SubIdx << "\n";
1786 if (MONum < MCID.getNumOperands()) {
1787 if (const TargetRegisterClass *DRC =
1788 TII->getRegClass(MCID, MONum, TRI, *MF)) {
1790 const TargetRegisterClass *SuperRC =
1791 TRI->getLargestLegalSuperClass(RC, *MF);
1793 report("No largest legal super class exists.", MO, MONum);
1796 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
1798 report("No matching super-reg register class.", MO, MONum);
1802 if (!RC->hasSuperClassEq(DRC)) {
1803 report("Illegal virtual register for instruction", MO, MONum);
1804 errs() << "Expected a " << TRI->getRegClassName(DRC)
1805 << " register, but got a " << TRI->getRegClassName(RC)
1814 case MachineOperand::MO_RegisterMask:
1815 regMasks.push_back(MO->getRegMask());
1818 case MachineOperand::MO_MachineBasicBlock:
1819 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
1820 report("PHI operand is not in the CFG", MO, MONum);
1823 case MachineOperand::MO_FrameIndex:
1824 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
1825 LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1826 int FI = MO->getIndex();
1827 LiveInterval &LI = LiveStks->getInterval(FI);
1828 SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
1830 bool stores = MI->mayStore();
1831 bool loads = MI->mayLoad();
1832 // For a memory-to-memory move, we need to check if the frame
1833 // index is used for storing or loading, by inspecting the
1835 if (stores && loads) {
1836 for (auto *MMO : MI->memoperands()) {
1837 const PseudoSourceValue *PSV = MMO->getPseudoValue();
1838 if (PSV == nullptr) continue;
1839 const FixedStackPseudoSourceValue *Value =
1840 dyn_cast<FixedStackPseudoSourceValue>(PSV);
1841 if (Value == nullptr) continue;
1842 if (Value->getFrameIndex() != FI) continue;
1850 if (loads == stores)
1851 report("Missing fixed stack memoperand.", MI);
1853 if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
1854 report("Instruction loads from dead spill slot", MO, MONum);
1855 errs() << "Live stack: " << LI << '\n';
1857 if (stores && !LI.liveAt(Idx.getRegSlot())) {
1858 report("Instruction stores to dead spill slot", MO, MONum);
1859 errs() << "Live stack: " << LI << '\n';
1869 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
1870 unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
1871 LaneBitmask LaneMask) {
1872 LiveQueryResult LRQ = LR.Query(UseIdx);
1873 // Check if we have a segment at the use, note however that we only need one
1874 // live subregister range, the others may be dead.
1875 if (!LRQ.valueIn() && LaneMask.none()) {
1876 report("No live segment at use", MO, MONum);
1877 report_context_liverange(LR);
1878 report_context_vreg_regunit(VRegOrUnit);
1879 report_context(UseIdx);
1881 if (MO->isKill() && !LRQ.isKill()) {
1882 report("Live range continues after kill flag", MO, MONum);
1883 report_context_liverange(LR);
1884 report_context_vreg_regunit(VRegOrUnit);
1886 report_context_lanemask(LaneMask);
1887 report_context(UseIdx);
1891 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
1892 unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
1893 bool SubRangeCheck, LaneBitmask LaneMask) {
1894 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
1895 assert(VNI && "NULL valno is not allowed");
1896 if (VNI->def != DefIdx) {
1897 report("Inconsistent valno->def", MO, MONum);
1898 report_context_liverange(LR);
1899 report_context_vreg_regunit(VRegOrUnit);
1901 report_context_lanemask(LaneMask);
1902 report_context(*VNI);
1903 report_context(DefIdx);
1906 report("No live segment at def", MO, MONum);
1907 report_context_liverange(LR);
1908 report_context_vreg_regunit(VRegOrUnit);
1910 report_context_lanemask(LaneMask);
1911 report_context(DefIdx);
1913 // Check that, if the dead def flag is present, LiveInts agree.
1915 LiveQueryResult LRQ = LR.Query(DefIdx);
1916 if (!LRQ.isDeadDef()) {
1917 assert(Register::isVirtualRegister(VRegOrUnit) &&
1918 "Expecting a virtual register.");
1919 // A dead subreg def only tells us that the specific subreg is dead. There
1920 // could be other non-dead defs of other subregs, or we could have other
1921 // parts of the register being live through the instruction. So unless we
1922 // are checking liveness for a subrange it is ok for the live range to
1923 // continue, given that we have a dead def of a subregister.
1924 if (SubRangeCheck || MO->getSubReg() == 0) {
1925 report("Live range continues after dead def flag", MO, MONum);
1926 report_context_liverange(LR);
1927 report_context_vreg_regunit(VRegOrUnit);
1929 report_context_lanemask(LaneMask);
1935 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1936 const MachineInstr *MI = MO->getParent();
1937 const unsigned Reg = MO->getReg();
1939 // Both use and def operands can read a register.
1940 if (MO->readsReg()) {
1942 addRegWithSubRegs(regsKilled, Reg);
1944 // Check that LiveVars knows this kill.
1945 if (LiveVars && Register::isVirtualRegister(Reg) && MO->isKill()) {
1946 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1947 if (!is_contained(VI.Kills, MI))
1948 report("Kill missing from LiveVariables", MO, MONum);
1951 // Check LiveInts liveness and kill.
1952 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1953 SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
1954 // Check the cached regunit intervals.
1955 if (Register::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1956 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1957 if (MRI->isReservedRegUnit(*Units))
1959 if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
1960 checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
1964 if (Register::isVirtualRegister(Reg)) {
1965 if (LiveInts->hasInterval(Reg)) {
1966 // This is a virtual register interval.
1967 const LiveInterval &LI = LiveInts->getInterval(Reg);
1968 checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg);
1970 if (LI.hasSubRanges() && !MO->isDef()) {
1971 unsigned SubRegIdx = MO->getSubReg();
1972 LaneBitmask MOMask = SubRegIdx != 0
1973 ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1974 : MRI->getMaxLaneMaskForVReg(Reg);
1975 LaneBitmask LiveInMask;
1976 for (const LiveInterval::SubRange &SR : LI.subranges()) {
1977 if ((MOMask & SR.LaneMask).none())
1979 checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
1980 LiveQueryResult LRQ = SR.Query(UseIdx);
1982 LiveInMask |= SR.LaneMask;
1984 // At least parts of the register has to be live at the use.
1985 if ((LiveInMask & MOMask).none()) {
1986 report("No live subrange at use", MO, MONum);
1988 report_context(UseIdx);
1992 report("Virtual register has no live interval", MO, MONum);
1997 // Use of a dead register.
1998 if (!regsLive.count(Reg)) {
1999 if (Register::isPhysicalRegister(Reg)) {
2000 // Reserved registers may be used even when 'dead'.
2001 bool Bad = !isReserved(Reg);
2002 // We are fine if just any subregister has a defined value.
2005 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
2006 if (regsLive.count(SubReg)) {
2012 // If there is an additional implicit-use of a super register we stop
2013 // here. By definition we are fine if the super register is not
2014 // (completely) dead, if the complete super register is dead we will
2015 // get a report for its operand.
2017 for (const MachineOperand &MOP : MI->uses()) {
2018 if (!MOP.isReg() || !MOP.isImplicit())
2021 if (!Register::isPhysicalRegister(MOP.getReg()))
2024 for (const MCPhysReg &SubReg : TRI->subregs(MOP.getReg())) {
2025 if (SubReg == Reg) {
2033 report("Using an undefined physical register", MO, MONum);
2034 } else if (MRI->def_empty(Reg)) {
2035 report("Reading virtual register without a def", MO, MONum);
2037 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
2038 // We don't know which virtual registers are live in, so only complain
2039 // if vreg was killed in this MBB. Otherwise keep track of vregs that
2040 // must be live in. PHI instructions are handled separately.
2041 if (MInfo.regsKilled.count(Reg))
2042 report("Using a killed virtual register", MO, MONum);
2043 else if (!MI->isPHI())
2044 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
2050 // Register defined.
2051 // TODO: verify that earlyclobber ops are not used.
2053 addRegWithSubRegs(regsDead, Reg);
2055 addRegWithSubRegs(regsDefined, Reg);
2058 if (MRI->isSSA() && Register::isVirtualRegister(Reg) &&
2059 std::next(MRI->def_begin(Reg)) != MRI->def_end())
2060 report("Multiple virtual register defs in SSA form", MO, MONum);
2062 // Check LiveInts for a live segment, but only for virtual registers.
2063 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2064 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
2065 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
2067 if (Register::isVirtualRegister(Reg)) {
2068 if (LiveInts->hasInterval(Reg)) {
2069 const LiveInterval &LI = LiveInts->getInterval(Reg);
2070 checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg);
2072 if (LI.hasSubRanges()) {
2073 unsigned SubRegIdx = MO->getSubReg();
2074 LaneBitmask MOMask = SubRegIdx != 0
2075 ? TRI->getSubRegIndexLaneMask(SubRegIdx)
2076 : MRI->getMaxLaneMaskForVReg(Reg);
2077 for (const LiveInterval::SubRange &SR : LI.subranges()) {
2078 if ((SR.LaneMask & MOMask).none())
2080 checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
2084 report("Virtual register has no Live interval", MO, MONum);
2091 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {}
2093 // This function gets called after visiting all instructions in a bundle. The
2094 // argument points to the bundle header.
2095 // Normal stand-alone instructions are also considered 'bundles', and this
2096 // function is called for all of them.
2097 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
2098 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
2099 set_union(MInfo.regsKilled, regsKilled);
2100 set_subtract(regsLive, regsKilled); regsKilled.clear();
2101 // Kill any masked registers.
2102 while (!regMasks.empty()) {
2103 const uint32_t *Mask = regMasks.pop_back_val();
2104 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
2105 if (Register::isPhysicalRegister(*I) &&
2106 MachineOperand::clobbersPhysReg(Mask, *I))
2107 regsDead.push_back(*I);
2109 set_subtract(regsLive, regsDead); regsDead.clear();
2110 set_union(regsLive, regsDefined); regsDefined.clear();
2114 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
2115 MBBInfoMap[MBB].regsLiveOut = regsLive;
2119 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
2120 if (!(stop > lastIndex)) {
2121 report("Block ends before last instruction index", MBB);
2122 errs() << "Block ends at " << stop
2123 << " last instruction was at " << lastIndex << '\n';
2129 // Calculate the largest possible vregsPassed sets. These are the registers that
2130 // can pass through an MBB live, but may not be live every time. It is assumed
2131 // that all vregsPassed sets are empty before the call.
2132 void MachineVerifier::calcRegsPassed() {
2133 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
2134 // have any vregsPassed.
2135 SmallPtrSet<const MachineBasicBlock*, 8> todo;
2136 for (const auto &MBB : *MF) {
2137 BBInfo &MInfo = MBBInfoMap[&MBB];
2138 if (!MInfo.reachable)
2140 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
2141 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
2142 BBInfo &SInfo = MBBInfoMap[*SuI];
2143 if (SInfo.addPassed(MInfo.regsLiveOut))
2148 // Iteratively push vregsPassed to successors. This will converge to the same
2149 // final state regardless of DenseSet iteration order.
2150 while (!todo.empty()) {
2151 const MachineBasicBlock *MBB = *todo.begin();
2153 BBInfo &MInfo = MBBInfoMap[MBB];
2154 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
2155 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
2158 BBInfo &SInfo = MBBInfoMap[*SuI];
2159 if (SInfo.addPassed(MInfo.vregsPassed))
2165 // Calculate the set of virtual registers that must be passed through each basic
2166 // block in order to satisfy the requirements of successor blocks. This is very
2167 // similar to calcRegsPassed, only backwards.
2168 void MachineVerifier::calcRegsRequired() {
2169 // First push live-in regs to predecessors' vregsRequired.
2170 SmallPtrSet<const MachineBasicBlock*, 8> todo;
2171 for (const auto &MBB : *MF) {
2172 BBInfo &MInfo = MBBInfoMap[&MBB];
2173 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
2174 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
2175 BBInfo &PInfo = MBBInfoMap[*PrI];
2176 if (PInfo.addRequired(MInfo.vregsLiveIn))
2181 // Iteratively push vregsRequired to predecessors. This will converge to the
2182 // same final state regardless of DenseSet iteration order.
2183 while (!todo.empty()) {
2184 const MachineBasicBlock *MBB = *todo.begin();
2186 BBInfo &MInfo = MBBInfoMap[MBB];
2187 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
2188 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
2191 BBInfo &SInfo = MBBInfoMap[*PrI];
2192 if (SInfo.addRequired(MInfo.vregsRequired))
2198 // Check PHI instructions at the beginning of MBB. It is assumed that
2199 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
2200 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
2201 BBInfo &MInfo = MBBInfoMap[&MBB];
2203 SmallPtrSet<const MachineBasicBlock*, 8> seen;
2204 for (const MachineInstr &Phi : MBB) {
2209 const MachineOperand &MODef = Phi.getOperand(0);
2210 if (!MODef.isReg() || !MODef.isDef()) {
2211 report("Expected first PHI operand to be a register def", &MODef, 0);
2214 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
2215 MODef.isEarlyClobber() || MODef.isDebug())
2216 report("Unexpected flag on PHI operand", &MODef, 0);
2217 Register DefReg = MODef.getReg();
2218 if (!Register::isVirtualRegister(DefReg))
2219 report("Expected first PHI operand to be a virtual register", &MODef, 0);
2221 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
2222 const MachineOperand &MO0 = Phi.getOperand(I);
2224 report("Expected PHI operand to be a register", &MO0, I);
2227 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
2228 MO0.isDebug() || MO0.isTied())
2229 report("Unexpected flag on PHI operand", &MO0, I);
2231 const MachineOperand &MO1 = Phi.getOperand(I + 1);
2233 report("Expected PHI operand to be a basic block", &MO1, I + 1);
2237 const MachineBasicBlock &Pre = *MO1.getMBB();
2238 if (!Pre.isSuccessor(&MBB)) {
2239 report("PHI input is not a predecessor block", &MO1, I + 1);
2243 if (MInfo.reachable) {
2245 BBInfo &PrInfo = MBBInfoMap[&Pre];
2246 if (!MO0.isUndef() && PrInfo.reachable &&
2247 !PrInfo.isLiveOut(MO0.getReg()))
2248 report("PHI operand is not live-out from predecessor", &MO0, I);
2252 // Did we see all predecessors?
2253 if (MInfo.reachable) {
2254 for (MachineBasicBlock *Pred : MBB.predecessors()) {
2255 if (!seen.count(Pred)) {
2256 report("Missing PHI operand", &Phi);
2257 errs() << printMBBReference(*Pred)
2258 << " is a predecessor according to the CFG.\n";
2265 void MachineVerifier::visitMachineFunctionAfter() {
2268 for (const MachineBasicBlock &MBB : *MF)
2271 // Now check liveness info if available
2274 // Check for killed virtual registers that should be live out.
2275 for (const auto &MBB : *MF) {
2276 BBInfo &MInfo = MBBInfoMap[&MBB];
2277 for (RegSet::iterator
2278 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
2280 if (MInfo.regsKilled.count(*I)) {
2281 report("Virtual register killed in block, but needed live out.", &MBB);
2282 errs() << "Virtual register " << printReg(*I)
2283 << " is used after the block.\n";
2288 BBInfo &MInfo = MBBInfoMap[&MF->front()];
2289 for (RegSet::iterator
2290 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
2292 report("Virtual register defs don't dominate all uses.", MF);
2293 report_context_vreg(*I);
2298 verifyLiveVariables();
2300 verifyLiveIntervals();
2302 // Check live-in list of each MBB. If a register is live into MBB, check
2303 // that the register is in regsLiveOut of each predecessor block. Since
2304 // this must come from a definition in the predecesssor or its live-in
2305 // list, this will catch a live-through case where the predecessor does not
2306 // have the register in its live-in list. This currently only checks
2307 // registers that have no aliases, are not allocatable and are not
2308 // reserved, which could mean a condition code register for instance.
2309 if (MRI->tracksLiveness())
2310 for (const auto &MBB : *MF)
2311 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
2312 MCPhysReg LiveInReg = P.PhysReg;
2313 bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
2314 if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg))
2316 for (const MachineBasicBlock *Pred : MBB.predecessors()) {
2317 BBInfo &PInfo = MBBInfoMap[Pred];
2318 if (!PInfo.regsLiveOut.count(LiveInReg)) {
2319 report("Live in register not found to be live out from predecessor.",
2321 errs() << TRI->getName(LiveInReg)
2322 << " not found to be live out from "
2323 << printMBBReference(*Pred) << "\n";
2328 for (auto CSInfo : MF->getCallSitesInfo())
2329 if (!CSInfo.first->isCall())
2330 report("Call site info referencing instruction that is not call", MF);
2333 void MachineVerifier::verifyLiveVariables() {
2334 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
2335 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
2336 unsigned Reg = Register::index2VirtReg(i);
2337 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
2338 for (const auto &MBB : *MF) {
2339 BBInfo &MInfo = MBBInfoMap[&MBB];
2341 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
2342 if (MInfo.vregsRequired.count(Reg)) {
2343 if (!VI.AliveBlocks.test(MBB.getNumber())) {
2344 report("LiveVariables: Block missing from AliveBlocks", &MBB);
2345 errs() << "Virtual register " << printReg(Reg)
2346 << " must be live through the block.\n";
2349 if (VI.AliveBlocks.test(MBB.getNumber())) {
2350 report("LiveVariables: Block should not be in AliveBlocks", &MBB);
2351 errs() << "Virtual register " << printReg(Reg)
2352 << " is not needed live through the block.\n";
2359 void MachineVerifier::verifyLiveIntervals() {
2360 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
2361 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
2362 unsigned Reg = Register::index2VirtReg(i);
2364 // Spilling and splitting may leave unused registers around. Skip them.
2365 if (MRI->reg_nodbg_empty(Reg))
2368 if (!LiveInts->hasInterval(Reg)) {
2369 report("Missing live interval for virtual register", MF);
2370 errs() << printReg(Reg, TRI) << " still has defs or uses\n";
2374 const LiveInterval &LI = LiveInts->getInterval(Reg);
2375 assert(Reg == LI.reg && "Invalid reg to interval mapping");
2376 verifyLiveInterval(LI);
2379 // Verify all the cached regunit intervals.
2380 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
2381 if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
2382 verifyLiveRange(*LR, i);
2385 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
2386 const VNInfo *VNI, unsigned Reg,
2387 LaneBitmask LaneMask) {
2388 if (VNI->isUnused())
2391 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
2394 report("Value not live at VNInfo def and not marked unused", MF);
2395 report_context(LR, Reg, LaneMask);
2396 report_context(*VNI);
2400 if (DefVNI != VNI) {
2401 report("Live segment at def has different VNInfo", MF);
2402 report_context(LR, Reg, LaneMask);
2403 report_context(*VNI);
2407 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
2409 report("Invalid VNInfo definition index", MF);
2410 report_context(LR, Reg, LaneMask);
2411 report_context(*VNI);
2415 if (VNI->isPHIDef()) {
2416 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
2417 report("PHIDef VNInfo is not defined at MBB start", MBB);
2418 report_context(LR, Reg, LaneMask);
2419 report_context(*VNI);
2425 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
2427 report("No instruction at VNInfo def index", MBB);
2428 report_context(LR, Reg, LaneMask);
2429 report_context(*VNI);
2434 bool hasDef = false;
2435 bool isEarlyClobber = false;
2436 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
2437 if (!MOI->isReg() || !MOI->isDef())
2439 if (Register::isVirtualRegister(Reg)) {
2440 if (MOI->getReg() != Reg)
2443 if (!Register::isPhysicalRegister(MOI->getReg()) ||
2444 !TRI->hasRegUnit(MOI->getReg(), Reg))
2447 if (LaneMask.any() &&
2448 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
2451 if (MOI->isEarlyClobber())
2452 isEarlyClobber = true;
2456 report("Defining instruction does not modify register", MI);
2457 report_context(LR, Reg, LaneMask);
2458 report_context(*VNI);
2461 // Early clobber defs begin at USE slots, but other defs must begin at
2463 if (isEarlyClobber) {
2464 if (!VNI->def.isEarlyClobber()) {
2465 report("Early clobber def must be at an early-clobber slot", MBB);
2466 report_context(LR, Reg, LaneMask);
2467 report_context(*VNI);
2469 } else if (!VNI->def.isRegister()) {
2470 report("Non-PHI, non-early clobber def must be at a register slot", MBB);
2471 report_context(LR, Reg, LaneMask);
2472 report_context(*VNI);
2477 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
2478 const LiveRange::const_iterator I,
2479 unsigned Reg, LaneBitmask LaneMask)
2481 const LiveRange::Segment &S = *I;
2482 const VNInfo *VNI = S.valno;
2483 assert(VNI && "Live segment has no valno");
2485 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
2486 report("Foreign valno in live segment", MF);
2487 report_context(LR, Reg, LaneMask);
2489 report_context(*VNI);
2492 if (VNI->isUnused()) {
2493 report("Live segment valno is marked unused", MF);
2494 report_context(LR, Reg, LaneMask);
2498 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
2500 report("Bad start of live segment, no basic block", MF);
2501 report_context(LR, Reg, LaneMask);
2505 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
2506 if (S.start != MBBStartIdx && S.start != VNI->def) {
2507 report("Live segment must begin at MBB entry or valno def", MBB);
2508 report_context(LR, Reg, LaneMask);
2512 const MachineBasicBlock *EndMBB =
2513 LiveInts->getMBBFromIndex(S.end.getPrevSlot());
2515 report("Bad end of live segment, no basic block", MF);
2516 report_context(LR, Reg, LaneMask);
2521 // No more checks for live-out segments.
2522 if (S.end == LiveInts->getMBBEndIdx(EndMBB))
2525 // RegUnit intervals are allowed dead phis.
2526 if (!Register::isVirtualRegister(Reg) && VNI->isPHIDef() &&
2527 S.start == VNI->def && S.end == VNI->def.getDeadSlot())
2530 // The live segment is ending inside EndMBB
2531 const MachineInstr *MI =
2532 LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
2534 report("Live segment doesn't end at a valid instruction", EndMBB);
2535 report_context(LR, Reg, LaneMask);
2540 // The block slot must refer to a basic block boundary.
2541 if (S.end.isBlock()) {
2542 report("Live segment ends at B slot of an instruction", EndMBB);
2543 report_context(LR, Reg, LaneMask);
2547 if (S.end.isDead()) {
2548 // Segment ends on the dead slot.
2549 // That means there must be a dead def.
2550 if (!SlotIndex::isSameInstr(S.start, S.end)) {
2551 report("Live segment ending at dead slot spans instructions", EndMBB);
2552 report_context(LR, Reg, LaneMask);
2557 // A live segment can only end at an early-clobber slot if it is being
2558 // redefined by an early-clobber def.
2559 if (S.end.isEarlyClobber()) {
2560 if (I+1 == LR.end() || (I+1)->start != S.end) {
2561 report("Live segment ending at early clobber slot must be "
2562 "redefined by an EC def in the same instruction", EndMBB);
2563 report_context(LR, Reg, LaneMask);
2568 // The following checks only apply to virtual registers. Physreg liveness
2569 // is too weird to check.
2570 if (Register::isVirtualRegister(Reg)) {
2571 // A live segment can end with either a redefinition, a kill flag on a
2572 // use, or a dead flag on a def.
2573 bool hasRead = false;
2574 bool hasSubRegDef = false;
2575 bool hasDeadDef = false;
2576 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
2577 if (!MOI->isReg() || MOI->getReg() != Reg)
2579 unsigned Sub = MOI->getSubReg();
2580 LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
2581 : LaneBitmask::getAll();
2584 hasSubRegDef = true;
2585 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2586 // mask for subregister defs. Read-undef defs will be handled by
2593 if (LaneMask.any() && (LaneMask & SLM).none())
2595 if (MOI->readsReg())
2598 if (S.end.isDead()) {
2599 // Make sure that the corresponding machine operand for a "dead" live
2600 // range has the dead flag. We cannot perform this check for subregister
2601 // liveranges as partially dead values are allowed.
2602 if (LaneMask.none() && !hasDeadDef) {
2603 report("Instruction ending live segment on dead slot has no dead flag",
2605 report_context(LR, Reg, LaneMask);
2610 // When tracking subregister liveness, the main range must start new
2611 // values on partial register writes, even if there is no read.
2612 if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
2614 report("Instruction ending live segment doesn't read the register",
2616 report_context(LR, Reg, LaneMask);
2623 // Now check all the basic blocks in this live segment.
2624 MachineFunction::const_iterator MFI = MBB->getIterator();
2625 // Is this live segment the beginning of a non-PHIDef VN?
2626 if (S.start == VNI->def && !VNI->isPHIDef()) {
2627 // Not live-in to any blocks.
2634 SmallVector<SlotIndex, 4> Undefs;
2635 if (LaneMask.any()) {
2636 LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
2637 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
2641 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
2642 // We don't know how to track physregs into a landing pad.
2643 if (!Register::isVirtualRegister(Reg) && MFI->isEHPad()) {
2644 if (&*MFI == EndMBB)
2650 // Is VNI a PHI-def in the current block?
2651 bool IsPHI = VNI->isPHIDef() &&
2652 VNI->def == LiveInts->getMBBStartIdx(&*MFI);
2654 // Check that VNI is live-out of all predecessors.
2655 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
2656 PE = MFI->pred_end(); PI != PE; ++PI) {
2657 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
2658 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
2660 // All predecessors must have a live-out value. However for a phi
2661 // instruction with subregister intervals
2662 // only one of the subregisters (not necessarily the current one) needs to
2664 if (!PVNI && (LaneMask.none() || !IsPHI)) {
2665 if (LiveRangeCalc::isJointlyDominated(*PI, Undefs, *Indexes))
2667 report("Register not marked live out of predecessor", *PI);
2668 report_context(LR, Reg, LaneMask);
2669 report_context(*VNI);
2670 errs() << " live into " << printMBBReference(*MFI) << '@'
2671 << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
2676 // Only PHI-defs can take different predecessor values.
2677 if (!IsPHI && PVNI != VNI) {
2678 report("Different value live out of predecessor", *PI);
2679 report_context(LR, Reg, LaneMask);
2680 errs() << "Valno #" << PVNI->id << " live out of "
2681 << printMBBReference(*(*PI)) << '@' << PEnd << "\nValno #"
2682 << VNI->id << " live into " << printMBBReference(*MFI) << '@'
2683 << LiveInts->getMBBStartIdx(&*MFI) << '\n';
2686 if (&*MFI == EndMBB)
2692 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
2693 LaneBitmask LaneMask) {
2694 for (const VNInfo *VNI : LR.valnos)
2695 verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
2697 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
2698 verifyLiveRangeSegment(LR, I, Reg, LaneMask);
2701 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
2702 unsigned Reg = LI.reg;
2703 assert(Register::isVirtualRegister(Reg));
2704 verifyLiveRange(LI, Reg);
2707 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2708 for (const LiveInterval::SubRange &SR : LI.subranges()) {
2709 if ((Mask & SR.LaneMask).any()) {
2710 report("Lane masks of sub ranges overlap in live interval", MF);
2713 if ((SR.LaneMask & ~MaxMask).any()) {
2714 report("Subrange lanemask is invalid", MF);
2718 report("Subrange must not be empty", MF);
2719 report_context(SR, LI.reg, SR.LaneMask);
2721 Mask |= SR.LaneMask;
2722 verifyLiveRange(SR, LI.reg, SR.LaneMask);
2723 if (!LI.covers(SR)) {
2724 report("A Subrange is not covered by the main range", MF);
2729 // Check the LI only has one connected component.
2730 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
2731 unsigned NumComp = ConEQ.Classify(LI);
2733 report("Multiple connected components in live interval", MF);
2735 for (unsigned comp = 0; comp != NumComp; ++comp) {
2736 errs() << comp << ": valnos";
2737 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
2738 E = LI.vni_end(); I!=E; ++I)
2739 if (comp == ConEQ.getEqClass(*I))
2740 errs() << ' ' << (*I)->id;
2748 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2749 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2751 // We use a bool plus an integer to capture the stack state.
2752 struct StackStateOfBB {
2753 StackStateOfBB() = default;
2754 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
2755 EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
2756 ExitIsSetup(ExitSetup) {}
2758 // Can be negative, which means we are setting up a frame.
2761 bool EntryIsSetup = false;
2762 bool ExitIsSetup = false;
2765 } // end anonymous namespace
2767 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2768 /// by a FrameDestroy <n>, stack adjustments are identical on all
2769 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
2770 void MachineVerifier::verifyStackFrame() {
2771 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
2772 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
2773 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
2776 SmallVector<StackStateOfBB, 8> SPState;
2777 SPState.resize(MF->getNumBlockIDs());
2778 df_iterator_default_set<const MachineBasicBlock*> Reachable;
2780 // Visit the MBBs in DFS order.
2781 for (df_ext_iterator<const MachineFunction *,
2782 df_iterator_default_set<const MachineBasicBlock *>>
2783 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
2784 DFI != DFE; ++DFI) {
2785 const MachineBasicBlock *MBB = *DFI;
2787 StackStateOfBB BBState;
2788 // Check the exit state of the DFS stack predecessor.
2789 if (DFI.getPathLength() >= 2) {
2790 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
2791 assert(Reachable.count(StackPred) &&
2792 "DFS stack predecessor is already visited.\n");
2793 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
2794 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
2795 BBState.ExitValue = BBState.EntryValue;
2796 BBState.ExitIsSetup = BBState.EntryIsSetup;
2799 // Update stack state by checking contents of MBB.
2800 for (const auto &I : *MBB) {
2801 if (I.getOpcode() == FrameSetupOpcode) {
2802 if (BBState.ExitIsSetup)
2803 report("FrameSetup is after another FrameSetup", &I);
2804 BBState.ExitValue -= TII->getFrameTotalSize(I);
2805 BBState.ExitIsSetup = true;
2808 if (I.getOpcode() == FrameDestroyOpcode) {
2809 int Size = TII->getFrameTotalSize(I);
2810 if (!BBState.ExitIsSetup)
2811 report("FrameDestroy is not after a FrameSetup", &I);
2812 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
2814 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
2815 report("FrameDestroy <n> is after FrameSetup <m>", &I);
2816 errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
2817 << AbsSPAdj << ">.\n";
2819 BBState.ExitValue += Size;
2820 BBState.ExitIsSetup = false;
2823 SPState[MBB->getNumber()] = BBState;
2825 // Make sure the exit state of any predecessor is consistent with the entry
2827 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
2828 E = MBB->pred_end(); I != E; ++I) {
2829 if (Reachable.count(*I) &&
2830 (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
2831 SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
2832 report("The exit stack state of a predecessor is inconsistent.", MBB);
2833 errs() << "Predecessor " << printMBBReference(*(*I))
2834 << " has exit state (" << SPState[(*I)->getNumber()].ExitValue
2835 << ", " << SPState[(*I)->getNumber()].ExitIsSetup << "), while "
2836 << printMBBReference(*MBB) << " has entry state ("
2837 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
2841 // Make sure the entry state of any successor is consistent with the exit
2843 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
2844 E = MBB->succ_end(); I != E; ++I) {
2845 if (Reachable.count(*I) &&
2846 (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
2847 SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
2848 report("The entry stack state of a successor is inconsistent.", MBB);
2849 errs() << "Successor " << printMBBReference(*(*I))
2850 << " has entry state (" << SPState[(*I)->getNumber()].EntryValue
2851 << ", " << SPState[(*I)->getNumber()].EntryIsSetup << "), while "
2852 << printMBBReference(*MBB) << " has exit state ("
2853 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
2857 // Make sure a basic block with return ends with zero stack adjustment.
2858 if (!MBB->empty() && MBB->back().isReturn()) {
2859 if (BBState.ExitIsSetup)
2860 report("A return block ends with a FrameSetup.", MBB);
2861 if (BBState.ExitValue)
2862 report("A return block ends with a nonzero stack adjustment.", MBB);