Change MachineVerifier to work on LiveRange + LiveInterval
[oota-llvm.git] / lib / CodeGen / MachineVerifier.cpp
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:
11 //
12 // Operand counts: All explicit operands must be present.
13 //
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
16 //
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
19 //
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 //===----------------------------------------------------------------------===//
25
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstrBundle.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/InlineAsm.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 using namespace llvm;
50
51 namespace {
52   struct MachineVerifier {
53
54     MachineVerifier(Pass *pass, const char *b) :
55       PASS(pass),
56       Banner(b),
57       OutFileName(getenv("LLVM_VERIFY_MACHINEINSTRS"))
58       {}
59
60     bool runOnMachineFunction(MachineFunction &MF);
61
62     Pass *const PASS;
63     const char *Banner;
64     const char *const OutFileName;
65     raw_ostream *OS;
66     const MachineFunction *MF;
67     const TargetMachine *TM;
68     const TargetInstrInfo *TII;
69     const TargetRegisterInfo *TRI;
70     const MachineRegisterInfo *MRI;
71
72     unsigned foundErrors;
73
74     typedef SmallVector<unsigned, 16> RegVector;
75     typedef SmallVector<const uint32_t*, 4> RegMaskVector;
76     typedef DenseSet<unsigned> RegSet;
77     typedef DenseMap<unsigned, const MachineInstr*> RegMap;
78     typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
79
80     const MachineInstr *FirstTerminator;
81     BlockSet FunctionBlocks;
82
83     BitVector regsReserved;
84     RegSet regsLive;
85     RegVector regsDefined, regsDead, regsKilled;
86     RegMaskVector regMasks;
87     RegSet regsLiveInButUnused;
88
89     SlotIndex lastIndex;
90
91     // Add Reg and any sub-registers to RV
92     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
93       RV.push_back(Reg);
94       if (TargetRegisterInfo::isPhysicalRegister(Reg))
95         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
96           RV.push_back(*SubRegs);
97     }
98
99     struct BBInfo {
100       // Is this MBB reachable from the MF entry point?
101       bool reachable;
102
103       // Vregs that must be live in because they are used without being
104       // defined. Map value is the user.
105       RegMap vregsLiveIn;
106
107       // Regs killed in MBB. They may be defined again, and will then be in both
108       // regsKilled and regsLiveOut.
109       RegSet regsKilled;
110
111       // Regs defined in MBB and live out. Note that vregs passing through may
112       // be live out without being mentioned here.
113       RegSet regsLiveOut;
114
115       // Vregs that pass through MBB untouched. This set is disjoint from
116       // regsKilled and regsLiveOut.
117       RegSet vregsPassed;
118
119       // Vregs that must pass through MBB because they are needed by a successor
120       // block. This set is disjoint from regsLiveOut.
121       RegSet vregsRequired;
122
123       // Set versions of block's predecessor and successor lists.
124       BlockSet Preds, Succs;
125
126       BBInfo() : reachable(false) {}
127
128       // Add register to vregsPassed if it belongs there. Return true if
129       // anything changed.
130       bool addPassed(unsigned Reg) {
131         if (!TargetRegisterInfo::isVirtualRegister(Reg))
132           return false;
133         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
134           return false;
135         return vregsPassed.insert(Reg).second;
136       }
137
138       // Same for a full set.
139       bool addPassed(const RegSet &RS) {
140         bool changed = false;
141         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
142           if (addPassed(*I))
143             changed = true;
144         return changed;
145       }
146
147       // Add register to vregsRequired if it belongs there. Return true if
148       // anything changed.
149       bool addRequired(unsigned Reg) {
150         if (!TargetRegisterInfo::isVirtualRegister(Reg))
151           return false;
152         if (regsLiveOut.count(Reg))
153           return false;
154         return vregsRequired.insert(Reg).second;
155       }
156
157       // Same for a full set.
158       bool addRequired(const RegSet &RS) {
159         bool changed = false;
160         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
161           if (addRequired(*I))
162             changed = true;
163         return changed;
164       }
165
166       // Same for a full map.
167       bool addRequired(const RegMap &RM) {
168         bool changed = false;
169         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
170           if (addRequired(I->first))
171             changed = true;
172         return changed;
173       }
174
175       // Live-out registers are either in regsLiveOut or vregsPassed.
176       bool isLiveOut(unsigned Reg) const {
177         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
178       }
179     };
180
181     // Extra register info per MBB.
182     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
183
184     bool isReserved(unsigned Reg) {
185       return Reg < regsReserved.size() && regsReserved.test(Reg);
186     }
187
188     bool isAllocatable(unsigned Reg) {
189       return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
190     }
191
192     // Analysis information if available
193     LiveVariables *LiveVars;
194     LiveIntervals *LiveInts;
195     LiveStacks *LiveStks;
196     SlotIndexes *Indexes;
197
198     void visitMachineFunctionBefore();
199     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
200     void visitMachineBundleBefore(const MachineInstr *MI);
201     void visitMachineInstrBefore(const MachineInstr *MI);
202     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
203     void visitMachineInstrAfter(const MachineInstr *MI);
204     void visitMachineBundleAfter(const MachineInstr *MI);
205     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
206     void visitMachineFunctionAfter();
207
208     void report(const char *msg, const MachineFunction *MF);
209     void report(const char *msg, const MachineBasicBlock *MBB);
210     void report(const char *msg, const MachineInstr *MI);
211     void report(const char *msg, const MachineOperand *MO, unsigned MONum);
212     void report(const char *msg, const MachineFunction *MF,
213                 const LiveInterval &LI);
214     void report(const char *msg, const MachineBasicBlock *MBB,
215                 const LiveInterval &LI);
216     void report(const char *msg, const MachineFunction *MF,
217                 const LiveRange &LR);
218     void report(const char *msg, const MachineBasicBlock *MBB,
219                 const LiveRange &LR);
220
221     void verifyInlineAsm(const MachineInstr *MI);
222
223     void checkLiveness(const MachineOperand *MO, unsigned MONum);
224     void markReachable(const MachineBasicBlock *MBB);
225     void calcRegsPassed();
226     void checkPHIOps(const MachineBasicBlock *MBB);
227
228     void calcRegsRequired();
229     void verifyLiveVariables();
230     void verifyLiveIntervals();
231     void verifyLiveInterval(const LiveInterval&);
232     void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned);
233     void verifyLiveRangeSegment(const LiveRange&,
234                                 const LiveRange::const_iterator I, unsigned);
235     void verifyLiveRange(const LiveRange&, unsigned);
236
237     void verifyStackFrame();
238   };
239
240   struct MachineVerifierPass : public MachineFunctionPass {
241     static char ID; // Pass ID, replacement for typeid
242     const char *const Banner;
243
244     MachineVerifierPass(const char *b = 0)
245       : MachineFunctionPass(ID), Banner(b) {
246         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
247       }
248
249     void getAnalysisUsage(AnalysisUsage &AU) const {
250       AU.setPreservesAll();
251       MachineFunctionPass::getAnalysisUsage(AU);
252     }
253
254     bool runOnMachineFunction(MachineFunction &MF) {
255       MF.verify(this, Banner);
256       return false;
257     }
258   };
259
260 }
261
262 char MachineVerifierPass::ID = 0;
263 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
264                 "Verify generated machine code", false, false)
265
266 FunctionPass *llvm::createMachineVerifierPass(const char *Banner) {
267   return new MachineVerifierPass(Banner);
268 }
269
270 void MachineFunction::verify(Pass *p, const char *Banner) const {
271   MachineVerifier(p, Banner)
272     .runOnMachineFunction(const_cast<MachineFunction&>(*this));
273 }
274
275 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
276   raw_ostream *OutFile = 0;
277   if (OutFileName) {
278     std::string ErrorInfo;
279     OutFile = new raw_fd_ostream(OutFileName, ErrorInfo, sys::fs::F_Append);
280     if (!ErrorInfo.empty()) {
281       errs() << "Error opening '" << OutFileName << "': " << ErrorInfo << '\n';
282       exit(1);
283     }
284
285     OS = OutFile;
286   } else {
287     OS = &errs();
288   }
289
290   foundErrors = 0;
291
292   this->MF = &MF;
293   TM = &MF.getTarget();
294   TII = TM->getInstrInfo();
295   TRI = TM->getRegisterInfo();
296   MRI = &MF.getRegInfo();
297
298   LiveVars = NULL;
299   LiveInts = NULL;
300   LiveStks = NULL;
301   Indexes = NULL;
302   if (PASS) {
303     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
304     // We don't want to verify LiveVariables if LiveIntervals is available.
305     if (!LiveInts)
306       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
307     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
308     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
309   }
310
311   visitMachineFunctionBefore();
312   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
313        MFI!=MFE; ++MFI) {
314     visitMachineBasicBlockBefore(MFI);
315     // Keep track of the current bundle header.
316     const MachineInstr *CurBundle = 0;
317     // Do we expect the next instruction to be part of the same bundle?
318     bool InBundle = false;
319
320     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
321            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
322       if (MBBI->getParent() != MFI) {
323         report("Bad instruction parent pointer", MFI);
324         *OS << "Instruction: " << *MBBI;
325         continue;
326       }
327
328       // Check for consistent bundle flags.
329       if (InBundle && !MBBI->isBundledWithPred())
330         report("Missing BundledPred flag, "
331                "BundledSucc was set on predecessor", MBBI);
332       if (!InBundle && MBBI->isBundledWithPred())
333         report("BundledPred flag is set, "
334                "but BundledSucc not set on predecessor", MBBI);
335
336       // Is this a bundle header?
337       if (!MBBI->isInsideBundle()) {
338         if (CurBundle)
339           visitMachineBundleAfter(CurBundle);
340         CurBundle = MBBI;
341         visitMachineBundleBefore(CurBundle);
342       } else if (!CurBundle)
343         report("No bundle header", MBBI);
344       visitMachineInstrBefore(MBBI);
345       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
346         visitMachineOperand(&MBBI->getOperand(I), I);
347       visitMachineInstrAfter(MBBI);
348
349       // Was this the last bundled instruction?
350       InBundle = MBBI->isBundledWithSucc();
351     }
352     if (CurBundle)
353       visitMachineBundleAfter(CurBundle);
354     if (InBundle)
355       report("BundledSucc flag set on last instruction in block", &MFI->back());
356     visitMachineBasicBlockAfter(MFI);
357   }
358   visitMachineFunctionAfter();
359
360   if (OutFile)
361     delete OutFile;
362   else if (foundErrors)
363     report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
364
365   // Clean up.
366   regsLive.clear();
367   regsDefined.clear();
368   regsDead.clear();
369   regsKilled.clear();
370   regMasks.clear();
371   regsLiveInButUnused.clear();
372   MBBInfoMap.clear();
373
374   return false;                 // no changes
375 }
376
377 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
378   assert(MF);
379   *OS << '\n';
380   if (!foundErrors++) {
381     if (Banner)
382       *OS << "# " << Banner << '\n';
383     MF->print(*OS, Indexes);
384   }
385   *OS << "*** Bad machine code: " << msg << " ***\n"
386       << "- function:    " << MF->getName() << "\n";
387 }
388
389 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
390   assert(MBB);
391   report(msg, MBB->getParent());
392   *OS << "- basic block: BB#" << MBB->getNumber()
393       << ' ' << MBB->getName()
394       << " (" << (const void*)MBB << ')';
395   if (Indexes)
396     *OS << " [" << Indexes->getMBBStartIdx(MBB)
397         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
398   *OS << '\n';
399 }
400
401 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
402   assert(MI);
403   report(msg, MI->getParent());
404   *OS << "- instruction: ";
405   if (Indexes && Indexes->hasIndex(MI))
406     *OS << Indexes->getInstructionIndex(MI) << '\t';
407   MI->print(*OS, TM);
408 }
409
410 void MachineVerifier::report(const char *msg,
411                              const MachineOperand *MO, unsigned MONum) {
412   assert(MO);
413   report(msg, MO->getParent());
414   *OS << "- operand " << MONum << ":   ";
415   MO->print(*OS, TM);
416   *OS << "\n";
417 }
418
419 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
420                              const LiveInterval &LI) {
421   report(msg, MF);
422   *OS << "- interval:    ";
423   if (TargetRegisterInfo::isVirtualRegister(LI.reg))
424     *OS << PrintReg(LI.reg, TRI);
425   else
426     *OS << PrintRegUnit(LI.reg, TRI);
427   *OS << ' ' << LI << '\n';
428 }
429
430 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
431                              const LiveInterval &LI) {
432   report(msg, MBB);
433   *OS << "- interval:    ";
434   if (TargetRegisterInfo::isVirtualRegister(LI.reg))
435     *OS << PrintReg(LI.reg, TRI);
436   else
437     *OS << PrintRegUnit(LI.reg, TRI);
438   *OS << ' ' << LI << '\n';
439 }
440
441 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
442                              const LiveRange &LR) {
443   report(msg, MBB);
444   *OS << "- liverange:    " << LR << "\n";
445 }
446
447 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
448                              const LiveRange &LR) {
449   report(msg, MF);
450   *OS << "- liverange:    " << LR << "\n";
451 }
452
453 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
454   BBInfo &MInfo = MBBInfoMap[MBB];
455   if (!MInfo.reachable) {
456     MInfo.reachable = true;
457     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
458            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
459       markReachable(*SuI);
460   }
461 }
462
463 void MachineVerifier::visitMachineFunctionBefore() {
464   lastIndex = SlotIndex();
465   regsReserved = MRI->getReservedRegs();
466
467   // A sub-register of a reserved register is also reserved
468   for (int Reg = regsReserved.find_first(); Reg>=0;
469        Reg = regsReserved.find_next(Reg)) {
470     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
471       // FIXME: This should probably be:
472       // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
473       regsReserved.set(*SubRegs);
474     }
475   }
476
477   markReachable(&MF->front());
478
479   // Build a set of the basic blocks in the function.
480   FunctionBlocks.clear();
481   for (MachineFunction::const_iterator
482        I = MF->begin(), E = MF->end(); I != E; ++I) {
483     FunctionBlocks.insert(I);
484     BBInfo &MInfo = MBBInfoMap[I];
485
486     MInfo.Preds.insert(I->pred_begin(), I->pred_end());
487     if (MInfo.Preds.size() != I->pred_size())
488       report("MBB has duplicate entries in its predecessor list.", I);
489
490     MInfo.Succs.insert(I->succ_begin(), I->succ_end());
491     if (MInfo.Succs.size() != I->succ_size())
492       report("MBB has duplicate entries in its successor list.", I);
493   }
494
495   // Check that the register use lists are sane.
496   MRI->verifyUseLists();
497
498   verifyStackFrame();
499 }
500
501 // Does iterator point to a and b as the first two elements?
502 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
503                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
504   if (*i == a)
505     return *++i == b;
506   if (*i == b)
507     return *++i == a;
508   return false;
509 }
510
511 void
512 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
513   FirstTerminator = 0;
514
515   if (MRI->isSSA()) {
516     // If this block has allocatable physical registers live-in, check that
517     // it is an entry block or landing pad.
518     for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
519            LE = MBB->livein_end();
520          LI != LE; ++LI) {
521       unsigned reg = *LI;
522       if (isAllocatable(reg) && !MBB->isLandingPad() &&
523           MBB != MBB->getParent()->begin()) {
524         report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
525       }
526     }
527   }
528
529   // Count the number of landing pad successors.
530   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
531   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
532        E = MBB->succ_end(); I != E; ++I) {
533     if ((*I)->isLandingPad())
534       LandingPadSuccs.insert(*I);
535     if (!FunctionBlocks.count(*I))
536       report("MBB has successor that isn't part of the function.", MBB);
537     if (!MBBInfoMap[*I].Preds.count(MBB)) {
538       report("Inconsistent CFG", MBB);
539       *OS << "MBB is not in the predecessor list of the successor BB#"
540           << (*I)->getNumber() << ".\n";
541     }
542   }
543
544   // Check the predecessor list.
545   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
546        E = MBB->pred_end(); I != E; ++I) {
547     if (!FunctionBlocks.count(*I))
548       report("MBB has predecessor that isn't part of the function.", MBB);
549     if (!MBBInfoMap[*I].Succs.count(MBB)) {
550       report("Inconsistent CFG", MBB);
551       *OS << "MBB is not in the successor list of the predecessor BB#"
552           << (*I)->getNumber() << ".\n";
553     }
554   }
555
556   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
557   const BasicBlock *BB = MBB->getBasicBlock();
558   if (LandingPadSuccs.size() > 1 &&
559       !(AsmInfo &&
560         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
561         BB && isa<SwitchInst>(BB->getTerminator())))
562     report("MBB has more than one landing pad successor", MBB);
563
564   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
565   MachineBasicBlock *TBB = 0, *FBB = 0;
566   SmallVector<MachineOperand, 4> Cond;
567   if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
568                           TBB, FBB, Cond)) {
569     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
570     // check whether its answers match up with reality.
571     if (!TBB && !FBB) {
572       // Block falls through to its successor.
573       MachineFunction::const_iterator MBBI = MBB;
574       ++MBBI;
575       if (MBBI == MF->end()) {
576         // It's possible that the block legitimately ends with a noreturn
577         // call or an unreachable, in which case it won't actually fall
578         // out the bottom of the function.
579       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
580         // It's possible that the block legitimately ends with a noreturn
581         // call or an unreachable, in which case it won't actuall fall
582         // out of the block.
583       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
584         report("MBB exits via unconditional fall-through but doesn't have "
585                "exactly one CFG successor!", MBB);
586       } else if (!MBB->isSuccessor(MBBI)) {
587         report("MBB exits via unconditional fall-through but its successor "
588                "differs from its CFG successor!", MBB);
589       }
590       if (!MBB->empty() && getBundleStart(&MBB->back())->isBarrier() &&
591           !TII->isPredicated(getBundleStart(&MBB->back()))) {
592         report("MBB exits via unconditional fall-through but ends with a "
593                "barrier instruction!", MBB);
594       }
595       if (!Cond.empty()) {
596         report("MBB exits via unconditional fall-through but has a condition!",
597                MBB);
598       }
599     } else if (TBB && !FBB && Cond.empty()) {
600       // Block unconditionally branches somewhere.
601       if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
602         report("MBB exits via unconditional branch but doesn't have "
603                "exactly one CFG successor!", MBB);
604       } else if (!MBB->isSuccessor(TBB)) {
605         report("MBB exits via unconditional branch but the CFG "
606                "successor doesn't match the actual successor!", MBB);
607       }
608       if (MBB->empty()) {
609         report("MBB exits via unconditional branch but doesn't contain "
610                "any instructions!", MBB);
611       } else if (!getBundleStart(&MBB->back())->isBarrier()) {
612         report("MBB exits via unconditional branch but doesn't end with a "
613                "barrier instruction!", MBB);
614       } else if (!getBundleStart(&MBB->back())->isTerminator()) {
615         report("MBB exits via unconditional branch but the branch isn't a "
616                "terminator instruction!", MBB);
617       }
618     } else if (TBB && !FBB && !Cond.empty()) {
619       // Block conditionally branches somewhere, otherwise falls through.
620       MachineFunction::const_iterator MBBI = MBB;
621       ++MBBI;
622       if (MBBI == MF->end()) {
623         report("MBB conditionally falls through out of function!", MBB);
624       } else if (MBB->succ_size() == 1) {
625         // A conditional branch with only one successor is weird, but allowed.
626         if (&*MBBI != TBB)
627           report("MBB exits via conditional branch/fall-through but only has "
628                  "one CFG successor!", MBB);
629         else if (TBB != *MBB->succ_begin())
630           report("MBB exits via conditional branch/fall-through but the CFG "
631                  "successor don't match the actual successor!", MBB);
632       } else if (MBB->succ_size() != 2) {
633         report("MBB exits via conditional branch/fall-through but doesn't have "
634                "exactly two CFG successors!", MBB);
635       } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
636         report("MBB exits via conditional branch/fall-through but the CFG "
637                "successors don't match the actual successors!", MBB);
638       }
639       if (MBB->empty()) {
640         report("MBB exits via conditional branch/fall-through but doesn't "
641                "contain any instructions!", MBB);
642       } else if (getBundleStart(&MBB->back())->isBarrier()) {
643         report("MBB exits via conditional branch/fall-through but ends with a "
644                "barrier instruction!", MBB);
645       } else if (!getBundleStart(&MBB->back())->isTerminator()) {
646         report("MBB exits via conditional branch/fall-through but the branch "
647                "isn't a terminator instruction!", MBB);
648       }
649     } else if (TBB && FBB) {
650       // Block conditionally branches somewhere, otherwise branches
651       // somewhere else.
652       if (MBB->succ_size() == 1) {
653         // A conditional branch with only one successor is weird, but allowed.
654         if (FBB != TBB)
655           report("MBB exits via conditional branch/branch through but only has "
656                  "one CFG successor!", MBB);
657         else if (TBB != *MBB->succ_begin())
658           report("MBB exits via conditional branch/branch through but the CFG "
659                  "successor don't match the actual successor!", MBB);
660       } else if (MBB->succ_size() != 2) {
661         report("MBB exits via conditional branch/branch but doesn't have "
662                "exactly two CFG successors!", MBB);
663       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
664         report("MBB exits via conditional branch/branch but the CFG "
665                "successors don't match the actual successors!", MBB);
666       }
667       if (MBB->empty()) {
668         report("MBB exits via conditional branch/branch but doesn't "
669                "contain any instructions!", MBB);
670       } else if (!getBundleStart(&MBB->back())->isBarrier()) {
671         report("MBB exits via conditional branch/branch but doesn't end with a "
672                "barrier instruction!", MBB);
673       } else if (!getBundleStart(&MBB->back())->isTerminator()) {
674         report("MBB exits via conditional branch/branch but the branch "
675                "isn't a terminator instruction!", MBB);
676       }
677       if (Cond.empty()) {
678         report("MBB exits via conditinal branch/branch but there's no "
679                "condition!", MBB);
680       }
681     } else {
682       report("AnalyzeBranch returned invalid data!", MBB);
683     }
684   }
685
686   regsLive.clear();
687   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
688          E = MBB->livein_end(); I != E; ++I) {
689     if (!TargetRegisterInfo::isPhysicalRegister(*I)) {
690       report("MBB live-in list contains non-physical register", MBB);
691       continue;
692     }
693     for (MCSubRegIterator SubRegs(*I, TRI, /*IncludeSelf=*/true);
694          SubRegs.isValid(); ++SubRegs)
695       regsLive.insert(*SubRegs);
696   }
697   regsLiveInButUnused = regsLive;
698
699   const MachineFrameInfo *MFI = MF->getFrameInfo();
700   assert(MFI && "Function has no frame info");
701   BitVector PR = MFI->getPristineRegs(MBB);
702   for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
703     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
704          SubRegs.isValid(); ++SubRegs)
705       regsLive.insert(*SubRegs);
706   }
707
708   regsKilled.clear();
709   regsDefined.clear();
710
711   if (Indexes)
712     lastIndex = Indexes->getMBBStartIdx(MBB);
713 }
714
715 // This function gets called for all bundle headers, including normal
716 // stand-alone unbundled instructions.
717 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
718   if (Indexes && Indexes->hasIndex(MI)) {
719     SlotIndex idx = Indexes->getInstructionIndex(MI);
720     if (!(idx > lastIndex)) {
721       report("Instruction index out of order", MI);
722       *OS << "Last instruction was at " << lastIndex << '\n';
723     }
724     lastIndex = idx;
725   }
726
727   // Ensure non-terminators don't follow terminators.
728   // Ignore predicated terminators formed by if conversion.
729   // FIXME: If conversion shouldn't need to violate this rule.
730   if (MI->isTerminator() && !TII->isPredicated(MI)) {
731     if (!FirstTerminator)
732       FirstTerminator = MI;
733   } else if (FirstTerminator) {
734     report("Non-terminator instruction after the first terminator", MI);
735     *OS << "First terminator was:\t" << *FirstTerminator;
736   }
737 }
738
739 // The operands on an INLINEASM instruction must follow a template.
740 // Verify that the flag operands make sense.
741 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
742   // The first two operands on INLINEASM are the asm string and global flags.
743   if (MI->getNumOperands() < 2) {
744     report("Too few operands on inline asm", MI);
745     return;
746   }
747   if (!MI->getOperand(0).isSymbol())
748     report("Asm string must be an external symbol", MI);
749   if (!MI->getOperand(1).isImm())
750     report("Asm flags must be an immediate", MI);
751   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
752   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
753   if (!isUInt<5>(MI->getOperand(1).getImm()))
754     report("Unknown asm flags", &MI->getOperand(1), 1);
755
756   assert(InlineAsm::MIOp_FirstOperand == 2 && "Asm format changed");
757
758   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
759   unsigned NumOps;
760   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
761     const MachineOperand &MO = MI->getOperand(OpNo);
762     // There may be implicit ops after the fixed operands.
763     if (!MO.isImm())
764       break;
765     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
766   }
767
768   if (OpNo > MI->getNumOperands())
769     report("Missing operands in last group", MI);
770
771   // An optional MDNode follows the groups.
772   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
773     ++OpNo;
774
775   // All trailing operands must be implicit registers.
776   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
777     const MachineOperand &MO = MI->getOperand(OpNo);
778     if (!MO.isReg() || !MO.isImplicit())
779       report("Expected implicit register after groups", &MO, OpNo);
780   }
781 }
782
783 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
784   const MCInstrDesc &MCID = MI->getDesc();
785   if (MI->getNumOperands() < MCID.getNumOperands()) {
786     report("Too few operands", MI);
787     *OS << MCID.getNumOperands() << " operands expected, but "
788         << MI->getNumExplicitOperands() << " given.\n";
789   }
790
791   // Check the tied operands.
792   if (MI->isInlineAsm())
793     verifyInlineAsm(MI);
794
795   // Check the MachineMemOperands for basic consistency.
796   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
797        E = MI->memoperands_end(); I != E; ++I) {
798     if ((*I)->isLoad() && !MI->mayLoad())
799       report("Missing mayLoad flag", MI);
800     if ((*I)->isStore() && !MI->mayStore())
801       report("Missing mayStore flag", MI);
802   }
803
804   // Debug values must not have a slot index.
805   // Other instructions must have one, unless they are inside a bundle.
806   if (LiveInts) {
807     bool mapped = !LiveInts->isNotInMIMap(MI);
808     if (MI->isDebugValue()) {
809       if (mapped)
810         report("Debug instruction has a slot index", MI);
811     } else if (MI->isInsideBundle()) {
812       if (mapped)
813         report("Instruction inside bundle has a slot index", MI);
814     } else {
815       if (!mapped)
816         report("Missing slot index", MI);
817     }
818   }
819
820   StringRef ErrorInfo;
821   if (!TII->verifyInstruction(MI, ErrorInfo))
822     report(ErrorInfo.data(), MI);
823 }
824
825 void
826 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
827   const MachineInstr *MI = MO->getParent();
828   const MCInstrDesc &MCID = MI->getDesc();
829
830   // The first MCID.NumDefs operands must be explicit register defines
831   if (MONum < MCID.getNumDefs()) {
832     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
833     if (!MO->isReg())
834       report("Explicit definition must be a register", MO, MONum);
835     else if (!MO->isDef() && !MCOI.isOptionalDef())
836       report("Explicit definition marked as use", MO, MONum);
837     else if (MO->isImplicit())
838       report("Explicit definition marked as implicit", MO, MONum);
839   } else if (MONum < MCID.getNumOperands()) {
840     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
841     // Don't check if it's the last operand in a variadic instruction. See,
842     // e.g., LDM_RET in the arm back end.
843     if (MO->isReg() &&
844         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
845       if (MO->isDef() && !MCOI.isOptionalDef())
846         report("Explicit operand marked as def", MO, MONum);
847       if (MO->isImplicit())
848         report("Explicit operand marked as implicit", MO, MONum);
849     }
850
851     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
852     if (TiedTo != -1) {
853       if (!MO->isReg())
854         report("Tied use must be a register", MO, MONum);
855       else if (!MO->isTied())
856         report("Operand should be tied", MO, MONum);
857       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
858         report("Tied def doesn't match MCInstrDesc", MO, MONum);
859     } else if (MO->isReg() && MO->isTied())
860       report("Explicit operand should not be tied", MO, MONum);
861   } else {
862     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
863     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
864       report("Extra explicit operand on non-variadic instruction", MO, MONum);
865   }
866
867   switch (MO->getType()) {
868   case MachineOperand::MO_Register: {
869     const unsigned Reg = MO->getReg();
870     if (!Reg)
871       return;
872     if (MRI->tracksLiveness() && !MI->isDebugValue())
873       checkLiveness(MO, MONum);
874
875     // Verify the consistency of tied operands.
876     if (MO->isTied()) {
877       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
878       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
879       if (!OtherMO.isReg())
880         report("Must be tied to a register", MO, MONum);
881       if (!OtherMO.isTied())
882         report("Missing tie flags on tied operand", MO, MONum);
883       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
884         report("Inconsistent tie links", MO, MONum);
885       if (MONum < MCID.getNumDefs()) {
886         if (OtherIdx < MCID.getNumOperands()) {
887           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
888             report("Explicit def tied to explicit use without tie constraint",
889                    MO, MONum);
890         } else {
891           if (!OtherMO.isImplicit())
892             report("Explicit def should be tied to implicit use", MO, MONum);
893         }
894       }
895     }
896
897     // Verify two-address constraints after leaving SSA form.
898     unsigned DefIdx;
899     if (!MRI->isSSA() && MO->isUse() &&
900         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
901         Reg != MI->getOperand(DefIdx).getReg())
902       report("Two-address instruction operands must be identical", MO, MONum);
903
904     // Check register classes.
905     if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
906       unsigned SubIdx = MO->getSubReg();
907
908       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
909         if (SubIdx) {
910           report("Illegal subregister index for physical register", MO, MONum);
911           return;
912         }
913         if (const TargetRegisterClass *DRC =
914               TII->getRegClass(MCID, MONum, TRI, *MF)) {
915           if (!DRC->contains(Reg)) {
916             report("Illegal physical register for instruction", MO, MONum);
917             *OS << TRI->getName(Reg) << " is not a "
918                 << DRC->getName() << " register.\n";
919           }
920         }
921       } else {
922         // Virtual register.
923         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
924         if (SubIdx) {
925           const TargetRegisterClass *SRC =
926             TRI->getSubClassWithSubReg(RC, SubIdx);
927           if (!SRC) {
928             report("Invalid subregister index for virtual register", MO, MONum);
929             *OS << "Register class " << RC->getName()
930                 << " does not support subreg index " << SubIdx << "\n";
931             return;
932           }
933           if (RC != SRC) {
934             report("Invalid register class for subregister index", MO, MONum);
935             *OS << "Register class " << RC->getName()
936                 << " does not fully support subreg index " << SubIdx << "\n";
937             return;
938           }
939         }
940         if (const TargetRegisterClass *DRC =
941               TII->getRegClass(MCID, MONum, TRI, *MF)) {
942           if (SubIdx) {
943             const TargetRegisterClass *SuperRC =
944               TRI->getLargestLegalSuperClass(RC);
945             if (!SuperRC) {
946               report("No largest legal super class exists.", MO, MONum);
947               return;
948             }
949             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
950             if (!DRC) {
951               report("No matching super-reg register class.", MO, MONum);
952               return;
953             }
954           }
955           if (!RC->hasSuperClassEq(DRC)) {
956             report("Illegal virtual register for instruction", MO, MONum);
957             *OS << "Expected a " << DRC->getName() << " register, but got a "
958                 << RC->getName() << " register\n";
959           }
960         }
961       }
962     }
963     break;
964   }
965
966   case MachineOperand::MO_RegisterMask:
967     regMasks.push_back(MO->getRegMask());
968     break;
969
970   case MachineOperand::MO_MachineBasicBlock:
971     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
972       report("PHI operand is not in the CFG", MO, MONum);
973     break;
974
975   case MachineOperand::MO_FrameIndex:
976     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
977         LiveInts && !LiveInts->isNotInMIMap(MI)) {
978       LiveInterval &LI = LiveStks->getInterval(MO->getIndex());
979       SlotIndex Idx = LiveInts->getInstructionIndex(MI);
980       if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
981         report("Instruction loads from dead spill slot", MO, MONum);
982         *OS << "Live stack: " << LI << '\n';
983       }
984       if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
985         report("Instruction stores to dead spill slot", MO, MONum);
986         *OS << "Live stack: " << LI << '\n';
987       }
988     }
989     break;
990
991   default:
992     break;
993   }
994 }
995
996 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
997   const MachineInstr *MI = MO->getParent();
998   const unsigned Reg = MO->getReg();
999
1000   // Both use and def operands can read a register.
1001   if (MO->readsReg()) {
1002     regsLiveInButUnused.erase(Reg);
1003
1004     if (MO->isKill())
1005       addRegWithSubRegs(regsKilled, Reg);
1006
1007     // Check that LiveVars knows this kill.
1008     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1009         MO->isKill()) {
1010       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1011       if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1012         report("Kill missing from LiveVariables", MO, MONum);
1013     }
1014
1015     // Check LiveInts liveness and kill.
1016     if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1017       SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1018       // Check the cached regunit intervals.
1019       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1020         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1021           if (const LiveInterval *LI = LiveInts->getCachedRegUnit(*Units)) {
1022             LiveQueryResult LRQ = LI->Query(UseIdx);
1023             if (!LRQ.valueIn()) {
1024               report("No live segment at use", MO, MONum);
1025               *OS << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1026                   << ' ' << *LI << '\n';
1027             }
1028             if (MO->isKill() && !LRQ.isKill()) {
1029               report("Live range continues after kill flag", MO, MONum);
1030               *OS << PrintRegUnit(*Units, TRI) << ' ' << *LI << '\n';
1031             }
1032           }
1033         }
1034       }
1035
1036       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1037         if (LiveInts->hasInterval(Reg)) {
1038           // This is a virtual register interval.
1039           const LiveInterval &LI = LiveInts->getInterval(Reg);
1040           LiveQueryResult LRQ = LI.Query(UseIdx);
1041           if (!LRQ.valueIn()) {
1042             report("No live segment at use", MO, MONum);
1043             *OS << UseIdx << " is not live in " << LI << '\n';
1044           }
1045           // Check for extra kill flags.
1046           // Note that we allow missing kill flags for now.
1047           if (MO->isKill() && !LRQ.isKill()) {
1048             report("Live range continues after kill flag", MO, MONum);
1049             *OS << "Live range: " << LI << '\n';
1050           }
1051         } else {
1052           report("Virtual register has no live interval", MO, MONum);
1053         }
1054       }
1055     }
1056
1057     // Use of a dead register.
1058     if (!regsLive.count(Reg)) {
1059       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1060         // Reserved registers may be used even when 'dead'.
1061         if (!isReserved(Reg))
1062           report("Using an undefined physical register", MO, MONum);
1063       } else if (MRI->def_empty(Reg)) {
1064         report("Reading virtual register without a def", MO, MONum);
1065       } else {
1066         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1067         // We don't know which virtual registers are live in, so only complain
1068         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1069         // must be live in. PHI instructions are handled separately.
1070         if (MInfo.regsKilled.count(Reg))
1071           report("Using a killed virtual register", MO, MONum);
1072         else if (!MI->isPHI())
1073           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1074       }
1075     }
1076   }
1077
1078   if (MO->isDef()) {
1079     // Register defined.
1080     // TODO: verify that earlyclobber ops are not used.
1081     if (MO->isDead())
1082       addRegWithSubRegs(regsDead, Reg);
1083     else
1084       addRegWithSubRegs(regsDefined, Reg);
1085
1086     // Verify SSA form.
1087     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1088         llvm::next(MRI->def_begin(Reg)) != MRI->def_end())
1089       report("Multiple virtual register defs in SSA form", MO, MONum);
1090
1091     // Check LiveInts for a live segment, but only for virtual registers.
1092     if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1093         !LiveInts->isNotInMIMap(MI)) {
1094       SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1095       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1096       if (LiveInts->hasInterval(Reg)) {
1097         const LiveInterval &LI = LiveInts->getInterval(Reg);
1098         if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1099           assert(VNI && "NULL valno is not allowed");
1100           if (VNI->def != DefIdx) {
1101             report("Inconsistent valno->def", MO, MONum);
1102             *OS << "Valno " << VNI->id << " is not defined at "
1103               << DefIdx << " in " << LI << '\n';
1104           }
1105         } else {
1106           report("No live segment at def", MO, MONum);
1107           *OS << DefIdx << " is not live in " << LI << '\n';
1108         }
1109       } else {
1110         report("Virtual register has no Live interval", MO, MONum);
1111       }
1112     }
1113   }
1114 }
1115
1116 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1117 }
1118
1119 // This function gets called after visiting all instructions in a bundle. The
1120 // argument points to the bundle header.
1121 // Normal stand-alone instructions are also considered 'bundles', and this
1122 // function is called for all of them.
1123 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1124   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1125   set_union(MInfo.regsKilled, regsKilled);
1126   set_subtract(regsLive, regsKilled); regsKilled.clear();
1127   // Kill any masked registers.
1128   while (!regMasks.empty()) {
1129     const uint32_t *Mask = regMasks.pop_back_val();
1130     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1131       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1132           MachineOperand::clobbersPhysReg(Mask, *I))
1133         regsDead.push_back(*I);
1134   }
1135   set_subtract(regsLive, regsDead);   regsDead.clear();
1136   set_union(regsLive, regsDefined);   regsDefined.clear();
1137 }
1138
1139 void
1140 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1141   MBBInfoMap[MBB].regsLiveOut = regsLive;
1142   regsLive.clear();
1143
1144   if (Indexes) {
1145     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1146     if (!(stop > lastIndex)) {
1147       report("Block ends before last instruction index", MBB);
1148       *OS << "Block ends at " << stop
1149           << " last instruction was at " << lastIndex << '\n';
1150     }
1151     lastIndex = stop;
1152   }
1153 }
1154
1155 // Calculate the largest possible vregsPassed sets. These are the registers that
1156 // can pass through an MBB live, but may not be live every time. It is assumed
1157 // that all vregsPassed sets are empty before the call.
1158 void MachineVerifier::calcRegsPassed() {
1159   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1160   // have any vregsPassed.
1161   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1162   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1163        MFI != MFE; ++MFI) {
1164     const MachineBasicBlock &MBB(*MFI);
1165     BBInfo &MInfo = MBBInfoMap[&MBB];
1166     if (!MInfo.reachable)
1167       continue;
1168     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1169            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1170       BBInfo &SInfo = MBBInfoMap[*SuI];
1171       if (SInfo.addPassed(MInfo.regsLiveOut))
1172         todo.insert(*SuI);
1173     }
1174   }
1175
1176   // Iteratively push vregsPassed to successors. This will converge to the same
1177   // final state regardless of DenseSet iteration order.
1178   while (!todo.empty()) {
1179     const MachineBasicBlock *MBB = *todo.begin();
1180     todo.erase(MBB);
1181     BBInfo &MInfo = MBBInfoMap[MBB];
1182     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1183            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1184       if (*SuI == MBB)
1185         continue;
1186       BBInfo &SInfo = MBBInfoMap[*SuI];
1187       if (SInfo.addPassed(MInfo.vregsPassed))
1188         todo.insert(*SuI);
1189     }
1190   }
1191 }
1192
1193 // Calculate the set of virtual registers that must be passed through each basic
1194 // block in order to satisfy the requirements of successor blocks. This is very
1195 // similar to calcRegsPassed, only backwards.
1196 void MachineVerifier::calcRegsRequired() {
1197   // First push live-in regs to predecessors' vregsRequired.
1198   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1199   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1200        MFI != MFE; ++MFI) {
1201     const MachineBasicBlock &MBB(*MFI);
1202     BBInfo &MInfo = MBBInfoMap[&MBB];
1203     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1204            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1205       BBInfo &PInfo = MBBInfoMap[*PrI];
1206       if (PInfo.addRequired(MInfo.vregsLiveIn))
1207         todo.insert(*PrI);
1208     }
1209   }
1210
1211   // Iteratively push vregsRequired to predecessors. This will converge to the
1212   // same final state regardless of DenseSet iteration order.
1213   while (!todo.empty()) {
1214     const MachineBasicBlock *MBB = *todo.begin();
1215     todo.erase(MBB);
1216     BBInfo &MInfo = MBBInfoMap[MBB];
1217     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1218            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1219       if (*PrI == MBB)
1220         continue;
1221       BBInfo &SInfo = MBBInfoMap[*PrI];
1222       if (SInfo.addRequired(MInfo.vregsRequired))
1223         todo.insert(*PrI);
1224     }
1225   }
1226 }
1227
1228 // Check PHI instructions at the beginning of MBB. It is assumed that
1229 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1230 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1231   SmallPtrSet<const MachineBasicBlock*, 8> seen;
1232   for (MachineBasicBlock::const_iterator BBI = MBB->begin(), BBE = MBB->end();
1233        BBI != BBE && BBI->isPHI(); ++BBI) {
1234     seen.clear();
1235
1236     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
1237       unsigned Reg = BBI->getOperand(i).getReg();
1238       const MachineBasicBlock *Pre = BBI->getOperand(i + 1).getMBB();
1239       if (!Pre->isSuccessor(MBB))
1240         continue;
1241       seen.insert(Pre);
1242       BBInfo &PrInfo = MBBInfoMap[Pre];
1243       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1244         report("PHI operand is not live-out from predecessor",
1245                &BBI->getOperand(i), i);
1246     }
1247
1248     // Did we see all predecessors?
1249     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1250            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1251       if (!seen.count(*PrI)) {
1252         report("Missing PHI operand", BBI);
1253         *OS << "BB#" << (*PrI)->getNumber()
1254             << " is a predecessor according to the CFG.\n";
1255       }
1256     }
1257   }
1258 }
1259
1260 void MachineVerifier::visitMachineFunctionAfter() {
1261   calcRegsPassed();
1262
1263   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1264        MFI != MFE; ++MFI) {
1265     BBInfo &MInfo = MBBInfoMap[MFI];
1266
1267     // Skip unreachable MBBs.
1268     if (!MInfo.reachable)
1269       continue;
1270
1271     checkPHIOps(MFI);
1272   }
1273
1274   // Now check liveness info if available
1275   calcRegsRequired();
1276
1277   // Check for killed virtual registers that should be live out.
1278   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1279        MFI != MFE; ++MFI) {
1280     BBInfo &MInfo = MBBInfoMap[MFI];
1281     for (RegSet::iterator
1282          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1283          ++I)
1284       if (MInfo.regsKilled.count(*I)) {
1285         report("Virtual register killed in block, but needed live out.", MFI);
1286         *OS << "Virtual register " << PrintReg(*I)
1287             << " is used after the block.\n";
1288       }
1289   }
1290
1291   if (!MF->empty()) {
1292     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1293     for (RegSet::iterator
1294          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1295          ++I)
1296       report("Virtual register def doesn't dominate all uses.",
1297              MRI->getVRegDef(*I));
1298   }
1299
1300   if (LiveVars)
1301     verifyLiveVariables();
1302   if (LiveInts)
1303     verifyLiveIntervals();
1304 }
1305
1306 void MachineVerifier::verifyLiveVariables() {
1307   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1308   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1309     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1310     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1311     for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
1312          MFI != MFE; ++MFI) {
1313       BBInfo &MInfo = MBBInfoMap[MFI];
1314
1315       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1316       if (MInfo.vregsRequired.count(Reg)) {
1317         if (!VI.AliveBlocks.test(MFI->getNumber())) {
1318           report("LiveVariables: Block missing from AliveBlocks", MFI);
1319           *OS << "Virtual register " << PrintReg(Reg)
1320               << " must be live through the block.\n";
1321         }
1322       } else {
1323         if (VI.AliveBlocks.test(MFI->getNumber())) {
1324           report("LiveVariables: Block should not be in AliveBlocks", MFI);
1325           *OS << "Virtual register " << PrintReg(Reg)
1326               << " is not needed live through the block.\n";
1327         }
1328       }
1329     }
1330   }
1331 }
1332
1333 void MachineVerifier::verifyLiveIntervals() {
1334   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1335   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1336     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1337
1338     // Spilling and splitting may leave unused registers around. Skip them.
1339     if (MRI->reg_nodbg_empty(Reg))
1340       continue;
1341
1342     if (!LiveInts->hasInterval(Reg)) {
1343       report("Missing live interval for virtual register", MF);
1344       *OS << PrintReg(Reg, TRI) << " still has defs or uses\n";
1345       continue;
1346     }
1347
1348     const LiveInterval &LI = LiveInts->getInterval(Reg);
1349     assert(Reg == LI.reg && "Invalid reg to interval mapping");
1350     verifyLiveInterval(LI);
1351   }
1352
1353   // Verify all the cached regunit intervals.
1354   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1355     if (const LiveInterval *LI = LiveInts->getCachedRegUnit(i))
1356       verifyLiveInterval(*LI);
1357 }
1358
1359 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1360                                            const VNInfo *VNI,
1361                                            unsigned Reg) {
1362   if (VNI->isUnused())
1363     return;
1364
1365   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1366
1367   if (!DefVNI) {
1368     report("Valno not live at def and not marked unused", MF, LR);
1369     *OS << "Valno #" << VNI->id << '\n';
1370     return;
1371   }
1372
1373   if (DefVNI != VNI) {
1374     report("Live segment at def has different valno", MF, LR);
1375     *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1376         << " where valno #" << DefVNI->id << " is live\n";
1377     return;
1378   }
1379
1380   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1381   if (!MBB) {
1382     report("Invalid definition index", MF, LR);
1383     *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1384         << " in " << LR << '\n';
1385     return;
1386   }
1387
1388   if (VNI->isPHIDef()) {
1389     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1390       report("PHIDef value is not defined at MBB start", MBB, LR);
1391       *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
1392           << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1393     }
1394     return;
1395   }
1396
1397   // Non-PHI def.
1398   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1399   if (!MI) {
1400     report("No instruction at def index", MBB, LR);
1401     *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1402     return;
1403   }
1404
1405   if (Reg != 0) {
1406     bool hasDef = false;
1407     bool isEarlyClobber = false;
1408     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1409       if (!MOI->isReg() || !MOI->isDef())
1410         continue;
1411       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1412         if (MOI->getReg() != Reg)
1413           continue;
1414       } else {
1415         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1416             !TRI->hasRegUnit(MOI->getReg(), Reg))
1417           continue;
1418       }
1419       hasDef = true;
1420       if (MOI->isEarlyClobber())
1421         isEarlyClobber = true;
1422     }
1423
1424     if (!hasDef) {
1425       report("Defining instruction does not modify register", MI);
1426       *OS << "Valno #" << VNI->id << " in " << LR << '\n';
1427     }
1428
1429     // Early clobber defs begin at USE slots, but other defs must begin at
1430     // DEF slots.
1431     if (isEarlyClobber) {
1432       if (!VNI->def.isEarlyClobber()) {
1433         report("Early clobber def must be at an early-clobber slot", MBB, LR);
1434         *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1435       }
1436     } else if (!VNI->def.isRegister()) {
1437       report("Non-PHI, non-early clobber def must be at a register slot",
1438              MBB, LR);
1439       *OS << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1440     }
1441   }
1442 }
1443
1444 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1445                                              const LiveRange::const_iterator I,
1446                                              unsigned Reg) {
1447   const LiveRange::Segment &S = *I;
1448   const VNInfo *VNI = S.valno;
1449   assert(VNI && "Live segment has no valno");
1450
1451   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1452     report("Foreign valno in live segment", MF, LR);
1453     *OS << S << " has a bad valno\n";
1454   }
1455
1456   if (VNI->isUnused()) {
1457     report("Live segment valno is marked unused", MF, LR);
1458     *OS << S << '\n';
1459   }
1460
1461   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1462   if (!MBB) {
1463     report("Bad start of live segment, no basic block", MF, LR);
1464     *OS << S << '\n';
1465     return;
1466   }
1467   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1468   if (S.start != MBBStartIdx && S.start != VNI->def) {
1469     report("Live segment must begin at MBB entry or valno def", MBB, LR);
1470     *OS << S << '\n';
1471   }
1472
1473   const MachineBasicBlock *EndMBB =
1474     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1475   if (!EndMBB) {
1476     report("Bad end of live segment, no basic block", MF, LR);
1477     *OS << S << '\n';
1478     return;
1479   }
1480
1481   // No more checks for live-out segments.
1482   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1483     return;
1484
1485   // RegUnit intervals are allowed dead phis.
1486   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1487       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1488     return;
1489
1490   // The live segment is ending inside EndMBB
1491   const MachineInstr *MI =
1492     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1493   if (!MI) {
1494     report("Live segment doesn't end at a valid instruction", EndMBB, LR);
1495     *OS << S << '\n';
1496     return;
1497   }
1498
1499   // The block slot must refer to a basic block boundary.
1500   if (S.end.isBlock()) {
1501     report("Live segment ends at B slot of an instruction", EndMBB, LR);
1502     *OS << S << '\n';
1503   }
1504
1505   if (S.end.isDead()) {
1506     // Segment ends on the dead slot.
1507     // That means there must be a dead def.
1508     if (!SlotIndex::isSameInstr(S.start, S.end)) {
1509       report("Live segment ending at dead slot spans instructions", EndMBB, LR);
1510       *OS << S << '\n';
1511     }
1512   }
1513
1514   // A live segment can only end at an early-clobber slot if it is being
1515   // redefined by an early-clobber def.
1516   if (S.end.isEarlyClobber()) {
1517     if (I+1 == LR.end() || (I+1)->start != S.end) {
1518       report("Live segment ending at early clobber slot must be "
1519              "redefined by an EC def in the same instruction", EndMBB, LR);
1520       *OS << S << '\n';
1521     }
1522   }
1523
1524   // The following checks only apply to virtual registers. Physreg liveness
1525   // is too weird to check.
1526   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1527     // A live segment can end with either a redefinition, a kill flag on a
1528     // use, or a dead flag on a def.
1529     bool hasRead = false;
1530     bool hasDeadDef = false;
1531     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1532       if (!MOI->isReg() || MOI->getReg() != Reg)
1533         continue;
1534       if (MOI->readsReg())
1535         hasRead = true;
1536       if (MOI->isDef() && MOI->isDead())
1537         hasDeadDef = true;
1538     }
1539
1540     if (S.end.isDead()) {
1541       if (!hasDeadDef) {
1542         report("Instruction doesn't have a dead def operand", MI);
1543         *OS << S << " in " << LR << '\n';
1544       }
1545     } else {
1546       if (!hasRead) {
1547         report("Instruction ending live segment doesn't read the register", MI);
1548         *OS << S << " in " << LR << '\n';
1549       }
1550     }
1551   }
1552
1553   // Now check all the basic blocks in this live segment.
1554   MachineFunction::const_iterator MFI = MBB;
1555   // Is this live segment the beginning of a non-PHIDef VN?
1556   if (S.start == VNI->def && !VNI->isPHIDef()) {
1557     // Not live-in to any blocks.
1558     if (MBB == EndMBB)
1559       return;
1560     // Skip this block.
1561     ++MFI;
1562   }
1563   for (;;) {
1564     assert(LiveInts->isLiveInToMBB(LR, MFI));
1565     // We don't know how to track physregs into a landing pad.
1566     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1567         MFI->isLandingPad()) {
1568       if (&*MFI == EndMBB)
1569         break;
1570       ++MFI;
1571       continue;
1572     }
1573
1574     // Is VNI a PHI-def in the current block?
1575     bool IsPHI = VNI->isPHIDef() &&
1576       VNI->def == LiveInts->getMBBStartIdx(MFI);
1577
1578     // Check that VNI is live-out of all predecessors.
1579     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1580          PE = MFI->pred_end(); PI != PE; ++PI) {
1581       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1582       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1583
1584       // All predecessors must have a live-out value.
1585       if (!PVNI) {
1586         report("Register not marked live out of predecessor", *PI, LR);
1587         *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1588             << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
1589             << PEnd << '\n';
1590         continue;
1591       }
1592
1593       // Only PHI-defs can take different predecessor values.
1594       if (!IsPHI && PVNI != VNI) {
1595         report("Different value live out of predecessor", *PI, LR);
1596         *OS << "Valno #" << PVNI->id << " live out of BB#"
1597             << (*PI)->getNumber() << '@' << PEnd
1598             << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
1599             << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
1600       }
1601     }
1602     if (&*MFI == EndMBB)
1603       break;
1604     ++MFI;
1605   }
1606 }
1607
1608 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg) {
1609   for (LiveRange::const_vni_iterator I = LR.vni_begin(), E = LR.vni_end();
1610        I != E; ++I)
1611     verifyLiveRangeValue(LR, *I, Reg);
1612
1613   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1614     verifyLiveRangeSegment(LR, I, Reg);
1615 }
1616
1617 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1618   verifyLiveRange(LI, LI.reg);
1619
1620   // Check the LI only has one connected component.
1621   if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1622     ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1623     unsigned NumComp = ConEQ.Classify(&LI);
1624     if (NumComp > 1) {
1625       report("Multiple connected components in live interval", MF, LI);
1626       for (unsigned comp = 0; comp != NumComp; ++comp) {
1627         *OS << comp << ": valnos";
1628         for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1629              E = LI.vni_end(); I!=E; ++I)
1630           if (comp == ConEQ.getEqClass(*I))
1631             *OS << ' ' << (*I)->id;
1632         *OS << '\n';
1633       }
1634     }
1635   }
1636 }
1637
1638 namespace {
1639   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1640   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1641   // value is zero.
1642   // We use a bool plus an integer to capture the stack state.
1643   struct StackStateOfBB {
1644     StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1645       ExitIsSetup(false) { }
1646     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1647       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1648       ExitIsSetup(ExitSetup) { }
1649     // Can be negative, which means we are setting up a frame.
1650     int EntryValue;
1651     int ExitValue;
1652     bool EntryIsSetup;
1653     bool ExitIsSetup;
1654   };
1655 }
1656
1657 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1658 /// by a FrameDestroy <n>, stack adjustments are identical on all
1659 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1660 void MachineVerifier::verifyStackFrame() {
1661   int FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
1662   int FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1663
1664   SmallVector<StackStateOfBB, 8> SPState;
1665   SPState.resize(MF->getNumBlockIDs());
1666   SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1667
1668   // Visit the MBBs in DFS order.
1669   for (df_ext_iterator<const MachineFunction*,
1670                        SmallPtrSet<const MachineBasicBlock*, 8> >
1671        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1672        DFI != DFE; ++DFI) {
1673     const MachineBasicBlock *MBB = *DFI;
1674
1675     StackStateOfBB BBState;
1676     // Check the exit state of the DFS stack predecessor.
1677     if (DFI.getPathLength() >= 2) {
1678       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1679       assert(Reachable.count(StackPred) &&
1680              "DFS stack predecessor is already visited.\n");
1681       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1682       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1683       BBState.ExitValue = BBState.EntryValue;
1684       BBState.ExitIsSetup = BBState.EntryIsSetup;
1685     }
1686
1687     // Update stack state by checking contents of MBB.
1688     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
1689          I != E; ++I) {
1690       if (I->getOpcode() == FrameSetupOpcode) {
1691         // The first operand of a FrameOpcode should be i32.
1692         int Size = I->getOperand(0).getImm();
1693         assert(Size >= 0 &&
1694           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1695
1696         if (BBState.ExitIsSetup)
1697           report("FrameSetup is after another FrameSetup", I); 
1698         BBState.ExitValue -= Size;
1699         BBState.ExitIsSetup = true;
1700       }
1701
1702       if (I->getOpcode() == FrameDestroyOpcode) {
1703         // The first operand of a FrameOpcode should be i32.
1704         int Size = I->getOperand(0).getImm();
1705         assert(Size >= 0 &&
1706           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1707
1708         if (!BBState.ExitIsSetup)
1709           report("FrameDestroy is not after a FrameSetup", I);
1710         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1711                                                BBState.ExitValue;
1712         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1713           report("FrameDestroy <n> is after FrameSetup <m>", I);
1714           *OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
1715               << AbsSPAdj << ">.\n";
1716         }
1717         BBState.ExitValue += Size;
1718         BBState.ExitIsSetup = false;
1719       }
1720     }
1721     SPState[MBB->getNumber()] = BBState;
1722
1723     // Make sure the exit state of any predecessor is consistent with the entry
1724     // state.
1725     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1726          E = MBB->pred_end(); I != E; ++I) {
1727       if (Reachable.count(*I) &&
1728           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1729            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1730         report("The exit stack state of a predecessor is inconsistent.", MBB);
1731         *OS << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1732             << SPState[(*I)->getNumber()].ExitValue << ", "
1733             << SPState[(*I)->getNumber()].ExitIsSetup
1734             << "), while BB#" << MBB->getNumber() << " has entry state ("
1735             << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1736       }
1737     }
1738
1739     // Make sure the entry state of any successor is consistent with the exit
1740     // state.
1741     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1742          E = MBB->succ_end(); I != E; ++I) {
1743       if (Reachable.count(*I) &&
1744           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1745            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1746         report("The entry stack state of a successor is inconsistent.", MBB);
1747         *OS << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1748             << SPState[(*I)->getNumber()].EntryValue << ", "
1749             << SPState[(*I)->getNumber()].EntryIsSetup
1750             << "), while BB#" << MBB->getNumber() << " has exit state ("
1751             << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1752       }
1753     }
1754
1755     // Make sure a basic block with return ends with zero stack adjustment.
1756     if (!MBB->empty() && MBB->back().isReturn()) {
1757       if (BBState.ExitIsSetup)
1758         report("A return block ends with a FrameSetup.", MBB);
1759       if (BBState.ExitValue)
1760         report("A return block ends with a nonzero stack adjustment.", MBB);
1761     }
1762   }
1763 }