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/MachineInstrBundle.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/ADT/DenseSet.h"
42 #include "llvm/ADT/SetOperations.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/raw_ostream.h"
50 struct MachineVerifier {
52 MachineVerifier(Pass *pass, const char *b) :
55 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
58 bool runOnMachineFunction(MachineFunction &MF);
62 const char *const OutFileName;
64 const MachineFunction *MF;
65 const TargetMachine *TM;
66 const TargetInstrInfo *TII;
67 const TargetRegisterInfo *TRI;
68 const MachineRegisterInfo *MRI;
72 typedef SmallVector<unsigned, 16> RegVector;
73 typedef SmallVector<const uint32_t*, 4> RegMaskVector;
74 typedef DenseSet<unsigned> RegSet;
75 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
77 const MachineInstr *FirstTerminator;
79 BitVector regsReserved;
80 BitVector regsAllocatable;
82 RegVector regsDefined, regsDead, regsKilled;
83 RegMaskVector regMasks;
84 RegSet regsLiveInButUnused;
88 // Add Reg and any sub-registers to RV
89 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
91 if (TargetRegisterInfo::isPhysicalRegister(Reg))
92 for (const uint16_t *R = TRI->getSubRegisters(Reg); *R; R++)
97 // Is this MBB reachable from the MF entry point?
100 // Vregs that must be live in because they are used without being
101 // defined. Map value is the user.
104 // Regs killed in MBB. They may be defined again, and will then be in both
105 // regsKilled and regsLiveOut.
108 // Regs defined in MBB and live out. Note that vregs passing through may
109 // be live out without being mentioned here.
112 // Vregs that pass through MBB untouched. This set is disjoint from
113 // regsKilled and regsLiveOut.
116 // Vregs that must pass through MBB because they are needed by a successor
117 // block. This set is disjoint from regsLiveOut.
118 RegSet vregsRequired;
120 BBInfo() : reachable(false) {}
122 // Add register to vregsPassed if it belongs there. Return true if
124 bool addPassed(unsigned Reg) {
125 if (!TargetRegisterInfo::isVirtualRegister(Reg))
127 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
129 return vregsPassed.insert(Reg).second;
132 // Same for a full set.
133 bool addPassed(const RegSet &RS) {
134 bool changed = false;
135 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
141 // Add register to vregsRequired if it belongs there. Return true if
143 bool addRequired(unsigned Reg) {
144 if (!TargetRegisterInfo::isVirtualRegister(Reg))
146 if (regsLiveOut.count(Reg))
148 return vregsRequired.insert(Reg).second;
151 // Same for a full set.
152 bool addRequired(const RegSet &RS) {
153 bool changed = false;
154 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
160 // Same for a full map.
161 bool addRequired(const RegMap &RM) {
162 bool changed = false;
163 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
164 if (addRequired(I->first))
169 // Live-out registers are either in regsLiveOut or vregsPassed.
170 bool isLiveOut(unsigned Reg) const {
171 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
175 // Extra register info per MBB.
176 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
178 bool isReserved(unsigned Reg) {
179 return Reg < regsReserved.size() && regsReserved.test(Reg);
182 bool isAllocatable(unsigned Reg) {
183 return Reg < regsAllocatable.size() && regsAllocatable.test(Reg);
186 // Analysis information if available
187 LiveVariables *LiveVars;
188 LiveIntervals *LiveInts;
189 LiveStacks *LiveStks;
190 SlotIndexes *Indexes;
192 void visitMachineFunctionBefore();
193 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
194 void visitMachineInstrBefore(const MachineInstr *MI);
195 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
196 void visitMachineInstrAfter(const MachineInstr *MI);
197 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
198 void visitMachineFunctionAfter();
200 void report(const char *msg, const MachineFunction *MF);
201 void report(const char *msg, const MachineBasicBlock *MBB);
202 void report(const char *msg, const MachineInstr *MI);
203 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
205 void markReachable(const MachineBasicBlock *MBB);
206 void calcRegsPassed();
207 void checkPHIOps(const MachineBasicBlock *MBB);
209 void calcRegsRequired();
210 void verifyLiveVariables();
211 void verifyLiveIntervals();
214 struct MachineVerifierPass : public MachineFunctionPass {
215 static char ID; // Pass ID, replacement for typeid
216 const char *const Banner;
218 MachineVerifierPass(const char *b = 0)
219 : MachineFunctionPass(ID), Banner(b) {
220 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
223 void getAnalysisUsage(AnalysisUsage &AU) const {
224 AU.setPreservesAll();
225 MachineFunctionPass::getAnalysisUsage(AU);
228 bool runOnMachineFunction(MachineFunction &MF) {
229 MF.verify(this, Banner);
236 char MachineVerifierPass::ID = 0;
237 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
238 "Verify generated machine code", false, false)
240 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
241 return new MachineVerifierPass(Banner);
244 void MachineFunction::verify(Pass *p, const char *Banner) const {
245 MachineVerifier(p, Banner)
246 .runOnMachineFunction(const_cast<MachineFunction&>(*this));
249 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
250 raw_ostream *OutFile = 0;
252 std::string ErrorInfo;
253 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
254 raw_fd_ostream::F_Append);
255 if (!ErrorInfo.empty()) {
256 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
268 TM = &MF.getTarget();
269 TII = TM->getInstrInfo();
270 TRI = TM->getRegisterInfo();
271 MRI = &MF.getRegInfo();
278 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
279 // We don't want to verify LiveVariables if LiveIntervals is available.
281 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
282 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
283 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
286 visitMachineFunctionBefore();
287 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
289 visitMachineBasicBlockBefore(MFI);
290 for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
291 MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
292 if (MBBI->getParent() != MFI) {
293 report("Bad instruction parent pointer", MFI);
294 *OS << "Instruction: " << *MBBI;
297 // Skip BUNDLE instruction for now. FIXME: We should add code to verify
298 // the BUNDLE's specifically.
299 if (MBBI->isBundle())
301 visitMachineInstrBefore(MBBI);
302 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
303 visitMachineOperand(&MBBI->getOperand(I), I);
304 visitMachineInstrAfter(MBBI);
306 visitMachineBasicBlockAfter(MFI);
308 visitMachineFunctionAfter();
312 else if (foundErrors)
313 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
321 regsLiveInButUnused.clear();
324 return false; // no changes
327 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
330 if (!foundErrors++) {
332 *OS << "# " << Banner << '\n';
333 MF->print(*OS, Indexes);
335 *OS << "*** Bad machine code: " << msg << " ***\n"
336 << "- function: " << MF->getFunction()->getName() << "\n";
339 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
341 report(msg, MBB->getParent());
342 *OS << "- basic block: " << MBB->getName()
344 << " (BB#" << MBB->getNumber() << ")";
346 *OS << " [" << Indexes->getMBBStartIdx(MBB)
347 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
351 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
353 report(msg, MI->getParent());
354 *OS << "- instruction: ";
355 if (Indexes && Indexes->hasIndex(MI))
356 *OS << Indexes->getInstructionIndex(MI) << '\t';
360 void MachineVerifier::report(const char *msg,
361 const MachineOperand *MO, unsigned MONum) {
363 report(msg, MO->getParent());
364 *OS << "- operand " << MONum << ": ";
369 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
370 BBInfo &MInfo = MBBInfoMap[MBB];
371 if (!MInfo.reachable) {
372 MInfo.reachable = true;
373 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
374 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
379 void MachineVerifier::visitMachineFunctionBefore() {
380 lastIndex = SlotIndex();
381 regsReserved = TRI->getReservedRegs(*MF);
383 // A sub-register of a reserved register is also reserved
384 for (int Reg = regsReserved.find_first(); Reg>=0;
385 Reg = regsReserved.find_next(Reg)) {
386 for (const uint16_t *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
387 // FIXME: This should probably be:
388 // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
389 regsReserved.set(*Sub);
393 regsAllocatable = TRI->getAllocatableSet(*MF);
395 markReachable(&MF->front());
398 // Does iterator point to a and b as the first two elements?
399 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
400 const MachineBasicBlock *a, const MachineBasicBlock *b) {
409 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
413 // If this block has allocatable physical registers live-in, check that
414 // it is an entry block or landing pad.
415 for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
416 LE = MBB->livein_end();
419 if (isAllocatable(reg) && !MBB->isLandingPad() &&
420 MBB != MBB->getParent()->begin()) {
421 report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
426 // Count the number of landing pad successors.
427 SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
428 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
429 E = MBB->succ_end(); I != E; ++I) {
430 if ((*I)->isLandingPad())
431 LandingPadSuccs.insert(*I);
434 const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
435 const BasicBlock *BB = MBB->getBasicBlock();
436 if (LandingPadSuccs.size() > 1 &&
438 AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
439 BB && isa<SwitchInst>(BB->getTerminator())))
440 report("MBB has more than one landing pad successor", MBB);
442 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
443 MachineBasicBlock *TBB = 0, *FBB = 0;
444 SmallVector<MachineOperand, 4> Cond;
445 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
447 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
448 // check whether its answers match up with reality.
450 // Block falls through to its successor.
451 MachineFunction::const_iterator MBBI = MBB;
453 if (MBBI == MF->end()) {
454 // It's possible that the block legitimately ends with a noreturn
455 // call or an unreachable, in which case it won't actually fall
456 // out the bottom of the function.
457 } else if (MBB->succ_size() == LandingPadSuccs.size()) {
458 // It's possible that the block legitimately ends with a noreturn
459 // call or an unreachable, in which case it won't actuall fall
461 } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
462 report("MBB exits via unconditional fall-through but doesn't have "
463 "exactly one CFG successor!", MBB);
464 } else if (!MBB->isSuccessor(MBBI)) {
465 report("MBB exits via unconditional fall-through but its successor "
466 "differs from its CFG successor!", MBB);
468 if (!MBB->empty() && MBB->back().isBarrier() &&
469 !TII->isPredicated(&MBB->back())) {
470 report("MBB exits via unconditional fall-through but ends with a "
471 "barrier instruction!", MBB);
474 report("MBB exits via unconditional fall-through but has a condition!",
477 } else if (TBB && !FBB && Cond.empty()) {
478 // Block unconditionally branches somewhere.
479 if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
480 report("MBB exits via unconditional branch but doesn't have "
481 "exactly one CFG successor!", MBB);
482 } else if (!MBB->isSuccessor(TBB)) {
483 report("MBB exits via unconditional branch but the CFG "
484 "successor doesn't match the actual successor!", MBB);
487 report("MBB exits via unconditional branch but doesn't contain "
488 "any instructions!", MBB);
489 } else if (!MBB->back().isBarrier()) {
490 report("MBB exits via unconditional branch but doesn't end with a "
491 "barrier instruction!", MBB);
492 } else if (!MBB->back().isTerminator()) {
493 report("MBB exits via unconditional branch but the branch isn't a "
494 "terminator instruction!", MBB);
496 } else if (TBB && !FBB && !Cond.empty()) {
497 // Block conditionally branches somewhere, otherwise falls through.
498 MachineFunction::const_iterator MBBI = MBB;
500 if (MBBI == MF->end()) {
501 report("MBB conditionally falls through out of function!", MBB);
502 } if (MBB->succ_size() != 2) {
503 report("MBB exits via conditional branch/fall-through but doesn't have "
504 "exactly two CFG successors!", MBB);
505 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
506 report("MBB exits via conditional branch/fall-through but the CFG "
507 "successors don't match the actual successors!", MBB);
510 report("MBB exits via conditional branch/fall-through but doesn't "
511 "contain any instructions!", MBB);
512 } else if (MBB->back().isBarrier()) {
513 report("MBB exits via conditional branch/fall-through but ends with a "
514 "barrier instruction!", MBB);
515 } else if (!MBB->back().isTerminator()) {
516 report("MBB exits via conditional branch/fall-through but the branch "
517 "isn't a terminator instruction!", MBB);
519 } else if (TBB && FBB) {
520 // Block conditionally branches somewhere, otherwise branches
522 if (MBB->succ_size() != 2) {
523 report("MBB exits via conditional branch/branch but doesn't have "
524 "exactly two CFG successors!", MBB);
525 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
526 report("MBB exits via conditional branch/branch but the CFG "
527 "successors don't match the actual successors!", MBB);
530 report("MBB exits via conditional branch/branch but doesn't "
531 "contain any instructions!", MBB);
532 } else if (!MBB->back().isBarrier()) {
533 report("MBB exits via conditional branch/branch but doesn't end with a "
534 "barrier instruction!", MBB);
535 } else if (!MBB->back().isTerminator()) {
536 report("MBB exits via conditional branch/branch but the branch "
537 "isn't a terminator instruction!", MBB);
540 report("MBB exits via conditinal branch/branch but there's no "
544 report("AnalyzeBranch returned invalid data!", MBB);
549 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
550 E = MBB->livein_end(); I != E; ++I) {
551 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
552 report("MBB live-in list contains non-physical register", MBB);
556 for (const uint16_t *R = TRI->getSubRegisters(*I); *R; R++)
559 regsLiveInButUnused = regsLive;
561 const MachineFrameInfo *MFI = MF->getFrameInfo();
562 assert(MFI && "Function has no frame info");
563 BitVector PR = MFI->getPristineRegs(MBB);
564 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
566 for (const uint16_t *R = TRI->getSubRegisters(I); *R; R++)
574 lastIndex = Indexes->getMBBStartIdx(MBB);
577 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
578 const MCInstrDesc &MCID = MI->getDesc();
579 if (MI->getNumOperands() < MCID.getNumOperands()) {
580 report("Too few operands", MI);
581 *OS << MCID.getNumOperands() << " operands expected, but "
582 << MI->getNumExplicitOperands() << " given.\n";
585 // Check the MachineMemOperands for basic consistency.
586 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
587 E = MI->memoperands_end(); I != E; ++I) {
588 if ((*I)->isLoad() && !MI->mayLoad())
589 report("Missing mayLoad flag", MI);
590 if ((*I)->isStore() && !MI->mayStore())
591 report("Missing mayStore flag", MI);
594 // Debug values must not have a slot index.
595 // Other instructions must have one, unless they are inside a bundle.
597 bool mapped = !LiveInts->isNotInMIMap(MI);
598 if (MI->isDebugValue()) {
600 report("Debug instruction has a slot index", MI);
601 } else if (MI->isInsideBundle()) {
603 report("Instruction inside bundle has a slot index", MI);
606 report("Missing slot index", MI);
610 // Ensure non-terminators don't follow terminators.
611 if (MI->isTerminator()) {
612 if (!FirstTerminator)
613 FirstTerminator = MI;
614 } else if (FirstTerminator) {
615 report("Non-terminator instruction after the first terminator", MI);
616 *OS << "First terminator was:\t" << *FirstTerminator;
620 if (!TII->verifyInstruction(MI, ErrorInfo))
621 report(ErrorInfo.data(), MI);
625 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
626 const MachineInstr *MI = MO->getParent();
627 const MCInstrDesc &MCID = MI->getDesc();
628 const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
630 // The first MCID.NumDefs operands must be explicit register defines
631 if (MONum < MCID.getNumDefs()) {
633 report("Explicit definition must be a register", MO, MONum);
634 else if (!MO->isDef())
635 report("Explicit definition marked as use", MO, MONum);
636 else if (MO->isImplicit())
637 report("Explicit definition marked as implicit", MO, MONum);
638 } else if (MONum < MCID.getNumOperands()) {
639 // Don't check if it's the last operand in a variadic instruction. See,
640 // e.g., LDM_RET in the arm back end.
642 !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
643 if (MO->isDef() && !MCOI.isOptionalDef())
644 report("Explicit operand marked as def", MO, MONum);
645 if (MO->isImplicit())
646 report("Explicit operand marked as implicit", MO, MONum);
649 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
650 if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
651 report("Extra explicit operand on non-variadic instruction", MO, MONum);
654 switch (MO->getType()) {
655 case MachineOperand::MO_Register: {
656 const unsigned Reg = MO->getReg();
660 // Check Live Variables.
661 if (MI->isDebugValue()) {
662 // Liveness checks are not valid for debug values.
663 } else if (MO->isUse() && !MO->isUndef()) {
664 regsLiveInButUnused.erase(Reg);
668 if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
669 // A two-addr use counts as a kill if use and def are the same.
670 unsigned DefReg = MI->getOperand(defIdx).getReg();
673 else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
674 report("Two-address instruction operands must be identical",
678 isKill = MO->isKill();
681 addRegWithSubRegs(regsKilled, Reg);
683 // Check that LiveVars knows this kill.
684 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
686 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
687 if (std::find(VI.Kills.begin(),
688 VI.Kills.end(), MI) == VI.Kills.end())
689 report("Kill missing from LiveVariables", MO, MONum);
692 // Check LiveInts liveness and kill.
693 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
694 LiveInts && !LiveInts->isNotInMIMap(MI)) {
695 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getRegSlot(true);
696 if (LiveInts->hasInterval(Reg)) {
697 const LiveInterval &LI = LiveInts->getInterval(Reg);
698 if (!LI.liveAt(UseIdx)) {
699 report("No live range at use", MO, MONum);
700 *OS << UseIdx << " is not live in " << LI << '\n';
702 // Check for extra kill flags.
703 // Note that we allow missing kill flags for now.
704 if (MO->isKill() && !LI.killedAt(UseIdx.getRegSlot())) {
705 report("Live range continues after kill flag", MO, MONum);
706 *OS << "Live range: " << LI << '\n';
709 report("Virtual register has no Live interval", MO, MONum);
713 // Use of a dead register.
714 if (!regsLive.count(Reg)) {
715 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
716 // Reserved registers may be used even when 'dead'.
717 if (!isReserved(Reg))
718 report("Using an undefined physical register", MO, MONum);
720 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
721 // We don't know which virtual registers are live in, so only complain
722 // if vreg was killed in this MBB. Otherwise keep track of vregs that
723 // must be live in. PHI instructions are handled separately.
724 if (MInfo.regsKilled.count(Reg))
725 report("Using a killed virtual register", MO, MONum);
726 else if (!MI->isPHI())
727 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
730 } else if (MO->isDef()) {
732 // TODO: verify that earlyclobber ops are not used.
734 addRegWithSubRegs(regsDead, Reg);
736 addRegWithSubRegs(regsDefined, Reg);
739 if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
740 llvm::next(MRI->def_begin(Reg)) != MRI->def_end())
741 report("Multiple virtual register defs in SSA form", MO, MONum);
743 // Check LiveInts for a live range, but only for virtual registers.
744 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
745 !LiveInts->isNotInMIMap(MI)) {
746 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getRegSlot();
747 if (LiveInts->hasInterval(Reg)) {
748 const LiveInterval &LI = LiveInts->getInterval(Reg);
749 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
750 assert(VNI && "NULL valno is not allowed");
751 if (VNI->def != DefIdx && !MO->isEarlyClobber()) {
752 report("Inconsistent valno->def", MO, MONum);
753 *OS << "Valno " << VNI->id << " is not defined at "
754 << DefIdx << " in " << LI << '\n';
757 report("No live range at def", MO, MONum);
758 *OS << DefIdx << " is not live in " << LI << '\n';
761 report("Virtual register has no Live interval", MO, MONum);
766 // Check register classes.
767 if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
768 unsigned SubIdx = MO->getSubReg();
770 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
772 report("Illegal subregister index for physical register", MO, MONum);
775 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID,MONum,TRI)) {
776 if (!DRC->contains(Reg)) {
777 report("Illegal physical register for instruction", MO, MONum);
778 *OS << TRI->getName(Reg) << " is not a "
779 << DRC->getName() << " register.\n";
784 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
786 const TargetRegisterClass *SRC =
787 TRI->getSubClassWithSubReg(RC, SubIdx);
789 report("Invalid subregister index for virtual register", MO, MONum);
790 *OS << "Register class " << RC->getName()
791 << " does not support subreg index " << SubIdx << "\n";
795 report("Invalid register class for subregister index", MO, MONum);
796 *OS << "Register class " << RC->getName()
797 << " does not fully support subreg index " << SubIdx << "\n";
801 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID,MONum,TRI)) {
803 const TargetRegisterClass *SuperRC =
804 TRI->getLargestLegalSuperClass(RC);
806 report("No largest legal super class exists.", MO, MONum);
809 DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
811 report("No matching super-reg register class.", MO, MONum);
815 if (!RC->hasSuperClassEq(DRC)) {
816 report("Illegal virtual register for instruction", MO, MONum);
817 *OS << "Expected a " << DRC->getName() << " register, but got a "
818 << RC->getName() << " register\n";
826 case MachineOperand::MO_RegisterMask:
827 regMasks.push_back(MO->getRegMask());
830 case MachineOperand::MO_MachineBasicBlock:
831 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
832 report("PHI operand is not in the CFG", MO, MONum);
835 case MachineOperand::MO_FrameIndex:
836 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
837 LiveInts && !LiveInts->isNotInMIMap(MI)) {
838 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
839 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
840 if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
841 report("Instruction loads from dead spill slot", MO, MONum);
842 *OS << "Live stack: " << LI << '\n';
844 if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
845 report("Instruction stores to dead spill slot", MO, MONum);
846 *OS << "Live stack: " << LI << '\n';
856 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
857 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
858 set_union(MInfo.regsKilled, regsKilled);
859 set_subtract(regsLive, regsKilled); regsKilled.clear();
860 // Kill any masked registers.
861 while (!regMasks.empty()) {
862 const uint32_t *Mask = regMasks.pop_back_val();
863 for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
864 if (TargetRegisterInfo::isPhysicalRegister(*I) &&
865 MachineOperand::clobbersPhysReg(Mask, *I))
866 regsDead.push_back(*I);
868 set_subtract(regsLive, regsDead); regsDead.clear();
869 set_union(regsLive, regsDefined); regsDefined.clear();
871 if (Indexes && Indexes->hasIndex(MI)) {
872 SlotIndex idx = Indexes->getInstructionIndex(MI);
873 if (!(idx > lastIndex)) {
874 report("Instruction index out of order", MI);
875 *OS << "Last instruction was at " << lastIndex << '\n';
882 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
883 MBBInfoMap[MBB].regsLiveOut = regsLive;
887 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
888 if (!(stop > lastIndex)) {
889 report("Block ends before last instruction index", MBB);
890 *OS << "Block ends at " << stop
891 << " last instruction was at " << lastIndex << '\n';
897 // Calculate the largest possible vregsPassed sets. These are the registers that
898 // can pass through an MBB live, but may not be live every time. It is assumed
899 // that all vregsPassed sets are empty before the call.
900 void MachineVerifier::calcRegsPassed() {
901 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
902 // have any vregsPassed.
903 DenseSet<const MachineBasicBlock*> todo;
904 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
906 const MachineBasicBlock &MBB(*MFI);
907 BBInfo &MInfo = MBBInfoMap[&MBB];
908 if (!MInfo.reachable)
910 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
911 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
912 BBInfo &SInfo = MBBInfoMap[*SuI];
913 if (SInfo.addPassed(MInfo.regsLiveOut))
918 // Iteratively push vregsPassed to successors. This will converge to the same
919 // final state regardless of DenseSet iteration order.
920 while (!todo.empty()) {
921 const MachineBasicBlock *MBB = *todo.begin();
923 BBInfo &MInfo = MBBInfoMap[MBB];
924 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
925 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
928 BBInfo &SInfo = MBBInfoMap[*SuI];
929 if (SInfo.addPassed(MInfo.vregsPassed))
935 // Calculate the set of virtual registers that must be passed through each basic
936 // block in order to satisfy the requirements of successor blocks. This is very
937 // similar to calcRegsPassed, only backwards.
938 void MachineVerifier::calcRegsRequired() {
939 // First push live-in regs to predecessors' vregsRequired.
940 DenseSet<const MachineBasicBlock*> todo;
941 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
943 const MachineBasicBlock &MBB(*MFI);
944 BBInfo &MInfo = MBBInfoMap[&MBB];
945 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
946 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
947 BBInfo &PInfo = MBBInfoMap[*PrI];
948 if (PInfo.addRequired(MInfo.vregsLiveIn))
953 // Iteratively push vregsRequired to predecessors. This will converge to the
954 // same final state regardless of DenseSet iteration order.
955 while (!todo.empty()) {
956 const MachineBasicBlock *MBB = *todo.begin();
958 BBInfo &MInfo = MBBInfoMap[MBB];
959 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
960 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
963 BBInfo &SInfo = MBBInfoMap[*PrI];
964 if (SInfo.addRequired(MInfo.vregsRequired))
970 // Check PHI instructions at the beginning of MBB. It is assumed that
971 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
972 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
973 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
974 BBI != BBE && BBI->isPHI(); ++BBI) {
975 DenseSet<const MachineBasicBlock*> seen;
977 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
978 unsigned Reg = BBI->getOperand(i).getReg();
979 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
980 if (!Pre->isSuccessor(MBB))
983 BBInfo &PrInfo = MBBInfoMap[Pre];
984 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
985 report("PHI operand is not live-out from predecessor",
986 &BBI->getOperand(i), i);
989 // Did we see all predecessors?
990 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
991 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
992 if (!seen.count(*PrI)) {
993 report("Missing PHI operand", BBI);
994 *OS << "BB#" << (*PrI)->getNumber()
995 << " is a predecessor according to the CFG.\n";
1001 void MachineVerifier::visitMachineFunctionAfter() {
1004 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1005 MFI != MFE; ++MFI) {
1006 BBInfo &MInfo = MBBInfoMap[MFI];
1008 // Skip unreachable MBBs.
1009 if (!MInfo.reachable)
1015 // Now check liveness info if available
1016 if (LiveVars || LiveInts)
1019 verifyLiveVariables();
1021 verifyLiveIntervals();
1024 void MachineVerifier::verifyLiveVariables() {
1025 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1026 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1027 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1028 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1029 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1030 MFI != MFE; ++MFI) {
1031 BBInfo &MInfo = MBBInfoMap[MFI];
1033 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1034 if (MInfo.vregsRequired.count(Reg)) {
1035 if (!VI.AliveBlocks.test(MFI->getNumber())) {
1036 report("LiveVariables: Block missing from AliveBlocks", MFI);
1037 *OS << "Virtual register " << PrintReg(Reg)
1038 << " must be live through the block.\n";
1041 if (VI.AliveBlocks.test(MFI->getNumber())) {
1042 report("LiveVariables: Block should not be in AliveBlocks", MFI);
1043 *OS << "Virtual register " << PrintReg(Reg)
1044 << " is not needed live through the block.\n";
1051 void MachineVerifier::verifyLiveIntervals() {
1052 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1053 for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
1054 LVE = LiveInts->end(); LVI != LVE; ++LVI) {
1055 const LiveInterval &LI = *LVI->second;
1057 // Spilling and splitting may leave unused registers around. Skip them.
1058 if (MRI->use_empty(LI.reg))
1061 // Physical registers have much weirdness going on, mostly from coalescing.
1062 // We should probably fix it, but for now just ignore them.
1063 if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
1066 assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
1068 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
1071 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
1074 if (!VNI->isUnused()) {
1075 report("Valno not live at def and not marked unused", MF);
1076 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1081 if (VNI->isUnused())
1084 if (DefVNI != VNI) {
1085 report("Live range at def has different valno", MF);
1086 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1087 << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
1091 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1093 report("Invalid definition index", MF);
1094 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1095 << " in " << LI << '\n';
1099 if (VNI->isPHIDef()) {
1100 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1101 report("PHIDef value is not defined at MBB start", MF);
1102 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1103 << ", not at the beginning of BB#" << MBB->getNumber()
1104 << " in " << LI << '\n';
1108 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1110 report("No instruction at def index", MF);
1111 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1112 << " in " << LI << '\n';
1116 bool hasDef = false;
1117 bool isEarlyClobber = false;
1118 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1119 if (!MOI->isReg() || !MOI->isDef())
1121 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1122 if (MOI->getReg() != LI.reg)
1125 if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1126 !TRI->regsOverlap(LI.reg, MOI->getReg()))
1130 if (MOI->isEarlyClobber())
1131 isEarlyClobber = true;
1135 report("Defining instruction does not modify register", MI);
1136 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1139 // Early clobber defs begin at USE slots, but other defs must begin at
1141 if (isEarlyClobber) {
1142 if (!VNI->def.isEarlyClobber()) {
1143 report("Early clobber def must be at an early-clobber slot", MF);
1144 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1145 << " in " << LI << '\n';
1147 } else if (!VNI->def.isRegister()) {
1148 report("Non-PHI, non-early clobber def must be at a register slot",
1150 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1151 << " in " << LI << '\n';
1156 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1157 const VNInfo *VNI = I->valno;
1158 assert(VNI && "Live range has no valno");
1160 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1161 report("Foreign valno in live range", MF);
1163 *OS << " has a valno not in " << LI << '\n';
1166 if (VNI->isUnused()) {
1167 report("Live range valno is marked unused", MF);
1169 *OS << " in " << LI << '\n';
1172 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1174 report("Bad start of live segment, no basic block", MF);
1176 *OS << " in " << LI << '\n';
1179 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1180 if (I->start != MBBStartIdx && I->start != VNI->def) {
1181 report("Live segment must begin at MBB entry or valno def", MBB);
1183 *OS << " in " << LI << '\n' << "Basic block starts at "
1184 << MBBStartIdx << '\n';
1187 const MachineBasicBlock *EndMBB =
1188 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1190 report("Bad end of live segment, no basic block", MF);
1192 *OS << " in " << LI << '\n';
1196 // No more checks for live-out segments.
1197 if (I->end == LiveInts->getMBBEndIdx(EndMBB))
1200 // The live segment is ending inside EndMBB
1201 const MachineInstr *MI =
1202 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1204 report("Live segment doesn't end at a valid instruction", EndMBB);
1206 *OS << " in " << LI << '\n' << "Basic block starts at "
1207 << MBBStartIdx << '\n';
1211 // The block slot must refer to a basic block boundary.
1212 if (I->end.isBlock()) {
1213 report("Live segment ends at B slot of an instruction", MI);
1215 *OS << " in " << LI << '\n';
1218 if (I->end.isDead()) {
1219 // Segment ends on the dead slot.
1220 // That means there must be a dead def.
1221 if (!SlotIndex::isSameInstr(I->start, I->end)) {
1222 report("Live segment ending at dead slot spans instructions", MI);
1224 *OS << " in " << LI << '\n';
1228 // A live segment can only end at an early-clobber slot if it is being
1229 // redefined by an early-clobber def.
1230 if (I->end.isEarlyClobber()) {
1231 if (I+1 == E || (I+1)->start != I->end) {
1232 report("Live segment ending at early clobber slot must be "
1233 "redefined by an EC def in the same instruction", MI);
1235 *OS << " in " << LI << '\n';
1239 // The following checks only apply to virtual registers. Physreg liveness
1240 // is too weird to check.
1241 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1242 // A live range can end with either a redefinition, a kill flag on a
1243 // use, or a dead flag on a def.
1244 bool hasRead = false;
1245 bool hasDeadDef = false;
1246 for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1247 if (!MOI->isReg() || MOI->getReg() != LI.reg)
1249 if (MOI->readsReg())
1251 if (MOI->isDef() && MOI->isDead())
1255 if (I->end.isDead()) {
1257 report("Instruction doesn't have a dead def operand", MI);
1259 *OS << " in " << LI << '\n';
1263 report("Instruction ending live range doesn't read the register",
1266 *OS << " in " << LI << '\n';
1271 // Now check all the basic blocks in this live segment.
1272 MachineFunction::const_iterator MFI = MBB;
1273 // Is this live range the beginning of a non-PHIDef VN?
1274 if (I->start == VNI->def && !VNI->isPHIDef()) {
1275 // Not live-in to any blocks.
1282 assert(LiveInts->isLiveInToMBB(LI, MFI));
1283 // We don't know how to track physregs into a landing pad.
1284 if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1285 MFI->isLandingPad()) {
1286 if (&*MFI == EndMBB)
1291 // Check that VNI is live-out of all predecessors.
1292 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1293 PE = MFI->pred_end(); PI != PE; ++PI) {
1294 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1295 const VNInfo *PVNI = LI.getVNInfoBefore(PEnd);
1297 if (VNI->isPHIDef() && VNI->def == LiveInts->getMBBStartIdx(MFI))
1301 report("Register not marked live out of predecessor", *PI);
1302 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1303 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1304 << PEnd << " in " << LI << '\n';
1309 report("Different value live out of predecessor", *PI);
1310 *OS << "Valno #" << PVNI->id << " live out of BB#"
1311 << (*PI)->getNumber() << '@' << PEnd
1312 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1313 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1316 if (&*MFI == EndMBB)
1322 // Check the LI only has one connected component.
1323 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1324 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1325 unsigned NumComp = ConEQ.Classify(&LI);
1327 report("Multiple connected components in live interval", MF);
1328 *OS << NumComp << " components in " << LI << '\n';
1329 for (unsigned comp = 0; comp != NumComp; ++comp) {
1330 *OS << comp << ": valnos";
1331 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1332 E = LI.vni_end(); I!=E; ++I)
1333 if (comp == ConEQ.getEqClass(*I))
1334 *OS << ' ' << (*I)->id;