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