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