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;
79 RegVector regsDefined, regsDead, regsKilled;
80 RegSet regsLiveInButUnused;
84 // Add Reg and any sub-registers to RV
85 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
87 if (TargetRegisterInfo::isPhysicalRegister(Reg))
88 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
93 // Is this MBB reachable from the MF entry point?
96 // Vregs that must be live in because they are used without being
97 // defined. Map value is the user.
100 // Regs killed in MBB. They may be defined again, and will then be in both
101 // regsKilled and regsLiveOut.
104 // Regs defined in MBB and live out. Note that vregs passing through may
105 // be live out without being mentioned here.
108 // Vregs that pass through MBB untouched. This set is disjoint from
109 // regsKilled and regsLiveOut.
112 // Vregs that must pass through MBB because they are needed by a successor
113 // block. This set is disjoint from regsLiveOut.
114 RegSet vregsRequired;
116 BBInfo() : reachable(false) {}
118 // Add register to vregsPassed if it belongs there. Return true if
120 bool addPassed(unsigned Reg) {
121 if (!TargetRegisterInfo::isVirtualRegister(Reg))
123 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
125 return vregsPassed.insert(Reg).second;
128 // Same for a full set.
129 bool addPassed(const RegSet &RS) {
130 bool changed = false;
131 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
137 // Add register to vregsRequired if it belongs there. Return true if
139 bool addRequired(unsigned Reg) {
140 if (!TargetRegisterInfo::isVirtualRegister(Reg))
142 if (regsLiveOut.count(Reg))
144 return vregsRequired.insert(Reg).second;
147 // Same for a full set.
148 bool addRequired(const RegSet &RS) {
149 bool changed = false;
150 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
156 // Same for a full map.
157 bool addRequired(const RegMap &RM) {
158 bool changed = false;
159 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
160 if (addRequired(I->first))
165 // Live-out registers are either in regsLiveOut or vregsPassed.
166 bool isLiveOut(unsigned Reg) const {
167 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
171 // Extra register info per MBB.
172 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
174 bool isReserved(unsigned Reg) {
175 return Reg < regsReserved.size() && regsReserved.test(Reg);
178 // Analysis information if available
179 LiveVariables *LiveVars;
180 LiveIntervals *LiveInts;
181 LiveStacks *LiveStks;
182 SlotIndexes *Indexes;
184 void visitMachineFunctionBefore();
185 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
186 void visitMachineInstrBefore(const MachineInstr *MI);
187 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
188 void visitMachineInstrAfter(const MachineInstr *MI);
189 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
190 void visitMachineFunctionAfter();
192 void report(const char *msg, const MachineFunction *MF);
193 void report(const char *msg, const MachineBasicBlock *MBB);
194 void report(const char *msg, const MachineInstr *MI);
195 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
197 void markReachable(const MachineBasicBlock *MBB);
198 void calcRegsPassed();
199 void checkPHIOps(const MachineBasicBlock *MBB);
201 void calcRegsRequired();
202 void verifyLiveVariables();
203 void verifyLiveIntervals();
206 struct MachineVerifierPass : public MachineFunctionPass {
207 static char ID; // Pass ID, replacement for typeid
208 const char *const Banner;
210 MachineVerifierPass(const char *b = 0)
211 : MachineFunctionPass(ID), Banner(b) {
212 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
215 void getAnalysisUsage(AnalysisUsage &AU) const {
216 AU.setPreservesAll();
217 MachineFunctionPass::getAnalysisUsage(AU);
220 bool runOnMachineFunction(MachineFunction &MF) {
221 MF.verify(this, Banner);
228 char MachineVerifierPass::ID = 0;
229 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
230 "Verify generated machine code", false, false)
232 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
233 return new MachineVerifierPass(Banner);
236 void MachineFunction::verify(Pass *p, const char *Banner) const {
237 MachineVerifier(p, Banner)
238 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
241 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
242 raw_ostream *OutFile = 0;
244 std::string ErrorInfo;
245 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
246 raw_fd_ostream::F_Append);
247 if (!ErrorInfo.empty()) {
248 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
260 TM = &MF.getTarget();
261 TII = TM->getInstrInfo();
262 TRI = TM->getRegisterInfo();
263 MRI = &MF.getRegInfo();
270 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
271 // We don't want to verify LiveVariables if LiveIntervals is available.
273 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
274 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
275 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
278 visitMachineFunctionBefore();
279 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
281 visitMachineBasicBlockBefore(MFI);
282 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
283 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
284 if (MBBI->getParent() != MFI) {
285 report("Bad instruction parent pointer", MFI);
286 *OS << "Instruction: " << *MBBI;
289 // Skip BUNDLE instruction for now. FIXME: We should add code to verify
290 // the BUNDLE's specifically.
291 if (MBBI->isBundle())
293 visitMachineInstrBefore(MBBI);
294 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
295 visitMachineOperand(&MBBI->getOperand(I), I);
296 visitMachineInstrAfter(MBBI);
298 visitMachineBasicBlockAfter(MFI);
300 visitMachineFunctionAfter();
304 else if (foundErrors)
305 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
312 regsLiveInButUnused.clear();
315 return false; // no changes
318 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
321 if (!foundErrors++) {
323 *OS << "# " << Banner << '\n';
324 MF->print(*OS, Indexes);
326 *OS << "*** Bad machine code: " << msg << " ***\n"
327 << "- function: " << MF->getFunction()->getName() << "\n";
330 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
332 report(msg, MBB->getParent());
333 *OS << "- basic block: " << MBB->getName()
335 << " (BB#" << MBB->getNumber() << ")";
337 *OS << " [" << Indexes->getMBBStartIdx(MBB)
338 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
342 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
344 report(msg, MI->getParent());
345 *OS << "- instruction: ";
346 if (Indexes && Indexes->hasIndex(MI))
347 *OS << Indexes->getInstructionIndex(MI) << '\t';
351 void MachineVerifier::report(const char *msg,
352 const MachineOperand *MO, unsigned MONum) {
354 report(msg, MO->getParent());
355 *OS << "- operand " << MONum << ": ";
360 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
361 BBInfo &MInfo = MBBInfoMap[MBB];
362 if (!MInfo.reachable) {
363 MInfo.reachable = true;
364 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
365 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
370 void MachineVerifier::visitMachineFunctionBefore() {
371 lastIndex = SlotIndex();
372 regsReserved = TRI->getReservedRegs(*MF);
374 // A sub-register of a reserved register is also reserved
375 for (int Reg = regsReserved.find_first(); Reg>=0;
376 Reg = regsReserved.find_next(Reg)) {
377 for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
378 // FIXME: This should probably be:
379 // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
380 regsReserved.set(*Sub);
383 markReachable(&MF->front());
386 // Does iterator point to a and b as the first two elements?
387 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
388 const MachineBasicBlock *a, const MachineBasicBlock *b) {
397 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
400 // Count the number of landing pad successors.
401 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
402 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
403 E = MBB->succ_end(); I != E; ++I) {
404 if ((*I)->isLandingPad())
405 LandingPadSuccs.insert(*I);
408 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
409 const BasicBlock *BB = MBB->getBasicBlock();
410 if (LandingPadSuccs.size() > 1 &&
412 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
413 BB && isa<SwitchInst>(BB->getTerminator())))
414 report("MBB has more than one landing pad successor", MBB);
416 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
417 MachineBasicBlock *TBB = 0, *FBB = 0;
418 SmallVector<MachineOperand, 4> Cond;
419 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
421 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
422 // check whether its answers match up with reality.
424 // Block falls through to its successor.
425 MachineFunction::const_iterator MBBI = MBB;
427 if (MBBI == MF->end()) {
428 // It's possible that the block legitimately ends with a noreturn
429 // call or an unreachable, in which case it won't actually fall
430 // out the bottom of the function.
431 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
432 // It's possible that the block legitimately ends with a noreturn
433 // call or an unreachable, in which case it won't actuall fall
435 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
436 report("MBB exits via unconditional fall-through but doesn't have "
437 "exactly one CFG successor!", MBB);
438 } else if (!MBB->isSuccessor(MBBI)) {
439 report("MBB exits via unconditional fall-through but its successor "
440 "differs from its CFG successor!", MBB);
442 if (!MBB->empty() && MBB->back().isBarrier() &&
443 !TII->isPredicated(&MBB->back())) {
444 report("MBB exits via unconditional fall-through but ends with a "
445 "barrier instruction!", MBB);
448 report("MBB exits via unconditional fall-through but has a condition!",
451 } else if (TBB && !FBB && Cond.empty()) {
452 // Block unconditionally branches somewhere.
453 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
454 report("MBB exits via unconditional branch but doesn't have "
455 "exactly one CFG successor!", MBB);
456 } else if (!MBB->isSuccessor(TBB)) {
457 report("MBB exits via unconditional branch but the CFG "
458 "successor doesn't match the actual successor!", MBB);
461 report("MBB exits via unconditional branch but doesn't contain "
462 "any instructions!", MBB);
463 } else if (!MBB->back().isBarrier()) {
464 report("MBB exits via unconditional branch but doesn't end with a "
465 "barrier instruction!", MBB);
466 } else if (!MBB->back().isTerminator()) {
467 report("MBB exits via unconditional branch but the branch isn't a "
468 "terminator instruction!", MBB);
470 } else if (TBB && !FBB && !Cond.empty()) {
471 // Block conditionally branches somewhere, otherwise falls through.
472 MachineFunction::const_iterator MBBI = MBB;
474 if (MBBI == MF->end()) {
475 report("MBB conditionally falls through out of function!", MBB);
476 } if (MBB->succ_size() != 2) {
477 report("MBB exits via conditional branch/fall-through but doesn't have "
478 "exactly two CFG successors!", MBB);
479 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
480 report("MBB exits via conditional branch/fall-through but the CFG "
481 "successors don't match the actual successors!", MBB);
484 report("MBB exits via conditional branch/fall-through but doesn't "
485 "contain any instructions!", MBB);
486 } else if (MBB->back().isBarrier()) {
487 report("MBB exits via conditional branch/fall-through but ends with a "
488 "barrier instruction!", MBB);
489 } else if (!MBB->back().isTerminator()) {
490 report("MBB exits via conditional branch/fall-through but the branch "
491 "isn't a terminator instruction!", MBB);
493 } else if (TBB && FBB) {
494 // Block conditionally branches somewhere, otherwise branches
496 if (MBB->succ_size() != 2) {
497 report("MBB exits via conditional branch/branch but doesn't have "
498 "exactly two CFG successors!", MBB);
499 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
500 report("MBB exits via conditional branch/branch but the CFG "
501 "successors don't match the actual successors!", MBB);
504 report("MBB exits via conditional branch/branch but doesn't "
505 "contain any instructions!", MBB);
506 } else if (!MBB->back().isBarrier()) {
507 report("MBB exits via conditional branch/branch but doesn't end with a "
508 "barrier instruction!", MBB);
509 } else if (!MBB->back().isTerminator()) {
510 report("MBB exits via conditional branch/branch but the branch "
511 "isn't a terminator instruction!", MBB);
514 report("MBB exits via conditinal branch/branch but there's no "
518 report("AnalyzeBranch returned invalid data!", MBB);
523 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
524 E = MBB->livein_end(); I != E; ++I) {
525 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
526 report("MBB live-in list contains non-physical register", MBB);
530 for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
533 regsLiveInButUnused = regsLive;
535 const MachineFrameInfo *MFI = MF->getFrameInfo();
536 assert(MFI && "Function has no frame info");
537 BitVector PR = MFI->getPristineRegs(MBB);
538 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
540 for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
548 lastIndex = Indexes->getMBBStartIdx(MBB);
551 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
552 const MCInstrDesc &MCID = MI->getDesc();
553 if (MI->getNumOperands() < MCID.getNumOperands()) {
554 report("Too few operands", MI);
555 *OS << MCID.getNumOperands() << " operands expected, but "
556 << MI->getNumExplicitOperands() << " given.\n";
559 // Check the MachineMemOperands for basic consistency.
560 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
561 E = MI->memoperands_end(); I != E; ++I) {
562 if ((*I)->isLoad() && !MI->mayLoad())
563 report("Missing mayLoad flag", MI);
564 if ((*I)->isStore() && !MI->mayStore())
565 report("Missing mayStore flag", MI);
568 // Debug values must not have a slot index.
569 // Other instructions must have one.
571 bool mapped = !LiveInts->isNotInMIMap(MI);
572 if (MI->isDebugValue()) {
574 report("Debug instruction has a slot index", MI);
577 report("Missing slot index", MI);
581 // Ensure non-terminators don't follow terminators.
582 if (MI->isTerminator()) {
583 if (!FirstTerminator)
584 FirstTerminator = MI;
585 } else if (FirstTerminator) {
586 report("Non-terminator instruction after the first terminator", MI);
587 *OS << "First terminator was:\t" << *FirstTerminator;
591 if (!TII->verifyInstruction(MI, ErrorInfo))
592 report(ErrorInfo.data(), MI);
596 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
597 const MachineInstr *MI = MO->getParent();
598 const MCInstrDesc &MCID = MI->getDesc();
599 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
601 // The first MCID.NumDefs operands must be explicit register defines
602 if (MONum < MCID.getNumDefs()) {
604 report("Explicit definition must be a register", MO, MONum);
605 else if (!MO->isDef())
606 report("Explicit definition marked as use", MO, MONum);
607 else if (MO->isImplicit())
608 report("Explicit definition marked as implicit", MO, MONum);
609 } else if (MONum < MCID.getNumOperands()) {
610 // Don't check if it's the last operand in a variadic instruction. See,
611 // e.g., LDM_RET in the arm back end.
613 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
614 if (MO->isDef() && !MCOI.isOptionalDef())
615 report("Explicit operand marked as def", MO, MONum);
616 if (MO->isImplicit())
617 report("Explicit operand marked as implicit", MO, MONum);
620 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
621 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
622 report("Extra explicit operand on non-variadic instruction", MO, MONum);
625 switch (MO->getType()) {
626 case MachineOperand::MO_Register: {
627 const unsigned Reg = MO->getReg();
631 // Check Live Variables.
632 if (MI->isDebugValue()) {
633 // Liveness checks are not valid for debug values.
634 } else if (MO->isUse() && !MO->isUndef()) {
635 regsLiveInButUnused.erase(Reg);
639 if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
640 // A two-addr use counts as a kill if use and def are the same.
641 unsigned DefReg = MI->getOperand(defIdx).getReg();
644 else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
645 report("Two-address instruction operands must be identical",
649 isKill = MO->isKill();
652 addRegWithSubRegs(regsKilled, Reg);
654 // Check that LiveVars knows this kill.
655 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
657 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
658 if (std::find(VI.Kills.begin(),
659 VI.Kills.end(), MI) == VI.Kills.end())
660 report("Kill missing from LiveVariables", MO, MONum);
663 // Check LiveInts liveness and kill.
664 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
665 LiveInts && !LiveInts->isNotInMIMap(MI)) {
666 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getRegSlot(true);
667 if (LiveInts->hasInterval(Reg)) {
668 const LiveInterval &LI = LiveInts->getInterval(Reg);
669 if (!LI.liveAt(UseIdx)) {
670 report("No live range at use", MO, MONum);
671 *OS << UseIdx << " is not live in " << LI << '\n';
673 // Check for extra kill flags.
674 // Note that we allow missing kill flags for now.
675 if (MO->isKill() && !LI.killedAt(UseIdx.getRegSlot())) {
676 report("Live range continues after kill flag", MO, MONum);
677 *OS << "Live range: " << LI << '\n';
680 report("Virtual register has no Live interval", MO, MONum);
684 // Use of a dead register.
685 if (!regsLive.count(Reg)) {
686 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
687 // Reserved registers may be used even when 'dead'.
688 if (!isReserved(Reg))
689 report("Using an undefined physical register", MO, MONum);
691 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
692 // We don't know which virtual registers are live in, so only complain
693 // if vreg was killed in this MBB. Otherwise keep track of vregs that
694 // must be live in. PHI instructions are handled separately.
695 if (MInfo.regsKilled.count(Reg))
696 report("Using a killed virtual register", MO, MONum);
697 else if (!MI->isPHI())
698 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
701 } else if (MO->isDef()) {
703 // TODO: verify that earlyclobber ops are not used.
705 addRegWithSubRegs(regsDead, Reg);
707 addRegWithSubRegs(regsDefined, Reg);
710 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
711 llvm::next(MRI->def_begin(Reg)) != MRI->def_end())
712 report("Multiple virtual register defs in SSA form", MO, MONum);
714 // Check LiveInts for a live range, but only for virtual registers.
715 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
716 !LiveInts->isNotInMIMap(MI)) {
717 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getRegSlot();
718 if (LiveInts->hasInterval(Reg)) {
719 const LiveInterval &LI = LiveInts->getInterval(Reg);
720 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
721 assert(VNI && "NULL valno is not allowed");
722 if (VNI->def != DefIdx && !MO->isEarlyClobber()) {
723 report("Inconsistent valno->def", MO, MONum);
724 *OS << "Valno " << VNI->id << " is not defined at "
725 << DefIdx << " in " << LI << '\n';
728 report("No live range at def", MO, MONum);
729 *OS << DefIdx << " is not live in " << LI << '\n';
732 report("Virtual register has no Live interval", MO, MONum);
737 // Check register classes.
738 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
739 unsigned SubIdx = MO->getSubReg();
741 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
743 report("Illegal subregister index for physical register", MO, MONum);
746 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID,MONum,TRI)) {
747 if (!DRC->contains(Reg)) {
748 report("Illegal physical register for instruction", MO, MONum);
749 *OS << TRI->getName(Reg) << " is not a "
750 << DRC->getName() << " register.\n";
755 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
757 const TargetRegisterClass *SRC =
758 TRI->getSubClassWithSubReg(RC, SubIdx);
760 report("Invalid subregister index for virtual register", MO, MONum);
761 *OS << "Register class " << RC->getName()
762 << " does not support subreg index " << SubIdx << "\n";
766 report("Invalid register class for subregister index", MO, MONum);
767 *OS << "Register class " << RC->getName()
768 << " does not fully support subreg index " << SubIdx << "\n";
772 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID,MONum,TRI)) {
774 const TargetRegisterClass *SuperRC =
775 TRI->getLargestLegalSuperClass(RC);
777 report("No largest legal super class exists.", MO, MONum);
780 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
782 report("No matching super-reg register class.", MO, MONum);
786 if (!RC->hasSuperClassEq(DRC)) {
787 report("Illegal virtual register for instruction", MO, MONum);
788 *OS << "Expected a " << DRC->getName() << " register, but got a "
789 << RC->getName() << " register\n";
797 case MachineOperand::MO_MachineBasicBlock:
798 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
799 report("PHI operand is not in the CFG", MO, MONum);
802 case MachineOperand::MO_FrameIndex:
803 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
804 LiveInts && !LiveInts->isNotInMIMap(MI)) {
805 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
806 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
807 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
808 report("Instruction loads from dead spill slot", MO, MONum);
809 *OS << "Live stack: " << LI << '\n';
811 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
812 report("Instruction stores to dead spill slot", MO, MONum);
813 *OS << "Live stack: " << LI << '\n';
823 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
824 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
825 set_union(MInfo.regsKilled, regsKilled);
826 set_subtract(regsLive, regsKilled); regsKilled.clear();
827 set_subtract(regsLive, regsDead); regsDead.clear();
828 set_union(regsLive, regsDefined); regsDefined.clear();
830 if (Indexes && Indexes->hasIndex(MI)) {
831 SlotIndex idx = Indexes->getInstructionIndex(MI);
832 if (!(idx > lastIndex)) {
833 report("Instruction index out of order", MI);
834 *OS << "Last instruction was at " << lastIndex << '\n';
841 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
842 MBBInfoMap[MBB].regsLiveOut = regsLive;
846 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
847 if (!(stop > lastIndex)) {
848 report("Block ends before last instruction index", MBB);
849 *OS << "Block ends at " << stop
850 << " last instruction was at " << lastIndex << '\n';
856 // Calculate the largest possible vregsPassed sets. These are the registers that
857 // can pass through an MBB live, but may not be live every time. It is assumed
858 // that all vregsPassed sets are empty before the call.
859 void MachineVerifier::calcRegsPassed() {
860 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
861 // have any vregsPassed.
862 DenseSet<const MachineBasicBlock*> todo;
863 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
865 const MachineBasicBlock &MBB(*MFI);
866 BBInfo &MInfo = MBBInfoMap[&MBB];
867 if (!MInfo.reachable)
869 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
870 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
871 BBInfo &SInfo = MBBInfoMap[*SuI];
872 if (SInfo.addPassed(MInfo.regsLiveOut))
877 // Iteratively push vregsPassed to successors. This will converge to the same
878 // final state regardless of DenseSet iteration order.
879 while (!todo.empty()) {
880 const MachineBasicBlock *MBB = *todo.begin();
882 BBInfo &MInfo = MBBInfoMap[MBB];
883 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
884 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
887 BBInfo &SInfo = MBBInfoMap[*SuI];
888 if (SInfo.addPassed(MInfo.vregsPassed))
894 // Calculate the set of virtual registers that must be passed through each basic
895 // block in order to satisfy the requirements of successor blocks. This is very
896 // similar to calcRegsPassed, only backwards.
897 void MachineVerifier::calcRegsRequired() {
898 // First push live-in regs to predecessors' vregsRequired.
899 DenseSet<const MachineBasicBlock*> todo;
900 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
902 const MachineBasicBlock &MBB(*MFI);
903 BBInfo &MInfo = MBBInfoMap[&MBB];
904 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
905 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
906 BBInfo &PInfo = MBBInfoMap[*PrI];
907 if (PInfo.addRequired(MInfo.vregsLiveIn))
912 // Iteratively push vregsRequired to predecessors. This will converge to the
913 // same final state regardless of DenseSet iteration order.
914 while (!todo.empty()) {
915 const MachineBasicBlock *MBB = *todo.begin();
917 BBInfo &MInfo = MBBInfoMap[MBB];
918 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
919 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
922 BBInfo &SInfo = MBBInfoMap[*PrI];
923 if (SInfo.addRequired(MInfo.vregsRequired))
929 // Check PHI instructions at the beginning of MBB. It is assumed that
930 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
931 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
932 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
933 BBI != BBE && BBI->isPHI(); ++BBI) {
934 DenseSet<const MachineBasicBlock*> seen;
936 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
937 unsigned Reg = BBI->getOperand(i).getReg();
938 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
939 if (!Pre->isSuccessor(MBB))
942 BBInfo &PrInfo = MBBInfoMap[Pre];
943 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
944 report("PHI operand is not live-out from predecessor",
945 &BBI->getOperand(i), i);
948 // Did we see all predecessors?
949 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
950 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
951 if (!seen.count(*PrI)) {
952 report("Missing PHI operand", BBI);
953 *OS << "BB#" << (*PrI)->getNumber()
954 << " is a predecessor according to the CFG.\n";
960 void MachineVerifier::visitMachineFunctionAfter() {
963 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
965 BBInfo &MInfo = MBBInfoMap[MFI];
967 // Skip unreachable MBBs.
968 if (!MInfo.reachable)
974 // Now check liveness info if available
975 if (LiveVars || LiveInts)
978 verifyLiveVariables();
980 verifyLiveIntervals();
983 void MachineVerifier::verifyLiveVariables() {
984 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
985 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
986 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
987 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
988 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
990 BBInfo &MInfo = MBBInfoMap[MFI];
992 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
993 if (MInfo.vregsRequired.count(Reg)) {
994 if (!VI.AliveBlocks.test(MFI->getNumber())) {
995 report("LiveVariables: Block missing from AliveBlocks", MFI);
996 *OS << "Virtual register " << PrintReg(Reg)
997 << " must be live through the block.\n";
1000 if (VI.AliveBlocks.test(MFI->getNumber())) {
1001 report("LiveVariables: Block should not be in AliveBlocks", MFI);
1002 *OS << "Virtual register " << PrintReg(Reg)
1003 << " is not needed live through the block.\n";
1010 void MachineVerifier::verifyLiveIntervals() {
1011 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1012 for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
1013 LVE = LiveInts->end(); LVI != LVE; ++LVI) {
1014 const LiveInterval &LI = *LVI->second;
1016 // Spilling and splitting may leave unused registers around. Skip them.
1017 if (MRI->use_empty(LI.reg))
1020 // Physical registers have much weirdness going on, mostly from coalescing.
1021 // We should probably fix it, but for now just ignore them.
1022 if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
1025 assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
1027 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
1030 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
1033 if (!VNI->isUnused()) {
1034 report("Valno not live at def and not marked unused", MF);
1035 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1040 if (VNI->isUnused())
1043 if (DefVNI != VNI) {
1044 report("Live range at def has different valno", MF);
1045 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1046 << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
1050 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1052 report("Invalid definition index", MF);
1053 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1054 << " in " << LI << '\n';
1058 if (VNI->isPHIDef()) {
1059 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1060 report("PHIDef value is not defined at MBB start", MF);
1061 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1062 << ", not at the beginning of BB#" << MBB->getNumber()
1063 << " in " << LI << '\n';
1067 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1069 report("No instruction at def index", MF);
1070 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1071 << " in " << LI << '\n';
1072 } else if (!MI->modifiesRegister(LI.reg, TRI)) {
1073 report("Defining instruction does not modify register", MI);
1074 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1077 bool isEarlyClobber = false;
1079 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1080 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1081 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() &&
1082 MOI->isEarlyClobber()) {
1083 isEarlyClobber = true;
1089 // Early clobber defs begin at USE slots, but other defs must begin at
1091 if (isEarlyClobber) {
1092 if (!VNI->def.isEarlyClobber()) {
1093 report("Early clobber def must be at an early-clobber slot", MF);
1094 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1095 << " in " << LI << '\n';
1097 } else if (!VNI->def.isRegister()) {
1098 report("Non-PHI, non-early clobber def must be at a register slot",
1100 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1101 << " in " << LI << '\n';
1106 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1107 const VNInfo *VNI = I->valno;
1108 assert(VNI && "Live range has no valno");
1110 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1111 report("Foreign valno in live range", MF);
1113 *OS << " has a valno not in " << LI << '\n';
1116 if (VNI->isUnused()) {
1117 report("Live range valno is marked unused", MF);
1119 *OS << " in " << LI << '\n';
1122 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1124 report("Bad start of live segment, no basic block", MF);
1126 *OS << " in " << LI << '\n';
1129 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1130 if (I->start != MBBStartIdx && I->start != VNI->def) {
1131 report("Live segment must begin at MBB entry or valno def", MBB);
1133 *OS << " in " << LI << '\n' << "Basic block starts at "
1134 << MBBStartIdx << '\n';
1137 const MachineBasicBlock *EndMBB =
1138 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1140 report("Bad end of live segment, no basic block", MF);
1142 *OS << " in " << LI << '\n';
1145 if (I->end != LiveInts->getMBBEndIdx(EndMBB)) {
1146 // The live segment is ending inside EndMBB
1147 const MachineInstr *MI =
1148 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1150 report("Live segment doesn't end at a valid instruction", EndMBB);
1152 *OS << " in " << LI << '\n' << "Basic block starts at "
1153 << MBBStartIdx << '\n';
1154 } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1155 !MI->readsVirtualRegister(LI.reg)) {
1156 // A live range can end with either a redefinition, a kill flag on a
1157 // use, or a dead flag on a def.
1158 // FIXME: Should we check for each of these?
1159 bool hasDeadDef = false;
1160 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1161 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1162 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() && MOI->isDead()) {
1169 report("Instruction killing live segment neither defines nor reads "
1172 *OS << " in " << LI << '\n';
1177 // Now check all the basic blocks in this live segment.
1178 MachineFunction::const_iterator MFI = MBB;
1179 // Is this live range the beginning of a non-PHIDef VN?
1180 if (I->start == VNI->def && !VNI->isPHIDef()) {
1181 // Not live-in to any blocks.
1188 assert(LiveInts->isLiveInToMBB(LI, MFI));
1189 // We don't know how to track physregs into a landing pad.
1190 if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1191 MFI->isLandingPad()) {
1192 if (&*MFI == EndMBB)
1197 // Check that VNI is live-out of all predecessors.
1198 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1199 PE = MFI->pred_end(); PI != PE; ++PI) {
1200 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1201 const VNInfo *PVNI = LI.getVNInfoBefore(PEnd);
1203 if (VNI->isPHIDef() && VNI->def == LiveInts->getMBBStartIdx(MFI))
1207 report("Register not marked live out of predecessor", *PI);
1208 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1209 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1210 << PEnd << " in " << LI << '\n';
1215 report("Different value live out of predecessor", *PI);
1216 *OS << "Valno #" << PVNI->id << " live out of BB#"
1217 << (*PI)->getNumber() << '@' << PEnd
1218 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1219 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1222 if (&*MFI == EndMBB)
1228 // Check the LI only has one connected component.
1229 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1230 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1231 unsigned NumComp = ConEQ.Classify(&LI);
1233 report("Multiple connected components in live interval", MF);
1234 *OS << NumComp << " components in " << LI << '\n';
1235 for (unsigned comp = 0; comp != NumComp; ++comp) {
1236 *OS << comp << ": valnos";
1237 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1238 E = LI.vni_end(); I!=E; ++I)
1239 if (comp == ConEQ.getEqClass(*I))
1240 *OS << ' ' << (*I)->id;