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/Function.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/CodeGen/LiveStackAnalysis.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/DenseSet.h"
39 #include "llvm/ADT/SetOperations.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
47 struct MachineVerifier {
49 MachineVerifier(Pass *pass, const char *b) :
52 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
55 bool runOnMachineFunction(MachineFunction &MF);
59 const char *const OutFileName;
61 const MachineFunction *MF;
62 const TargetMachine *TM;
63 const TargetRegisterInfo *TRI;
64 const MachineRegisterInfo *MRI;
68 typedef SmallVector<unsigned, 16> RegVector;
69 typedef DenseSet<unsigned> RegSet;
70 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
72 BitVector regsReserved;
74 RegVector regsDefined, regsDead, regsKilled;
75 RegSet regsLiveInButUnused;
79 // Add Reg and any sub-registers to RV
80 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
82 if (TargetRegisterInfo::isPhysicalRegister(Reg))
83 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
88 // Is this MBB reachable from the MF entry point?
91 // Vregs that must be live in because they are used without being
92 // defined. Map value is the user.
95 // Regs killed in MBB. They may be defined again, and will then be in both
96 // regsKilled and regsLiveOut.
99 // Regs defined in MBB and live out. Note that vregs passing through may
100 // be live out without being mentioned here.
103 // Vregs that pass through MBB untouched. This set is disjoint from
104 // regsKilled and regsLiveOut.
107 // Vregs that must pass through MBB because they are needed by a successor
108 // block. This set is disjoint from regsLiveOut.
109 RegSet vregsRequired;
111 BBInfo() : reachable(false) {}
113 // Add register to vregsPassed if it belongs there. Return true if
115 bool addPassed(unsigned Reg) {
116 if (!TargetRegisterInfo::isVirtualRegister(Reg))
118 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
120 return vregsPassed.insert(Reg).second;
123 // Same for a full set.
124 bool addPassed(const RegSet &RS) {
125 bool changed = false;
126 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
132 // Add register to vregsRequired if it belongs there. Return true if
134 bool addRequired(unsigned Reg) {
135 if (!TargetRegisterInfo::isVirtualRegister(Reg))
137 if (regsLiveOut.count(Reg))
139 return vregsRequired.insert(Reg).second;
142 // Same for a full set.
143 bool addRequired(const RegSet &RS) {
144 bool changed = false;
145 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
151 // Same for a full map.
152 bool addRequired(const RegMap &RM) {
153 bool changed = false;
154 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
155 if (addRequired(I->first))
160 // Live-out registers are either in regsLiveOut or vregsPassed.
161 bool isLiveOut(unsigned Reg) const {
162 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
166 // Extra register info per MBB.
167 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
169 bool isReserved(unsigned Reg) {
170 return Reg < regsReserved.size() && regsReserved.test(Reg);
173 // Analysis information if available
174 LiveVariables *LiveVars;
175 LiveIntervals *LiveInts;
176 LiveStacks *LiveStks;
177 SlotIndexes *Indexes;
179 void visitMachineFunctionBefore();
180 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
181 void visitMachineInstrBefore(const MachineInstr *MI);
182 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
183 void visitMachineInstrAfter(const MachineInstr *MI);
184 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
185 void visitMachineFunctionAfter();
187 void report(const char *msg, const MachineFunction *MF);
188 void report(const char *msg, const MachineBasicBlock *MBB);
189 void report(const char *msg, const MachineInstr *MI);
190 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
192 void markReachable(const MachineBasicBlock *MBB);
193 void calcRegsPassed();
194 void checkPHIOps(const MachineBasicBlock *MBB);
196 void calcRegsRequired();
197 void verifyLiveVariables();
198 void verifyLiveIntervals();
201 struct MachineVerifierPass : public MachineFunctionPass {
202 static char ID; // Pass ID, replacement for typeid
203 const char *const Banner;
205 MachineVerifierPass(const char *b = 0)
206 : MachineFunctionPass(ID), Banner(b) {
207 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
210 void getAnalysisUsage(AnalysisUsage &AU) const {
211 AU.setPreservesAll();
212 MachineFunctionPass::getAnalysisUsage(AU);
215 bool runOnMachineFunction(MachineFunction &MF) {
216 MF.verify(this, Banner);
223 char MachineVerifierPass::ID = 0;
224 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
225 "Verify generated machine code", false, false)
227 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
228 return new MachineVerifierPass(Banner);
231 void MachineFunction::verify(Pass *p, const char *Banner) const {
232 MachineVerifier(p, Banner)
233 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
236 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
237 raw_ostream *OutFile = 0;
239 std::string ErrorInfo;
240 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
241 raw_fd_ostream::F_Append);
242 if (!ErrorInfo.empty()) {
243 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
255 TM = &MF.getTarget();
256 TRI = TM->getRegisterInfo();
257 MRI = &MF.getRegInfo();
264 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
265 // We don't want to verify LiveVariables if LiveIntervals is available.
267 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
268 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
269 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
272 visitMachineFunctionBefore();
273 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
275 visitMachineBasicBlockBefore(MFI);
276 for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
277 MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
278 if (MBBI->getParent() != MFI) {
279 report("Bad instruction parent pointer", MFI);
280 *OS << "Instruction: " << *MBBI;
283 visitMachineInstrBefore(MBBI);
284 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
285 visitMachineOperand(&MBBI->getOperand(I), I);
286 visitMachineInstrAfter(MBBI);
288 visitMachineBasicBlockAfter(MFI);
290 visitMachineFunctionAfter();
294 else if (foundErrors)
295 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
302 regsLiveInButUnused.clear();
305 return false; // no changes
308 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
311 if (!foundErrors++) {
313 *OS << "# " << Banner << '\n';
314 MF->print(*OS, Indexes);
316 *OS << "*** Bad machine code: " << msg << " ***\n"
317 << "- function: " << MF->getFunction()->getNameStr() << "\n";
320 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
322 report(msg, MBB->getParent());
323 *OS << "- basic block: " << MBB->getName()
325 << " (BB#" << MBB->getNumber() << ")";
327 *OS << " [" << Indexes->getMBBStartIdx(MBB)
328 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
332 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
334 report(msg, MI->getParent());
335 *OS << "- instruction: ";
336 if (Indexes && Indexes->hasIndex(MI))
337 *OS << Indexes->getInstructionIndex(MI) << '\t';
341 void MachineVerifier::report(const char *msg,
342 const MachineOperand *MO, unsigned MONum) {
344 report(msg, MO->getParent());
345 *OS << "- operand " << MONum << ": ";
350 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
351 BBInfo &MInfo = MBBInfoMap[MBB];
352 if (!MInfo.reachable) {
353 MInfo.reachable = true;
354 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
355 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
360 void MachineVerifier::visitMachineFunctionBefore() {
361 lastIndex = SlotIndex();
362 regsReserved = TRI->getReservedRegs(*MF);
364 // A sub-register of a reserved register is also reserved
365 for (int Reg = regsReserved.find_first(); Reg>=0;
366 Reg = regsReserved.find_next(Reg)) {
367 for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
368 // FIXME: This should probably be:
369 // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
370 regsReserved.set(*Sub);
373 markReachable(&MF->front());
376 // Does iterator point to a and b as the first two elements?
377 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
378 const MachineBasicBlock *a, const MachineBasicBlock *b) {
387 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
388 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
390 // Count the number of landing pad successors.
391 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
392 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
393 E = MBB->succ_end(); I != E; ++I) {
394 if ((*I)->isLandingPad())
395 LandingPadSuccs.insert(*I);
397 if (LandingPadSuccs.size() > 1)
398 report("MBB has more than one landing pad successor", MBB);
400 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
401 MachineBasicBlock *TBB = 0, *FBB = 0;
402 SmallVector<MachineOperand, 4> Cond;
403 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
405 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
406 // check whether its answers match up with reality.
408 // Block falls through to its successor.
409 MachineFunction::const_iterator MBBI = MBB;
411 if (MBBI == MF->end()) {
412 // It's possible that the block legitimately ends with a noreturn
413 // call or an unreachable, in which case it won't actually fall
414 // out the bottom of the function.
415 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
416 // It's possible that the block legitimately ends with a noreturn
417 // call or an unreachable, in which case it won't actuall fall
419 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
420 report("MBB exits via unconditional fall-through but doesn't have "
421 "exactly one CFG successor!", MBB);
422 } else if (!MBB->isSuccessor(MBBI)) {
423 report("MBB exits via unconditional fall-through but its successor "
424 "differs from its CFG successor!", MBB);
426 if (!MBB->empty() && MBB->back().getDesc().isBarrier() &&
427 !TII->isPredicated(&MBB->back())) {
428 report("MBB exits via unconditional fall-through but ends with a "
429 "barrier instruction!", MBB);
432 report("MBB exits via unconditional fall-through but has a condition!",
435 } else if (TBB && !FBB && Cond.empty()) {
436 // Block unconditionally branches somewhere.
437 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
438 report("MBB exits via unconditional branch but doesn't have "
439 "exactly one CFG successor!", MBB);
440 } else if (!MBB->isSuccessor(TBB)) {
441 report("MBB exits via unconditional branch but the CFG "
442 "successor doesn't match the actual successor!", MBB);
445 report("MBB exits via unconditional branch but doesn't contain "
446 "any instructions!", MBB);
447 } else if (!MBB->back().getDesc().isBarrier()) {
448 report("MBB exits via unconditional branch but doesn't end with a "
449 "barrier instruction!", MBB);
450 } else if (!MBB->back().getDesc().isTerminator()) {
451 report("MBB exits via unconditional branch but the branch isn't a "
452 "terminator instruction!", MBB);
454 } else if (TBB && !FBB && !Cond.empty()) {
455 // Block conditionally branches somewhere, otherwise falls through.
456 MachineFunction::const_iterator MBBI = MBB;
458 if (MBBI == MF->end()) {
459 report("MBB conditionally falls through out of function!", MBB);
460 } if (MBB->succ_size() != 2) {
461 report("MBB exits via conditional branch/fall-through but doesn't have "
462 "exactly two CFG successors!", MBB);
463 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
464 report("MBB exits via conditional branch/fall-through but the CFG "
465 "successors don't match the actual successors!", MBB);
468 report("MBB exits via conditional branch/fall-through but doesn't "
469 "contain any instructions!", MBB);
470 } else if (MBB->back().getDesc().isBarrier()) {
471 report("MBB exits via conditional branch/fall-through but ends with a "
472 "barrier instruction!", MBB);
473 } else if (!MBB->back().getDesc().isTerminator()) {
474 report("MBB exits via conditional branch/fall-through but the branch "
475 "isn't a terminator instruction!", MBB);
477 } else if (TBB && FBB) {
478 // Block conditionally branches somewhere, otherwise branches
480 if (MBB->succ_size() != 2) {
481 report("MBB exits via conditional branch/branch but doesn't have "
482 "exactly two CFG successors!", MBB);
483 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
484 report("MBB exits via conditional branch/branch but the CFG "
485 "successors don't match the actual successors!", MBB);
488 report("MBB exits via conditional branch/branch but doesn't "
489 "contain any instructions!", MBB);
490 } else if (!MBB->back().getDesc().isBarrier()) {
491 report("MBB exits via conditional branch/branch but doesn't end with a "
492 "barrier instruction!", MBB);
493 } else if (!MBB->back().getDesc().isTerminator()) {
494 report("MBB exits via conditional branch/branch but the branch "
495 "isn't a terminator instruction!", MBB);
498 report("MBB exits via conditinal branch/branch but there's no "
502 report("AnalyzeBranch returned invalid data!", MBB);
507 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
508 E = MBB->livein_end(); I != E; ++I) {
509 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
510 report("MBB live-in list contains non-physical register", MBB);
514 for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
517 regsLiveInButUnused = regsLive;
519 const MachineFrameInfo *MFI = MF->getFrameInfo();
520 assert(MFI && "Function has no frame info");
521 BitVector PR = MFI->getPristineRegs(MBB);
522 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
524 for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
532 lastIndex = Indexes->getMBBStartIdx(MBB);
535 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
536 const TargetInstrDesc &TI = MI->getDesc();
537 if (MI->getNumOperands() < TI.getNumOperands()) {
538 report("Too few operands", MI);
539 *OS << TI.getNumOperands() << " operands expected, but "
540 << MI->getNumExplicitOperands() << " given.\n";
543 // Check the MachineMemOperands for basic consistency.
544 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
545 E = MI->memoperands_end(); I != E; ++I) {
546 if ((*I)->isLoad() && !TI.mayLoad())
547 report("Missing mayLoad flag", MI);
548 if ((*I)->isStore() && !TI.mayStore())
549 report("Missing mayStore flag", MI);
552 // Debug values must not have a slot index.
553 // Other instructions must have one.
555 bool mapped = !LiveInts->isNotInMIMap(MI);
556 if (MI->isDebugValue()) {
558 report("Debug instruction has a slot index", MI);
561 report("Missing slot index", MI);
568 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
569 const MachineInstr *MI = MO->getParent();
570 const TargetInstrDesc &TI = MI->getDesc();
571 const TargetOperandInfo &TOI = TI.OpInfo[MONum];
573 // The first TI.NumDefs operands must be explicit register defines
574 if (MONum < TI.getNumDefs()) {
576 report("Explicit definition must be a register", MO, MONum);
577 else if (!MO->isDef())
578 report("Explicit definition marked as use", MO, MONum);
579 else if (MO->isImplicit())
580 report("Explicit definition marked as implicit", MO, MONum);
581 } else if (MONum < TI.getNumOperands()) {
582 // Don't check if it's the last operand in a variadic instruction. See,
583 // e.g., LDM_RET in the arm back end.
584 if (MO->isReg() && !(TI.isVariadic() && MONum == TI.getNumOperands()-1)) {
585 if (MO->isDef() && !TOI.isOptionalDef())
586 report("Explicit operand marked as def", MO, MONum);
587 if (MO->isImplicit())
588 report("Explicit operand marked as implicit", MO, MONum);
591 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
592 if (MO->isReg() && !MO->isImplicit() && !TI.isVariadic() && MO->getReg())
593 report("Extra explicit operand on non-variadic instruction", MO, MONum);
596 switch (MO->getType()) {
597 case MachineOperand::MO_Register: {
598 const unsigned Reg = MO->getReg();
602 // Check Live Variables.
603 if (MI->isDebugValue()) {
604 // Liveness checks are not valid for debug values.
605 } else if (MO->isUndef()) {
606 // An <undef> doesn't refer to any register, so just skip it.
607 } else if (MO->isUse()) {
608 regsLiveInButUnused.erase(Reg);
612 if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
613 // A two-addr use counts as a kill if use and def are the same.
614 unsigned DefReg = MI->getOperand(defIdx).getReg();
617 // And in that case an explicit kill flag is not allowed.
619 report("Illegal kill flag on two-address instruction operand",
621 } else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
622 report("Two-address instruction operands must be identical",
626 isKill = MO->isKill();
629 addRegWithSubRegs(regsKilled, Reg);
631 // Check that LiveVars knows this kill.
632 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
634 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
635 if (std::find(VI.Kills.begin(),
636 VI.Kills.end(), MI) == VI.Kills.end())
637 report("Kill missing from LiveVariables", MO, MONum);
640 // Check LiveInts liveness and kill.
641 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
642 LiveInts && !LiveInts->isNotInMIMap(MI)) {
643 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getUseIndex();
644 if (LiveInts->hasInterval(Reg)) {
645 const LiveInterval &LI = LiveInts->getInterval(Reg);
646 if (!LI.liveAt(UseIdx)) {
647 report("No live range at use", MO, MONum);
648 *OS << UseIdx << " is not live in " << LI << '\n';
650 // Verify isKill == LI.killedAt.
651 // Two-address instrs don't have kill flags on the tied operands, and
653 // %r1 = add %r1, %r1
654 // without a kill flag on the untied operand.
655 // MI->findRegisterUseOperandIdx finds the first operand using reg.
656 if (!MI->isRegTiedToDefOperand(MI->findRegisterUseOperandIdx(Reg))) {
657 // MI could kill register without a kill flag on MO.
658 bool miKill = MI->killsRegister(Reg);
659 bool liKill = LI.killedAt(UseIdx.getDefIndex());
660 if (miKill && !liKill) {
661 report("Live range continues after kill flag", MO, MONum);
662 *OS << "Live range: " << LI << '\n';
664 if (!miKill && liKill) {
665 report("Live range ends without kill flag", MO, MONum);
666 *OS << "Live range: " << LI << '\n';
670 report("Virtual register has no Live interval", MO, MONum);
674 // Use of a dead register.
675 if (!regsLive.count(Reg)) {
676 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
677 // Reserved registers may be used even when 'dead'.
678 if (!isReserved(Reg))
679 report("Using an undefined physical register", MO, MONum);
681 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
682 // We don't know which virtual registers are live in, so only complain
683 // if vreg was killed in this MBB. Otherwise keep track of vregs that
684 // must be live in. PHI instructions are handled separately.
685 if (MInfo.regsKilled.count(Reg))
686 report("Using a killed virtual register", MO, MONum);
687 else if (!MI->isPHI())
688 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
694 // TODO: verify that earlyclobber ops are not used.
696 addRegWithSubRegs(regsDead, Reg);
698 addRegWithSubRegs(regsDefined, Reg);
700 // Check LiveInts for a live range, but only for virtual registers.
701 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
702 !LiveInts->isNotInMIMap(MI)) {
703 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getDefIndex();
704 if (LiveInts->hasInterval(Reg)) {
705 const LiveInterval &LI = LiveInts->getInterval(Reg);
706 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
707 assert(VNI && "NULL valno is not allowed");
708 if (VNI->def != DefIdx && !MO->isEarlyClobber()) {
709 report("Inconsistent valno->def", MO, MONum);
710 *OS << "Valno " << VNI->id << " is not defined at "
711 << DefIdx << " in " << LI << '\n';
714 report("No live range at def", MO, MONum);
715 *OS << DefIdx << " is not live in " << LI << '\n';
718 report("Virtual register has no Live interval", MO, MONum);
723 // Check register classes.
724 if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
725 unsigned SubIdx = MO->getSubReg();
727 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
730 unsigned s = TRI->getSubReg(Reg, SubIdx);
732 report("Invalid subregister index for physical register",
738 if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
739 if (!DRC->contains(sr)) {
740 report("Illegal physical register for instruction", MO, MONum);
741 *OS << TRI->getName(sr) << " is not a "
742 << DRC->getName() << " register.\n";
747 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
749 const TargetRegisterClass *SRC = RC->getSubRegisterRegClass(SubIdx);
751 report("Invalid subregister index for virtual register", MO, MONum);
752 *OS << "Register class " << RC->getName()
753 << " does not support subreg index " << SubIdx << "\n";
758 if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
759 if (RC != DRC && !RC->hasSuperClass(DRC)) {
760 report("Illegal virtual register for instruction", MO, MONum);
761 *OS << "Expected a " << DRC->getName() << " register, but got a "
762 << RC->getName() << " register\n";
770 case MachineOperand::MO_MachineBasicBlock:
771 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
772 report("PHI operand is not in the CFG", MO, MONum);
775 case MachineOperand::MO_FrameIndex:
776 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
777 LiveInts && !LiveInts->isNotInMIMap(MI)) {
778 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
779 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
780 if (TI.mayLoad() && !LI.liveAt(Idx.getUseIndex())) {
781 report("Instruction loads from dead spill slot", MO, MONum);
782 *OS << "Live stack: " << LI << '\n';
784 if (TI.mayStore() && !LI.liveAt(Idx.getDefIndex())) {
785 report("Instruction stores to dead spill slot", MO, MONum);
786 *OS << "Live stack: " << LI << '\n';
796 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
797 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
798 set_union(MInfo.regsKilled, regsKilled);
799 set_subtract(regsLive, regsKilled); regsKilled.clear();
800 set_subtract(regsLive, regsDead); regsDead.clear();
801 set_union(regsLive, regsDefined); regsDefined.clear();
803 if (Indexes && Indexes->hasIndex(MI)) {
804 SlotIndex idx = Indexes->getInstructionIndex(MI);
805 if (!(idx > lastIndex)) {
806 report("Instruction index out of order", MI);
807 *OS << "Last instruction was at " << lastIndex << '\n';
814 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
815 MBBInfoMap[MBB].regsLiveOut = regsLive;
819 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
820 if (!(stop > lastIndex)) {
821 report("Block ends before last instruction index", MBB);
822 *OS << "Block ends at " << stop
823 << " last instruction was at " << lastIndex << '\n';
829 // Calculate the largest possible vregsPassed sets. These are the registers that
830 // can pass through an MBB live, but may not be live every time. It is assumed
831 // that all vregsPassed sets are empty before the call.
832 void MachineVerifier::calcRegsPassed() {
833 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
834 // have any vregsPassed.
835 DenseSet<const MachineBasicBlock*> todo;
836 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
838 const MachineBasicBlock &MBB(*MFI);
839 BBInfo &MInfo = MBBInfoMap[&MBB];
840 if (!MInfo.reachable)
842 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
843 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
844 BBInfo &SInfo = MBBInfoMap[*SuI];
845 if (SInfo.addPassed(MInfo.regsLiveOut))
850 // Iteratively push vregsPassed to successors. This will converge to the same
851 // final state regardless of DenseSet iteration order.
852 while (!todo.empty()) {
853 const MachineBasicBlock *MBB = *todo.begin();
855 BBInfo &MInfo = MBBInfoMap[MBB];
856 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
857 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
860 BBInfo &SInfo = MBBInfoMap[*SuI];
861 if (SInfo.addPassed(MInfo.vregsPassed))
867 // Calculate the set of virtual registers that must be passed through each basic
868 // block in order to satisfy the requirements of successor blocks. This is very
869 // similar to calcRegsPassed, only backwards.
870 void MachineVerifier::calcRegsRequired() {
871 // First push live-in regs to predecessors' vregsRequired.
872 DenseSet<const MachineBasicBlock*> todo;
873 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
875 const MachineBasicBlock &MBB(*MFI);
876 BBInfo &MInfo = MBBInfoMap[&MBB];
877 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
878 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
879 BBInfo &PInfo = MBBInfoMap[*PrI];
880 if (PInfo.addRequired(MInfo.vregsLiveIn))
885 // Iteratively push vregsRequired to predecessors. This will converge to the
886 // same final state regardless of DenseSet iteration order.
887 while (!todo.empty()) {
888 const MachineBasicBlock *MBB = *todo.begin();
890 BBInfo &MInfo = MBBInfoMap[MBB];
891 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
892 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
895 BBInfo &SInfo = MBBInfoMap[*PrI];
896 if (SInfo.addRequired(MInfo.vregsRequired))
902 // Check PHI instructions at the beginning of MBB. It is assumed that
903 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
904 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
905 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
906 BBI != BBE && BBI->isPHI(); ++BBI) {
907 DenseSet<const MachineBasicBlock*> seen;
909 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
910 unsigned Reg = BBI->getOperand(i).getReg();
911 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
912 if (!Pre->isSuccessor(MBB))
915 BBInfo &PrInfo = MBBInfoMap[Pre];
916 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
917 report("PHI operand is not live-out from predecessor",
918 &BBI->getOperand(i), i);
921 // Did we see all predecessors?
922 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
923 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
924 if (!seen.count(*PrI)) {
925 report("Missing PHI operand", BBI);
926 *OS << "BB#" << (*PrI)->getNumber()
927 << " is a predecessor according to the CFG.\n";
933 void MachineVerifier::visitMachineFunctionAfter() {
936 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
938 BBInfo &MInfo = MBBInfoMap[MFI];
940 // Skip unreachable MBBs.
941 if (!MInfo.reachable)
947 // Now check liveness info if available
948 if (LiveVars || LiveInts)
951 verifyLiveVariables();
953 verifyLiveIntervals();
956 void MachineVerifier::verifyLiveVariables() {
957 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
958 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
959 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
960 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
961 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
963 BBInfo &MInfo = MBBInfoMap[MFI];
965 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
966 if (MInfo.vregsRequired.count(Reg)) {
967 if (!VI.AliveBlocks.test(MFI->getNumber())) {
968 report("LiveVariables: Block missing from AliveBlocks", MFI);
969 *OS << "Virtual register " << PrintReg(Reg)
970 << " must be live through the block.\n";
973 if (VI.AliveBlocks.test(MFI->getNumber())) {
974 report("LiveVariables: Block should not be in AliveBlocks", MFI);
975 *OS << "Virtual register " << PrintReg(Reg)
976 << " is not needed live through the block.\n";
983 void MachineVerifier::verifyLiveIntervals() {
984 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
985 for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
986 LVE = LiveInts->end(); LVI != LVE; ++LVI) {
987 const LiveInterval &LI = *LVI->second;
989 // Spilling and splitting may leave unused registers around. Skip them.
990 if (MRI->use_empty(LI.reg))
993 // Physical registers have much weirdness going on, mostly from coalescing.
994 // We should probably fix it, but for now just ignore them.
995 if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
998 assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
1000 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
1003 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
1006 if (!VNI->isUnused()) {
1007 report("Valno not live at def and not marked unused", MF);
1008 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1013 if (VNI->isUnused())
1016 if (DefVNI != VNI) {
1017 report("Live range at def has different valno", MF);
1018 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1019 << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
1023 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1025 report("Invalid definition index", MF);
1026 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1027 << " in " << LI << '\n';
1031 if (VNI->isPHIDef()) {
1032 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1033 report("PHIDef value is not defined at MBB start", MF);
1034 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1035 << ", not at the beginning of BB#" << MBB->getNumber()
1036 << " in " << LI << '\n';
1040 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1042 report("No instruction at def index", MF);
1043 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1044 << " in " << LI << '\n';
1045 } else if (!MI->modifiesRegister(LI.reg, TRI)) {
1046 report("Defining instruction does not modify register", MI);
1047 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1050 bool isEarlyClobber = false;
1052 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1053 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1054 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() &&
1055 MOI->isEarlyClobber()) {
1056 isEarlyClobber = true;
1062 // Early clobber defs begin at USE slots, but other defs must begin at
1064 if (isEarlyClobber) {
1065 if (!VNI->def.isUse()) {
1066 report("Early clobber def must be at a USE slot", MF);
1067 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1068 << " in " << LI << '\n';
1070 } else if (!VNI->def.isDef()) {
1071 report("Non-PHI, non-early clobber def must be at a DEF slot", MF);
1072 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1073 << " in " << LI << '\n';
1078 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1079 const VNInfo *VNI = I->valno;
1080 assert(VNI && "Live range has no valno");
1082 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1083 report("Foreign valno in live range", MF);
1085 *OS << " has a valno not in " << LI << '\n';
1088 if (VNI->isUnused()) {
1089 report("Live range valno is marked unused", MF);
1091 *OS << " in " << LI << '\n';
1094 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1096 report("Bad start of live segment, no basic block", MF);
1098 *OS << " in " << LI << '\n';
1101 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1102 if (I->start != MBBStartIdx && I->start != VNI->def) {
1103 report("Live segment must begin at MBB entry or valno def", MBB);
1105 *OS << " in " << LI << '\n' << "Basic block starts at "
1106 << MBBStartIdx << '\n';
1109 const MachineBasicBlock *EndMBB =
1110 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1112 report("Bad end of live segment, no basic block", MF);
1114 *OS << " in " << LI << '\n';
1117 if (I->end != LiveInts->getMBBEndIdx(EndMBB)) {
1118 // The live segment is ending inside EndMBB
1119 const MachineInstr *MI =
1120 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1122 report("Live segment doesn't end at a valid instruction", EndMBB);
1124 *OS << " in " << LI << '\n' << "Basic block starts at "
1125 << MBBStartIdx << '\n';
1126 } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1127 !MI->readsVirtualRegister(LI.reg)) {
1128 // A live range can end with either a redefinition, a kill flag on a
1129 // use, or a dead flag on a def.
1130 // FIXME: Should we check for each of these?
1131 bool hasDeadDef = false;
1132 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1133 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1134 if (MOI->isReg() && MOI->getReg() == LI.reg && MOI->isDef() && MOI->isDead()) {
1141 report("Instruction killing live segment neither defines nor reads "
1144 *OS << " in " << LI << '\n';
1149 // Now check all the basic blocks in this live segment.
1150 MachineFunction::const_iterator MFI = MBB;
1151 // Is this live range the beginning of a non-PHIDef VN?
1152 if (I->start == VNI->def && !VNI->isPHIDef()) {
1153 // Not live-in to any blocks.
1160 assert(LiveInts->isLiveInToMBB(LI, MFI));
1161 // We don't know how to track physregs into a landing pad.
1162 if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1163 MFI->isLandingPad()) {
1164 if (&*MFI == EndMBB)
1169 // Check that VNI is live-out of all predecessors.
1170 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1171 PE = MFI->pred_end(); PI != PE; ++PI) {
1172 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI).getPrevSlot();
1173 const VNInfo *PVNI = LI.getVNInfoAt(PEnd);
1175 if (VNI->isPHIDef() && VNI->def == LiveInts->getMBBStartIdx(MFI)) {
1176 if (PVNI && !PVNI->hasPHIKill()) {
1177 report("Value live out of predecessor doesn't have PHIKill", MF);
1178 *OS << "Valno #" << PVNI->id << " live out of BB#"
1179 << (*PI)->getNumber() << '@' << PEnd
1180 << " doesn't have PHIKill, but Valno #" << VNI->id
1181 << " is PHIDef and defined at the beginning of BB#"
1182 << MFI->getNumber() << '@' << LiveInts->getMBBStartIdx(MFI)
1183 << " in " << LI << '\n';
1189 report("Register not marked live out of predecessor", *PI);
1190 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1191 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live at "
1192 << PEnd << " in " << LI << '\n';
1197 report("Different value live out of predecessor", *PI);
1198 *OS << "Valno #" << PVNI->id << " live out of BB#"
1199 << (*PI)->getNumber() << '@' << PEnd
1200 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1201 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1204 if (&*MFI == EndMBB)
1210 // Check the LI only has one connected component.
1211 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1212 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1213 unsigned NumComp = ConEQ.Classify(&LI);
1215 report("Multiple connected components in live interval", MF);
1216 *OS << NumComp << " components in " << LI << '\n';
1217 for (unsigned comp = 0; comp != NumComp; ++comp) {
1218 *OS << comp << ": valnos";
1219 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1220 E = LI.vni_end(); I!=E; ++I)
1221 if (comp == ConEQ.getEqClass(*I))
1222 *OS << ' ' << (*I)->id;