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