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