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/Instructions.h"
27 #include "llvm/Function.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveVariables.h"
30 #include "llvm/CodeGen/LiveStackAnalysis.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/ADT/DenseSet.h"
41 #include "llvm/ADT/SetOperations.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
49 struct MachineVerifier {
51 MachineVerifier(Pass *pass, const char *b) :
54 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
57 bool runOnMachineFunction(MachineFunction &MF);
61 const char *const OutFileName;
63 const MachineFunction *MF;
64 const TargetMachine *TM;
65 const TargetInstrInfo *TII;
66 const TargetRegisterInfo *TRI;
67 const MachineRegisterInfo *MRI;
71 typedef SmallVector<unsigned, 16> RegVector;
72 typedef DenseSet<unsigned> RegSet;
73 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
75 const MachineInstr *FirstTerminator;
77 BitVector regsReserved;
78 BitVector regsAllocatable;
80 RegVector regsDefined, regsDead, regsKilled;
81 RegSet regsLiveInButUnused;
85 // Add Reg and any sub-registers to RV
86 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
88 if (TargetRegisterInfo::isPhysicalRegister(Reg))
89 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
94 // Is this MBB reachable from the MF entry point?
97 // Vregs that must be live in because they are used without being
98 // defined. Map value is the user.
101 // Regs killed in MBB. They may be defined again, and will then be in both
102 // regsKilled and regsLiveOut.
105 // Regs defined in MBB and live out. Note that vregs passing through may
106 // be live out without being mentioned here.
109 // Vregs that pass through MBB untouched. This set is disjoint from
110 // regsKilled and regsLiveOut.
113 // Vregs that must pass through MBB because they are needed by a successor
114 // block. This set is disjoint from regsLiveOut.
115 RegSet vregsRequired;
117 BBInfo() : reachable(false) {}
119 // Add register to vregsPassed if it belongs there. Return true if
121 bool addPassed(unsigned Reg) {
122 if (!TargetRegisterInfo::isVirtualRegister(Reg))
124 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
126 return vregsPassed.insert(Reg).second;
129 // Same for a full set.
130 bool addPassed(const RegSet &RS) {
131 bool changed = false;
132 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
138 // Add register to vregsRequired if it belongs there. Return true if
140 bool addRequired(unsigned Reg) {
141 if (!TargetRegisterInfo::isVirtualRegister(Reg))
143 if (regsLiveOut.count(Reg))
145 return vregsRequired.insert(Reg).second;
148 // Same for a full set.
149 bool addRequired(const RegSet &RS) {
150 bool changed = false;
151 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
157 // Same for a full map.
158 bool addRequired(const RegMap &RM) {
159 bool changed = false;
160 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
161 if (addRequired(I->first))
166 // Live-out registers are either in regsLiveOut or vregsPassed.
167 bool isLiveOut(unsigned Reg) const {
168 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
172 // Extra register info per MBB.
173 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
175 bool isReserved(unsigned Reg) {
176 return Reg < regsReserved.size() && regsReserved.test(Reg);
179 bool isAllocatable(unsigned Reg) {
180 return Reg < regsAllocatable.size() && regsAllocatable.test(Reg);
183 // Analysis information if available
184 LiveVariables *LiveVars;
185 LiveIntervals *LiveInts;
186 LiveStacks *LiveStks;
187 SlotIndexes *Indexes;
189 void visitMachineFunctionBefore();
190 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
191 void visitMachineInstrBefore(const MachineInstr *MI);
192 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
193 void visitMachineInstrAfter(const MachineInstr *MI);
194 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
195 void visitMachineFunctionAfter();
197 void report(const char *msg, const MachineFunction *MF);
198 void report(const char *msg, const MachineBasicBlock *MBB);
199 void report(const char *msg, const MachineInstr *MI);
200 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
202 void markReachable(const MachineBasicBlock *MBB);
203 void calcRegsPassed();
204 void checkPHIOps(const MachineBasicBlock *MBB);
206 void calcRegsRequired();
207 void verifyLiveVariables();
208 void verifyLiveIntervals();
211 struct MachineVerifierPass : public MachineFunctionPass {
212 static char ID; // Pass ID, replacement for typeid
213 const char *const Banner;
215 MachineVerifierPass(const char *b = 0)
216 : MachineFunctionPass(ID), Banner(b) {
217 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
220 void getAnalysisUsage(AnalysisUsage &AU) const {
221 AU.setPreservesAll();
222 MachineFunctionPass::getAnalysisUsage(AU);
225 bool runOnMachineFunction(MachineFunction &MF) {
226 MF.verify(this, Banner);
233 char MachineVerifierPass::ID = 0;
234 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
235 "Verify generated machine code", false, false)
237 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
238 return new MachineVerifierPass(Banner);
241 void MachineFunction::verify(Pass *p, const char *Banner) const {
242 MachineVerifier(p, Banner)
243 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
246 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
247 raw_ostream *OutFile = 0;
249 std::string ErrorInfo;
250 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
251 raw_fd_ostream::F_Append);
252 if (!ErrorInfo.empty()) {
253 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
265 TM = &MF.getTarget();
266 TII = TM->getInstrInfo();
267 TRI = TM->getRegisterInfo();
268 MRI = &MF.getRegInfo();
275 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
276 // We don't want to verify LiveVariables if LiveIntervals is available.
278 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
279 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
280 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
283 visitMachineFunctionBefore();
284 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
286 visitMachineBasicBlockBefore(MFI);
287 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
288 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
289 if (MBBI->getParent() != MFI) {
290 report("Bad instruction parent pointer", MFI);
291 *OS << "Instruction: " << *MBBI;
294 // Skip BUNDLE instruction for now. FIXME: We should add code to verify
295 // the BUNDLE's specifically.
296 if (MBBI->isBundle())
298 visitMachineInstrBefore(MBBI);
299 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
300 visitMachineOperand(&MBBI->getOperand(I), I);
301 visitMachineInstrAfter(MBBI);
303 visitMachineBasicBlockAfter(MFI);
305 visitMachineFunctionAfter();
309 else if (foundErrors)
310 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
317 regsLiveInButUnused.clear();
320 return false; // no changes
323 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
326 if (!foundErrors++) {
328 *OS << "# " << Banner << '\n';
329 MF->print(*OS, Indexes);
331 *OS << "*** Bad machine code: " << msg << " ***\n"
332 << "- function: " << MF->getFunction()->getName() << "\n";
335 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
337 report(msg, MBB->getParent());
338 *OS << "- basic block: " << MBB->getName()
340 << " (BB#" << MBB->getNumber() << ")";
342 *OS << " [" << Indexes->getMBBStartIdx(MBB)
343 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
347 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
349 report(msg, MI->getParent());
350 *OS << "- instruction: ";
351 if (Indexes && Indexes->hasIndex(MI))
352 *OS << Indexes->getInstructionIndex(MI) << '\t';
356 void MachineVerifier::report(const char *msg,
357 const MachineOperand *MO, unsigned MONum) {
359 report(msg, MO->getParent());
360 *OS << "- operand " << MONum << ": ";
365 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
366 BBInfo &MInfo = MBBInfoMap[MBB];
367 if (!MInfo.reachable) {
368 MInfo.reachable = true;
369 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
370 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
375 void MachineVerifier::visitMachineFunctionBefore() {
376 lastIndex = SlotIndex();
377 regsReserved = TRI->getReservedRegs(*MF);
379 // A sub-register of a reserved register is also reserved
380 for (int Reg = regsReserved.find_first(); Reg>=0;
381 Reg = regsReserved.find_next(Reg)) {
382 for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
383 // FIXME: This should probably be:
384 // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
385 regsReserved.set(*Sub);
389 regsAllocatable = TRI->getAllocatableSet(*MF);
391 markReachable(&MF->front());
394 // Does iterator point to a and b as the first two elements?
395 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
396 const MachineBasicBlock *a, const MachineBasicBlock *b) {
405 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
409 // If this block has allocatable physical registers live-in, check that
410 // it is an entry block or landing pad.
411 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
412 LE = MBB->livein_end();
415 if (isAllocatable(reg) && !MBB->isLandingPad() &&
416 MBB != MBB->getParent()->begin()) {
417 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
422 // Count the number of landing pad successors.
423 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
424 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
425 E = MBB->succ_end(); I != E; ++I) {
426 if ((*I)->isLandingPad())
427 LandingPadSuccs.insert(*I);
430 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
431 const BasicBlock *BB = MBB->getBasicBlock();
432 if (LandingPadSuccs.size() > 1 &&
434 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
435 BB && isa<SwitchInst>(BB->getTerminator())))
436 report("MBB has more than one landing pad successor", MBB);
438 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
439 MachineBasicBlock *TBB = 0, *FBB = 0;
440 SmallVector<MachineOperand, 4> Cond;
441 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
443 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
444 // check whether its answers match up with reality.
446 // Block falls through to its successor.
447 MachineFunction::const_iterator MBBI = MBB;
449 if (MBBI == MF->end()) {
450 // It's possible that the block legitimately ends with a noreturn
451 // call or an unreachable, in which case it won't actually fall
452 // out the bottom of the function.
453 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
454 // It's possible that the block legitimately ends with a noreturn
455 // call or an unreachable, in which case it won't actuall fall
457 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
458 report("MBB exits via unconditional fall-through but doesn't have "
459 "exactly one CFG successor!", MBB);
460 } else if (!MBB->isSuccessor(MBBI)) {
461 report("MBB exits via unconditional fall-through but its successor "
462 "differs from its CFG successor!", MBB);
464 if (!MBB->empty() && MBB->back().isBarrier() &&
465 !TII->isPredicated(&MBB->back())) {
466 report("MBB exits via unconditional fall-through but ends with a "
467 "barrier instruction!", MBB);
470 report("MBB exits via unconditional fall-through but has a condition!",
473 } else if (TBB && !FBB && Cond.empty()) {
474 // Block unconditionally branches somewhere.
475 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
476 report("MBB exits via unconditional branch but doesn't have "
477 "exactly one CFG successor!", MBB);
478 } else if (!MBB->isSuccessor(TBB)) {
479 report("MBB exits via unconditional branch but the CFG "
480 "successor doesn't match the actual successor!", MBB);
483 report("MBB exits via unconditional branch but doesn't contain "
484 "any instructions!", MBB);
485 } else if (!MBB->back().isBarrier()) {
486 report("MBB exits via unconditional branch but doesn't end with a "
487 "barrier instruction!", MBB);
488 } else if (!MBB->back().isTerminator()) {
489 report("MBB exits via unconditional branch but the branch isn't a "
490 "terminator instruction!", MBB);
492 } else if (TBB && !FBB && !Cond.empty()) {
493 // Block conditionally branches somewhere, otherwise falls through.
494 MachineFunction::const_iterator MBBI = MBB;
496 if (MBBI == MF->end()) {
497 report("MBB conditionally falls through out of function!", MBB);
498 } if (MBB->succ_size() != 2) {
499 report("MBB exits via conditional branch/fall-through but doesn't have "
500 "exactly two CFG successors!", MBB);
501 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
502 report("MBB exits via conditional branch/fall-through but the CFG "
503 "successors don't match the actual successors!", MBB);
506 report("MBB exits via conditional branch/fall-through but doesn't "
507 "contain any instructions!", MBB);
508 } else if (MBB->back().isBarrier()) {
509 report("MBB exits via conditional branch/fall-through but ends with a "
510 "barrier instruction!", MBB);
511 } else if (!MBB->back().isTerminator()) {
512 report("MBB exits via conditional branch/fall-through but the branch "
513 "isn't a terminator instruction!", MBB);
515 } else if (TBB && FBB) {
516 // Block conditionally branches somewhere, otherwise branches
518 if (MBB->succ_size() != 2) {
519 report("MBB exits via conditional branch/branch but doesn't have "
520 "exactly two CFG successors!", MBB);
521 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
522 report("MBB exits via conditional branch/branch but the CFG "
523 "successors don't match the actual successors!", MBB);
526 report("MBB exits via conditional branch/branch but doesn't "
527 "contain any instructions!", MBB);
528 } else if (!MBB->back().isBarrier()) {
529 report("MBB exits via conditional branch/branch but doesn't end with a "
530 "barrier instruction!", MBB);
531 } else if (!MBB->back().isTerminator()) {
532 report("MBB exits via conditional branch/branch but the branch "
533 "isn't a terminator instruction!", MBB);
536 report("MBB exits via conditinal branch/branch but there's no "
540 report("AnalyzeBranch returned invalid data!", MBB);
545 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
546 E = MBB->livein_end(); I != E; ++I) {
547 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
548 report("MBB live-in list contains non-physical register", MBB);
552 for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
555 regsLiveInButUnused = regsLive;
557 const MachineFrameInfo *MFI = MF->getFrameInfo();
558 assert(MFI && "Function has no frame info");
559 BitVector PR = MFI->getPristineRegs(MBB);
560 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
562 for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
570 lastIndex = Indexes->getMBBStartIdx(MBB);
573 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
574 const MCInstrDesc &MCID = MI->getDesc();
575 if (MI->getNumOperands() < MCID.getNumOperands()) {
576 report("Too few operands", MI);
577 *OS << MCID.getNumOperands() << " operands expected, but "
578 << MI->getNumExplicitOperands() << " given.\n";
581 // Check the MachineMemOperands for basic consistency.
582 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
583 E = MI->memoperands_end(); I != E; ++I) {
584 if ((*I)->isLoad() && !MI->mayLoad())
585 report("Missing mayLoad flag", MI);
586 if ((*I)->isStore() && !MI->mayStore())
587 report("Missing mayStore flag", MI);
590 // Debug values must not have a slot index.
591 // Other instructions must have one.
593 bool mapped = !LiveInts->isNotInMIMap(MI);
594 if (MI->isDebugValue()) {
596 report("Debug instruction has a slot index", MI);
599 report("Missing slot index", MI);
603 // Ensure non-terminators don't follow terminators.
604 if (MI->isTerminator()) {
605 if (!FirstTerminator)
606 FirstTerminator = MI;
607 } else if (FirstTerminator) {
608 report("Non-terminator instruction after the first terminator", MI);
609 *OS << "First terminator was:\t" << *FirstTerminator;
613 if (!TII->verifyInstruction(MI, ErrorInfo))
614 report(ErrorInfo.data(), MI);
618 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
619 const MachineInstr *MI = MO->getParent();
620 const MCInstrDesc &MCID = MI->getDesc();
621 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
623 // The first MCID.NumDefs operands must be explicit register defines
624 if (MONum < MCID.getNumDefs()) {
626 report("Explicit definition must be a register", MO, MONum);
627 else if (!MO->isDef())
628 report("Explicit definition marked as use", MO, MONum);
629 else if (MO->isImplicit())
630 report("Explicit definition marked as implicit", MO, MONum);
631 } else if (MONum < MCID.getNumOperands()) {
632 // Don't check if it's the last operand in a variadic instruction. See,
633 // e.g., LDM_RET in the arm back end.
635 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
636 if (MO->isDef() && !MCOI.isOptionalDef())
637 report("Explicit operand marked as def", MO, MONum);
638 if (MO->isImplicit())
639 report("Explicit operand marked as implicit", MO, MONum);
642 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
643 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
644 report("Extra explicit operand on non-variadic instruction", MO, MONum);
647 switch (MO->getType()) {
648 case MachineOperand::MO_Register: {
649 const unsigned Reg = MO->getReg();
653 // Check Live Variables.
654 if (MI->isDebugValue()) {
655 // Liveness checks are not valid for debug values.
656 } else if (MO->isUse() && !MO->isUndef()) {
657 regsLiveInButUnused.erase(Reg);
661 if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
662 // A two-addr use counts as a kill if use and def are the same.
663 unsigned DefReg = MI->getOperand(defIdx).getReg();
666 else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
667 report("Two-address instruction operands must be identical",
671 isKill = MO->isKill();
674 addRegWithSubRegs(regsKilled, Reg);
676 // Check that LiveVars knows this kill.
677 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
679 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
680 if (std::find(VI.Kills.begin(),
681 VI.Kills.end(), MI) == VI.Kills.end())
682 report("Kill missing from LiveVariables", MO, MONum);
685 // Check LiveInts liveness and kill.
686 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
687 LiveInts && !LiveInts->isNotInMIMap(MI)) {
688 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getRegSlot(true);
689 if (LiveInts->hasInterval(Reg)) {
690 const LiveInterval &LI = LiveInts->getInterval(Reg);
691 if (!LI.liveAt(UseIdx)) {
692 report("No live range at use", MO, MONum);
693 *OS << UseIdx << " is not live in " << LI << '\n';
695 // Check for extra kill flags.
696 // Note that we allow missing kill flags for now.
697 if (MO->isKill() && !LI.killedAt(UseIdx.getRegSlot())) {
698 report("Live range continues after kill flag", MO, MONum);
699 *OS << "Live range: " << LI << '\n';
702 report("Virtual register has no Live interval", MO, MONum);
706 // Use of a dead register.
707 if (!regsLive.count(Reg)) {
708 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
709 // Reserved registers may be used even when 'dead'.
710 if (!isReserved(Reg))
711 report("Using an undefined physical register", MO, MONum);
713 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
714 // We don't know which virtual registers are live in, so only complain
715 // if vreg was killed in this MBB. Otherwise keep track of vregs that
716 // must be live in. PHI instructions are handled separately.
717 if (MInfo.regsKilled.count(Reg))
718 report("Using a killed virtual register", MO, MONum);
719 else if (!MI->isPHI())
720 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
723 } else if (MO->isDef()) {
725 // TODO: verify that earlyclobber ops are not used.
727 addRegWithSubRegs(regsDead, Reg);
729 addRegWithSubRegs(regsDefined, Reg);
732 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
733 llvm::next(MRI->def_begin(Reg)) != MRI->def_end())
734 report("Multiple virtual register defs in SSA form", MO, MONum);
736 // Check LiveInts for a live range, but only for virtual registers.
737 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
738 !LiveInts->isNotInMIMap(MI)) {
739 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getRegSlot();
740 if (LiveInts->hasInterval(Reg)) {
741 const LiveInterval &LI = LiveInts->getInterval(Reg);
742 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
743 assert(VNI && "NULL valno is not allowed");
744 if (VNI->def != DefIdx && !MO->isEarlyClobber()) {
745 report("Inconsistent valno->def", MO, MONum);
746 *OS << "Valno " << VNI->id << " is not defined at "
747 << DefIdx << " in " << LI << '\n';
750 report("No live range at def", MO, MONum);
751 *OS << DefIdx << " is not live in " << LI << '\n';
754 report("Virtual register has no Live interval", MO, MONum);
759 // Check register classes.
760 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
761 unsigned SubIdx = MO->getSubReg();
763 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
765 report("Illegal subregister index for physical register", MO, MONum);
768 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID,MONum,TRI)) {
769 if (!DRC->contains(Reg)) {
770 report("Illegal physical register for instruction", MO, MONum);
771 *OS << TRI->getName(Reg) << " is not a "
772 << DRC->getName() << " register.\n";
777 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
779 const TargetRegisterClass *SRC =
780 TRI->getSubClassWithSubReg(RC, SubIdx);
782 report("Invalid subregister index for virtual register", MO, MONum);
783 *OS << "Register class " << RC->getName()
784 << " does not support subreg index " << SubIdx << "\n";
788 report("Invalid register class for subregister index", MO, MONum);
789 *OS << "Register class " << RC->getName()
790 << " does not fully support subreg index " << SubIdx << "\n";
794 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID,MONum,TRI)) {
796 const TargetRegisterClass *SuperRC =
797 TRI->getLargestLegalSuperClass(RC);
799 report("No largest legal super class exists.", MO, MONum);
802 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
804 report("No matching super-reg register class.", MO, MONum);
808 if (!RC->hasSuperClassEq(DRC)) {
809 report("Illegal virtual register for instruction", MO, MONum);
810 *OS << "Expected a " << DRC->getName() << " register, but got a "
811 << RC->getName() << " register\n";
819 case MachineOperand::MO_MachineBasicBlock:
820 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
821 report("PHI operand is not in the CFG", MO, MONum);
824 case MachineOperand::MO_FrameIndex:
825 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
826 LiveInts && !LiveInts->isNotInMIMap(MI)) {
827 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
828 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
829 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
830 report("Instruction loads from dead spill slot", MO, MONum);
831 *OS << "Live stack: " << LI << '\n';
833 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
834 report("Instruction stores to dead spill slot", MO, MONum);
835 *OS << "Live stack: " << LI << '\n';
845 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
846 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
847 set_union(MInfo.regsKilled, regsKilled);
848 set_subtract(regsLive, regsKilled); regsKilled.clear();
849 set_subtract(regsLive, regsDead); regsDead.clear();
850 set_union(regsLive, regsDefined); regsDefined.clear();
852 if (Indexes && Indexes->hasIndex(MI)) {
853 SlotIndex idx = Indexes->getInstructionIndex(MI);
854 if (!(idx > lastIndex)) {
855 report("Instruction index out of order", MI);
856 *OS << "Last instruction was at " << lastIndex << '\n';
863 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
864 MBBInfoMap[MBB].regsLiveOut = regsLive;
868 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
869 if (!(stop > lastIndex)) {
870 report("Block ends before last instruction index", MBB);
871 *OS << "Block ends at " << stop
872 << " last instruction was at " << lastIndex << '\n';
878 // Calculate the largest possible vregsPassed sets. These are the registers that
879 // can pass through an MBB live, but may not be live every time. It is assumed
880 // that all vregsPassed sets are empty before the call.
881 void MachineVerifier::calcRegsPassed() {
882 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
883 // have any vregsPassed.
884 DenseSet<const MachineBasicBlock*> todo;
885 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
887 const MachineBasicBlock &MBB(*MFI);
888 BBInfo &MInfo = MBBInfoMap[&MBB];
889 if (!MInfo.reachable)
891 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
892 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
893 BBInfo &SInfo = MBBInfoMap[*SuI];
894 if (SInfo.addPassed(MInfo.regsLiveOut))
899 // Iteratively push vregsPassed to successors. This will converge to the same
900 // final state regardless of DenseSet iteration order.
901 while (!todo.empty()) {
902 const MachineBasicBlock *MBB = *todo.begin();
904 BBInfo &MInfo = MBBInfoMap[MBB];
905 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
906 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
909 BBInfo &SInfo = MBBInfoMap[*SuI];
910 if (SInfo.addPassed(MInfo.vregsPassed))
916 // Calculate the set of virtual registers that must be passed through each basic
917 // block in order to satisfy the requirements of successor blocks. This is very
918 // similar to calcRegsPassed, only backwards.
919 void MachineVerifier::calcRegsRequired() {
920 // First push live-in regs to predecessors' vregsRequired.
921 DenseSet<const MachineBasicBlock*> todo;
922 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
924 const MachineBasicBlock &MBB(*MFI);
925 BBInfo &MInfo = MBBInfoMap[&MBB];
926 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
927 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
928 BBInfo &PInfo = MBBInfoMap[*PrI];
929 if (PInfo.addRequired(MInfo.vregsLiveIn))
934 // Iteratively push vregsRequired to predecessors. This will converge to the
935 // same final state regardless of DenseSet iteration order.
936 while (!todo.empty()) {
937 const MachineBasicBlock *MBB = *todo.begin();
939 BBInfo &MInfo = MBBInfoMap[MBB];
940 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
941 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
944 BBInfo &SInfo = MBBInfoMap[*PrI];
945 if (SInfo.addRequired(MInfo.vregsRequired))
951 // Check PHI instructions at the beginning of MBB. It is assumed that
952 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
953 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
954 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
955 BBI != BBE && BBI->isPHI(); ++BBI) {
956 DenseSet<const MachineBasicBlock*> seen;
958 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
959 unsigned Reg = BBI->getOperand(i).getReg();
960 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
961 if (!Pre->isSuccessor(MBB))
964 BBInfo &PrInfo = MBBInfoMap[Pre];
965 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
966 report("PHI operand is not live-out from predecessor",
967 &BBI->getOperand(i), i);
970 // Did we see all predecessors?
971 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
972 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
973 if (!seen.count(*PrI)) {
974 report("Missing PHI operand", BBI);
975 *OS << "BB#" << (*PrI)->getNumber()
976 << " is a predecessor according to the CFG.\n";
982 void MachineVerifier::visitMachineFunctionAfter() {
985 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
987 BBInfo &MInfo = MBBInfoMap[MFI];
989 // Skip unreachable MBBs.
990 if (!MInfo.reachable)
996 // Now check liveness info if available
997 if (LiveVars || LiveInts)
1000 verifyLiveVariables();
1002 verifyLiveIntervals();
1005 void MachineVerifier::verifyLiveVariables() {
1006 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1007 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1008 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1009 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1010 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1011 MFI != MFE; ++MFI) {
1012 BBInfo &MInfo = MBBInfoMap[MFI];
1014 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1015 if (MInfo.vregsRequired.count(Reg)) {
1016 if (!VI.AliveBlocks.test(MFI->getNumber())) {
1017 report("LiveVariables: Block missing from AliveBlocks", MFI);
1018 *OS << "Virtual register " << PrintReg(Reg)
1019 << " must be live through the block.\n";
1022 if (VI.AliveBlocks.test(MFI->getNumber())) {
1023 report("LiveVariables: Block should not be in AliveBlocks", MFI);
1024 *OS << "Virtual register " << PrintReg(Reg)
1025 << " is not needed live through the block.\n";
1032 void MachineVerifier::verifyLiveIntervals() {
1033 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1034 for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
1035 LVE = LiveInts->end(); LVI != LVE; ++LVI) {
1036 const LiveInterval &LI = *LVI->second;
1038 // Spilling and splitting may leave unused registers around. Skip them.
1039 if (MRI->use_empty(LI.reg))
1042 // Physical registers have much weirdness going on, mostly from coalescing.
1043 // We should probably fix it, but for now just ignore them.
1044 if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
1047 assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
1049 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
1052 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
1055 if (!VNI->isUnused()) {
1056 report("Valno not live at def and not marked unused", MF);
1057 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1062 if (VNI->isUnused())
1065 if (DefVNI != VNI) {
1066 report("Live range at def has different valno", MF);
1067 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1068 << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
1072 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1074 report("Invalid definition index", MF);
1075 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1076 << " in " << LI << '\n';
1080 if (VNI->isPHIDef()) {
1081 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1082 report("PHIDef value is not defined at MBB start", MF);
1083 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1084 << ", not at the beginning of BB#" << MBB->getNumber()
1085 << " in " << LI << '\n';
1089 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1091 report("No instruction at def index", MF);
1092 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1093 << " in " << LI << '\n';
1094 } else if (!MI->modifiesRegister(LI.reg, TRI)) {
1095 report("Defining instruction does not modify register", MI);
1096 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1099 bool isEarlyClobber = false;
1101 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1102 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1103 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() &&
1104 MOI->isEarlyClobber()) {
1105 isEarlyClobber = true;
1111 // Early clobber defs begin at USE slots, but other defs must begin at
1113 if (isEarlyClobber) {
1114 if (!VNI->def.isEarlyClobber()) {
1115 report("Early clobber def must be at an early-clobber slot", MF);
1116 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1117 << " in " << LI << '\n';
1119 } else if (!VNI->def.isRegister()) {
1120 report("Non-PHI, non-early clobber def must be at a register slot",
1122 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1123 << " in " << LI << '\n';
1128 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1129 const VNInfo *VNI = I->valno;
1130 assert(VNI && "Live range has no valno");
1132 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1133 report("Foreign valno in live range", MF);
1135 *OS << " has a valno not in " << LI << '\n';
1138 if (VNI->isUnused()) {
1139 report("Live range valno is marked unused", MF);
1141 *OS << " in " << LI << '\n';
1144 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1146 report("Bad start of live segment, no basic block", MF);
1148 *OS << " in " << LI << '\n';
1151 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1152 if (I->start != MBBStartIdx && I->start != VNI->def) {
1153 report("Live segment must begin at MBB entry or valno def", MBB);
1155 *OS << " in " << LI << '\n' << "Basic block starts at "
1156 << MBBStartIdx << '\n';
1159 const MachineBasicBlock *EndMBB =
1160 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1162 report("Bad end of live segment, no basic block", MF);
1164 *OS << " in " << LI << '\n';
1167 if (I->end != LiveInts->getMBBEndIdx(EndMBB)) {
1168 // The live segment is ending inside EndMBB
1169 const MachineInstr *MI =
1170 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1172 report("Live segment doesn't end at a valid instruction", EndMBB);
1174 *OS << " in " << LI << '\n' << "Basic block starts at "
1175 << MBBStartIdx << '\n';
1176 } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1177 !MI->readsVirtualRegister(LI.reg)) {
1178 // A live range can end with either a redefinition, a kill flag on a
1179 // use, or a dead flag on a def.
1180 // FIXME: Should we check for each of these?
1181 bool hasDeadDef = false;
1182 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1183 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1184 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() && MOI->isDead()) {
1191 report("Instruction killing live segment neither defines nor reads "
1194 *OS << " in " << LI << '\n';
1199 // Now check all the basic blocks in this live segment.
1200 MachineFunction::const_iterator MFI = MBB;
1201 // Is this live range the beginning of a non-PHIDef VN?
1202 if (I->start == VNI->def && !VNI->isPHIDef()) {
1203 // Not live-in to any blocks.
1210 assert(LiveInts->isLiveInToMBB(LI, MFI));
1211 // We don't know how to track physregs into a landing pad.
1212 if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1213 MFI->isLandingPad()) {
1214 if (&*MFI == EndMBB)
1219 // Check that VNI is live-out of all predecessors.
1220 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1221 PE = MFI->pred_end(); PI != PE; ++PI) {
1222 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1223 const VNInfo *PVNI = LI.getVNInfoBefore(PEnd);
1225 if (VNI->isPHIDef() && VNI->def == LiveInts->getMBBStartIdx(MFI))
1229 report("Register not marked live out of predecessor", *PI);
1230 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1231 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1232 << PEnd << " in " << LI << '\n';
1237 report("Different value live out of predecessor", *PI);
1238 *OS << "Valno #" << PVNI->id << " live out of BB#"
1239 << (*PI)->getNumber() << '@' << PEnd
1240 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1241 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1244 if (&*MFI == EndMBB)
1250 // Check the LI only has one connected component.
1251 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1252 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1253 unsigned NumComp = ConEQ.Classify(&LI);
1255 report("Multiple connected components in live interval", MF);
1256 *OS << NumComp << " components in " << LI << '\n';
1257 for (unsigned comp = 0; comp != NumComp; ++comp) {
1258 *OS << comp << ": valnos";
1259 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1260 E = LI.vni_end(); I!=E; ++I)
1261 if (comp == ConEQ.getEqClass(*I))
1262 *OS << ' ' << (*I)->id;