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