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