xref: /llvm-project/llvm/lib/CodeGen/MachineVerifier.cpp (revision b2154af25f52589360eb43e2b74413dbba461aff)
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 "LiveRangeCalc.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SetOperations.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/EHPersonalities.h"
38 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
39 #include "llvm/CodeGen/LiveInterval.h"
40 #include "llvm/CodeGen/LiveIntervals.h"
41 #include "llvm/CodeGen/LiveStacks.h"
42 #include "llvm/CodeGen/LiveVariables.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBundle.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/PseudoSourceValue.h"
53 #include "llvm/CodeGen/SlotIndexes.h"
54 #include "llvm/CodeGen/StackMaps.h"
55 #include "llvm/CodeGen/TargetInstrInfo.h"
56 #include "llvm/CodeGen/TargetOpcodes.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/MC/LaneBitmask.h"
64 #include "llvm/MC/MCAsmInfo.h"
65 #include "llvm/MC/MCInstrDesc.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/LowLevelTypeImpl.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetMachine.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <iterator>
80 #include <string>
81 #include <utility>
82 
83 using namespace llvm;
84 
85 namespace {
86 
87   struct MachineVerifier {
88     MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
89 
90     unsigned verify(MachineFunction &MF);
91 
92     Pass *const PASS;
93     const char *Banner;
94     const MachineFunction *MF;
95     const TargetMachine *TM;
96     const TargetInstrInfo *TII;
97     const TargetRegisterInfo *TRI;
98     const MachineRegisterInfo *MRI;
99 
100     unsigned foundErrors;
101 
102     // Avoid querying the MachineFunctionProperties for each operand.
103     bool isFunctionRegBankSelected;
104     bool isFunctionSelected;
105 
106     using RegVector = SmallVector<unsigned, 16>;
107     using RegMaskVector = SmallVector<const uint32_t *, 4>;
108     using RegSet = DenseSet<unsigned>;
109     using RegMap = DenseMap<unsigned, const MachineInstr *>;
110     using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
111 
112     const MachineInstr *FirstTerminator;
113     BlockSet FunctionBlocks;
114 
115     BitVector regsReserved;
116     RegSet regsLive;
117     RegVector regsDefined, regsDead, regsKilled;
118     RegMaskVector regMasks;
119 
120     SlotIndex lastIndex;
121 
122     // Add Reg and any sub-registers to RV
123     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
124       RV.push_back(Reg);
125       if (TargetRegisterInfo::isPhysicalRegister(Reg))
126         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
127           RV.push_back(*SubRegs);
128     }
129 
130     struct BBInfo {
131       // Is this MBB reachable from the MF entry point?
132       bool reachable = false;
133 
134       // Vregs that must be live in because they are used without being
135       // defined. Map value is the user.
136       RegMap vregsLiveIn;
137 
138       // Regs killed in MBB. They may be defined again, and will then be in both
139       // regsKilled and regsLiveOut.
140       RegSet regsKilled;
141 
142       // Regs defined in MBB and live out. Note that vregs passing through may
143       // be live out without being mentioned here.
144       RegSet regsLiveOut;
145 
146       // Vregs that pass through MBB untouched. This set is disjoint from
147       // regsKilled and regsLiveOut.
148       RegSet vregsPassed;
149 
150       // Vregs that must pass through MBB because they are needed by a successor
151       // block. This set is disjoint from regsLiveOut.
152       RegSet vregsRequired;
153 
154       // Set versions of block's predecessor and successor lists.
155       BlockSet Preds, Succs;
156 
157       BBInfo() = default;
158 
159       // Add register to vregsPassed if it belongs there. Return true if
160       // anything changed.
161       bool addPassed(unsigned Reg) {
162         if (!TargetRegisterInfo::isVirtualRegister(Reg))
163           return false;
164         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
165           return false;
166         return vregsPassed.insert(Reg).second;
167       }
168 
169       // Same for a full set.
170       bool addPassed(const RegSet &RS) {
171         bool changed = false;
172         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
173           if (addPassed(*I))
174             changed = true;
175         return changed;
176       }
177 
178       // Add register to vregsRequired if it belongs there. Return true if
179       // anything changed.
180       bool addRequired(unsigned Reg) {
181         if (!TargetRegisterInfo::isVirtualRegister(Reg))
182           return false;
183         if (regsLiveOut.count(Reg))
184           return false;
185         return vregsRequired.insert(Reg).second;
186       }
187 
188       // Same for a full set.
189       bool addRequired(const RegSet &RS) {
190         bool changed = false;
191         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
192           if (addRequired(*I))
193             changed = true;
194         return changed;
195       }
196 
197       // Same for a full map.
198       bool addRequired(const RegMap &RM) {
199         bool changed = false;
200         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
201           if (addRequired(I->first))
202             changed = true;
203         return changed;
204       }
205 
206       // Live-out registers are either in regsLiveOut or vregsPassed.
207       bool isLiveOut(unsigned Reg) const {
208         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
209       }
210     };
211 
212     // Extra register info per MBB.
213     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
214 
215     bool isReserved(unsigned Reg) {
216       return Reg < regsReserved.size() && regsReserved.test(Reg);
217     }
218 
219     bool isAllocatable(unsigned Reg) const {
220       return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
221         !regsReserved.test(Reg);
222     }
223 
224     // Analysis information if available
225     LiveVariables *LiveVars;
226     LiveIntervals *LiveInts;
227     LiveStacks *LiveStks;
228     SlotIndexes *Indexes;
229 
230     void visitMachineFunctionBefore();
231     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
232     void visitMachineBundleBefore(const MachineInstr *MI);
233     void visitMachineInstrBefore(const MachineInstr *MI);
234     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
235     void visitMachineInstrAfter(const MachineInstr *MI);
236     void visitMachineBundleAfter(const MachineInstr *MI);
237     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
238     void visitMachineFunctionAfter();
239 
240     void report(const char *msg, const MachineFunction *MF);
241     void report(const char *msg, const MachineBasicBlock *MBB);
242     void report(const char *msg, const MachineInstr *MI);
243     void report(const char *msg, const MachineOperand *MO, unsigned MONum,
244                 LLT MOVRegType = LLT{});
245 
246     void report_context(const LiveInterval &LI) const;
247     void report_context(const LiveRange &LR, unsigned VRegUnit,
248                         LaneBitmask LaneMask) const;
249     void report_context(const LiveRange::Segment &S) const;
250     void report_context(const VNInfo &VNI) const;
251     void report_context(SlotIndex Pos) const;
252     void report_context_liverange(const LiveRange &LR) const;
253     void report_context_lanemask(LaneBitmask LaneMask) const;
254     void report_context_vreg(unsigned VReg) const;
255     void report_context_vreg_regunit(unsigned VRegOrUnit) const;
256 
257     void verifyInlineAsm(const MachineInstr *MI);
258 
259     void checkLiveness(const MachineOperand *MO, unsigned MONum);
260     void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
261                             SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
262                             LaneBitmask LaneMask = LaneBitmask::getNone());
263     void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
264                             SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
265                             bool SubRangeCheck = false,
266                             LaneBitmask LaneMask = LaneBitmask::getNone());
267 
268     void markReachable(const MachineBasicBlock *MBB);
269     void calcRegsPassed();
270     void checkPHIOps(const MachineBasicBlock &MBB);
271 
272     void calcRegsRequired();
273     void verifyLiveVariables();
274     void verifyLiveIntervals();
275     void verifyLiveInterval(const LiveInterval&);
276     void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
277                               LaneBitmask);
278     void verifyLiveRangeSegment(const LiveRange&,
279                                 const LiveRange::const_iterator I, unsigned,
280                                 LaneBitmask);
281     void verifyLiveRange(const LiveRange&, unsigned,
282                          LaneBitmask LaneMask = LaneBitmask::getNone());
283 
284     void verifyStackFrame();
285 
286     void verifySlotIndexes() const;
287     void verifyProperties(const MachineFunction &MF);
288   };
289 
290   struct MachineVerifierPass : public MachineFunctionPass {
291     static char ID; // Pass ID, replacement for typeid
292 
293     const std::string Banner;
294 
295     MachineVerifierPass(std::string banner = std::string())
296       : MachineFunctionPass(ID), Banner(std::move(banner)) {
297         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
298       }
299 
300     void getAnalysisUsage(AnalysisUsage &AU) const override {
301       AU.setPreservesAll();
302       MachineFunctionPass::getAnalysisUsage(AU);
303     }
304 
305     bool runOnMachineFunction(MachineFunction &MF) override {
306       unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
307       if (FoundErrors)
308         report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
309       return false;
310     }
311   };
312 
313 } // end anonymous namespace
314 
315 char MachineVerifierPass::ID = 0;
316 
317 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
318                 "Verify generated machine code", false, false)
319 
320 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
321   return new MachineVerifierPass(Banner);
322 }
323 
324 bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
325     const {
326   MachineFunction &MF = const_cast<MachineFunction&>(*this);
327   unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
328   if (AbortOnErrors && FoundErrors)
329     report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
330   return FoundErrors == 0;
331 }
332 
333 void MachineVerifier::verifySlotIndexes() const {
334   if (Indexes == nullptr)
335     return;
336 
337   // Ensure the IdxMBB list is sorted by slot indexes.
338   SlotIndex Last;
339   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
340        E = Indexes->MBBIndexEnd(); I != E; ++I) {
341     assert(!Last.isValid() || I->first > Last);
342     Last = I->first;
343   }
344 }
345 
346 void MachineVerifier::verifyProperties(const MachineFunction &MF) {
347   // If a pass has introduced virtual registers without clearing the
348   // NoVRegs property (or set it without allocating the vregs)
349   // then report an error.
350   if (MF.getProperties().hasProperty(
351           MachineFunctionProperties::Property::NoVRegs) &&
352       MRI->getNumVirtRegs())
353     report("Function has NoVRegs property but there are VReg operands", &MF);
354 }
355 
356 unsigned MachineVerifier::verify(MachineFunction &MF) {
357   foundErrors = 0;
358 
359   this->MF = &MF;
360   TM = &MF.getTarget();
361   TII = MF.getSubtarget().getInstrInfo();
362   TRI = MF.getSubtarget().getRegisterInfo();
363   MRI = &MF.getRegInfo();
364 
365   const bool isFunctionFailedISel = MF.getProperties().hasProperty(
366       MachineFunctionProperties::Property::FailedISel);
367   isFunctionRegBankSelected =
368       !isFunctionFailedISel &&
369       MF.getProperties().hasProperty(
370           MachineFunctionProperties::Property::RegBankSelected);
371   isFunctionSelected = !isFunctionFailedISel &&
372                        MF.getProperties().hasProperty(
373                            MachineFunctionProperties::Property::Selected);
374   LiveVars = nullptr;
375   LiveInts = nullptr;
376   LiveStks = nullptr;
377   Indexes = nullptr;
378   if (PASS) {
379     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
380     // We don't want to verify LiveVariables if LiveIntervals is available.
381     if (!LiveInts)
382       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
383     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
384     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
385   }
386 
387   verifySlotIndexes();
388 
389   verifyProperties(MF);
390 
391   visitMachineFunctionBefore();
392   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
393        MFI!=MFE; ++MFI) {
394     visitMachineBasicBlockBefore(&*MFI);
395     // Keep track of the current bundle header.
396     const MachineInstr *CurBundle = nullptr;
397     // Do we expect the next instruction to be part of the same bundle?
398     bool InBundle = false;
399 
400     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
401            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
402       if (MBBI->getParent() != &*MFI) {
403         report("Bad instruction parent pointer", &*MFI);
404         errs() << "Instruction: " << *MBBI;
405         continue;
406       }
407 
408       // Check for consistent bundle flags.
409       if (InBundle && !MBBI->isBundledWithPred())
410         report("Missing BundledPred flag, "
411                "BundledSucc was set on predecessor",
412                &*MBBI);
413       if (!InBundle && MBBI->isBundledWithPred())
414         report("BundledPred flag is set, "
415                "but BundledSucc not set on predecessor",
416                &*MBBI);
417 
418       // Is this a bundle header?
419       if (!MBBI->isInsideBundle()) {
420         if (CurBundle)
421           visitMachineBundleAfter(CurBundle);
422         CurBundle = &*MBBI;
423         visitMachineBundleBefore(CurBundle);
424       } else if (!CurBundle)
425         report("No bundle header", &*MBBI);
426       visitMachineInstrBefore(&*MBBI);
427       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
428         const MachineInstr &MI = *MBBI;
429         const MachineOperand &Op = MI.getOperand(I);
430         if (Op.getParent() != &MI) {
431           // Make sure to use correct addOperand / RemoveOperand / ChangeTo
432           // functions when replacing operands of a MachineInstr.
433           report("Instruction has operand with wrong parent set", &MI);
434         }
435 
436         visitMachineOperand(&Op, I);
437       }
438 
439       visitMachineInstrAfter(&*MBBI);
440 
441       // Was this the last bundled instruction?
442       InBundle = MBBI->isBundledWithSucc();
443     }
444     if (CurBundle)
445       visitMachineBundleAfter(CurBundle);
446     if (InBundle)
447       report("BundledSucc flag set on last instruction in block", &MFI->back());
448     visitMachineBasicBlockAfter(&*MFI);
449   }
450   visitMachineFunctionAfter();
451 
452   // Clean up.
453   regsLive.clear();
454   regsDefined.clear();
455   regsDead.clear();
456   regsKilled.clear();
457   regMasks.clear();
458   MBBInfoMap.clear();
459 
460   return foundErrors;
461 }
462 
463 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
464   assert(MF);
465   errs() << '\n';
466   if (!foundErrors++) {
467     if (Banner)
468       errs() << "# " << Banner << '\n';
469     if (LiveInts != nullptr)
470       LiveInts->print(errs());
471     else
472       MF->print(errs(), Indexes);
473   }
474   errs() << "*** Bad machine code: " << msg << " ***\n"
475       << "- function:    " << MF->getName() << "\n";
476 }
477 
478 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
479   assert(MBB);
480   report(msg, MBB->getParent());
481   errs() << "- basic block: " << printMBBReference(*MBB) << ' '
482          << MBB->getName() << " (" << (const void *)MBB << ')';
483   if (Indexes)
484     errs() << " [" << Indexes->getMBBStartIdx(MBB)
485         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
486   errs() << '\n';
487 }
488 
489 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
490   assert(MI);
491   report(msg, MI->getParent());
492   errs() << "- instruction: ";
493   if (Indexes && Indexes->hasIndex(*MI))
494     errs() << Indexes->getInstructionIndex(*MI) << '\t';
495   MI->print(errs(), /*SkipOpers=*/true);
496 }
497 
498 void MachineVerifier::report(const char *msg, const MachineOperand *MO,
499                              unsigned MONum, LLT MOVRegType) {
500   assert(MO);
501   report(msg, MO->getParent());
502   errs() << "- operand " << MONum << ":   ";
503   MO->print(errs(), MOVRegType, TRI);
504   errs() << "\n";
505 }
506 
507 void MachineVerifier::report_context(SlotIndex Pos) const {
508   errs() << "- at:          " << Pos << '\n';
509 }
510 
511 void MachineVerifier::report_context(const LiveInterval &LI) const {
512   errs() << "- interval:    " << LI << '\n';
513 }
514 
515 void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit,
516                                      LaneBitmask LaneMask) const {
517   report_context_liverange(LR);
518   report_context_vreg_regunit(VRegUnit);
519   if (LaneMask.any())
520     report_context_lanemask(LaneMask);
521 }
522 
523 void MachineVerifier::report_context(const LiveRange::Segment &S) const {
524   errs() << "- segment:     " << S << '\n';
525 }
526 
527 void MachineVerifier::report_context(const VNInfo &VNI) const {
528   errs() << "- ValNo:       " << VNI.id << " (def " << VNI.def << ")\n";
529 }
530 
531 void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
532   errs() << "- liverange:   " << LR << '\n';
533 }
534 
535 void MachineVerifier::report_context_vreg(unsigned VReg) const {
536   errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
537 }
538 
539 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const {
540   if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) {
541     report_context_vreg(VRegOrUnit);
542   } else {
543     errs() << "- regunit:     " << printRegUnit(VRegOrUnit, TRI) << '\n';
544   }
545 }
546 
547 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
548   errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
549 }
550 
551 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
552   BBInfo &MInfo = MBBInfoMap[MBB];
553   if (!MInfo.reachable) {
554     MInfo.reachable = true;
555     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
556            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
557       markReachable(*SuI);
558   }
559 }
560 
561 void MachineVerifier::visitMachineFunctionBefore() {
562   lastIndex = SlotIndex();
563   regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
564                                            : TRI->getReservedRegs(*MF);
565 
566   if (!MF->empty())
567     markReachable(&MF->front());
568 
569   // Build a set of the basic blocks in the function.
570   FunctionBlocks.clear();
571   for (const auto &MBB : *MF) {
572     FunctionBlocks.insert(&MBB);
573     BBInfo &MInfo = MBBInfoMap[&MBB];
574 
575     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
576     if (MInfo.Preds.size() != MBB.pred_size())
577       report("MBB has duplicate entries in its predecessor list.", &MBB);
578 
579     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
580     if (MInfo.Succs.size() != MBB.succ_size())
581       report("MBB has duplicate entries in its successor list.", &MBB);
582   }
583 
584   // Check that the register use lists are sane.
585   MRI->verifyUseLists();
586 
587   if (!MF->empty())
588     verifyStackFrame();
589 }
590 
591 // Does iterator point to a and b as the first two elements?
592 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
593                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
594   if (*i == a)
595     return *++i == b;
596   if (*i == b)
597     return *++i == a;
598   return false;
599 }
600 
601 void
602 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
603   FirstTerminator = nullptr;
604 
605   if (!MF->getProperties().hasProperty(
606       MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
607     // If this block has allocatable physical registers live-in, check that
608     // it is an entry block or landing pad.
609     for (const auto &LI : MBB->liveins()) {
610       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
611           MBB->getIterator() != MBB->getParent()->begin()) {
612         report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
613       }
614     }
615   }
616 
617   // Count the number of landing pad successors.
618   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
619   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
620        E = MBB->succ_end(); I != E; ++I) {
621     if ((*I)->isEHPad())
622       LandingPadSuccs.insert(*I);
623     if (!FunctionBlocks.count(*I))
624       report("MBB has successor that isn't part of the function.", MBB);
625     if (!MBBInfoMap[*I].Preds.count(MBB)) {
626       report("Inconsistent CFG", MBB);
627       errs() << "MBB is not in the predecessor list of the successor "
628              << printMBBReference(*(*I)) << ".\n";
629     }
630   }
631 
632   // Check the predecessor list.
633   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
634        E = MBB->pred_end(); I != E; ++I) {
635     if (!FunctionBlocks.count(*I))
636       report("MBB has predecessor that isn't part of the function.", MBB);
637     if (!MBBInfoMap[*I].Succs.count(MBB)) {
638       report("Inconsistent CFG", MBB);
639       errs() << "MBB is not in the successor list of the predecessor "
640              << printMBBReference(*(*I)) << ".\n";
641     }
642   }
643 
644   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
645   const BasicBlock *BB = MBB->getBasicBlock();
646   const Function &F = MF->getFunction();
647   if (LandingPadSuccs.size() > 1 &&
648       !(AsmInfo &&
649         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
650         BB && isa<SwitchInst>(BB->getTerminator())) &&
651       !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
652     report("MBB has more than one landing pad successor", MBB);
653 
654   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
655   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
656   SmallVector<MachineOperand, 4> Cond;
657   if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
658                           Cond)) {
659     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
660     // check whether its answers match up with reality.
661     if (!TBB && !FBB) {
662       // Block falls through to its successor.
663       MachineFunction::const_iterator MBBI = MBB->getIterator();
664       ++MBBI;
665       if (MBBI == MF->end()) {
666         // It's possible that the block legitimately ends with a noreturn
667         // call or an unreachable, in which case it won't actually fall
668         // out the bottom of the function.
669       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
670         // It's possible that the block legitimately ends with a noreturn
671         // call or an unreachable, in which case it won't actuall fall
672         // out of the block.
673       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
674         report("MBB exits via unconditional fall-through but doesn't have "
675                "exactly one CFG successor!", MBB);
676       } else if (!MBB->isSuccessor(&*MBBI)) {
677         report("MBB exits via unconditional fall-through but its successor "
678                "differs from its CFG successor!", MBB);
679       }
680       if (!MBB->empty() && MBB->back().isBarrier() &&
681           !TII->isPredicated(MBB->back())) {
682         report("MBB exits via unconditional fall-through but ends with a "
683                "barrier instruction!", MBB);
684       }
685       if (!Cond.empty()) {
686         report("MBB exits via unconditional fall-through but has a condition!",
687                MBB);
688       }
689     } else if (TBB && !FBB && Cond.empty()) {
690       // Block unconditionally branches somewhere.
691       // If the block has exactly one successor, that happens to be a
692       // landingpad, accept it as valid control flow.
693       if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
694           (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
695            *MBB->succ_begin() != *LandingPadSuccs.begin())) {
696         report("MBB exits via unconditional branch but doesn't have "
697                "exactly one CFG successor!", MBB);
698       } else if (!MBB->isSuccessor(TBB)) {
699         report("MBB exits via unconditional branch but the CFG "
700                "successor doesn't match the actual successor!", MBB);
701       }
702       if (MBB->empty()) {
703         report("MBB exits via unconditional branch but doesn't contain "
704                "any instructions!", MBB);
705       } else if (!MBB->back().isBarrier()) {
706         report("MBB exits via unconditional branch but doesn't end with a "
707                "barrier instruction!", MBB);
708       } else if (!MBB->back().isTerminator()) {
709         report("MBB exits via unconditional branch but the branch isn't a "
710                "terminator instruction!", MBB);
711       }
712     } else if (TBB && !FBB && !Cond.empty()) {
713       // Block conditionally branches somewhere, otherwise falls through.
714       MachineFunction::const_iterator MBBI = MBB->getIterator();
715       ++MBBI;
716       if (MBBI == MF->end()) {
717         report("MBB conditionally falls through out of function!", MBB);
718       } else if (MBB->succ_size() == 1) {
719         // A conditional branch with only one successor is weird, but allowed.
720         if (&*MBBI != TBB)
721           report("MBB exits via conditional branch/fall-through but only has "
722                  "one CFG successor!", MBB);
723         else if (TBB != *MBB->succ_begin())
724           report("MBB exits via conditional branch/fall-through but the CFG "
725                  "successor don't match the actual successor!", MBB);
726       } else if (MBB->succ_size() != 2) {
727         report("MBB exits via conditional branch/fall-through but doesn't have "
728                "exactly two CFG successors!", MBB);
729       } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
730         report("MBB exits via conditional branch/fall-through but the CFG "
731                "successors don't match the actual successors!", MBB);
732       }
733       if (MBB->empty()) {
734         report("MBB exits via conditional branch/fall-through but doesn't "
735                "contain any instructions!", MBB);
736       } else if (MBB->back().isBarrier()) {
737         report("MBB exits via conditional branch/fall-through but ends with a "
738                "barrier instruction!", MBB);
739       } else if (!MBB->back().isTerminator()) {
740         report("MBB exits via conditional branch/fall-through but the branch "
741                "isn't a terminator instruction!", MBB);
742       }
743     } else if (TBB && FBB) {
744       // Block conditionally branches somewhere, otherwise branches
745       // somewhere else.
746       if (MBB->succ_size() == 1) {
747         // A conditional branch with only one successor is weird, but allowed.
748         if (FBB != TBB)
749           report("MBB exits via conditional branch/branch through but only has "
750                  "one CFG successor!", MBB);
751         else if (TBB != *MBB->succ_begin())
752           report("MBB exits via conditional branch/branch through but the CFG "
753                  "successor don't match the actual successor!", MBB);
754       } else if (MBB->succ_size() != 2) {
755         report("MBB exits via conditional branch/branch but doesn't have "
756                "exactly two CFG successors!", MBB);
757       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
758         report("MBB exits via conditional branch/branch but the CFG "
759                "successors don't match the actual successors!", MBB);
760       }
761       if (MBB->empty()) {
762         report("MBB exits via conditional branch/branch but doesn't "
763                "contain any instructions!", MBB);
764       } else if (!MBB->back().isBarrier()) {
765         report("MBB exits via conditional branch/branch but doesn't end with a "
766                "barrier instruction!", MBB);
767       } else if (!MBB->back().isTerminator()) {
768         report("MBB exits via conditional branch/branch but the branch "
769                "isn't a terminator instruction!", MBB);
770       }
771       if (Cond.empty()) {
772         report("MBB exits via conditinal branch/branch but there's no "
773                "condition!", MBB);
774       }
775     } else {
776       report("AnalyzeBranch returned invalid data!", MBB);
777     }
778   }
779 
780   regsLive.clear();
781   if (MRI->tracksLiveness()) {
782     for (const auto &LI : MBB->liveins()) {
783       if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
784         report("MBB live-in list contains non-physical register", MBB);
785         continue;
786       }
787       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
788            SubRegs.isValid(); ++SubRegs)
789         regsLive.insert(*SubRegs);
790     }
791   }
792 
793   const MachineFrameInfo &MFI = MF->getFrameInfo();
794   BitVector PR = MFI.getPristineRegs(*MF);
795   for (unsigned I : PR.set_bits()) {
796     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
797          SubRegs.isValid(); ++SubRegs)
798       regsLive.insert(*SubRegs);
799   }
800 
801   regsKilled.clear();
802   regsDefined.clear();
803 
804   if (Indexes)
805     lastIndex = Indexes->getMBBStartIdx(MBB);
806 }
807 
808 // This function gets called for all bundle headers, including normal
809 // stand-alone unbundled instructions.
810 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
811   if (Indexes && Indexes->hasIndex(*MI)) {
812     SlotIndex idx = Indexes->getInstructionIndex(*MI);
813     if (!(idx > lastIndex)) {
814       report("Instruction index out of order", MI);
815       errs() << "Last instruction was at " << lastIndex << '\n';
816     }
817     lastIndex = idx;
818   }
819 
820   // Ensure non-terminators don't follow terminators.
821   // Ignore predicated terminators formed by if conversion.
822   // FIXME: If conversion shouldn't need to violate this rule.
823   if (MI->isTerminator() && !TII->isPredicated(*MI)) {
824     if (!FirstTerminator)
825       FirstTerminator = MI;
826   } else if (FirstTerminator) {
827     report("Non-terminator instruction after the first terminator", MI);
828     errs() << "First terminator was:\t" << *FirstTerminator;
829   }
830 }
831 
832 // The operands on an INLINEASM instruction must follow a template.
833 // Verify that the flag operands make sense.
834 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
835   // The first two operands on INLINEASM are the asm string and global flags.
836   if (MI->getNumOperands() < 2) {
837     report("Too few operands on inline asm", MI);
838     return;
839   }
840   if (!MI->getOperand(0).isSymbol())
841     report("Asm string must be an external symbol", MI);
842   if (!MI->getOperand(1).isImm())
843     report("Asm flags must be an immediate", MI);
844   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
845   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
846   // and Extra_IsConvergent = 32.
847   if (!isUInt<6>(MI->getOperand(1).getImm()))
848     report("Unknown asm flags", &MI->getOperand(1), 1);
849 
850   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
851 
852   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
853   unsigned NumOps;
854   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
855     const MachineOperand &MO = MI->getOperand(OpNo);
856     // There may be implicit ops after the fixed operands.
857     if (!MO.isImm())
858       break;
859     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
860   }
861 
862   if (OpNo > MI->getNumOperands())
863     report("Missing operands in last group", MI);
864 
865   // An optional MDNode follows the groups.
866   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
867     ++OpNo;
868 
869   // All trailing operands must be implicit registers.
870   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
871     const MachineOperand &MO = MI->getOperand(OpNo);
872     if (!MO.isReg() || !MO.isImplicit())
873       report("Expected implicit register after groups", &MO, OpNo);
874   }
875 }
876 
877 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
878   const MCInstrDesc &MCID = MI->getDesc();
879   if (MI->getNumOperands() < MCID.getNumOperands()) {
880     report("Too few operands", MI);
881     errs() << MCID.getNumOperands() << " operands expected, but "
882            << MI->getNumOperands() << " given.\n";
883   }
884 
885   if (MI->isPHI() && MF->getProperties().hasProperty(
886                          MachineFunctionProperties::Property::NoPHIs))
887     report("Found PHI instruction with NoPHIs property set", MI);
888 
889   // Check the tied operands.
890   if (MI->isInlineAsm())
891     verifyInlineAsm(MI);
892 
893   // Check the MachineMemOperands for basic consistency.
894   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
895                                   E = MI->memoperands_end();
896        I != E; ++I) {
897     if ((*I)->isLoad() && !MI->mayLoad())
898       report("Missing mayLoad flag", MI);
899     if ((*I)->isStore() && !MI->mayStore())
900       report("Missing mayStore flag", MI);
901   }
902 
903   // Debug values must not have a slot index.
904   // Other instructions must have one, unless they are inside a bundle.
905   if (LiveInts) {
906     bool mapped = !LiveInts->isNotInMIMap(*MI);
907     if (MI->isDebugInstr()) {
908       if (mapped)
909         report("Debug instruction has a slot index", MI);
910     } else if (MI->isInsideBundle()) {
911       if (mapped)
912         report("Instruction inside bundle has a slot index", MI);
913     } else {
914       if (!mapped)
915         report("Missing slot index", MI);
916     }
917   }
918 
919   if (isPreISelGenericOpcode(MCID.getOpcode())) {
920     if (isFunctionSelected)
921       report("Unexpected generic instruction in a Selected function", MI);
922 
923     // Check types.
924     SmallVector<LLT, 4> Types;
925     for (unsigned I = 0; I < MCID.getNumOperands(); ++I) {
926       if (!MCID.OpInfo[I].isGenericType())
927         continue;
928       // Generic instructions specify type equality constraints between some of
929       // their operands. Make sure these are consistent.
930       size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex();
931       Types.resize(std::max(TypeIdx + 1, Types.size()));
932 
933       const MachineOperand *MO = &MI->getOperand(I);
934       LLT OpTy = MRI->getType(MO->getReg());
935       // Don't report a type mismatch if there is no actual mismatch, only a
936       // type missing, to reduce noise:
937       if (OpTy.isValid()) {
938         // Only the first valid type for a type index will be printed: don't
939         // overwrite it later so it's always clear which type was expected:
940         if (!Types[TypeIdx].isValid())
941           Types[TypeIdx] = OpTy;
942         else if (Types[TypeIdx] != OpTy)
943           report("Type mismatch in generic instruction", MO, I, OpTy);
944       } else {
945         // Generic instructions must have types attached to their operands.
946         report("Generic instruction is missing a virtual register type", MO, I);
947       }
948     }
949 
950     // Generic opcodes must not have physical register operands.
951     for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
952       const MachineOperand *MO = &MI->getOperand(I);
953       if (MO->isReg() && TargetRegisterInfo::isPhysicalRegister(MO->getReg()))
954         report("Generic instruction cannot have physical register", MO, I);
955     }
956   }
957 
958   StringRef ErrorInfo;
959   if (!TII->verifyInstruction(*MI, ErrorInfo))
960     report(ErrorInfo.data(), MI);
961 
962   // Verify properties of various specific instruction types
963   switch(MI->getOpcode()) {
964   default:
965     break;
966   case TargetOpcode::G_LOAD:
967   case TargetOpcode::G_STORE:
968     // Generic loads and stores must have a single MachineMemOperand
969     // describing that access.
970     if (!MI->hasOneMemOperand())
971       report("Generic instruction accessing memory must have one mem operand",
972              MI);
973     break;
974   case TargetOpcode::G_PHI: {
975     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
976     if (!DstTy.isValid() ||
977         !std::all_of(MI->operands_begin() + 1, MI->operands_end(),
978                      [this, &DstTy](const MachineOperand &MO) {
979                        if (!MO.isReg())
980                          return true;
981                        LLT Ty = MRI->getType(MO.getReg());
982                        if (!Ty.isValid() || (Ty != DstTy))
983                          return false;
984                        return true;
985                      }))
986       report("Generic Instruction G_PHI has operands with incompatible/missing "
987              "types",
988              MI);
989     break;
990   }
991   case TargetOpcode::G_SEXT:
992   case TargetOpcode::G_ZEXT:
993   case TargetOpcode::G_ANYEXT:
994   case TargetOpcode::G_TRUNC:
995   case TargetOpcode::G_FPEXT:
996   case TargetOpcode::G_FPTRUNC: {
997     // Number of operands and presense of types is already checked (and
998     // reported in case of any issues), so no need to report them again. As
999     // we're trying to report as many issues as possible at once, however, the
1000     // instructions aren't guaranteed to have the right number of operands or
1001     // types attached to them at this point
1002     assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1003     if (MI->getNumOperands() < MCID.getNumOperands())
1004       break;
1005     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1006     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1007     if (!DstTy.isValid() || !SrcTy.isValid())
1008       break;
1009 
1010     LLT DstElTy = DstTy.isVector() ? DstTy.getElementType() : DstTy;
1011     LLT SrcElTy = SrcTy.isVector() ? SrcTy.getElementType() : SrcTy;
1012     if (DstElTy.isPointer() || SrcElTy.isPointer())
1013       report("Generic extend/truncate can not operate on pointers", MI);
1014 
1015     if (DstTy.isVector() != SrcTy.isVector()) {
1016       report("Generic extend/truncate must be all-vector or all-scalar", MI);
1017       // Generally we try to report as many issues as possible at once, but in
1018       // this case it's not clear what should we be comparing the size of the
1019       // scalar with: the size of the whole vector or its lane. Instead of
1020       // making an arbitrary choice and emitting not so helpful message, let's
1021       // avoid the extra noise and stop here.
1022       break;
1023     }
1024     if (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements())
1025       report("Generic vector extend/truncate must preserve number of lanes",
1026              MI);
1027     unsigned DstSize = DstElTy.getSizeInBits();
1028     unsigned SrcSize = SrcElTy.getSizeInBits();
1029     switch (MI->getOpcode()) {
1030     default:
1031       if (DstSize <= SrcSize)
1032         report("Generic extend has destination type no larger than source", MI);
1033       break;
1034     case TargetOpcode::G_TRUNC:
1035     case TargetOpcode::G_FPTRUNC:
1036       if (DstSize >= SrcSize)
1037         report("Generic truncate has destination type no smaller than source",
1038                MI);
1039       break;
1040     }
1041     break;
1042   }
1043   case TargetOpcode::COPY: {
1044     if (foundErrors)
1045       break;
1046     const MachineOperand &DstOp = MI->getOperand(0);
1047     const MachineOperand &SrcOp = MI->getOperand(1);
1048     LLT DstTy = MRI->getType(DstOp.getReg());
1049     LLT SrcTy = MRI->getType(SrcOp.getReg());
1050     if (SrcTy.isValid() && DstTy.isValid()) {
1051       // If both types are valid, check that the types are the same.
1052       if (SrcTy != DstTy) {
1053         report("Copy Instruction is illegal with mismatching types", MI);
1054         errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
1055       }
1056     }
1057     if (SrcTy.isValid() || DstTy.isValid()) {
1058       // If one of them have valid types, let's just check they have the same
1059       // size.
1060       unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI);
1061       unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI);
1062       assert(SrcSize && "Expecting size here");
1063       assert(DstSize && "Expecting size here");
1064       if (SrcSize != DstSize)
1065         if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
1066           report("Copy Instruction is illegal with mismatching sizes", MI);
1067           errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
1068                  << "\n";
1069         }
1070     }
1071     break;
1072   }
1073   case TargetOpcode::STATEPOINT:
1074     if (!MI->getOperand(StatepointOpers::IDPos).isImm() ||
1075         !MI->getOperand(StatepointOpers::NBytesPos).isImm() ||
1076         !MI->getOperand(StatepointOpers::NCallArgsPos).isImm())
1077       report("meta operands to STATEPOINT not constant!", MI);
1078     break;
1079 
1080     auto VerifyStackMapConstant = [&](unsigned Offset) {
1081       if (!MI->getOperand(Offset).isImm() ||
1082           MI->getOperand(Offset).getImm() != StackMaps::ConstantOp ||
1083           !MI->getOperand(Offset + 1).isImm())
1084         report("stack map constant to STATEPOINT not well formed!", MI);
1085     };
1086     const unsigned VarStart = StatepointOpers(MI).getVarIdx();
1087     VerifyStackMapConstant(VarStart + StatepointOpers::CCOffset);
1088     VerifyStackMapConstant(VarStart + StatepointOpers::FlagsOffset);
1089     VerifyStackMapConstant(VarStart + StatepointOpers::NumDeoptOperandsOffset);
1090 
1091     // TODO: verify we have properly encoded deopt arguments
1092   };
1093 }
1094 
1095 void
1096 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
1097   const MachineInstr *MI = MO->getParent();
1098   const MCInstrDesc &MCID = MI->getDesc();
1099   unsigned NumDefs = MCID.getNumDefs();
1100   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
1101     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
1102 
1103   // The first MCID.NumDefs operands must be explicit register defines
1104   if (MONum < NumDefs) {
1105     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1106     if (!MO->isReg())
1107       report("Explicit definition must be a register", MO, MONum);
1108     else if (!MO->isDef() && !MCOI.isOptionalDef())
1109       report("Explicit definition marked as use", MO, MONum);
1110     else if (MO->isImplicit())
1111       report("Explicit definition marked as implicit", MO, MONum);
1112   } else if (MONum < MCID.getNumOperands()) {
1113     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1114     // Don't check if it's the last operand in a variadic instruction. See,
1115     // e.g., LDM_RET in the arm back end.
1116     if (MO->isReg() &&
1117         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
1118       if (MO->isDef() && !MCOI.isOptionalDef())
1119         report("Explicit operand marked as def", MO, MONum);
1120       if (MO->isImplicit())
1121         report("Explicit operand marked as implicit", MO, MONum);
1122     }
1123 
1124     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
1125     if (TiedTo != -1) {
1126       if (!MO->isReg())
1127         report("Tied use must be a register", MO, MONum);
1128       else if (!MO->isTied())
1129         report("Operand should be tied", MO, MONum);
1130       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
1131         report("Tied def doesn't match MCInstrDesc", MO, MONum);
1132       else if (TargetRegisterInfo::isPhysicalRegister(MO->getReg())) {
1133         const MachineOperand &MOTied = MI->getOperand(TiedTo);
1134         if (!MOTied.isReg())
1135           report("Tied counterpart must be a register", &MOTied, TiedTo);
1136         else if (TargetRegisterInfo::isPhysicalRegister(MOTied.getReg()) &&
1137                  MO->getReg() != MOTied.getReg())
1138           report("Tied physical registers must match.", &MOTied, TiedTo);
1139       }
1140     } else if (MO->isReg() && MO->isTied())
1141       report("Explicit operand should not be tied", MO, MONum);
1142   } else {
1143     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1144     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
1145       report("Extra explicit operand on non-variadic instruction", MO, MONum);
1146   }
1147 
1148   switch (MO->getType()) {
1149   case MachineOperand::MO_Register: {
1150     const unsigned Reg = MO->getReg();
1151     if (!Reg)
1152       return;
1153     if (MRI->tracksLiveness() && !MI->isDebugValue())
1154       checkLiveness(MO, MONum);
1155 
1156     // Verify the consistency of tied operands.
1157     if (MO->isTied()) {
1158       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
1159       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
1160       if (!OtherMO.isReg())
1161         report("Must be tied to a register", MO, MONum);
1162       if (!OtherMO.isTied())
1163         report("Missing tie flags on tied operand", MO, MONum);
1164       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
1165         report("Inconsistent tie links", MO, MONum);
1166       if (MONum < MCID.getNumDefs()) {
1167         if (OtherIdx < MCID.getNumOperands()) {
1168           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
1169             report("Explicit def tied to explicit use without tie constraint",
1170                    MO, MONum);
1171         } else {
1172           if (!OtherMO.isImplicit())
1173             report("Explicit def should be tied to implicit use", MO, MONum);
1174         }
1175       }
1176     }
1177 
1178     // Verify two-address constraints after leaving SSA form.
1179     unsigned DefIdx;
1180     if (!MRI->isSSA() && MO->isUse() &&
1181         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
1182         Reg != MI->getOperand(DefIdx).getReg())
1183       report("Two-address instruction operands must be identical", MO, MONum);
1184 
1185     // Check register classes.
1186     unsigned SubIdx = MO->getSubReg();
1187 
1188     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1189       if (SubIdx) {
1190         report("Illegal subregister index for physical register", MO, MONum);
1191         return;
1192       }
1193       if (MONum < MCID.getNumOperands()) {
1194         if (const TargetRegisterClass *DRC =
1195               TII->getRegClass(MCID, MONum, TRI, *MF)) {
1196           if (!DRC->contains(Reg)) {
1197             report("Illegal physical register for instruction", MO, MONum);
1198             errs() << printReg(Reg, TRI) << " is not a "
1199                    << TRI->getRegClassName(DRC) << " register.\n";
1200           }
1201         }
1202       }
1203       if (MO->isRenamable()) {
1204         if (MRI->isReserved(Reg)) {
1205           report("isRenamable set on reserved register", MO, MONum);
1206           return;
1207         }
1208       }
1209       if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) {
1210         report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum);
1211         return;
1212       }
1213     } else {
1214       // Virtual register.
1215       const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
1216       if (!RC) {
1217         // This is a generic virtual register.
1218 
1219         // If we're post-Select, we can't have gvregs anymore.
1220         if (isFunctionSelected) {
1221           report("Generic virtual register invalid in a Selected function",
1222                  MO, MONum);
1223           return;
1224         }
1225 
1226         // The gvreg must have a type and it must not have a SubIdx.
1227         LLT Ty = MRI->getType(Reg);
1228         if (!Ty.isValid()) {
1229           report("Generic virtual register must have a valid type", MO,
1230                  MONum);
1231           return;
1232         }
1233 
1234         const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
1235 
1236         // If we're post-RegBankSelect, the gvreg must have a bank.
1237         if (!RegBank && isFunctionRegBankSelected) {
1238           report("Generic virtual register must have a bank in a "
1239                  "RegBankSelected function",
1240                  MO, MONum);
1241           return;
1242         }
1243 
1244         // Make sure the register fits into its register bank if any.
1245         if (RegBank && Ty.isValid() &&
1246             RegBank->getSize() < Ty.getSizeInBits()) {
1247           report("Register bank is too small for virtual register", MO,
1248                  MONum);
1249           errs() << "Register bank " << RegBank->getName() << " too small("
1250                  << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
1251                  << "-bits\n";
1252           return;
1253         }
1254         if (SubIdx)  {
1255           report("Generic virtual register does not subregister index", MO,
1256                  MONum);
1257           return;
1258         }
1259 
1260         // If this is a target specific instruction and this operand
1261         // has register class constraint, the virtual register must
1262         // comply to it.
1263         if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
1264             MONum < MCID.getNumOperands() &&
1265             TII->getRegClass(MCID, MONum, TRI, *MF)) {
1266           report("Virtual register does not match instruction constraint", MO,
1267                  MONum);
1268           errs() << "Expect register class "
1269                  << TRI->getRegClassName(
1270                         TII->getRegClass(MCID, MONum, TRI, *MF))
1271                  << " but got nothing\n";
1272           return;
1273         }
1274 
1275         break;
1276       }
1277       if (SubIdx) {
1278         const TargetRegisterClass *SRC =
1279           TRI->getSubClassWithSubReg(RC, SubIdx);
1280         if (!SRC) {
1281           report("Invalid subregister index for virtual register", MO, MONum);
1282           errs() << "Register class " << TRI->getRegClassName(RC)
1283               << " does not support subreg index " << SubIdx << "\n";
1284           return;
1285         }
1286         if (RC != SRC) {
1287           report("Invalid register class for subregister index", MO, MONum);
1288           errs() << "Register class " << TRI->getRegClassName(RC)
1289               << " does not fully support subreg index " << SubIdx << "\n";
1290           return;
1291         }
1292       }
1293       if (MONum < MCID.getNumOperands()) {
1294         if (const TargetRegisterClass *DRC =
1295               TII->getRegClass(MCID, MONum, TRI, *MF)) {
1296           if (SubIdx) {
1297             const TargetRegisterClass *SuperRC =
1298                 TRI->getLargestLegalSuperClass(RC, *MF);
1299             if (!SuperRC) {
1300               report("No largest legal super class exists.", MO, MONum);
1301               return;
1302             }
1303             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
1304             if (!DRC) {
1305               report("No matching super-reg register class.", MO, MONum);
1306               return;
1307             }
1308           }
1309           if (!RC->hasSuperClassEq(DRC)) {
1310             report("Illegal virtual register for instruction", MO, MONum);
1311             errs() << "Expected a " << TRI->getRegClassName(DRC)
1312                 << " register, but got a " << TRI->getRegClassName(RC)
1313                 << " register\n";
1314           }
1315         }
1316       }
1317     }
1318     break;
1319   }
1320 
1321   case MachineOperand::MO_RegisterMask:
1322     regMasks.push_back(MO->getRegMask());
1323     break;
1324 
1325   case MachineOperand::MO_MachineBasicBlock:
1326     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
1327       report("PHI operand is not in the CFG", MO, MONum);
1328     break;
1329 
1330   case MachineOperand::MO_FrameIndex:
1331     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
1332         LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1333       int FI = MO->getIndex();
1334       LiveInterval &LI = LiveStks->getInterval(FI);
1335       SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
1336 
1337       bool stores = MI->mayStore();
1338       bool loads = MI->mayLoad();
1339       // For a memory-to-memory move, we need to check if the frame
1340       // index is used for storing or loading, by inspecting the
1341       // memory operands.
1342       if (stores && loads) {
1343         for (auto *MMO : MI->memoperands()) {
1344           const PseudoSourceValue *PSV = MMO->getPseudoValue();
1345           if (PSV == nullptr) continue;
1346           const FixedStackPseudoSourceValue *Value =
1347             dyn_cast<FixedStackPseudoSourceValue>(PSV);
1348           if (Value == nullptr) continue;
1349           if (Value->getFrameIndex() != FI) continue;
1350 
1351           if (MMO->isStore())
1352             loads = false;
1353           else
1354             stores = false;
1355           break;
1356         }
1357         if (loads == stores)
1358           report("Missing fixed stack memoperand.", MI);
1359       }
1360       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
1361         report("Instruction loads from dead spill slot", MO, MONum);
1362         errs() << "Live stack: " << LI << '\n';
1363       }
1364       if (stores && !LI.liveAt(Idx.getRegSlot())) {
1365         report("Instruction stores to dead spill slot", MO, MONum);
1366         errs() << "Live stack: " << LI << '\n';
1367       }
1368     }
1369     break;
1370 
1371   default:
1372     break;
1373   }
1374 }
1375 
1376 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
1377     unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
1378     LaneBitmask LaneMask) {
1379   LiveQueryResult LRQ = LR.Query(UseIdx);
1380   // Check if we have a segment at the use, note however that we only need one
1381   // live subregister range, the others may be dead.
1382   if (!LRQ.valueIn() && LaneMask.none()) {
1383     report("No live segment at use", MO, MONum);
1384     report_context_liverange(LR);
1385     report_context_vreg_regunit(VRegOrUnit);
1386     report_context(UseIdx);
1387   }
1388   if (MO->isKill() && !LRQ.isKill()) {
1389     report("Live range continues after kill flag", MO, MONum);
1390     report_context_liverange(LR);
1391     report_context_vreg_regunit(VRegOrUnit);
1392     if (LaneMask.any())
1393       report_context_lanemask(LaneMask);
1394     report_context(UseIdx);
1395   }
1396 }
1397 
1398 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
1399     unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
1400     bool SubRangeCheck, LaneBitmask LaneMask) {
1401   if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
1402     assert(VNI && "NULL valno is not allowed");
1403     if (VNI->def != DefIdx) {
1404       report("Inconsistent valno->def", MO, MONum);
1405       report_context_liverange(LR);
1406       report_context_vreg_regunit(VRegOrUnit);
1407       if (LaneMask.any())
1408         report_context_lanemask(LaneMask);
1409       report_context(*VNI);
1410       report_context(DefIdx);
1411     }
1412   } else {
1413     report("No live segment at def", MO, MONum);
1414     report_context_liverange(LR);
1415     report_context_vreg_regunit(VRegOrUnit);
1416     if (LaneMask.any())
1417       report_context_lanemask(LaneMask);
1418     report_context(DefIdx);
1419   }
1420   // Check that, if the dead def flag is present, LiveInts agree.
1421   if (MO->isDead()) {
1422     LiveQueryResult LRQ = LR.Query(DefIdx);
1423     if (!LRQ.isDeadDef()) {
1424       assert(TargetRegisterInfo::isVirtualRegister(VRegOrUnit) &&
1425              "Expecting a virtual register.");
1426       // A dead subreg def only tells us that the specific subreg is dead. There
1427       // could be other non-dead defs of other subregs, or we could have other
1428       // parts of the register being live through the instruction. So unless we
1429       // are checking liveness for a subrange it is ok for the live range to
1430       // continue, given that we have a dead def of a subregister.
1431       if (SubRangeCheck || MO->getSubReg() == 0) {
1432         report("Live range continues after dead def flag", MO, MONum);
1433         report_context_liverange(LR);
1434         report_context_vreg_regunit(VRegOrUnit);
1435         if (LaneMask.any())
1436           report_context_lanemask(LaneMask);
1437       }
1438     }
1439   }
1440 }
1441 
1442 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1443   const MachineInstr *MI = MO->getParent();
1444   const unsigned Reg = MO->getReg();
1445 
1446   // Both use and def operands can read a register.
1447   if (MO->readsReg()) {
1448     if (MO->isKill())
1449       addRegWithSubRegs(regsKilled, Reg);
1450 
1451     // Check that LiveVars knows this kill.
1452     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1453         MO->isKill()) {
1454       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1455       if (!is_contained(VI.Kills, MI))
1456         report("Kill missing from LiveVariables", MO, MONum);
1457     }
1458 
1459     // Check LiveInts liveness and kill.
1460     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1461       SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
1462       // Check the cached regunit intervals.
1463       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1464         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1465           if (MRI->isReservedRegUnit(*Units))
1466             continue;
1467           if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
1468             checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
1469         }
1470       }
1471 
1472       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1473         if (LiveInts->hasInterval(Reg)) {
1474           // This is a virtual register interval.
1475           const LiveInterval &LI = LiveInts->getInterval(Reg);
1476           checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg);
1477 
1478           if (LI.hasSubRanges() && !MO->isDef()) {
1479             unsigned SubRegIdx = MO->getSubReg();
1480             LaneBitmask MOMask = SubRegIdx != 0
1481                                ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1482                                : MRI->getMaxLaneMaskForVReg(Reg);
1483             LaneBitmask LiveInMask;
1484             for (const LiveInterval::SubRange &SR : LI.subranges()) {
1485               if ((MOMask & SR.LaneMask).none())
1486                 continue;
1487               checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
1488               LiveQueryResult LRQ = SR.Query(UseIdx);
1489               if (LRQ.valueIn())
1490                 LiveInMask |= SR.LaneMask;
1491             }
1492             // At least parts of the register has to be live at the use.
1493             if ((LiveInMask & MOMask).none()) {
1494               report("No live subrange at use", MO, MONum);
1495               report_context(LI);
1496               report_context(UseIdx);
1497             }
1498           }
1499         } else {
1500           report("Virtual register has no live interval", MO, MONum);
1501         }
1502       }
1503     }
1504 
1505     // Use of a dead register.
1506     if (!regsLive.count(Reg)) {
1507       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1508         // Reserved registers may be used even when 'dead'.
1509         bool Bad = !isReserved(Reg);
1510         // We are fine if just any subregister has a defined value.
1511         if (Bad) {
1512           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
1513                ++SubRegs) {
1514             if (regsLive.count(*SubRegs)) {
1515               Bad = false;
1516               break;
1517             }
1518           }
1519         }
1520         // If there is an additional implicit-use of a super register we stop
1521         // here. By definition we are fine if the super register is not
1522         // (completely) dead, if the complete super register is dead we will
1523         // get a report for its operand.
1524         if (Bad) {
1525           for (const MachineOperand &MOP : MI->uses()) {
1526             if (!MOP.isReg() || !MOP.isImplicit())
1527               continue;
1528 
1529             if (!TargetRegisterInfo::isPhysicalRegister(MOP.getReg()))
1530               continue;
1531 
1532             for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1533                  ++SubRegs) {
1534               if (*SubRegs == Reg) {
1535                 Bad = false;
1536                 break;
1537               }
1538             }
1539           }
1540         }
1541         if (Bad)
1542           report("Using an undefined physical register", MO, MONum);
1543       } else if (MRI->def_empty(Reg)) {
1544         report("Reading virtual register without a def", MO, MONum);
1545       } else {
1546         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1547         // We don't know which virtual registers are live in, so only complain
1548         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1549         // must be live in. PHI instructions are handled separately.
1550         if (MInfo.regsKilled.count(Reg))
1551           report("Using a killed virtual register", MO, MONum);
1552         else if (!MI->isPHI())
1553           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1554       }
1555     }
1556   }
1557 
1558   if (MO->isDef()) {
1559     // Register defined.
1560     // TODO: verify that earlyclobber ops are not used.
1561     if (MO->isDead())
1562       addRegWithSubRegs(regsDead, Reg);
1563     else
1564       addRegWithSubRegs(regsDefined, Reg);
1565 
1566     // Verify SSA form.
1567     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1568         std::next(MRI->def_begin(Reg)) != MRI->def_end())
1569       report("Multiple virtual register defs in SSA form", MO, MONum);
1570 
1571     // Check LiveInts for a live segment, but only for virtual registers.
1572     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
1573       SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
1574       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1575 
1576       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1577         if (LiveInts->hasInterval(Reg)) {
1578           const LiveInterval &LI = LiveInts->getInterval(Reg);
1579           checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg);
1580 
1581           if (LI.hasSubRanges()) {
1582             unsigned SubRegIdx = MO->getSubReg();
1583             LaneBitmask MOMask = SubRegIdx != 0
1584               ? TRI->getSubRegIndexLaneMask(SubRegIdx)
1585               : MRI->getMaxLaneMaskForVReg(Reg);
1586             for (const LiveInterval::SubRange &SR : LI.subranges()) {
1587               if ((SR.LaneMask & MOMask).none())
1588                 continue;
1589               checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
1590             }
1591           }
1592         } else {
1593           report("Virtual register has no Live interval", MO, MONum);
1594         }
1595       }
1596     }
1597   }
1598 }
1599 
1600 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {}
1601 
1602 // This function gets called after visiting all instructions in a bundle. The
1603 // argument points to the bundle header.
1604 // Normal stand-alone instructions are also considered 'bundles', and this
1605 // function is called for all of them.
1606 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1607   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1608   set_union(MInfo.regsKilled, regsKilled);
1609   set_subtract(regsLive, regsKilled); regsKilled.clear();
1610   // Kill any masked registers.
1611   while (!regMasks.empty()) {
1612     const uint32_t *Mask = regMasks.pop_back_val();
1613     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1614       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1615           MachineOperand::clobbersPhysReg(Mask, *I))
1616         regsDead.push_back(*I);
1617   }
1618   set_subtract(regsLive, regsDead);   regsDead.clear();
1619   set_union(regsLive, regsDefined);   regsDefined.clear();
1620 }
1621 
1622 void
1623 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1624   MBBInfoMap[MBB].regsLiveOut = regsLive;
1625   regsLive.clear();
1626 
1627   if (Indexes) {
1628     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1629     if (!(stop > lastIndex)) {
1630       report("Block ends before last instruction index", MBB);
1631       errs() << "Block ends at " << stop
1632           << " last instruction was at " << lastIndex << '\n';
1633     }
1634     lastIndex = stop;
1635   }
1636 }
1637 
1638 // Calculate the largest possible vregsPassed sets. These are the registers that
1639 // can pass through an MBB live, but may not be live every time. It is assumed
1640 // that all vregsPassed sets are empty before the call.
1641 void MachineVerifier::calcRegsPassed() {
1642   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1643   // have any vregsPassed.
1644   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1645   for (const auto &MBB : *MF) {
1646     BBInfo &MInfo = MBBInfoMap[&MBB];
1647     if (!MInfo.reachable)
1648       continue;
1649     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1650            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1651       BBInfo &SInfo = MBBInfoMap[*SuI];
1652       if (SInfo.addPassed(MInfo.regsLiveOut))
1653         todo.insert(*SuI);
1654     }
1655   }
1656 
1657   // Iteratively push vregsPassed to successors. This will converge to the same
1658   // final state regardless of DenseSet iteration order.
1659   while (!todo.empty()) {
1660     const MachineBasicBlock *MBB = *todo.begin();
1661     todo.erase(MBB);
1662     BBInfo &MInfo = MBBInfoMap[MBB];
1663     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1664            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1665       if (*SuI == MBB)
1666         continue;
1667       BBInfo &SInfo = MBBInfoMap[*SuI];
1668       if (SInfo.addPassed(MInfo.vregsPassed))
1669         todo.insert(*SuI);
1670     }
1671   }
1672 }
1673 
1674 // Calculate the set of virtual registers that must be passed through each basic
1675 // block in order to satisfy the requirements of successor blocks. This is very
1676 // similar to calcRegsPassed, only backwards.
1677 void MachineVerifier::calcRegsRequired() {
1678   // First push live-in regs to predecessors' vregsRequired.
1679   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1680   for (const auto &MBB : *MF) {
1681     BBInfo &MInfo = MBBInfoMap[&MBB];
1682     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1683            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1684       BBInfo &PInfo = MBBInfoMap[*PrI];
1685       if (PInfo.addRequired(MInfo.vregsLiveIn))
1686         todo.insert(*PrI);
1687     }
1688   }
1689 
1690   // Iteratively push vregsRequired to predecessors. This will converge to the
1691   // same final state regardless of DenseSet iteration order.
1692   while (!todo.empty()) {
1693     const MachineBasicBlock *MBB = *todo.begin();
1694     todo.erase(MBB);
1695     BBInfo &MInfo = MBBInfoMap[MBB];
1696     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1697            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1698       if (*PrI == MBB)
1699         continue;
1700       BBInfo &SInfo = MBBInfoMap[*PrI];
1701       if (SInfo.addRequired(MInfo.vregsRequired))
1702         todo.insert(*PrI);
1703     }
1704   }
1705 }
1706 
1707 // Check PHI instructions at the beginning of MBB. It is assumed that
1708 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1709 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
1710   BBInfo &MInfo = MBBInfoMap[&MBB];
1711 
1712   SmallPtrSet<const MachineBasicBlock*, 8> seen;
1713   for (const MachineInstr &Phi : MBB) {
1714     if (!Phi.isPHI())
1715       break;
1716     seen.clear();
1717 
1718     const MachineOperand &MODef = Phi.getOperand(0);
1719     if (!MODef.isReg() || !MODef.isDef()) {
1720       report("Expected first PHI operand to be a register def", &MODef, 0);
1721       continue;
1722     }
1723     if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
1724         MODef.isEarlyClobber() || MODef.isDebug())
1725       report("Unexpected flag on PHI operand", &MODef, 0);
1726     unsigned DefReg = MODef.getReg();
1727     if (!TargetRegisterInfo::isVirtualRegister(DefReg))
1728       report("Expected first PHI operand to be a virtual register", &MODef, 0);
1729 
1730     for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
1731       const MachineOperand &MO0 = Phi.getOperand(I);
1732       if (!MO0.isReg()) {
1733         report("Expected PHI operand to be a register", &MO0, I);
1734         continue;
1735       }
1736       if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
1737           MO0.isDebug() || MO0.isTied())
1738         report("Unexpected flag on PHI operand", &MO0, I);
1739 
1740       const MachineOperand &MO1 = Phi.getOperand(I + 1);
1741       if (!MO1.isMBB()) {
1742         report("Expected PHI operand to be a basic block", &MO1, I + 1);
1743         continue;
1744       }
1745 
1746       const MachineBasicBlock &Pre = *MO1.getMBB();
1747       if (!Pre.isSuccessor(&MBB)) {
1748         report("PHI input is not a predecessor block", &MO1, I + 1);
1749         continue;
1750       }
1751 
1752       if (MInfo.reachable) {
1753         seen.insert(&Pre);
1754         BBInfo &PrInfo = MBBInfoMap[&Pre];
1755         if (!MO0.isUndef() && PrInfo.reachable &&
1756             !PrInfo.isLiveOut(MO0.getReg()))
1757           report("PHI operand is not live-out from predecessor", &MO0, I);
1758       }
1759     }
1760 
1761     // Did we see all predecessors?
1762     if (MInfo.reachable) {
1763       for (MachineBasicBlock *Pred : MBB.predecessors()) {
1764         if (!seen.count(Pred)) {
1765           report("Missing PHI operand", &Phi);
1766           errs() << printMBBReference(*Pred)
1767                  << " is a predecessor according to the CFG.\n";
1768         }
1769       }
1770     }
1771   }
1772 }
1773 
1774 void MachineVerifier::visitMachineFunctionAfter() {
1775   calcRegsPassed();
1776 
1777   for (const MachineBasicBlock &MBB : *MF)
1778     checkPHIOps(MBB);
1779 
1780   // Now check liveness info if available
1781   calcRegsRequired();
1782 
1783   // Check for killed virtual registers that should be live out.
1784   for (const auto &MBB : *MF) {
1785     BBInfo &MInfo = MBBInfoMap[&MBB];
1786     for (RegSet::iterator
1787          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1788          ++I)
1789       if (MInfo.regsKilled.count(*I)) {
1790         report("Virtual register killed in block, but needed live out.", &MBB);
1791         errs() << "Virtual register " << printReg(*I)
1792                << " is used after the block.\n";
1793       }
1794   }
1795 
1796   if (!MF->empty()) {
1797     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1798     for (RegSet::iterator
1799          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1800          ++I) {
1801       report("Virtual register defs don't dominate all uses.", MF);
1802       report_context_vreg(*I);
1803     }
1804   }
1805 
1806   if (LiveVars)
1807     verifyLiveVariables();
1808   if (LiveInts)
1809     verifyLiveIntervals();
1810 }
1811 
1812 void MachineVerifier::verifyLiveVariables() {
1813   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1814   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1815     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1816     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1817     for (const auto &MBB : *MF) {
1818       BBInfo &MInfo = MBBInfoMap[&MBB];
1819 
1820       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1821       if (MInfo.vregsRequired.count(Reg)) {
1822         if (!VI.AliveBlocks.test(MBB.getNumber())) {
1823           report("LiveVariables: Block missing from AliveBlocks", &MBB);
1824           errs() << "Virtual register " << printReg(Reg)
1825                  << " must be live through the block.\n";
1826         }
1827       } else {
1828         if (VI.AliveBlocks.test(MBB.getNumber())) {
1829           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1830           errs() << "Virtual register " << printReg(Reg)
1831                  << " is not needed live through the block.\n";
1832         }
1833       }
1834     }
1835   }
1836 }
1837 
1838 void MachineVerifier::verifyLiveIntervals() {
1839   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1840   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1841     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1842 
1843     // Spilling and splitting may leave unused registers around. Skip them.
1844     if (MRI->reg_nodbg_empty(Reg))
1845       continue;
1846 
1847     if (!LiveInts->hasInterval(Reg)) {
1848       report("Missing live interval for virtual register", MF);
1849       errs() << printReg(Reg, TRI) << " still has defs or uses\n";
1850       continue;
1851     }
1852 
1853     const LiveInterval &LI = LiveInts->getInterval(Reg);
1854     assert(Reg == LI.reg && "Invalid reg to interval mapping");
1855     verifyLiveInterval(LI);
1856   }
1857 
1858   // Verify all the cached regunit intervals.
1859   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1860     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1861       verifyLiveRange(*LR, i);
1862 }
1863 
1864 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1865                                            const VNInfo *VNI, unsigned Reg,
1866                                            LaneBitmask LaneMask) {
1867   if (VNI->isUnused())
1868     return;
1869 
1870   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1871 
1872   if (!DefVNI) {
1873     report("Value not live at VNInfo def and not marked unused", MF);
1874     report_context(LR, Reg, LaneMask);
1875     report_context(*VNI);
1876     return;
1877   }
1878 
1879   if (DefVNI != VNI) {
1880     report("Live segment at def has different VNInfo", MF);
1881     report_context(LR, Reg, LaneMask);
1882     report_context(*VNI);
1883     return;
1884   }
1885 
1886   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1887   if (!MBB) {
1888     report("Invalid VNInfo definition index", MF);
1889     report_context(LR, Reg, LaneMask);
1890     report_context(*VNI);
1891     return;
1892   }
1893 
1894   if (VNI->isPHIDef()) {
1895     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1896       report("PHIDef VNInfo is not defined at MBB start", MBB);
1897       report_context(LR, Reg, LaneMask);
1898       report_context(*VNI);
1899     }
1900     return;
1901   }
1902 
1903   // Non-PHI def.
1904   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1905   if (!MI) {
1906     report("No instruction at VNInfo def index", MBB);
1907     report_context(LR, Reg, LaneMask);
1908     report_context(*VNI);
1909     return;
1910   }
1911 
1912   if (Reg != 0) {
1913     bool hasDef = false;
1914     bool isEarlyClobber = false;
1915     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
1916       if (!MOI->isReg() || !MOI->isDef())
1917         continue;
1918       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1919         if (MOI->getReg() != Reg)
1920           continue;
1921       } else {
1922         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1923             !TRI->hasRegUnit(MOI->getReg(), Reg))
1924           continue;
1925       }
1926       if (LaneMask.any() &&
1927           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
1928         continue;
1929       hasDef = true;
1930       if (MOI->isEarlyClobber())
1931         isEarlyClobber = true;
1932     }
1933 
1934     if (!hasDef) {
1935       report("Defining instruction does not modify register", MI);
1936       report_context(LR, Reg, LaneMask);
1937       report_context(*VNI);
1938     }
1939 
1940     // Early clobber defs begin at USE slots, but other defs must begin at
1941     // DEF slots.
1942     if (isEarlyClobber) {
1943       if (!VNI->def.isEarlyClobber()) {
1944         report("Early clobber def must be at an early-clobber slot", MBB);
1945         report_context(LR, Reg, LaneMask);
1946         report_context(*VNI);
1947       }
1948     } else if (!VNI->def.isRegister()) {
1949       report("Non-PHI, non-early clobber def must be at a register slot", MBB);
1950       report_context(LR, Reg, LaneMask);
1951       report_context(*VNI);
1952     }
1953   }
1954 }
1955 
1956 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1957                                              const LiveRange::const_iterator I,
1958                                              unsigned Reg, LaneBitmask LaneMask)
1959 {
1960   const LiveRange::Segment &S = *I;
1961   const VNInfo *VNI = S.valno;
1962   assert(VNI && "Live segment has no valno");
1963 
1964   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1965     report("Foreign valno in live segment", MF);
1966     report_context(LR, Reg, LaneMask);
1967     report_context(S);
1968     report_context(*VNI);
1969   }
1970 
1971   if (VNI->isUnused()) {
1972     report("Live segment valno is marked unused", MF);
1973     report_context(LR, Reg, LaneMask);
1974     report_context(S);
1975   }
1976 
1977   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1978   if (!MBB) {
1979     report("Bad start of live segment, no basic block", MF);
1980     report_context(LR, Reg, LaneMask);
1981     report_context(S);
1982     return;
1983   }
1984   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1985   if (S.start != MBBStartIdx && S.start != VNI->def) {
1986     report("Live segment must begin at MBB entry or valno def", MBB);
1987     report_context(LR, Reg, LaneMask);
1988     report_context(S);
1989   }
1990 
1991   const MachineBasicBlock *EndMBB =
1992     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1993   if (!EndMBB) {
1994     report("Bad end of live segment, no basic block", MF);
1995     report_context(LR, Reg, LaneMask);
1996     report_context(S);
1997     return;
1998   }
1999 
2000   // No more checks for live-out segments.
2001   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
2002     return;
2003 
2004   // RegUnit intervals are allowed dead phis.
2005   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
2006       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
2007     return;
2008 
2009   // The live segment is ending inside EndMBB
2010   const MachineInstr *MI =
2011     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
2012   if (!MI) {
2013     report("Live segment doesn't end at a valid instruction", EndMBB);
2014     report_context(LR, Reg, LaneMask);
2015     report_context(S);
2016     return;
2017   }
2018 
2019   // The block slot must refer to a basic block boundary.
2020   if (S.end.isBlock()) {
2021     report("Live segment ends at B slot of an instruction", EndMBB);
2022     report_context(LR, Reg, LaneMask);
2023     report_context(S);
2024   }
2025 
2026   if (S.end.isDead()) {
2027     // Segment ends on the dead slot.
2028     // That means there must be a dead def.
2029     if (!SlotIndex::isSameInstr(S.start, S.end)) {
2030       report("Live segment ending at dead slot spans instructions", EndMBB);
2031       report_context(LR, Reg, LaneMask);
2032       report_context(S);
2033     }
2034   }
2035 
2036   // A live segment can only end at an early-clobber slot if it is being
2037   // redefined by an early-clobber def.
2038   if (S.end.isEarlyClobber()) {
2039     if (I+1 == LR.end() || (I+1)->start != S.end) {
2040       report("Live segment ending at early clobber slot must be "
2041              "redefined by an EC def in the same instruction", EndMBB);
2042       report_context(LR, Reg, LaneMask);
2043       report_context(S);
2044     }
2045   }
2046 
2047   // The following checks only apply to virtual registers. Physreg liveness
2048   // is too weird to check.
2049   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2050     // A live segment can end with either a redefinition, a kill flag on a
2051     // use, or a dead flag on a def.
2052     bool hasRead = false;
2053     bool hasSubRegDef = false;
2054     bool hasDeadDef = false;
2055     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
2056       if (!MOI->isReg() || MOI->getReg() != Reg)
2057         continue;
2058       unsigned Sub = MOI->getSubReg();
2059       LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
2060                                  : LaneBitmask::getAll();
2061       if (MOI->isDef()) {
2062         if (Sub != 0) {
2063           hasSubRegDef = true;
2064           // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2065           // mask for subregister defs. Read-undef defs will be handled by
2066           // readsReg below.
2067           SLM = ~SLM;
2068         }
2069         if (MOI->isDead())
2070           hasDeadDef = true;
2071       }
2072       if (LaneMask.any() && (LaneMask & SLM).none())
2073         continue;
2074       if (MOI->readsReg())
2075         hasRead = true;
2076     }
2077     if (S.end.isDead()) {
2078       // Make sure that the corresponding machine operand for a "dead" live
2079       // range has the dead flag. We cannot perform this check for subregister
2080       // liveranges as partially dead values are allowed.
2081       if (LaneMask.none() && !hasDeadDef) {
2082         report("Instruction ending live segment on dead slot has no dead flag",
2083                MI);
2084         report_context(LR, Reg, LaneMask);
2085         report_context(S);
2086       }
2087     } else {
2088       if (!hasRead) {
2089         // When tracking subregister liveness, the main range must start new
2090         // values on partial register writes, even if there is no read.
2091         if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
2092             !hasSubRegDef) {
2093           report("Instruction ending live segment doesn't read the register",
2094                  MI);
2095           report_context(LR, Reg, LaneMask);
2096           report_context(S);
2097         }
2098       }
2099     }
2100   }
2101 
2102   // Now check all the basic blocks in this live segment.
2103   MachineFunction::const_iterator MFI = MBB->getIterator();
2104   // Is this live segment the beginning of a non-PHIDef VN?
2105   if (S.start == VNI->def && !VNI->isPHIDef()) {
2106     // Not live-in to any blocks.
2107     if (MBB == EndMBB)
2108       return;
2109     // Skip this block.
2110     ++MFI;
2111   }
2112 
2113   SmallVector<SlotIndex, 4> Undefs;
2114   if (LaneMask.any()) {
2115     LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
2116     OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
2117   }
2118 
2119   while (true) {
2120     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
2121     // We don't know how to track physregs into a landing pad.
2122     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
2123         MFI->isEHPad()) {
2124       if (&*MFI == EndMBB)
2125         break;
2126       ++MFI;
2127       continue;
2128     }
2129 
2130     // Is VNI a PHI-def in the current block?
2131     bool IsPHI = VNI->isPHIDef() &&
2132       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
2133 
2134     // Check that VNI is live-out of all predecessors.
2135     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
2136          PE = MFI->pred_end(); PI != PE; ++PI) {
2137       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
2138       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
2139 
2140       // All predecessors must have a live-out value. However for a phi
2141       // instruction with subregister intervals
2142       // only one of the subregisters (not necessarily the current one) needs to
2143       // be defined.
2144       if (!PVNI && (LaneMask.none() || !IsPHI)) {
2145         if (LiveRangeCalc::isJointlyDominated(*PI, Undefs, *Indexes))
2146           continue;
2147         report("Register not marked live out of predecessor", *PI);
2148         report_context(LR, Reg, LaneMask);
2149         report_context(*VNI);
2150         errs() << " live into " << printMBBReference(*MFI) << '@'
2151                << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
2152                << PEnd << '\n';
2153         continue;
2154       }
2155 
2156       // Only PHI-defs can take different predecessor values.
2157       if (!IsPHI && PVNI != VNI) {
2158         report("Different value live out of predecessor", *PI);
2159         report_context(LR, Reg, LaneMask);
2160         errs() << "Valno #" << PVNI->id << " live out of "
2161                << printMBBReference(*(*PI)) << '@' << PEnd << "\nValno #"
2162                << VNI->id << " live into " << printMBBReference(*MFI) << '@'
2163                << LiveInts->getMBBStartIdx(&*MFI) << '\n';
2164       }
2165     }
2166     if (&*MFI == EndMBB)
2167       break;
2168     ++MFI;
2169   }
2170 }
2171 
2172 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
2173                                       LaneBitmask LaneMask) {
2174   for (const VNInfo *VNI : LR.valnos)
2175     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
2176 
2177   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
2178     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
2179 }
2180 
2181 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
2182   unsigned Reg = LI.reg;
2183   assert(TargetRegisterInfo::isVirtualRegister(Reg));
2184   verifyLiveRange(LI, Reg);
2185 
2186   LaneBitmask Mask;
2187   LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2188   for (const LiveInterval::SubRange &SR : LI.subranges()) {
2189     if ((Mask & SR.LaneMask).any()) {
2190       report("Lane masks of sub ranges overlap in live interval", MF);
2191       report_context(LI);
2192     }
2193     if ((SR.LaneMask & ~MaxMask).any()) {
2194       report("Subrange lanemask is invalid", MF);
2195       report_context(LI);
2196     }
2197     if (SR.empty()) {
2198       report("Subrange must not be empty", MF);
2199       report_context(SR, LI.reg, SR.LaneMask);
2200     }
2201     Mask |= SR.LaneMask;
2202     verifyLiveRange(SR, LI.reg, SR.LaneMask);
2203     if (!LI.covers(SR)) {
2204       report("A Subrange is not covered by the main range", MF);
2205       report_context(LI);
2206     }
2207   }
2208 
2209   // Check the LI only has one connected component.
2210   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
2211   unsigned NumComp = ConEQ.Classify(LI);
2212   if (NumComp > 1) {
2213     report("Multiple connected components in live interval", MF);
2214     report_context(LI);
2215     for (unsigned comp = 0; comp != NumComp; ++comp) {
2216       errs() << comp << ": valnos";
2217       for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
2218            E = LI.vni_end(); I!=E; ++I)
2219         if (comp == ConEQ.getEqClass(*I))
2220           errs() << ' ' << (*I)->id;
2221       errs() << '\n';
2222     }
2223   }
2224 }
2225 
2226 namespace {
2227 
2228   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2229   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2230   // value is zero.
2231   // We use a bool plus an integer to capture the stack state.
2232   struct StackStateOfBB {
2233     StackStateOfBB() = default;
2234     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
2235       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
2236       ExitIsSetup(ExitSetup) {}
2237 
2238     // Can be negative, which means we are setting up a frame.
2239     int EntryValue = 0;
2240     int ExitValue = 0;
2241     bool EntryIsSetup = false;
2242     bool ExitIsSetup = false;
2243   };
2244 
2245 } // end anonymous namespace
2246 
2247 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2248 /// by a FrameDestroy <n>, stack adjustments are identical on all
2249 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
2250 void MachineVerifier::verifyStackFrame() {
2251   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
2252   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
2253   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
2254     return;
2255 
2256   SmallVector<StackStateOfBB, 8> SPState;
2257   SPState.resize(MF->getNumBlockIDs());
2258   df_iterator_default_set<const MachineBasicBlock*> Reachable;
2259 
2260   // Visit the MBBs in DFS order.
2261   for (df_ext_iterator<const MachineFunction *,
2262                        df_iterator_default_set<const MachineBasicBlock *>>
2263        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
2264        DFI != DFE; ++DFI) {
2265     const MachineBasicBlock *MBB = *DFI;
2266 
2267     StackStateOfBB BBState;
2268     // Check the exit state of the DFS stack predecessor.
2269     if (DFI.getPathLength() >= 2) {
2270       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
2271       assert(Reachable.count(StackPred) &&
2272              "DFS stack predecessor is already visited.\n");
2273       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
2274       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
2275       BBState.ExitValue = BBState.EntryValue;
2276       BBState.ExitIsSetup = BBState.EntryIsSetup;
2277     }
2278 
2279     // Update stack state by checking contents of MBB.
2280     for (const auto &I : *MBB) {
2281       if (I.getOpcode() == FrameSetupOpcode) {
2282         if (BBState.ExitIsSetup)
2283           report("FrameSetup is after another FrameSetup", &I);
2284         BBState.ExitValue -= TII->getFrameTotalSize(I);
2285         BBState.ExitIsSetup = true;
2286       }
2287 
2288       if (I.getOpcode() == FrameDestroyOpcode) {
2289         int Size = TII->getFrameTotalSize(I);
2290         if (!BBState.ExitIsSetup)
2291           report("FrameDestroy is not after a FrameSetup", &I);
2292         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
2293                                                BBState.ExitValue;
2294         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
2295           report("FrameDestroy <n> is after FrameSetup <m>", &I);
2296           errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
2297               << AbsSPAdj << ">.\n";
2298         }
2299         BBState.ExitValue += Size;
2300         BBState.ExitIsSetup = false;
2301       }
2302     }
2303     SPState[MBB->getNumber()] = BBState;
2304 
2305     // Make sure the exit state of any predecessor is consistent with the entry
2306     // state.
2307     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
2308          E = MBB->pred_end(); I != E; ++I) {
2309       if (Reachable.count(*I) &&
2310           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
2311            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
2312         report("The exit stack state of a predecessor is inconsistent.", MBB);
2313         errs() << "Predecessor " << printMBBReference(*(*I))
2314                << " has exit state (" << SPState[(*I)->getNumber()].ExitValue
2315                << ", " << SPState[(*I)->getNumber()].ExitIsSetup << "), while "
2316                << printMBBReference(*MBB) << " has entry state ("
2317                << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
2318       }
2319     }
2320 
2321     // Make sure the entry state of any successor is consistent with the exit
2322     // state.
2323     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
2324          E = MBB->succ_end(); I != E; ++I) {
2325       if (Reachable.count(*I) &&
2326           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
2327            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
2328         report("The entry stack state of a successor is inconsistent.", MBB);
2329         errs() << "Successor " << printMBBReference(*(*I))
2330                << " has entry state (" << SPState[(*I)->getNumber()].EntryValue
2331                << ", " << SPState[(*I)->getNumber()].EntryIsSetup << "), while "
2332                << printMBBReference(*MBB) << " has exit state ("
2333                << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
2334       }
2335     }
2336 
2337     // Make sure a basic block with return ends with zero stack adjustment.
2338     if (!MBB->empty() && MBB->back().isReturn()) {
2339       if (BBState.ExitIsSetup)
2340         report("A return block ends with a FrameSetup.", MBB);
2341       if (BBState.ExitValue)
2342         report("A return block ends with a nonzero stack adjustment.", MBB);
2343     }
2344   }
2345 }
2346