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