1 //===-- MachineVerifier.cpp - Machine Code Verifier -------------*- C++ -*-===//
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/ADT/DenseSet.h"
27 #include "llvm/ADT/SetOperations.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Function.h"
30 #include "llvm/CodeGen/LiveVariables.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
46 struct VISIBILITY_HIDDEN MachineVerifier : public MachineFunctionPass {
47 static char ID; // Pass ID, replacement for typeid
49 MachineVerifier(bool allowDoubleDefs = false) :
50 MachineFunctionPass(&ID),
51 allowVirtDoubleDefs(allowDoubleDefs),
52 allowPhysDoubleDefs(allowDoubleDefs),
53 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
56 void getAnalysisUsage(AnalysisUsage &AU) const {
60 bool runOnMachineFunction(MachineFunction &MF);
62 const bool allowVirtDoubleDefs;
63 const bool allowPhysDoubleDefs;
65 const char *const OutFileName;
67 const MachineFunction *MF;
68 const TargetMachine *TM;
69 const TargetRegisterInfo *TRI;
70 const MachineRegisterInfo *MRI;
74 typedef SmallVector<unsigned, 16> RegVector;
75 typedef DenseSet<unsigned> RegSet;
76 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
78 BitVector regsReserved;
80 RegVector regsDefined, regsImpDefined, regsDead, regsKilled;
82 // Add Reg and any sub-registers to RV
83 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
85 if (TargetRegisterInfo::isPhysicalRegister(Reg))
86 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
90 // Does RS contain any super-registers of Reg?
91 bool anySuperRegisters(const RegSet &RS, unsigned Reg) {
92 for (const unsigned *R = TRI->getSuperRegisters(Reg); *R; R++)
99 // Is this MBB reachable from the MF entry point?
102 // Vregs that must be live in because they are used without being
103 // defined. Map value is the user.
106 // Vregs that must be dead in because they are defined without being
107 // killed first. Map value is the defining instruction.
110 // Regs killed in MBB. They may be defined again, and will then be in both
111 // regsKilled and regsLiveOut.
114 // Regs defined in MBB and live out. Note that vregs passing through may
115 // be live out without being mentioned here.
118 // Vregs that pass through MBB untouched. This set is disjoint from
119 // regsKilled and regsLiveOut.
122 BBInfo() : reachable(false) {}
124 // Add register to vregsPassed if it belongs there. Return true if
126 bool addPassed(unsigned Reg) {
127 if (!TargetRegisterInfo::isVirtualRegister(Reg))
129 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
131 return vregsPassed.insert(Reg).second;
134 // Same for a full set.
135 bool addPassed(const RegSet &RS) {
136 bool changed = false;
137 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
143 // Live-out registers are either in regsLiveOut or vregsPassed.
144 bool isLiveOut(unsigned Reg) const {
145 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
149 // Extra register info per MBB.
150 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
152 bool isReserved(unsigned Reg) {
153 return Reg < regsReserved.size() && regsReserved[Reg];
156 void visitMachineFunctionBefore();
157 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
158 void visitMachineInstrBefore(const MachineInstr *MI);
159 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
160 void visitMachineInstrAfter(const MachineInstr *MI);
161 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
162 void visitMachineFunctionAfter();
164 void report(const char *msg, const MachineFunction *MF);
165 void report(const char *msg, const MachineBasicBlock *MBB);
166 void report(const char *msg, const MachineInstr *MI);
167 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
169 void markReachable(const MachineBasicBlock *MBB);
170 void calcMaxRegsPassed();
171 void calcMinRegsPassed();
172 void checkPHIOps(const MachineBasicBlock *MBB);
176 char MachineVerifier::ID = 0;
177 static RegisterPass<MachineVerifier>
178 MachineVer("machineverifier", "Verify generated machine code");
179 static const PassInfo *const MachineVerifyID = &MachineVer;
182 llvm::createMachineVerifierPass(bool allowPhysDoubleDefs)
184 return new MachineVerifier(allowPhysDoubleDefs);
188 MachineVerifier::runOnMachineFunction(MachineFunction &MF)
190 std::ofstream OutFile;
192 OutFile.open(OutFileName, std::ios::out | std::ios::app);
201 TM = &MF.getTarget();
202 TRI = TM->getRegisterInfo();
203 MRI = &MF.getRegInfo();
205 visitMachineFunctionBefore();
206 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
208 visitMachineBasicBlockBefore(MFI);
209 for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
210 MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
211 visitMachineInstrBefore(MBBI);
212 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
213 visitMachineOperand(&MBBI->getOperand(I), I);
214 visitMachineInstrAfter(MBBI);
216 visitMachineBasicBlockAfter(MFI);
218 visitMachineFunctionAfter();
222 else if (foundErrors) {
224 raw_string_ostream Msg(msg);
225 Msg << "Found " << foundErrors << " machine code errors.";
226 llvm_report_error(Msg.str());
229 return false; // no changes
233 MachineVerifier::report(const char *msg, const MachineFunction *MF)
239 *OS << "*** Bad machine code: " << msg << " ***\n"
240 << "- function: " << MF->getFunction()->getNameStr() << "\n";
244 MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB)
247 report(msg, MBB->getParent());
248 *OS << "- basic block: " << MBB->getBasicBlock()->getNameStr()
250 << " (#" << MBB->getNumber() << ")\n";
254 MachineVerifier::report(const char *msg, const MachineInstr *MI)
257 report(msg, MI->getParent());
258 *OS << "- instruction: ";
263 MachineVerifier::report(const char *msg,
264 const MachineOperand *MO, unsigned MONum)
267 report(msg, MO->getParent());
268 *OS << "- operand " << MONum << ": ";
274 MachineVerifier::markReachable(const MachineBasicBlock *MBB)
276 BBInfo &MInfo = MBBInfoMap[MBB];
277 if (!MInfo.reachable) {
278 MInfo.reachable = true;
279 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
280 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
286 MachineVerifier::visitMachineFunctionBefore()
288 regsReserved = TRI->getReservedRegs(*MF);
289 markReachable(&MF->front());
293 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB)
296 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
297 E = MBB->livein_end(); I != E; ++I) {
298 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
299 report("MBB live-in list contains non-physical register", MBB);
303 for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
308 regsImpDefined.clear();
312 MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI)
314 const TargetInstrDesc &TI = MI->getDesc();
315 if (MI->getNumExplicitOperands() < TI.getNumOperands()) {
316 report("Too few operands", MI);
317 *OS << TI.getNumOperands() << " operands expected, but "
318 << MI->getNumExplicitOperands() << " given.\n";
320 if (!TI.isVariadic()) {
321 if (MI->getNumExplicitOperands() > TI.getNumOperands()) {
322 report("Too many operands", MI);
323 *OS << TI.getNumOperands() << " operands expected, but "
324 << MI->getNumExplicitOperands() << " given.\n";
330 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum)
332 const MachineInstr *MI = MO->getParent();
333 const TargetInstrDesc &TI = MI->getDesc();
335 // The first TI.NumDefs operands must be explicit register defines
336 if (MONum < TI.getNumDefs()) {
338 report("Explicit definition must be a register", MO, MONum);
339 else if (!MO->isDef())
340 report("Explicit definition marked as use", MO, MONum);
341 else if (MO->isImplicit())
342 report("Explicit definition marked as implicit", MO, MONum);
345 switch (MO->getType()) {
346 case MachineOperand::MO_Register: {
347 const unsigned Reg = MO->getReg();
351 // Check Live Variables.
354 addRegWithSubRegs(regsKilled, Reg);
355 // Tied operands on two-address instuctions MUST NOT have a <kill> flag.
356 if (MI->isRegTiedToDefOperand(MONum))
357 report("Illegal kill flag on two-address instruction operand",
360 // TwoAddress instr modifying a reg is treated as kill+def.
362 if (MI->isRegTiedToDefOperand(MONum, &defIdx) &&
363 MI->getOperand(defIdx).getReg() == Reg)
364 addRegWithSubRegs(regsKilled, Reg);
366 // Explicit use of a dead register.
367 if (!MO->isImplicit() && !regsLive.count(Reg)) {
368 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
369 // Reserved registers may be used even when 'dead'.
370 if (!isReserved(Reg))
371 report("Using an undefined physical register", MO, MONum);
373 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
374 // We don't know which virtual registers are live in, so only complain
375 // if vreg was killed in this MBB. Otherwise keep track of vregs that
376 // must be live in. PHI instructions are handled separately.
377 if (MInfo.regsKilled.count(Reg))
378 report("Using a killed virtual register", MO, MONum);
379 else if (MI->getOpcode() != TargetInstrInfo::PHI)
380 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
385 // TODO: verify that earlyclobber ops are not used.
386 if (MO->isImplicit())
387 addRegWithSubRegs(regsImpDefined, Reg);
389 addRegWithSubRegs(regsDefined, Reg);
392 addRegWithSubRegs(regsDead, Reg);
395 // Check register classes.
396 if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
397 const TargetOperandInfo &TOI = TI.OpInfo[MONum];
398 unsigned SubIdx = MO->getSubReg();
400 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
403 unsigned s = TRI->getSubReg(Reg, SubIdx);
405 report("Invalid subregister index for physical register",
412 const TargetRegisterClass *DRC = TRI->getRegClass(TOI.RegClass);
413 if (!DRC->contains(sr)) {
414 report("Illegal physical register for instruction", MO, MONum);
415 *OS << TRI->getName(sr) << " is not a "
416 << DRC->getName() << " register.\n";
421 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
423 if (RC->subregclasses_begin()+SubIdx >= RC->subregclasses_end()) {
424 report("Invalid subregister index for virtual register", MO, MONum);
427 RC = *(RC->subregclasses_begin()+SubIdx);
430 const TargetRegisterClass *DRC = TRI->getRegClass(TOI.RegClass);
431 if (RC != DRC && !RC->hasSuperClass(DRC)) {
432 report("Illegal virtual register for instruction", MO, MONum);
433 *OS << "Expected a " << DRC->getName() << " register, but got a "
434 << RC->getName() << " register\n";
441 // Can PHI instrs refer to MBBs not in the CFG? X86 and ARM do.
442 // case MachineOperand::MO_MachineBasicBlock:
443 // if (MI->getOpcode() == TargetInstrInfo::PHI) {
444 // if (!MO->getMBB()->isSuccessor(MI->getParent()))
445 // report("PHI operand is not in the CFG", MO, MONum);
454 MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI)
456 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
457 set_union(MInfo.regsKilled, regsKilled);
458 set_subtract(regsLive, regsKilled);
461 for (RegVector::const_iterator I = regsDefined.begin(),
462 E = regsDefined.end(); I != E; ++I) {
463 if (regsLive.count(*I)) {
464 if (TargetRegisterInfo::isPhysicalRegister(*I)) {
465 // We allow double defines to physical registers with live
467 if (!allowPhysDoubleDefs && !isReserved(*I) &&
468 !anySuperRegisters(regsLive, *I)) {
469 report("Redefining a live physical register", MI);
470 *OS << "Register " << TRI->getName(*I)
471 << " was defined but already live.\n";
474 if (!allowVirtDoubleDefs) {
475 report("Redefining a live virtual register", MI);
476 *OS << "Virtual register %reg" << *I
477 << " was defined but already live.\n";
480 } else if (TargetRegisterInfo::isVirtualRegister(*I) &&
481 !MInfo.regsKilled.count(*I)) {
482 // Virtual register defined without being killed first must be dead on
484 MInfo.vregsDeadIn.insert(std::make_pair(*I, MI));
488 set_union(regsLive, regsDefined); regsDefined.clear();
489 set_union(regsLive, regsImpDefined); regsImpDefined.clear();
490 set_subtract(regsLive, regsDead); regsDead.clear();
494 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB)
496 MBBInfoMap[MBB].regsLiveOut = regsLive;
500 // Calculate the largest possible vregsPassed sets. These are the registers that
501 // can pass through an MBB live, but may not be live every time. It is assumed
502 // that all vregsPassed sets are empty before the call.
504 MachineVerifier::calcMaxRegsPassed()
506 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
507 // have any vregsPassed.
508 DenseSet<const MachineBasicBlock*> todo;
509 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
511 const MachineBasicBlock &MBB(*MFI);
512 BBInfo &MInfo = MBBInfoMap[&MBB];
513 if (!MInfo.reachable)
515 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
516 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
517 BBInfo &SInfo = MBBInfoMap[*SuI];
518 if (SInfo.addPassed(MInfo.regsLiveOut))
523 // Iteratively push vregsPassed to successors. This will converge to the same
524 // final state regardless of DenseSet iteration order.
525 while (!todo.empty()) {
526 const MachineBasicBlock *MBB = *todo.begin();
528 BBInfo &MInfo = MBBInfoMap[MBB];
529 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
530 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
533 BBInfo &SInfo = MBBInfoMap[*SuI];
534 if (SInfo.addPassed(MInfo.vregsPassed))
540 // Calculate the minimum vregsPassed set. These are the registers that always
541 // pass live through an MBB. The calculation assumes that calcMaxRegsPassed has
542 // been called earlier.
544 MachineVerifier::calcMinRegsPassed()
546 DenseSet<const MachineBasicBlock*> todo;
547 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
551 while (!todo.empty()) {
552 const MachineBasicBlock *MBB = *todo.begin();
554 BBInfo &MInfo = MBBInfoMap[MBB];
556 // Remove entries from vRegsPassed that are not live out from all
557 // reachable predecessors.
559 for (RegSet::iterator I = MInfo.vregsPassed.begin(),
560 E = MInfo.vregsPassed.end(); I != E; ++I) {
561 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
562 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
563 BBInfo &PrInfo = MBBInfoMap[*PrI];
564 if (PrInfo.reachable && !PrInfo.isLiveOut(*I)) {
570 // If any regs removed, we need to recheck successors.
572 set_subtract(MInfo.vregsPassed, dead);
573 todo.insert(MBB->succ_begin(), MBB->succ_end());
578 // Check PHI instructions at the beginning of MBB. It is assumed that
579 // calcMinRegsPassed has been run so BBInfo::isLiveOut is valid.
581 MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB)
583 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
584 BBI != BBE && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI) {
585 DenseSet<const MachineBasicBlock*> seen;
587 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
588 unsigned Reg = BBI->getOperand(i).getReg();
589 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
590 if (!Pre->isSuccessor(MBB))
593 BBInfo &PrInfo = MBBInfoMap[Pre];
594 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
595 report("PHI operand is not live-out from predecessor",
596 &BBI->getOperand(i), i);
599 // Did we see all predecessors?
600 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
601 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
602 if (!seen.count(*PrI)) {
603 report("Missing PHI operand", BBI);
604 *OS << "MBB #" << (*PrI)->getNumber()
605 << " is a predecessor according to the CFG.\n";
612 MachineVerifier::visitMachineFunctionAfter()
616 // With the maximal set of vregsPassed we can verify dead-in registers.
617 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
619 BBInfo &MInfo = MBBInfoMap[MFI];
621 // Skip unreachable MBBs.
622 if (!MInfo.reachable)
625 for (MachineBasicBlock::const_pred_iterator PrI = MFI->pred_begin(),
626 PrE = MFI->pred_end(); PrI != PrE; ++PrI) {
627 BBInfo &PrInfo = MBBInfoMap[*PrI];
628 if (!PrInfo.reachable)
631 // Verify physical live-ins. EH landing pads have magic live-ins so we
633 if (!MFI->isLandingPad()) {
634 for (MachineBasicBlock::const_livein_iterator I = MFI->livein_begin(),
635 E = MFI->livein_end(); I != E; ++I) {
636 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
637 !isReserved (*I) && !PrInfo.isLiveOut(*I)) {
638 report("Live-in physical register is not live-out from predecessor",
640 *OS << "Register " << TRI->getName(*I)
641 << " is not live-out from MBB #" << (*PrI)->getNumber()
648 // Verify dead-in virtual registers.
649 if (!allowVirtDoubleDefs) {
650 for (RegMap::iterator I = MInfo.vregsDeadIn.begin(),
651 E = MInfo.vregsDeadIn.end(); I != E; ++I) {
652 // DeadIn register must be in neither regsLiveOut or vregsPassed of
654 if (PrInfo.isLiveOut(I->first)) {
655 report("Live-in virtual register redefined", I->second);
656 *OS << "Register %reg" << I->first
657 << " was live-out from predecessor MBB #"
658 << (*PrI)->getNumber() << ".\n";
667 // With the minimal set of vregsPassed we can verify live-in virtual
668 // registers, including PHI instructions.
669 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
671 BBInfo &MInfo = MBBInfoMap[MFI];
673 // Skip unreachable MBBs.
674 if (!MInfo.reachable)
679 for (MachineBasicBlock::const_pred_iterator PrI = MFI->pred_begin(),
680 PrE = MFI->pred_end(); PrI != PrE; ++PrI) {
681 BBInfo &PrInfo = MBBInfoMap[*PrI];
682 if (!PrInfo.reachable)
685 for (RegMap::iterator I = MInfo.vregsLiveIn.begin(),
686 E = MInfo.vregsLiveIn.end(); I != E; ++I) {
687 if (!PrInfo.isLiveOut(I->first)) {
688 report("Used virtual register is not live-in", I->second);
689 *OS << "Register %reg" << I->first
690 << " is not live-out from predecessor MBB #"
691 << (*PrI)->getNumber()