Fixed some bugs.
[llvm/zpu.git] / lib / CodeGen / MachineVerifier.cpp
blob8ada60a55331426db1d2b8c0ab9f5864d7b2be5b
1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
44 using namespace llvm;
46 namespace {
47 struct MachineVerifier {
49 MachineVerifier(Pass *pass) :
50 PASS(pass),
51 OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
54 bool runOnMachineFunction(MachineFunction &MF);
56 Pass *const PASS;
57 const char *const OutFileName;
58 raw_ostream *OS;
59 const MachineFunction *MF;
60 const TargetMachine *TM;
61 const TargetRegisterInfo *TRI;
62 const MachineRegisterInfo *MRI;
64 unsigned foundErrors;
66 typedef SmallVector<unsigned, 16> RegVector;
67 typedef DenseSet<unsigned> RegSet;
68 typedef DenseMap<unsigned, const MachineInstr*> RegMap;
70 BitVector regsReserved;
71 RegSet regsLive;
72 RegVector regsDefined, regsDead, regsKilled;
73 RegSet regsLiveInButUnused;
75 // Add Reg and any sub-registers to RV
76 void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
77 RV.push_back(Reg);
78 if (TargetRegisterInfo::isPhysicalRegister(Reg))
79 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
80 RV.push_back(*R);
83 struct BBInfo {
84 // Is this MBB reachable from the MF entry point?
85 bool reachable;
87 // Vregs that must be live in because they are used without being
88 // defined. Map value is the user.
89 RegMap vregsLiveIn;
91 // Regs killed in MBB. They may be defined again, and will then be in both
92 // regsKilled and regsLiveOut.
93 RegSet regsKilled;
95 // Regs defined in MBB and live out. Note that vregs passing through may
96 // be live out without being mentioned here.
97 RegSet regsLiveOut;
99 // Vregs that pass through MBB untouched. This set is disjoint from
100 // regsKilled and regsLiveOut.
101 RegSet vregsPassed;
103 // Vregs that must pass through MBB because they are needed by a successor
104 // block. This set is disjoint from regsLiveOut.
105 RegSet vregsRequired;
107 BBInfo() : reachable(false) {}
109 // Add register to vregsPassed if it belongs there. Return true if
110 // anything changed.
111 bool addPassed(unsigned Reg) {
112 if (!TargetRegisterInfo::isVirtualRegister(Reg))
113 return false;
114 if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
115 return false;
116 return vregsPassed.insert(Reg).second;
119 // Same for a full set.
120 bool addPassed(const RegSet &RS) {
121 bool changed = false;
122 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
123 if (addPassed(*I))
124 changed = true;
125 return changed;
128 // Add register to vregsRequired if it belongs there. Return true if
129 // anything changed.
130 bool addRequired(unsigned Reg) {
131 if (!TargetRegisterInfo::isVirtualRegister(Reg))
132 return false;
133 if (regsLiveOut.count(Reg))
134 return false;
135 return vregsRequired.insert(Reg).second;
138 // Same for a full set.
139 bool addRequired(const RegSet &RS) {
140 bool changed = false;
141 for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
142 if (addRequired(*I))
143 changed = true;
144 return changed;
147 // Same for a full map.
148 bool addRequired(const RegMap &RM) {
149 bool changed = false;
150 for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
151 if (addRequired(I->first))
152 changed = true;
153 return changed;
156 // Live-out registers are either in regsLiveOut or vregsPassed.
157 bool isLiveOut(unsigned Reg) const {
158 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
162 // Extra register info per MBB.
163 DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
165 bool isReserved(unsigned Reg) {
166 return Reg < regsReserved.size() && regsReserved.test(Reg);
169 // Analysis information if available
170 LiveVariables *LiveVars;
171 LiveIntervals *LiveInts;
172 LiveStacks *LiveStks;
173 SlotIndexes *Indexes;
175 void visitMachineFunctionBefore();
176 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
177 void visitMachineInstrBefore(const MachineInstr *MI);
178 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
179 void visitMachineInstrAfter(const MachineInstr *MI);
180 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
181 void visitMachineFunctionAfter();
183 void report(const char *msg, const MachineFunction *MF);
184 void report(const char *msg, const MachineBasicBlock *MBB);
185 void report(const char *msg, const MachineInstr *MI);
186 void report(const char *msg, const MachineOperand *MO, unsigned MONum);
188 void markReachable(const MachineBasicBlock *MBB);
189 void calcRegsPassed();
190 void checkPHIOps(const MachineBasicBlock *MBB);
192 void calcRegsRequired();
193 void verifyLiveVariables();
194 void verifyLiveIntervals();
197 struct MachineVerifierPass : public MachineFunctionPass {
198 static char ID; // Pass ID, replacement for typeid
200 MachineVerifierPass()
201 : MachineFunctionPass(ID) {
202 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
205 void getAnalysisUsage(AnalysisUsage &AU) const {
206 AU.setPreservesAll();
207 MachineFunctionPass::getAnalysisUsage(AU);
210 bool runOnMachineFunction(MachineFunction &MF) {
211 MF.verify(this);
212 return false;
218 char MachineVerifierPass::ID = 0;
219 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
220 "Verify generated machine code", false, false)
222 FunctionPass *llvm::createMachineVerifierPass() {
223 return new MachineVerifierPass();
226 void MachineFunction::verify(Pass *p) const {
227 MachineVerifier(p).runOnMachineFunction(const_cast<MachineFunction&>(*this));
230 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
231 raw_ostream *OutFile = 0;
232 if (OutFileName) {
233 std::string ErrorInfo;
234 OutFile = new raw_fd_ostream(OutFileName, ErrorInfo,
235 raw_fd_ostream::F_Append);
236 if (!ErrorInfo.empty()) {
237 errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
238 exit(1);
241 OS = OutFile;
242 } else {
243 OS = &errs();
246 foundErrors = 0;
248 this->MF = &MF;
249 TM = &MF.getTarget();
250 TRI = TM->getRegisterInfo();
251 MRI = &MF.getRegInfo();
253 LiveVars = NULL;
254 LiveInts = NULL;
255 LiveStks = NULL;
256 Indexes = NULL;
257 if (PASS) {
258 LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
259 // We don't want to verify LiveVariables if LiveIntervals is available.
260 if (!LiveInts)
261 LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
262 LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
263 Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
266 visitMachineFunctionBefore();
267 for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
268 MFI!=MFE; ++MFI) {
269 visitMachineBasicBlockBefore(MFI);
270 for (MachineBasicBlock::const_iterator MBBI = MFI->begin(),
271 MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
272 visitMachineInstrBefore(MBBI);
273 for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
274 visitMachineOperand(&MBBI->getOperand(I), I);
275 visitMachineInstrAfter(MBBI);
277 visitMachineBasicBlockAfter(MFI);
279 visitMachineFunctionAfter();
281 if (OutFile)
282 delete OutFile;
283 else if (foundErrors)
284 report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
286 // Clean up.
287 regsLive.clear();
288 regsDefined.clear();
289 regsDead.clear();
290 regsKilled.clear();
291 regsLiveInButUnused.clear();
292 MBBInfoMap.clear();
294 return false; // no changes
297 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
298 assert(MF);
299 *OS << '\n';
300 if (!foundErrors++)
301 MF->print(*OS, Indexes);
302 *OS << "*** Bad machine code: " << msg << " ***\n"
303 << "- function: " << MF->getFunction()->getNameStr() << "\n";
306 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
307 assert(MBB);
308 report(msg, MBB->getParent());
309 *OS << "- basic block: " << MBB->getName()
310 << " " << (void*)MBB
311 << " (BB#" << MBB->getNumber() << ")";
312 if (Indexes)
313 *OS << " [" << Indexes->getMBBStartIdx(MBB)
314 << ';' << Indexes->getMBBEndIdx(MBB) << ')';
315 *OS << '\n';
318 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
319 assert(MI);
320 report(msg, MI->getParent());
321 *OS << "- instruction: ";
322 if (Indexes && Indexes->hasIndex(MI))
323 *OS << Indexes->getInstructionIndex(MI) << '\t';
324 MI->print(*OS, TM);
327 void MachineVerifier::report(const char *msg,
328 const MachineOperand *MO, unsigned MONum) {
329 assert(MO);
330 report(msg, MO->getParent());
331 *OS << "- operand " << MONum << ": ";
332 MO->print(*OS, TM);
333 *OS << "\n";
336 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
337 BBInfo &MInfo = MBBInfoMap[MBB];
338 if (!MInfo.reachable) {
339 MInfo.reachable = true;
340 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
341 SuE = MBB->succ_end(); SuI != SuE; ++SuI)
342 markReachable(*SuI);
346 void MachineVerifier::visitMachineFunctionBefore() {
347 regsReserved = TRI->getReservedRegs(*MF);
349 // A sub-register of a reserved register is also reserved
350 for (int Reg = regsReserved.find_first(); Reg>=0;
351 Reg = regsReserved.find_next(Reg)) {
352 for (const unsigned *Sub = TRI->getSubRegisters(Reg); *Sub; ++Sub) {
353 // FIXME: This should probably be:
354 // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
355 regsReserved.set(*Sub);
358 markReachable(&MF->front());
361 // Does iterator point to a and b as the first two elements?
362 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
363 const MachineBasicBlock *a, const MachineBasicBlock *b) {
364 if (*i == a)
365 return *++i == b;
366 if (*i == b)
367 return *++i == a;
368 return false;
371 void
372 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
373 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
375 // Count the number of landing pad successors.
376 unsigned LandingPadSuccs = 0;
377 for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
378 E = MBB->succ_end(); I != E; ++I)
379 LandingPadSuccs += (*I)->isLandingPad();
380 if (LandingPadSuccs > 1)
381 report("MBB has more than one landing pad successor", MBB);
383 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
384 MachineBasicBlock *TBB = 0, *FBB = 0;
385 SmallVector<MachineOperand, 4> Cond;
386 if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
387 TBB, FBB, Cond)) {
388 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
389 // check whether its answers match up with reality.
390 if (!TBB && !FBB) {
391 // Block falls through to its successor.
392 MachineFunction::const_iterator MBBI = MBB;
393 ++MBBI;
394 if (MBBI == MF->end()) {
395 // It's possible that the block legitimately ends with a noreturn
396 // call or an unreachable, in which case it won't actually fall
397 // out the bottom of the function.
398 } else if (MBB->succ_size() == LandingPadSuccs) {
399 // It's possible that the block legitimately ends with a noreturn
400 // call or an unreachable, in which case it won't actuall fall
401 // out of the block.
402 } else if (MBB->succ_size() != 1+LandingPadSuccs) {
403 report("MBB exits via unconditional fall-through but doesn't have "
404 "exactly one CFG successor!", MBB);
405 } else if (!MBB->isSuccessor(MBBI)) {
406 report("MBB exits via unconditional fall-through but its successor "
407 "differs from its CFG successor!", MBB);
409 if (!MBB->empty() && MBB->back().getDesc().isBarrier() &&
410 !TII->isPredicated(&MBB->back())) {
411 report("MBB exits via unconditional fall-through but ends with a "
412 "barrier instruction!", MBB);
414 if (!Cond.empty()) {
415 report("MBB exits via unconditional fall-through but has a condition!",
416 MBB);
418 } else if (TBB && !FBB && Cond.empty()) {
419 // Block unconditionally branches somewhere.
420 if (MBB->succ_size() != 1+LandingPadSuccs) {
421 report("MBB exits via unconditional branch but doesn't have "
422 "exactly one CFG successor!", MBB);
423 } else if (!MBB->isSuccessor(TBB)) {
424 report("MBB exits via unconditional branch but the CFG "
425 "successor doesn't match the actual successor!", MBB);
427 if (MBB->empty()) {
428 report("MBB exits via unconditional branch but doesn't contain "
429 "any instructions!", MBB);
430 } else if (!MBB->back().getDesc().isBarrier()) {
431 report("MBB exits via unconditional branch but doesn't end with a "
432 "barrier instruction!", MBB);
433 } else if (!MBB->back().getDesc().isTerminator()) {
434 report("MBB exits via unconditional branch but the branch isn't a "
435 "terminator instruction!", MBB);
437 } else if (TBB && !FBB && !Cond.empty()) {
438 // Block conditionally branches somewhere, otherwise falls through.
439 MachineFunction::const_iterator MBBI = MBB;
440 ++MBBI;
441 if (MBBI == MF->end()) {
442 report("MBB conditionally falls through out of function!", MBB);
443 } if (MBB->succ_size() != 2) {
444 report("MBB exits via conditional branch/fall-through but doesn't have "
445 "exactly two CFG successors!", MBB);
446 } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
447 report("MBB exits via conditional branch/fall-through but the CFG "
448 "successors don't match the actual successors!", MBB);
450 if (MBB->empty()) {
451 report("MBB exits via conditional branch/fall-through but doesn't "
452 "contain any instructions!", MBB);
453 } else if (MBB->back().getDesc().isBarrier()) {
454 report("MBB exits via conditional branch/fall-through but ends with a "
455 "barrier instruction!", MBB);
456 } else if (!MBB->back().getDesc().isTerminator()) {
457 report("MBB exits via conditional branch/fall-through but the branch "
458 "isn't a terminator instruction!", MBB);
460 } else if (TBB && FBB) {
461 // Block conditionally branches somewhere, otherwise branches
462 // somewhere else.
463 if (MBB->succ_size() != 2) {
464 report("MBB exits via conditional branch/branch but doesn't have "
465 "exactly two CFG successors!", MBB);
466 } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
467 report("MBB exits via conditional branch/branch but the CFG "
468 "successors don't match the actual successors!", MBB);
470 if (MBB->empty()) {
471 report("MBB exits via conditional branch/branch but doesn't "
472 "contain any instructions!", MBB);
473 } else if (!MBB->back().getDesc().isBarrier()) {
474 report("MBB exits via conditional branch/branch but doesn't end with a "
475 "barrier instruction!", MBB);
476 } else if (!MBB->back().getDesc().isTerminator()) {
477 report("MBB exits via conditional branch/branch but the branch "
478 "isn't a terminator instruction!", MBB);
480 if (Cond.empty()) {
481 report("MBB exits via conditinal branch/branch but there's no "
482 "condition!", MBB);
484 } else {
485 report("AnalyzeBranch returned invalid data!", MBB);
489 regsLive.clear();
490 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
491 E = MBB->livein_end(); I != E; ++I) {
492 if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
493 report("MBB live-in list contains non-physical register", MBB);
494 continue;
496 regsLive.insert(*I);
497 for (const unsigned *R = TRI->getSubRegisters(*I); *R; R++)
498 regsLive.insert(*R);
500 regsLiveInButUnused = regsLive;
502 const MachineFrameInfo *MFI = MF->getFrameInfo();
503 assert(MFI && "Function has no frame info");
504 BitVector PR = MFI->getPristineRegs(MBB);
505 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
506 regsLive.insert(I);
507 for (const unsigned *R = TRI->getSubRegisters(I); *R; R++)
508 regsLive.insert(*R);
511 regsKilled.clear();
512 regsDefined.clear();
515 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
516 const TargetInstrDesc &TI = MI->getDesc();
517 if (MI->getNumOperands() < TI.getNumOperands()) {
518 report("Too few operands", MI);
519 *OS << TI.getNumOperands() << " operands expected, but "
520 << MI->getNumExplicitOperands() << " given.\n";
523 // Check the MachineMemOperands for basic consistency.
524 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
525 E = MI->memoperands_end(); I != E; ++I) {
526 if ((*I)->isLoad() && !TI.mayLoad())
527 report("Missing mayLoad flag", MI);
528 if ((*I)->isStore() && !TI.mayStore())
529 report("Missing mayStore flag", MI);
532 // Debug values must not have a slot index.
533 // Other instructions must have one.
534 if (LiveInts) {
535 bool mapped = !LiveInts->isNotInMIMap(MI);
536 if (MI->isDebugValue()) {
537 if (mapped)
538 report("Debug instruction has a slot index", MI);
539 } else {
540 if (!mapped)
541 report("Missing slot index", MI);
547 void
548 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
549 const MachineInstr *MI = MO->getParent();
550 const TargetInstrDesc &TI = MI->getDesc();
552 // The first TI.NumDefs operands must be explicit register defines
553 if (MONum < TI.getNumDefs()) {
554 if (!MO->isReg())
555 report("Explicit definition must be a register", MO, MONum);
556 else if (!MO->isDef())
557 report("Explicit definition marked as use", MO, MONum);
558 else if (MO->isImplicit())
559 report("Explicit definition marked as implicit", MO, MONum);
560 } else if (MONum < TI.getNumOperands()) {
561 if (MO->isReg()) {
562 if (MO->isDef())
563 report("Explicit operand marked as def", MO, MONum);
564 if (MO->isImplicit())
565 report("Explicit operand marked as implicit", MO, MONum);
567 } else {
568 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
569 if (MO->isReg() && !MO->isImplicit() && !TI.isVariadic() && MO->getReg())
570 report("Extra explicit operand on non-variadic instruction", MO, MONum);
573 switch (MO->getType()) {
574 case MachineOperand::MO_Register: {
575 const unsigned Reg = MO->getReg();
576 if (!Reg)
577 return;
579 // Check Live Variables.
580 if (MO->isUndef()) {
581 // An <undef> doesn't refer to any register, so just skip it.
582 } else if (MO->isUse()) {
583 regsLiveInButUnused.erase(Reg);
585 bool isKill = false;
586 unsigned defIdx;
587 if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
588 // A two-addr use counts as a kill if use and def are the same.
589 unsigned DefReg = MI->getOperand(defIdx).getReg();
590 if (Reg == DefReg) {
591 isKill = true;
592 // And in that case an explicit kill flag is not allowed.
593 if (MO->isKill())
594 report("Illegal kill flag on two-address instruction operand",
595 MO, MONum);
596 } else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
597 report("Two-address instruction operands must be identical",
598 MO, MONum);
600 } else
601 isKill = MO->isKill();
603 if (isKill)
604 addRegWithSubRegs(regsKilled, Reg);
606 // Check that LiveVars knows this kill.
607 if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
608 MO->isKill()) {
609 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
610 if (std::find(VI.Kills.begin(),
611 VI.Kills.end(), MI) == VI.Kills.end())
612 report("Kill missing from LiveVariables", MO, MONum);
615 // Check LiveInts liveness and kill.
616 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
617 LiveInts && !LiveInts->isNotInMIMap(MI)) {
618 SlotIndex UseIdx = LiveInts->getInstructionIndex(MI).getUseIndex();
619 if (LiveInts->hasInterval(Reg)) {
620 const LiveInterval &LI = LiveInts->getInterval(Reg);
621 if (!LI.liveAt(UseIdx)) {
622 report("No live range at use", MO, MONum);
623 *OS << UseIdx << " is not live in " << LI << '\n';
625 // Verify isKill == LI.killedAt.
626 if (!MI->isRegTiedToDefOperand(MONum)) {
627 // MI could kill register without a kill flag on MO.
628 bool miKill = MI->killsRegister(Reg);
629 bool liKill = LI.killedAt(UseIdx.getDefIndex());
630 if (miKill && !liKill) {
631 report("Live range continues after kill flag", MO, MONum);
632 *OS << "Live range: " << LI << '\n';
634 if (!miKill && liKill) {
635 report("Live range ends without kill flag", MO, MONum);
636 *OS << "Live range: " << LI << '\n';
639 } else {
640 report("Virtual register has no Live interval", MO, MONum);
644 // Use of a dead register.
645 if (!regsLive.count(Reg)) {
646 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
647 // Reserved registers may be used even when 'dead'.
648 if (!isReserved(Reg))
649 report("Using an undefined physical register", MO, MONum);
650 } else {
651 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
652 // We don't know which virtual registers are live in, so only complain
653 // if vreg was killed in this MBB. Otherwise keep track of vregs that
654 // must be live in. PHI instructions are handled separately.
655 if (MInfo.regsKilled.count(Reg))
656 report("Using a killed virtual register", MO, MONum);
657 else if (!MI->isPHI())
658 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
661 } else {
662 assert(MO->isDef());
663 // Register defined.
664 // TODO: verify that earlyclobber ops are not used.
665 if (MO->isDead())
666 addRegWithSubRegs(regsDead, Reg);
667 else
668 addRegWithSubRegs(regsDefined, Reg);
670 // Check LiveInts for a live range, but only for virtual registers.
671 if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
672 !LiveInts->isNotInMIMap(MI)) {
673 SlotIndex DefIdx = LiveInts->getInstructionIndex(MI).getDefIndex();
674 if (LiveInts->hasInterval(Reg)) {
675 const LiveInterval &LI = LiveInts->getInterval(Reg);
676 if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
677 assert(VNI && "NULL valno is not allowed");
678 if (VNI->def != DefIdx) {
679 report("Inconsistent valno->def", MO, MONum);
680 *OS << "Valno " << VNI->id << " is not defined at "
681 << DefIdx << " in " << LI << '\n';
683 } else {
684 report("No live range at def", MO, MONum);
685 *OS << DefIdx << " is not live in " << LI << '\n';
687 } else {
688 report("Virtual register has no Live interval", MO, MONum);
693 // Check register classes.
694 if (MONum < TI.getNumOperands() && !MO->isImplicit()) {
695 const TargetOperandInfo &TOI = TI.OpInfo[MONum];
696 unsigned SubIdx = MO->getSubReg();
698 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
699 unsigned sr = Reg;
700 if (SubIdx) {
701 unsigned s = TRI->getSubReg(Reg, SubIdx);
702 if (!s) {
703 report("Invalid subregister index for physical register",
704 MO, MONum);
705 return;
707 sr = s;
709 if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
710 if (!DRC->contains(sr)) {
711 report("Illegal physical register for instruction", MO, MONum);
712 *OS << TRI->getName(sr) << " is not a "
713 << DRC->getName() << " register.\n";
716 } else {
717 // Virtual register.
718 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
719 if (SubIdx) {
720 const TargetRegisterClass *SRC = RC->getSubRegisterRegClass(SubIdx);
721 if (!SRC) {
722 report("Invalid subregister index for virtual register", MO, MONum);
723 *OS << "Register class " << RC->getName()
724 << " does not support subreg index " << SubIdx << "\n";
725 return;
727 RC = SRC;
729 if (const TargetRegisterClass *DRC = TOI.getRegClass(TRI)) {
730 if (RC != DRC && !RC->hasSuperClass(DRC)) {
731 report("Illegal virtual register for instruction", MO, MONum);
732 *OS << "Expected a " << DRC->getName() << " register, but got a "
733 << RC->getName() << " register\n";
738 break;
741 case MachineOperand::MO_MachineBasicBlock:
742 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
743 report("PHI operand is not in the CFG", MO, MONum);
744 break;
746 case MachineOperand::MO_FrameIndex:
747 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
748 LiveInts && !LiveInts->isNotInMIMap(MI)) {
749 LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
750 SlotIndex Idx = LiveInts->getInstructionIndex(MI);
751 if (TI.mayLoad() && !LI.liveAt(Idx.getUseIndex())) {
752 report("Instruction loads from dead spill slot", MO, MONum);
753 *OS << "Live stack: " << LI << '\n';
755 if (TI.mayStore() && !LI.liveAt(Idx.getDefIndex())) {
756 report("Instruction stores to dead spill slot", MO, MONum);
757 *OS << "Live stack: " << LI << '\n';
760 break;
762 default:
763 break;
767 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
768 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
769 set_union(MInfo.regsKilled, regsKilled);
770 set_subtract(regsLive, regsKilled); regsKilled.clear();
771 set_subtract(regsLive, regsDead); regsDead.clear();
772 set_union(regsLive, regsDefined); regsDefined.clear();
775 void
776 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
777 MBBInfoMap[MBB].regsLiveOut = regsLive;
778 regsLive.clear();
781 // Calculate the largest possible vregsPassed sets. These are the registers that
782 // can pass through an MBB live, but may not be live every time. It is assumed
783 // that all vregsPassed sets are empty before the call.
784 void MachineVerifier::calcRegsPassed() {
785 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
786 // have any vregsPassed.
787 DenseSet<const MachineBasicBlock*> todo;
788 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
789 MFI != MFE; ++MFI) {
790 const MachineBasicBlock &MBB(*MFI);
791 BBInfo &MInfo = MBBInfoMap[&MBB];
792 if (!MInfo.reachable)
793 continue;
794 for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
795 SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
796 BBInfo &SInfo = MBBInfoMap[*SuI];
797 if (SInfo.addPassed(MInfo.regsLiveOut))
798 todo.insert(*SuI);
802 // Iteratively push vregsPassed to successors. This will converge to the same
803 // final state regardless of DenseSet iteration order.
804 while (!todo.empty()) {
805 const MachineBasicBlock *MBB = *todo.begin();
806 todo.erase(MBB);
807 BBInfo &MInfo = MBBInfoMap[MBB];
808 for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
809 SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
810 if (*SuI == MBB)
811 continue;
812 BBInfo &SInfo = MBBInfoMap[*SuI];
813 if (SInfo.addPassed(MInfo.vregsPassed))
814 todo.insert(*SuI);
819 // Calculate the set of virtual registers that must be passed through each basic
820 // block in order to satisfy the requirements of successor blocks. This is very
821 // similar to calcRegsPassed, only backwards.
822 void MachineVerifier::calcRegsRequired() {
823 // First push live-in regs to predecessors' vregsRequired.
824 DenseSet<const MachineBasicBlock*> todo;
825 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
826 MFI != MFE; ++MFI) {
827 const MachineBasicBlock &MBB(*MFI);
828 BBInfo &MInfo = MBBInfoMap[&MBB];
829 for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
830 PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
831 BBInfo &PInfo = MBBInfoMap[*PrI];
832 if (PInfo.addRequired(MInfo.vregsLiveIn))
833 todo.insert(*PrI);
837 // Iteratively push vregsRequired to predecessors. This will converge to the
838 // same final state regardless of DenseSet iteration order.
839 while (!todo.empty()) {
840 const MachineBasicBlock *MBB = *todo.begin();
841 todo.erase(MBB);
842 BBInfo &MInfo = MBBInfoMap[MBB];
843 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
844 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
845 if (*PrI == MBB)
846 continue;
847 BBInfo &SInfo = MBBInfoMap[*PrI];
848 if (SInfo.addRequired(MInfo.vregsRequired))
849 todo.insert(*PrI);
854 // Check PHI instructions at the beginning of MBB. It is assumed that
855 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
856 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
857 for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
858 BBI != BBE && BBI->isPHI(); ++BBI) {
859 DenseSet<const MachineBasicBlock*> seen;
861 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
862 unsigned Reg = BBI->getOperand(i).getReg();
863 const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
864 if (!Pre->isSuccessor(MBB))
865 continue;
866 seen.insert(Pre);
867 BBInfo &PrInfo = MBBInfoMap[Pre];
868 if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
869 report("PHI operand is not live-out from predecessor",
870 &BBI->getOperand(i), i);
873 // Did we see all predecessors?
874 for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
875 PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
876 if (!seen.count(*PrI)) {
877 report("Missing PHI operand", BBI);
878 *OS << "BB#" << (*PrI)->getNumber()
879 << " is a predecessor according to the CFG.\n";
885 void MachineVerifier::visitMachineFunctionAfter() {
886 calcRegsPassed();
888 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
889 MFI != MFE; ++MFI) {
890 BBInfo &MInfo = MBBInfoMap[MFI];
892 // Skip unreachable MBBs.
893 if (!MInfo.reachable)
894 continue;
896 checkPHIOps(MFI);
899 // Now check liveness info if available
900 if (LiveVars || LiveInts)
901 calcRegsRequired();
902 if (LiveVars)
903 verifyLiveVariables();
904 if (LiveInts)
905 verifyLiveIntervals();
908 void MachineVerifier::verifyLiveVariables() {
909 assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
910 for (unsigned Reg = TargetRegisterInfo::FirstVirtualRegister,
911 RegE = MRI->getLastVirtReg()-1; Reg != RegE; ++Reg) {
912 LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
913 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
914 MFI != MFE; ++MFI) {
915 BBInfo &MInfo = MBBInfoMap[MFI];
917 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
918 if (MInfo.vregsRequired.count(Reg)) {
919 if (!VI.AliveBlocks.test(MFI->getNumber())) {
920 report("LiveVariables: Block missing from AliveBlocks", MFI);
921 *OS << "Virtual register %reg" << Reg
922 << " must be live through the block.\n";
924 } else {
925 if (VI.AliveBlocks.test(MFI->getNumber())) {
926 report("LiveVariables: Block should not be in AliveBlocks", MFI);
927 *OS << "Virtual register %reg" << Reg
928 << " is not needed live through the block.\n";
935 void MachineVerifier::verifyLiveIntervals() {
936 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
937 for (LiveIntervals::const_iterator LVI = LiveInts->begin(),
938 LVE = LiveInts->end(); LVI != LVE; ++LVI) {
939 const LiveInterval &LI = *LVI->second;
941 // Spilling and splitting may leave unused registers around. Skip them.
942 if (MRI->use_empty(LI.reg))
943 continue;
945 // Physical registers have much weirdness going on, mostly from coalescing.
946 // We should probably fix it, but for now just ignore them.
947 if (TargetRegisterInfo::isPhysicalRegister(LI.reg))
948 continue;
950 assert(LVI->first == LI.reg && "Invalid reg to interval mapping");
952 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
953 I!=E; ++I) {
954 VNInfo *VNI = *I;
955 const VNInfo *DefVNI = LI.getVNInfoAt(VNI->def);
957 if (!DefVNI) {
958 if (!VNI->isUnused()) {
959 report("Valno not live at def and not marked unused", MF);
960 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
962 continue;
965 if (VNI->isUnused())
966 continue;
968 if (DefVNI != VNI) {
969 report("Live range at def has different valno", MF);
970 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
971 << " where valno #" << DefVNI->id << " is live in " << LI << '\n';
972 continue;
975 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
976 if (!MBB) {
977 report("Invalid definition index", MF);
978 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
979 << " in " << LI << '\n';
980 continue;
983 if (VNI->isPHIDef()) {
984 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
985 report("PHIDef value is not defined at MBB start", MF);
986 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
987 << ", not at the beginning of BB#" << MBB->getNumber()
988 << " in " << LI << '\n';
990 } else {
991 // Non-PHI def.
992 if (!VNI->def.isDef()) {
993 report("Non-PHI def must be at a DEF slot", MF);
994 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
995 << " in " << LI << '\n';
997 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
998 if (!MI) {
999 report("No instruction at def index", MF);
1000 *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1001 << " in " << LI << '\n';
1002 } else if (!MI->modifiesRegister(LI.reg, TRI)) {
1003 report("Defining instruction does not modify register", MI);
1004 *OS << "Valno #" << VNI->id << " in " << LI << '\n';
1009 for (LiveInterval::const_iterator I = LI.begin(), E = LI.end(); I!=E; ++I) {
1010 const VNInfo *VNI = I->valno;
1011 assert(VNI && "Live range has no valno");
1013 if (VNI->id >= LI.getNumValNums() || VNI != LI.getValNumInfo(VNI->id)) {
1014 report("Foreign valno in live range", MF);
1015 I->print(*OS);
1016 *OS << " has a valno not in " << LI << '\n';
1019 if (VNI->isUnused()) {
1020 report("Live range valno is marked unused", MF);
1021 I->print(*OS);
1022 *OS << " in " << LI << '\n';
1025 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(I->start);
1026 if (!MBB) {
1027 report("Bad start of live segment, no basic block", MF);
1028 I->print(*OS);
1029 *OS << " in " << LI << '\n';
1030 continue;
1032 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1033 if (I->start != MBBStartIdx && I->start != VNI->def) {
1034 report("Live segment must begin at MBB entry or valno def", MBB);
1035 I->print(*OS);
1036 *OS << " in " << LI << '\n' << "Basic block starts at "
1037 << MBBStartIdx << '\n';
1040 const MachineBasicBlock *EndMBB =
1041 LiveInts->getMBBFromIndex(I->end.getPrevSlot());
1042 if (!EndMBB) {
1043 report("Bad end of live segment, no basic block", MF);
1044 I->print(*OS);
1045 *OS << " in " << LI << '\n';
1046 continue;
1048 if (I->end != LiveInts->getMBBEndIdx(EndMBB)) {
1049 // The live segment is ending inside EndMBB
1050 const MachineInstr *MI =
1051 LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
1052 if (!MI) {
1053 report("Live segment doesn't end at a valid instruction", EndMBB);
1054 I->print(*OS);
1055 *OS << " in " << LI << '\n' << "Basic block starts at "
1056 << MBBStartIdx << '\n';
1057 } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
1058 !MI->readsVirtualRegister(LI.reg)) {
1059 // FIXME: Should we require a kill flag?
1060 report("Instruction killing live segment doesn't read register", MI);
1061 I->print(*OS);
1062 *OS << " in " << LI << '\n';
1066 // Now check all the basic blocks in this live segment.
1067 MachineFunction::const_iterator MFI = MBB;
1068 // Is LI live-in to MBB and not a PHIDef?
1069 if (I->start == VNI->def) {
1070 // Not live-in to any blocks.
1071 if (MBB == EndMBB)
1072 continue;
1073 // Skip this block.
1074 ++MFI;
1076 for (;;) {
1077 assert(LiveInts->isLiveInToMBB(LI, MFI));
1078 // We don't know how to track physregs into a landing pad.
1079 if (TargetRegisterInfo::isPhysicalRegister(LI.reg) &&
1080 MFI->isLandingPad()) {
1081 if (&*MFI == EndMBB)
1082 break;
1083 ++MFI;
1084 continue;
1086 // Check that VNI is live-out of all predecessors.
1087 for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1088 PE = MFI->pred_end(); PI != PE; ++PI) {
1089 SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI).getPrevSlot();
1090 const VNInfo *PVNI = LI.getVNInfoAt(PEnd);
1091 if (!PVNI) {
1092 report("Register not marked live out of predecessor", *PI);
1093 *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1094 << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live at "
1095 << PEnd << " in " << LI << '\n';
1096 } else if (PVNI != VNI) {
1097 report("Different value live out of predecessor", *PI);
1098 *OS << "Valno #" << PVNI->id << " live out of BB#"
1099 << (*PI)->getNumber() << '@' << PEnd
1100 << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1101 << '@' << LiveInts->getMBBStartIdx(MFI) << " in " << LI << '\n';
1104 if (&*MFI == EndMBB)
1105 break;
1106 ++MFI;
1110 // Check the LI only has one connected component.
1111 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1112 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1113 unsigned NumComp = ConEQ.Classify(&LI);
1114 if (NumComp > 1) {
1115 report("Multiple connected components in live interval", MF);
1116 *OS << NumComp << " components in " << LI << '\n';
1117 for (unsigned comp = 0; comp != NumComp; ++comp) {
1118 *OS << comp << ": valnos";
1119 for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1120 E = LI.vni_end(); I!=E; ++I)
1121 if (comp == ConEQ.getEqClass(*I))
1122 *OS << ' ' << (*I)->id;
1123 *OS << '\n';