1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Pass to verify generated machine code. The following is checked:
12 // Operand counts: All explicit operands must be present.
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
26 #include "llvm/BasicBlock.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveVariables.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineInstrBundle.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineMemOperand.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/ADT/DenseSet.h"
43 #include "llvm/ADT/SetOperations.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
51 struct MachineVerifier {
53 MachineVerifier(Pass *pass, const char *b) :
56 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
59 bool runOnMachineFunction(MachineFunction &MF);
63 const char *const OutFileName;
65 const MachineFunction *MF;
66 const TargetMachine *TM;
67 const TargetInstrInfo *TII;
68 const TargetRegisterInfo *TRI;
69 const MachineRegisterInfo *MRI;
73 typedef SmallVector<unsigned, 16> RegVector;
74 typedef SmallVector<const uint32_t*, 4> RegMaskVector;
75 typedef DenseSet<unsigned> RegSet;
76 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
77 typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
79 const MachineInstr *FirstTerminator;
80 BlockSet FunctionBlocks;
82 BitVector regsReserved;
83 BitVector regsAllocatable;
85 RegVector regsDefined, regsDead, regsKilled;
86 RegMaskVector regMasks;
87 RegSet regsLiveInButUnused;
91 // Add Reg and any sub-registers to RV
92 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
94 if (TargetRegisterInfo::isPhysicalRegister(Reg))
95 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
96 RV.push_back(*SubRegs);
100 // Is this MBB reachable from the MF entry point?
103 // Vregs that must be live in because they are used without being
104 // defined. Map value is the user.
107 // Regs killed in MBB. They may be defined again, and will then be in both
108 // regsKilled and regsLiveOut.
111 // Regs defined in MBB and live out. Note that vregs passing through may
112 // be live out without being mentioned here.
115 // Vregs that pass through MBB untouched. This set is disjoint from
116 // regsKilled and regsLiveOut.
119 // Vregs that must pass through MBB because they are needed by a successor
120 // block. This set is disjoint from regsLiveOut.
121 RegSet vregsRequired;
123 // Set versions of block's predecessor and successor lists.
124 BlockSet Preds, Succs;
126 BBInfo() : reachable(false) {}
128 // Add register to vregsPassed if it belongs there. Return true if
130 bool addPassed(unsigned Reg) {
131 if (!TargetRegisterInfo::isVirtualRegister(Reg))
133 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
135 return vregsPassed.insert(Reg).second;
138 // Same for a full set.
139 bool addPassed(const RegSet &RS) {
140 bool changed = false;
141 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
147 // Add register to vregsRequired if it belongs there. Return true if
149 bool addRequired(unsigned Reg) {
150 if (!TargetRegisterInfo::isVirtualRegister(Reg))
152 if (regsLiveOut.count(Reg))
154 return vregsRequired.insert(Reg).second;
157 // Same for a full set.
158 bool addRequired(const RegSet &RS) {
159 bool changed = false;
160 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
166 // Same for a full map.
167 bool addRequired(const RegMap &RM) {
168 bool changed = false;
169 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
170 if (addRequired(I->first))
175 // Live-out registers are either in regsLiveOut or vregsPassed.
176 bool isLiveOut(unsigned Reg) const {
177 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
181 // Extra register info per MBB.
182 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
184 bool isReserved(unsigned Reg) {
185 return Reg < regsReserved.size() && regsReserved.test(Reg);
188 bool isAllocatable(unsigned Reg) {
189 return Reg < regsAllocatable.size() && regsAllocatable.test(Reg);
192 // Analysis information if available
193 LiveVariables *LiveVars;
194 LiveIntervals *LiveInts;
195 LiveStacks *LiveStks;
196 SlotIndexes *Indexes;
198 void visitMachineFunctionBefore();
199 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
200 void visitMachineBundleBefore(const MachineInstr *MI);
201 void visitMachineInstrBefore(const MachineInstr *MI);
202 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
203 void visitMachineInstrAfter(const MachineInstr *MI);
204 void visitMachineBundleAfter(const MachineInstr *MI);
205 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
206 void visitMachineFunctionAfter();
208 void report(const char *msg, const MachineFunction *MF);
209 void report(const char *msg, const MachineBasicBlock *MBB);
210 void report(const char *msg, const MachineInstr *MI);
211 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
212 void report(const char *msg, const MachineFunction *MF,
213 const LiveInterval &LI);
214 void report(const char *msg, const MachineBasicBlock *MBB,
215 const LiveInterval &LI);
217 void verifyInlineAsm(const MachineInstr *MI);
218 void verifyTiedOperands(const MachineInstr *MI);
220 void checkLiveness(const MachineOperand *MO, unsigned MONum);
221 void markReachable(const MachineBasicBlock *MBB);
222 void calcRegsPassed();
223 void checkPHIOps(const MachineBasicBlock *MBB);
225 void calcRegsRequired();
226 void verifyLiveVariables();
227 void verifyLiveIntervals();
228 void verifyLiveInterval(const LiveInterval&);
229 void verifyLiveIntervalValue(const LiveInterval&, VNInfo*);
230 void verifyLiveIntervalSegment(const LiveInterval&,
231 LiveInterval::const_iterator);
234 struct MachineVerifierPass : public MachineFunctionPass {
235 static char ID; // Pass ID, replacement for typeid
236 const char *const Banner;
238 MachineVerifierPass(const char *b = 0)
239 : MachineFunctionPass(ID), Banner(b) {
240 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
243 void getAnalysisUsage(AnalysisUsage &AU) const {
244 AU.setPreservesAll();
245 MachineFunctionPass::getAnalysisUsage(AU);
248 bool runOnMachineFunction(MachineFunction &MF) {
249 MF.verify(this, Banner);
256 char MachineVerifierPass::ID = 0;
257 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
258 "Verify generated machine code", false, false)
260 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
261 return new MachineVerifierPass(Banner);
264 void MachineFunction::verify(Pass *p, const char *Banner) const {
265 MachineVerifier(p, Banner)
266 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
269 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
270 raw_ostream *OutFile = 0;
272 std::string ErrorInfo;
273 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
274 raw_fd_ostream::F_Append);
275 if (!ErrorInfo.empty()) {
276 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
288 TM = &MF.getTarget();
289 TII = TM->getInstrInfo();
290 TRI = TM->getRegisterInfo();
291 MRI = &MF.getRegInfo();
298 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
299 // We don't want to verify LiveVariables if LiveIntervals is available.
301 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
302 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
303 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
306 visitMachineFunctionBefore();
307 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
309 visitMachineBasicBlockBefore(MFI);
310 // Keep track of the current bundle header.
311 const MachineInstr *CurBundle = 0;
312 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
313 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
314 if (MBBI->getParent() != MFI) {
315 report("Bad instruction parent pointer", MFI);
316 *OS << "Instruction: " << *MBBI;
319 // Is this a bundle header?
320 if (!MBBI->isInsideBundle()) {
322 visitMachineBundleAfter(CurBundle);
324 visitMachineBundleBefore(CurBundle);
325 } else if (!CurBundle)
326 report("No bundle header", MBBI);
327 visitMachineInstrBefore(MBBI);
328 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
329 visitMachineOperand(&MBBI->getOperand(I), I);
330 visitMachineInstrAfter(MBBI);
333 visitMachineBundleAfter(CurBundle);
334 visitMachineBasicBlockAfter(MFI);
336 visitMachineFunctionAfter();
340 else if (foundErrors)
341 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
349 regsLiveInButUnused.clear();
352 return false; // no changes
355 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
358 if (!foundErrors++) {
360 *OS << "# " << Banner << '\n';
361 MF->print(*OS, Indexes);
363 *OS << "*** Bad machine code: " << msg << " ***\n"
364 << "- function: " << MF->getName() << "\n";
367 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
369 report(msg, MBB->getParent());
370 *OS << "- basic block: BB#" << MBB->getNumber()
371 << ' ' << MBB->getName()
372 << " (" << (void*)MBB << ')';
374 *OS << " [" << Indexes->getMBBStartIdx(MBB)
375 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
379 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
381 report(msg, MI->getParent());
382 *OS << "- instruction: ";
383 if (Indexes && Indexes->hasIndex(MI))
384 *OS << Indexes->getInstructionIndex(MI) << '\t';
388 void MachineVerifier::report(const char *msg,
389 const MachineOperand *MO, unsigned MONum) {
391 report(msg, MO->getParent());
392 *OS << "- operand " << MONum << ": ";
397 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
398 const LiveInterval &LI) {
400 *OS << "- interval: ";
401 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
402 *OS << PrintReg(LI.reg, TRI);
404 *OS << PrintRegUnit(LI.reg, TRI);
405 *OS << ' ' << LI << '\n';
408 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
409 const LiveInterval &LI) {
411 *OS << "- interval: ";
412 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
413 *OS << PrintReg(LI.reg, TRI);
415 *OS << PrintRegUnit(LI.reg, TRI);
416 *OS << ' ' << LI << '\n';
419 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
420 BBInfo &MInfo = MBBInfoMap[MBB];
421 if (!MInfo.reachable) {
422 MInfo.reachable = true;
423 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
424 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
429 void MachineVerifier::visitMachineFunctionBefore() {
430 lastIndex = SlotIndex();
431 regsReserved = TRI->getReservedRegs(*MF);
433 // A sub-register of a reserved register is also reserved
434 for (int Reg = regsReserved.find_first(); Reg>=0;
435 Reg = regsReserved.find_next(Reg)) {
436 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
437 // FIXME: This should probably be:
438 // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
439 regsReserved.set(*SubRegs);
443 regsAllocatable = TRI->getAllocatableSet(*MF);
445 markReachable(&MF->front());
447 // Build a set of the basic blocks in the function.
448 FunctionBlocks.clear();
449 for (MachineFunction::const_iterator
450 I = MF->begin(), E = MF->end(); I != E; ++I) {
451 FunctionBlocks.insert(I);
452 BBInfo &MInfo = MBBInfoMap[I];
454 MInfo.Preds.insert(I->pred_begin(), I->pred_end());
455 if (MInfo.Preds.size() != I->pred_size())
456 report("MBB has duplicate entries in its predecessor list.", I);
458 MInfo.Succs.insert(I->succ_begin(), I->succ_end());
459 if (MInfo.Succs.size() != I->succ_size())
460 report("MBB has duplicate entries in its successor list.", I);
464 // Does iterator point to a and b as the first two elements?
465 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
466 const MachineBasicBlock *a, const MachineBasicBlock *b) {
475 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
479 // If this block has allocatable physical registers live-in, check that
480 // it is an entry block or landing pad.
481 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
482 LE = MBB->livein_end();
485 if (isAllocatable(reg) && !MBB->isLandingPad() &&
486 MBB != MBB->getParent()->begin()) {
487 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
492 // Count the number of landing pad successors.
493 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
494 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
495 E = MBB->succ_end(); I != E; ++I) {
496 if ((*I)->isLandingPad())
497 LandingPadSuccs.insert(*I);
498 if (!FunctionBlocks.count(*I))
499 report("MBB has successor that isn't part of the function.", MBB);
500 if (!MBBInfoMap[*I].Preds.count(MBB)) {
501 report("Inconsistent CFG", MBB);
502 *OS << "MBB is not in the predecessor list of the successor BB#"
503 << (*I)->getNumber() << ".\n";
507 // Check the predecessor list.
508 for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
509 E = MBB->pred_end(); I != E; ++I) {
510 if (!FunctionBlocks.count(*I))
511 report("MBB has predecessor that isn't part of the function.", MBB);
512 if (!MBBInfoMap[*I].Succs.count(MBB)) {
513 report("Inconsistent CFG", MBB);
514 *OS << "MBB is not in the successor list of the predecessor BB#"
515 << (*I)->getNumber() << ".\n";
519 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
520 const BasicBlock *BB = MBB->getBasicBlock();
521 if (LandingPadSuccs.size() > 1 &&
523 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
524 BB && isa<SwitchInst>(BB->getTerminator())))
525 report("MBB has more than one landing pad successor", MBB);
527 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
528 MachineBasicBlock *TBB = 0, *FBB = 0;
529 SmallVector<MachineOperand, 4> Cond;
530 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
532 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
533 // check whether its answers match up with reality.
535 // Block falls through to its successor.
536 MachineFunction::const_iterator MBBI = MBB;
538 if (MBBI == MF->end()) {
539 // It's possible that the block legitimately ends with a noreturn
540 // call or an unreachable, in which case it won't actually fall
541 // out the bottom of the function.
542 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
543 // It's possible that the block legitimately ends with a noreturn
544 // call or an unreachable, in which case it won't actuall fall
546 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
547 report("MBB exits via unconditional fall-through but doesn't have "
548 "exactly one CFG successor!", MBB);
549 } else if (!MBB->isSuccessor(MBBI)) {
550 report("MBB exits via unconditional fall-through but its successor "
551 "differs from its CFG successor!", MBB);
553 if (!MBB->empty() && getBundleStart(&MBB->back())->isBarrier() &&
554 !TII->isPredicated(getBundleStart(&MBB->back()))) {
555 report("MBB exits via unconditional fall-through but ends with a "
556 "barrier instruction!", MBB);
559 report("MBB exits via unconditional fall-through but has a condition!",
562 } else if (TBB && !FBB && Cond.empty()) {
563 // Block unconditionally branches somewhere.
564 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
565 report("MBB exits via unconditional branch but doesn't have "
566 "exactly one CFG successor!", MBB);
567 } else if (!MBB->isSuccessor(TBB)) {
568 report("MBB exits via unconditional branch but the CFG "
569 "successor doesn't match the actual successor!", MBB);
572 report("MBB exits via unconditional branch but doesn't contain "
573 "any instructions!", MBB);
574 } else if (!getBundleStart(&MBB->back())->isBarrier()) {
575 report("MBB exits via unconditional branch but doesn't end with a "
576 "barrier instruction!", MBB);
577 } else if (!getBundleStart(&MBB->back())->isTerminator()) {
578 report("MBB exits via unconditional branch but the branch isn't a "
579 "terminator instruction!", MBB);
581 } else if (TBB && !FBB && !Cond.empty()) {
582 // Block conditionally branches somewhere, otherwise falls through.
583 MachineFunction::const_iterator MBBI = MBB;
585 if (MBBI == MF->end()) {
586 report("MBB conditionally falls through out of function!", MBB);
587 } if (MBB->succ_size() == 1) {
588 // A conditional branch with only one successor is weird, but allowed.
590 report("MBB exits via conditional branch/fall-through but only has "
591 "one CFG successor!", MBB);
592 else if (TBB != *MBB->succ_begin())
593 report("MBB exits via conditional branch/fall-through but the CFG "
594 "successor don't match the actual successor!", MBB);
595 } else if (MBB->succ_size() != 2) {
596 report("MBB exits via conditional branch/fall-through but doesn't have "
597 "exactly two CFG successors!", MBB);
598 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
599 report("MBB exits via conditional branch/fall-through but the CFG "
600 "successors don't match the actual successors!", MBB);
603 report("MBB exits via conditional branch/fall-through but doesn't "
604 "contain any instructions!", MBB);
605 } else if (getBundleStart(&MBB->back())->isBarrier()) {
606 report("MBB exits via conditional branch/fall-through but ends with a "
607 "barrier instruction!", MBB);
608 } else if (!getBundleStart(&MBB->back())->isTerminator()) {
609 report("MBB exits via conditional branch/fall-through but the branch "
610 "isn't a terminator instruction!", MBB);
612 } else if (TBB && FBB) {
613 // Block conditionally branches somewhere, otherwise branches
615 if (MBB->succ_size() == 1) {
616 // A conditional branch with only one successor is weird, but allowed.
618 report("MBB exits via conditional branch/branch through but only has "
619 "one CFG successor!", MBB);
620 else if (TBB != *MBB->succ_begin())
621 report("MBB exits via conditional branch/branch through but the CFG "
622 "successor don't match the actual successor!", MBB);
623 } else if (MBB->succ_size() != 2) {
624 report("MBB exits via conditional branch/branch but doesn't have "
625 "exactly two CFG successors!", MBB);
626 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
627 report("MBB exits via conditional branch/branch but the CFG "
628 "successors don't match the actual successors!", MBB);
631 report("MBB exits via conditional branch/branch but doesn't "
632 "contain any instructions!", MBB);
633 } else if (!getBundleStart(&MBB->back())->isBarrier()) {
634 report("MBB exits via conditional branch/branch but doesn't end with a "
635 "barrier instruction!", MBB);
636 } else if (!getBundleStart(&MBB->back())->isTerminator()) {
637 report("MBB exits via conditional branch/branch but the branch "
638 "isn't a terminator instruction!", MBB);
641 report("MBB exits via conditinal branch/branch but there's no "
645 report("AnalyzeBranch returned invalid data!", MBB);
650 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
651 E = MBB->livein_end(); I != E; ++I) {
652 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
653 report("MBB live-in list contains non-physical register", MBB);
657 for (MCSubRegIterator SubRegs(*I, TRI); SubRegs.isValid(); ++SubRegs)
658 regsLive.insert(*SubRegs);
660 regsLiveInButUnused = regsLive;
662 const MachineFrameInfo *MFI = MF->getFrameInfo();
663 assert(MFI && "Function has no frame info");
664 BitVector PR = MFI->getPristineRegs(MBB);
665 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
667 for (MCSubRegIterator SubRegs(I, TRI); SubRegs.isValid(); ++SubRegs)
668 regsLive.insert(*SubRegs);
675 lastIndex = Indexes->getMBBStartIdx(MBB);
678 // This function gets called for all bundle headers, including normal
679 // stand-alone unbundled instructions.
680 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
681 if (Indexes && Indexes->hasIndex(MI)) {
682 SlotIndex idx = Indexes->getInstructionIndex(MI);
683 if (!(idx > lastIndex)) {
684 report("Instruction index out of order", MI);
685 *OS << "Last instruction was at " << lastIndex << '\n';
690 // Ensure non-terminators don't follow terminators.
691 // Ignore predicated terminators formed by if conversion.
692 // FIXME: If conversion shouldn't need to violate this rule.
693 if (MI->isTerminator() && !TII->isPredicated(MI)) {
694 if (!FirstTerminator)
695 FirstTerminator = MI;
696 } else if (FirstTerminator) {
697 report("Non-terminator instruction after the first terminator", MI);
698 *OS << "First terminator was:\t" << *FirstTerminator;
702 // The operands on an INLINEASM instruction must follow a template.
703 // Verify that the flag operands make sense.
704 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
705 // The first two operands on INLINEASM are the asm string and global flags.
706 if (MI->getNumOperands() < 2) {
707 report("Too few operands on inline asm", MI);
710 if (!MI->getOperand(0).isSymbol())
711 report("Asm string must be an external symbol", MI);
712 if (!MI->getOperand(1).isImm())
713 report("Asm flags must be an immediate", MI);
714 // Allowed flags are Extra_HasSideEffects = 1, and Extra_IsAlignStack = 2.
715 if (!isUInt<2>(MI->getOperand(1).getImm()))
716 report("Unknown asm flags", &MI->getOperand(1), 1);
718 assert(InlineAsm::MIOp_FirstOperand == 2 && "Asm format changed");
720 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
722 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
723 const MachineOperand &MO = MI->getOperand(OpNo);
724 // There may be implicit ops after the fixed operands.
727 NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
730 if (OpNo > MI->getNumOperands())
731 report("Missing operands in last group", MI);
733 // An optional MDNode follows the groups.
734 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
737 // All trailing operands must be implicit registers.
738 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
739 const MachineOperand &MO = MI->getOperand(OpNo);
740 if (!MO.isReg() || !MO.isImplicit())
741 report("Expected implicit register after groups", &MO, OpNo);
745 // Verify the consistency of tied operands.
746 void MachineVerifier::verifyTiedOperands(const MachineInstr *MI) {
747 const MCInstrDesc &MCID = MI->getDesc();
748 SmallVector<unsigned, 4> Defs;
749 SmallVector<unsigned, 4> Uses;
750 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
751 const MachineOperand &MO = MI->getOperand(i);
752 if (!MO.isReg() || !MO.isTied())
759 if (Defs.size() < Uses.size()) {
760 report("No tied def for tied use", &MO, i);
763 if (i >= MCID.getNumOperands())
765 int DefIdx = MCID.getOperandConstraint(i, MCOI::TIED_TO);
766 if (unsigned(DefIdx) != Defs[Uses.size() - 1]) {
767 report(" def doesn't match MCInstrDesc", &MO, i);
768 *OS << "Descriptor says tied def should be operand " << DefIdx << ".\n";
771 if (Defs.size() > Uses.size()) {
772 unsigned i = Defs[Uses.size() - 1];
773 report("No tied use for tied def", &MI->getOperand(i), i);
777 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
778 const MCInstrDesc &MCID = MI->getDesc();
779 if (MI->getNumOperands() < MCID.getNumOperands()) {
780 report("Too few operands", MI);
781 *OS << MCID.getNumOperands() << " operands expected, but "
782 << MI->getNumExplicitOperands() << " given.\n";
785 // Check the tied operands.
786 if (MI->isInlineAsm())
789 verifyTiedOperands(MI);
791 // Check the MachineMemOperands for basic consistency.
792 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
793 E = MI->memoperands_end(); I != E; ++I) {
794 if ((*I)->isLoad() && !MI->mayLoad())
795 report("Missing mayLoad flag", MI);
796 if ((*I)->isStore() && !MI->mayStore())
797 report("Missing mayStore flag", MI);
800 // Debug values must not have a slot index.
801 // Other instructions must have one, unless they are inside a bundle.
803 bool mapped = !LiveInts->isNotInMIMap(MI);
804 if (MI->isDebugValue()) {
806 report("Debug instruction has a slot index", MI);
807 } else if (MI->isInsideBundle()) {
809 report("Instruction inside bundle has a slot index", MI);
812 report("Missing slot index", MI);
817 if (!TII->verifyInstruction(MI, ErrorInfo))
818 report(ErrorInfo.data(), MI);
822 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
823 const MachineInstr *MI = MO->getParent();
824 const MCInstrDesc &MCID = MI->getDesc();
826 // The first MCID.NumDefs operands must be explicit register defines
827 if (MONum < MCID.getNumDefs()) {
828 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
830 report("Explicit definition must be a register", MO, MONum);
831 else if (!MO->isDef() && !MCOI.isOptionalDef())
832 report("Explicit definition marked as use", MO, MONum);
833 else if (MO->isImplicit())
834 report("Explicit definition marked as implicit", MO, MONum);
835 } else if (MONum < MCID.getNumOperands()) {
836 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
837 // Don't check if it's the last operand in a variadic instruction. See,
838 // e.g., LDM_RET in the arm back end.
840 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
841 if (MO->isDef() && !MCOI.isOptionalDef())
842 report("Explicit operand marked as def", MO, MONum);
843 if (MO->isImplicit())
844 report("Explicit operand marked as implicit", MO, MONum);
847 if (MCID.getOperandConstraint(MONum, MCOI::TIED_TO) != -1) {
849 report("Tied use must be a register", MO, MONum);
850 else if (!MO->isTied())
851 report("Operand should be tied", MO, MONum);
852 } else if (MO->isReg() && MO->isTied())
853 report("Explicit operand should not be tied", MO, MONum);
855 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
856 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
857 report("Extra explicit operand on non-variadic instruction", MO, MONum);
860 switch (MO->getType()) {
861 case MachineOperand::MO_Register: {
862 const unsigned Reg = MO->getReg();
865 if (MRI->tracksLiveness() && !MI->isDebugValue())
866 checkLiveness(MO, MONum);
868 // Verify two-address constraints after leaving SSA form.
870 if (!MRI->isSSA() && MO->isUse() &&
871 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
872 Reg != MI->getOperand(DefIdx).getReg())
873 report("Two-address instruction operands must be identical", MO, MONum);
875 // Check register classes.
876 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
877 unsigned SubIdx = MO->getSubReg();
879 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
881 report("Illegal subregister index for physical register", MO, MONum);
884 if (const TargetRegisterClass *DRC =
885 TII->getRegClass(MCID, MONum, TRI, *MF)) {
886 if (!DRC->contains(Reg)) {
887 report("Illegal physical register for instruction", MO, MONum);
888 *OS << TRI->getName(Reg) << " is not a "
889 << DRC->getName() << " register.\n";
894 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
896 const TargetRegisterClass *SRC =
897 TRI->getSubClassWithSubReg(RC, SubIdx);
899 report("Invalid subregister index for virtual register", MO, MONum);
900 *OS << "Register class " << RC->getName()
901 << " does not support subreg index " << SubIdx << "\n";
905 report("Invalid register class for subregister index", MO, MONum);
906 *OS << "Register class " << RC->getName()
907 << " does not fully support subreg index " << SubIdx << "\n";
911 if (const TargetRegisterClass *DRC =
912 TII->getRegClass(MCID, MONum, TRI, *MF)) {
914 const TargetRegisterClass *SuperRC =
915 TRI->getLargestLegalSuperClass(RC);
917 report("No largest legal super class exists.", MO, MONum);
920 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
922 report("No matching super-reg register class.", MO, MONum);
926 if (!RC->hasSuperClassEq(DRC)) {
927 report("Illegal virtual register for instruction", MO, MONum);
928 *OS << "Expected a " << DRC->getName() << " register, but got a "
929 << RC->getName() << " register\n";
937 case MachineOperand::MO_RegisterMask:
938 regMasks.push_back(MO->getRegMask());
941 case MachineOperand::MO_MachineBasicBlock:
942 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
943 report("PHI operand is not in the CFG", MO, MONum);
946 case MachineOperand::MO_FrameIndex:
947 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
948 LiveInts && !LiveInts->isNotInMIMap(MI)) {
949 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
950 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
951 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
952 report("Instruction loads from dead spill slot", MO, MONum);
953 *OS << "Live stack: " << LI << '\n';
955 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
956 report("Instruction stores to dead spill slot", MO, MONum);
957 *OS << "Live stack: " << LI << '\n';
967 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
968 const MachineInstr *MI = MO->getParent();
969 const unsigned Reg = MO->getReg();
971 // Both use and def operands can read a register.
972 if (MO->readsReg()) {
973 regsLiveInButUnused.erase(Reg);
976 addRegWithSubRegs(regsKilled, Reg);
978 // Check that LiveVars knows this kill.
979 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
981 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
982 if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
983 report("Kill missing from LiveVariables", MO, MONum);
986 // Check LiveInts liveness and kill.
987 if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
988 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
989 // Check the cached regunit intervals.
990 if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
991 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
992 if (const LiveInterval *LI = LiveInts->getCachedRegUnit(*Units)) {
993 LiveRangeQuery LRQ(*LI, UseIdx);
994 if (!LRQ.valueIn()) {
995 report("No live range at use", MO, MONum);
996 *OS << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
997 << ' ' << *LI << '\n';
999 if (MO->isKill() && !LRQ.isKill()) {
1000 report("Live range continues after kill flag", MO, MONum);
1001 *OS << PrintRegUnit(*Units, TRI) << ' ' << *LI << '\n';
1007 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1008 if (LiveInts->hasInterval(Reg)) {
1009 // This is a virtual register interval.
1010 const LiveInterval &LI = LiveInts->getInterval(Reg);
1011 LiveRangeQuery LRQ(LI, UseIdx);
1012 if (!LRQ.valueIn()) {
1013 report("No live range at use", MO, MONum);
1014 *OS << UseIdx << " is not live in " << LI << '\n';
1016 // Check for extra kill flags.
1017 // Note that we allow missing kill flags for now.
1018 if (MO->isKill() && !LRQ.isKill()) {
1019 report("Live range continues after kill flag", MO, MONum);
1020 *OS << "Live range: " << LI << '\n';
1023 report("Virtual register has no live interval", MO, MONum);
1028 // Use of a dead register.
1029 if (!regsLive.count(Reg)) {
1030 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1031 // Reserved registers may be used even when 'dead'.
1032 if (!isReserved(Reg))
1033 report("Using an undefined physical register", MO, MONum);
1034 } else if (MRI->def_empty(Reg)) {
1035 report("Reading virtual register without a def", MO, MONum);
1037 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1038 // We don't know which virtual registers are live in, so only complain
1039 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1040 // must be live in. PHI instructions are handled separately.
1041 if (MInfo.regsKilled.count(Reg))
1042 report("Using a killed virtual register", MO, MONum);
1043 else if (!MI->isPHI())
1044 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1050 // Register defined.
1051 // TODO: verify that earlyclobber ops are not used.
1053 addRegWithSubRegs(regsDead, Reg);
1055 addRegWithSubRegs(regsDefined, Reg);
1058 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1059 llvm::next(MRI->def_begin(Reg)) != MRI->def_end())
1060 report("Multiple virtual register defs in SSA form", MO, MONum);
1062 // Check LiveInts for a live range, but only for virtual registers.
1063 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1064 !LiveInts->isNotInMIMap(MI)) {
1065 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1066 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1067 if (LiveInts->hasInterval(Reg)) {
1068 const LiveInterval &LI = LiveInts->getInterval(Reg);
1069 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1070 assert(VNI && "NULL valno is not allowed");
1071 if (VNI->def != DefIdx) {
1072 report("Inconsistent valno->def", MO, MONum);
1073 *OS << "Valno " << VNI->id << " is not defined at "
1074 << DefIdx << " in " << LI << '\n';
1077 report("No live range at def", MO, MONum);
1078 *OS << DefIdx << " is not live in " << LI << '\n';
1081 report("Virtual register has no Live interval", MO, MONum);
1087 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1090 // This function gets called after visiting all instructions in a bundle. The
1091 // argument points to the bundle header.
1092 // Normal stand-alone instructions are also considered 'bundles', and this
1093 // function is called for all of them.
1094 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1095 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1096 set_union(MInfo.regsKilled, regsKilled);
1097 set_subtract(regsLive, regsKilled); regsKilled.clear();
1098 // Kill any masked registers.
1099 while (!regMasks.empty()) {
1100 const uint32_t *Mask = regMasks.pop_back_val();
1101 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1102 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1103 MachineOperand::clobbersPhysReg(Mask, *I))
1104 regsDead.push_back(*I);
1106 set_subtract(regsLive, regsDead); regsDead.clear();
1107 set_union(regsLive, regsDefined); regsDefined.clear();
1111 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1112 MBBInfoMap[MBB].regsLiveOut = regsLive;
1116 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1117 if (!(stop > lastIndex)) {
1118 report("Block ends before last instruction index", MBB);
1119 *OS << "Block ends at " << stop
1120 << " last instruction was at " << lastIndex << '\n';
1126 // Calculate the largest possible vregsPassed sets. These are the registers that
1127 // can pass through an MBB live, but may not be live every time. It is assumed
1128 // that all vregsPassed sets are empty before the call.
1129 void MachineVerifier::calcRegsPassed() {
1130 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1131 // have any vregsPassed.
1132 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1133 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1134 MFI != MFE; ++MFI) {
1135 const MachineBasicBlock &MBB(*MFI);
1136 BBInfo &MInfo = MBBInfoMap[&MBB];
1137 if (!MInfo.reachable)
1139 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1140 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1141 BBInfo &SInfo = MBBInfoMap[*SuI];
1142 if (SInfo.addPassed(MInfo.regsLiveOut))
1147 // Iteratively push vregsPassed to successors. This will converge to the same
1148 // final state regardless of DenseSet iteration order.
1149 while (!todo.empty()) {
1150 const MachineBasicBlock *MBB = *todo.begin();
1152 BBInfo &MInfo = MBBInfoMap[MBB];
1153 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1154 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1157 BBInfo &SInfo = MBBInfoMap[*SuI];
1158 if (SInfo.addPassed(MInfo.vregsPassed))
1164 // Calculate the set of virtual registers that must be passed through each basic
1165 // block in order to satisfy the requirements of successor blocks. This is very
1166 // similar to calcRegsPassed, only backwards.
1167 void MachineVerifier::calcRegsRequired() {
1168 // First push live-in regs to predecessors' vregsRequired.
1169 SmallPtrSet<const MachineBasicBlock*, 8> todo;
1170 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1171 MFI != MFE; ++MFI) {
1172 const MachineBasicBlock &MBB(*MFI);
1173 BBInfo &MInfo = MBBInfoMap[&MBB];
1174 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1175 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1176 BBInfo &PInfo = MBBInfoMap[*PrI];
1177 if (PInfo.addRequired(MInfo.vregsLiveIn))
1182 // Iteratively push vregsRequired to predecessors. This will converge to the
1183 // same final state regardless of DenseSet iteration order.
1184 while (!todo.empty()) {
1185 const MachineBasicBlock *MBB = *todo.begin();
1187 BBInfo &MInfo = MBBInfoMap[MBB];
1188 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1189 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1192 BBInfo &SInfo = MBBInfoMap[*PrI];
1193 if (SInfo.addRequired(MInfo.vregsRequired))
1199 // Check PHI instructions at the beginning of MBB. It is assumed that
1200 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1201 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1202 SmallPtrSet<const MachineBasicBlock*, 8> seen;
1203 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
1204 BBI != BBE && BBI->isPHI(); ++BBI) {
1207 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
1208 unsigned Reg = BBI->getOperand(i).getReg();
1209 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
1210 if (!Pre->isSuccessor(MBB))
1213 BBInfo &PrInfo = MBBInfoMap[Pre];
1214 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1215 report("PHI operand is not live-out from predecessor",
1216 &BBI->getOperand(i), i);
1219 // Did we see all predecessors?
1220 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1221 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1222 if (!seen.count(*PrI)) {
1223 report("Missing PHI operand", BBI);
1224 *OS << "BB#" << (*PrI)->getNumber()
1225 << " is a predecessor according to the CFG.\n";
1231 void MachineVerifier::visitMachineFunctionAfter() {
1234 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1235 MFI != MFE; ++MFI) {
1236 BBInfo &MInfo = MBBInfoMap[MFI];
1238 // Skip unreachable MBBs.
1239 if (!MInfo.reachable)
1245 // Now check liveness info if available
1248 // Check for killed virtual registers that should be live out.
1249 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1250 MFI != MFE; ++MFI) {
1251 BBInfo &MInfo = MBBInfoMap[MFI];
1252 for (RegSet::iterator
1253 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1255 if (MInfo.regsKilled.count(*I)) {
1256 report("Virtual register killed in block, but needed live out.", MFI);
1257 *OS << "Virtual register " << PrintReg(*I)
1258 << " is used after the block.\n";
1263 BBInfo &MInfo = MBBInfoMap[&MF->front()];
1264 for (RegSet::iterator
1265 I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1267 report("Virtual register def doesn't dominate all uses.",
1268 MRI->getVRegDef(*I));
1272 verifyLiveVariables();
1274 verifyLiveIntervals();
1277 void MachineVerifier::verifyLiveVariables() {
1278 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1279 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1280 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1281 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1282 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1283 MFI != MFE; ++MFI) {
1284 BBInfo &MInfo = MBBInfoMap[MFI];
1286 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1287 if (MInfo.vregsRequired.count(Reg)) {
1288 if (!VI.AliveBlocks.test(MFI->getNumber())) {
1289 report("LiveVariables: Block missing from AliveBlocks", MFI);
1290 *OS << "Virtual register " << PrintReg(Reg)
1291 << " must be live through the block.\n";
1294 if (VI.AliveBlocks.test(MFI->getNumber())) {
1295 report("LiveVariables: Block should not be in AliveBlocks", MFI);
1296 *OS << "Virtual register " << PrintReg(Reg)
1297 << " is not needed live through the block.\n";
1304 void MachineVerifier::verifyLiveIntervals() {
1305 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1306 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1307 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1309 // Spilling and splitting may leave unused registers around. Skip them.
1310 if (MRI->reg_nodbg_empty(Reg))
1313 if (!LiveInts->hasInterval(Reg)) {
1314 report("Missing live interval for virtual register", MF);
1315 *OS << PrintReg(Reg, TRI) << " still has defs or uses\n";
1319 const LiveInterval &LI = LiveInts->getInterval(Reg);
1320 assert(Reg == LI.reg && "Invalid reg to interval mapping");
1321 verifyLiveInterval(LI);
1324 // Verify all the cached regunit intervals.
1325 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1326 if (const LiveInterval *LI = LiveInts->getCachedRegUnit(i))
1327 verifyLiveInterval(*LI);
1330 void MachineVerifier::verifyLiveIntervalValue(const LiveInterval &LI,
1332 if (VNI->isUnused())
1335 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
1338 report("Valno not live at def and not marked unused", MF, LI);
1339 *OS << "Valno #" << VNI->id << '\n';
1343 if (DefVNI != VNI) {
1344 report("Live range at def has different valno", MF, LI);
1345 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1346 << " where valno #" << DefVNI->id << " is live\n";
1350 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1352 report("Invalid definition index", MF, LI);
1353 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1354 << " in " << LI << '\n';
1358 if (VNI->isPHIDef()) {
1359 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1360 report("PHIDef value is not defined at MBB start", MBB, LI);
1361 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1362 << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1368 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1370 report("No instruction at def index", MBB, LI);
1371 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1375 bool hasDef = false;
1376 bool isEarlyClobber = false;
1377 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1378 if (!MOI->isReg() || !MOI->isDef())
1380 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1381 if (MOI->getReg() != LI.reg)
1384 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1385 !TRI->hasRegUnit(MOI->getReg(), LI.reg))
1389 if (MOI->isEarlyClobber())
1390 isEarlyClobber = true;
1394 report("Defining instruction does not modify register", MI);
1395 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1398 // Early clobber defs begin at USE slots, but other defs must begin at
1400 if (isEarlyClobber) {
1401 if (!VNI->def.isEarlyClobber()) {
1402 report("Early clobber def must be at an early-clobber slot", MBB, LI);
1403 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1405 } else if (!VNI->def.isRegister()) {
1406 report("Non-PHI, non-early clobber def must be at a register slot",
1408 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1413 MachineVerifier::verifyLiveIntervalSegment(const LiveInterval &LI,
1414 LiveInterval::const_iterator I) {
1415 const VNInfo *VNI = I->valno;
1416 assert(VNI && "Live range has no valno");
1418 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1419 report("Foreign valno in live range", MF, LI);
1420 *OS << *I << " has a bad valno\n";
1423 if (VNI->isUnused()) {
1424 report("Live range valno is marked unused", MF, LI);
1428 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1430 report("Bad start of live segment, no basic block", MF, LI);
1434 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1435 if (I->start != MBBStartIdx && I->start != VNI->def) {
1436 report("Live segment must begin at MBB entry or valno def", MBB, LI);
1440 const MachineBasicBlock *EndMBB =
1441 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1443 report("Bad end of live segment, no basic block", MF, LI);
1448 // No more checks for live-out segments.
1449 if (I->end == LiveInts->getMBBEndIdx(EndMBB))
1452 // RegUnit intervals are allowed dead phis.
1453 if (!TargetRegisterInfo::isVirtualRegister(LI.reg) && VNI->isPHIDef() &&
1454 I->start == VNI->def && I->end == VNI->def.getDeadSlot())
1457 // The live segment is ending inside EndMBB
1458 const MachineInstr *MI =
1459 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1461 report("Live segment doesn't end at a valid instruction", EndMBB, LI);
1466 // The block slot must refer to a basic block boundary.
1467 if (I->end.isBlock()) {
1468 report("Live segment ends at B slot of an instruction", EndMBB, LI);
1472 if (I->end.isDead()) {
1473 // Segment ends on the dead slot.
1474 // That means there must be a dead def.
1475 if (!SlotIndex::isSameInstr(I->start, I->end)) {
1476 report("Live segment ending at dead slot spans instructions", EndMBB, LI);
1481 // A live segment can only end at an early-clobber slot if it is being
1482 // redefined by an early-clobber def.
1483 if (I->end.isEarlyClobber()) {
1484 if (I+1 == LI.end() || (I+1)->start != I->end) {
1485 report("Live segment ending at early clobber slot must be "
1486 "redefined by an EC def in the same instruction", EndMBB, LI);
1491 // The following checks only apply to virtual registers. Physreg liveness
1492 // is too weird to check.
1493 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1494 // A live range can end with either a redefinition, a kill flag on a
1495 // use, or a dead flag on a def.
1496 bool hasRead = false;
1497 bool hasDeadDef = false;
1498 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1499 if (!MOI->isReg() || MOI->getReg() != LI.reg)
1501 if (MOI->readsReg())
1503 if (MOI->isDef() && MOI->isDead())
1507 if (I->end.isDead()) {
1509 report("Instruction doesn't have a dead def operand", MI);
1511 *OS << " in " << LI << '\n';
1515 report("Instruction ending live range doesn't read the register", MI);
1516 *OS << *I << " in " << LI << '\n';
1521 // Now check all the basic blocks in this live segment.
1522 MachineFunction::const_iterator MFI = MBB;
1523 // Is this live range the beginning of a non-PHIDef VN?
1524 if (I->start == VNI->def && !VNI->isPHIDef()) {
1525 // Not live-in to any blocks.
1532 assert(LiveInts->isLiveInToMBB(LI, MFI));
1533 // We don't know how to track physregs into a landing pad.
1534 if (!TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1535 MFI->isLandingPad()) {
1536 if (&*MFI == EndMBB)
1542 // Is VNI a PHI-def in the current block?
1543 bool IsPHI = VNI->isPHIDef() &&
1544 VNI->def == LiveInts->getMBBStartIdx(MFI);
1546 // Check that VNI is live-out of all predecessors.
1547 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1548 PE = MFI->pred_end(); PI != PE; ++PI) {
1549 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1550 const VNInfo *PVNI = LI.getVNInfoBefore(PEnd);
1552 // All predecessors must have a live-out value.
1554 report("Register not marked live out of predecessor", *PI, LI);
1555 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1556 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1561 // Only PHI-defs can take different predecessor values.
1562 if (!IsPHI && PVNI != VNI) {
1563 report("Different value live out of predecessor", *PI, LI);
1564 *OS << "Valno #" << PVNI->id << " live out of BB#"
1565 << (*PI)->getNumber() << '@' << PEnd
1566 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1567 << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
1570 if (&*MFI == EndMBB)
1576 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1577 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
1579 verifyLiveIntervalValue(LI, *I);
1581 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I)
1582 verifyLiveIntervalSegment(LI, I);
1584 // Check the LI only has one connected component.
1585 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1586 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1587 unsigned NumComp = ConEQ.Classify(&LI);
1589 report("Multiple connected components in live interval", MF, LI);
1590 for (unsigned comp = 0; comp != NumComp; ++comp) {
1591 *OS << comp << ": valnos";
1592 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1593 E = LI.vni_end(); I!=E; ++I)
1594 if (comp == ConEQ.getEqClass(*I))
1595 *OS << ' ' << (*I)->id;