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