xref: /llvm-project/llvm/lib/CodeGen/MachineVerifier.cpp (revision adaa603224fee842b4f71824617adb3b0c7d9cf1)
1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Pass to verify generated machine code. The following is checked:
10 //
11 // Operand counts: All explicit operands must be present.
12 //
13 // Register classes: All physical and virtual register operands must be
14 // compatible with the register class required by the instruction descriptor.
15 //
16 // Register live intervals: Registers must be defined only once, and must be
17 // defined before use.
18 //
19 // The machine code verifier is enabled with the command-line option
20 // -verify-machineinstrs.
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/CodeGen/MachineVerifier.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/PostOrderIterator.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SetOperations.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/Twine.h"
35 #include "llvm/CodeGen/CodeGenCommonISel.h"
36 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
37 #include "llvm/CodeGen/LiveInterval.h"
38 #include "llvm/CodeGen/LiveIntervals.h"
39 #include "llvm/CodeGen/LiveRangeCalc.h"
40 #include "llvm/CodeGen/LiveStacks.h"
41 #include "llvm/CodeGen/LiveVariables.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineConvergenceVerifier.h"
44 #include "llvm/CodeGen/MachineDominators.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineFunctionPass.h"
48 #include "llvm/CodeGen/MachineInstr.h"
49 #include "llvm/CodeGen/MachineInstrBundle.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/PseudoSourceValue.h"
54 #include "llvm/CodeGen/RegisterBank.h"
55 #include "llvm/CodeGen/RegisterBankInfo.h"
56 #include "llvm/CodeGen/SlotIndexes.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGenTypes/LowLevelType.h"
64 #include "llvm/IR/BasicBlock.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/EHPersonalities.h"
67 #include "llvm/IR/Function.h"
68 #include "llvm/IR/InlineAsm.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/InitializePasses.h"
71 #include "llvm/MC/LaneBitmask.h"
72 #include "llvm/MC/MCAsmInfo.h"
73 #include "llvm/MC/MCDwarf.h"
74 #include "llvm/MC/MCInstrDesc.h"
75 #include "llvm/MC/MCRegisterInfo.h"
76 #include "llvm/MC/MCTargetOptions.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/ManagedStatic.h"
81 #include "llvm/Support/MathExtras.h"
82 #include "llvm/Support/ModRef.h"
83 #include "llvm/Support/Mutex.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include <algorithm>
87 #include <cassert>
88 #include <cstddef>
89 #include <cstdint>
90 #include <iterator>
91 #include <string>
92 #include <utility>
93 
94 using namespace llvm;
95 
96 namespace {
97 
98 /// Used the by the ReportedErrors class to guarantee only one error is reported
99 /// at one time.
100 static ManagedStatic<sys::SmartMutex<true>> ReportedErrorsLock;
101 
102 struct MachineVerifier {
103   MachineVerifier(MachineFunctionAnalysisManager &MFAM, const char *b,
104                   raw_ostream *OS, bool AbortOnError = true)
105       : MFAM(&MFAM), OS(OS ? *OS : nulls()), Banner(b),
106         ReportedErrs(AbortOnError) {}
107 
108   MachineVerifier(Pass *pass, const char *b, raw_ostream *OS,
109                   bool AbortOnError = true)
110       : PASS(pass), OS(OS ? *OS : nulls()), Banner(b),
111         ReportedErrs(AbortOnError) {}
112 
113   MachineVerifier(const char *b, LiveVariables *LiveVars,
114                   LiveIntervals *LiveInts, LiveStacks *LiveStks,
115                   SlotIndexes *Indexes, raw_ostream *OS,
116                   bool AbortOnError = true)
117       : OS(OS ? *OS : nulls()), Banner(b), LiveVars(LiveVars),
118         LiveInts(LiveInts), LiveStks(LiveStks), Indexes(Indexes),
119         ReportedErrs(AbortOnError) {}
120 
121   /// \returns true if no problems were found.
122   bool verify(const MachineFunction &MF);
123 
124   MachineFunctionAnalysisManager *MFAM = nullptr;
125   Pass *const PASS = nullptr;
126   raw_ostream &OS;
127   const char *Banner;
128   const MachineFunction *MF = nullptr;
129   const TargetMachine *TM = nullptr;
130   const TargetInstrInfo *TII = nullptr;
131   const TargetRegisterInfo *TRI = nullptr;
132   const MachineRegisterInfo *MRI = nullptr;
133   const RegisterBankInfo *RBI = nullptr;
134 
135   // Avoid querying the MachineFunctionProperties for each operand.
136   bool isFunctionRegBankSelected = false;
137   bool isFunctionSelected = false;
138   bool isFunctionTracksDebugUserValues = false;
139 
140   using RegVector = SmallVector<Register, 16>;
141   using RegMaskVector = SmallVector<const uint32_t *, 4>;
142   using RegSet = DenseSet<Register>;
143   using RegMap = DenseMap<Register, const MachineInstr *>;
144   using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
145 
146   const MachineInstr *FirstNonPHI = nullptr;
147   const MachineInstr *FirstTerminator = nullptr;
148   BlockSet FunctionBlocks;
149 
150   BitVector regsReserved;
151   RegSet regsLive;
152   RegVector regsDefined, regsDead, regsKilled;
153   RegMaskVector regMasks;
154 
155   SlotIndex lastIndex;
156 
157   // Add Reg and any sub-registers to RV
158   void addRegWithSubRegs(RegVector &RV, Register Reg) {
159     RV.push_back(Reg);
160     if (Reg.isPhysical())
161       append_range(RV, TRI->subregs(Reg.asMCReg()));
162   }
163 
164   struct BBInfo {
165     // Is this MBB reachable from the MF entry point?
166     bool reachable = false;
167 
168     // Vregs that must be live in because they are used without being
169     // defined. Map value is the user. vregsLiveIn doesn't include regs
170     // that only are used by PHI nodes.
171     RegMap vregsLiveIn;
172 
173     // Regs killed in MBB. They may be defined again, and will then be in both
174     // regsKilled and regsLiveOut.
175     RegSet regsKilled;
176 
177     // Regs defined in MBB and live out. Note that vregs passing through may
178     // be live out without being mentioned here.
179     RegSet regsLiveOut;
180 
181     // Vregs that pass through MBB untouched. This set is disjoint from
182     // regsKilled and regsLiveOut.
183     RegSet vregsPassed;
184 
185     // Vregs that must pass through MBB because they are needed by a successor
186     // block. This set is disjoint from regsLiveOut.
187     RegSet vregsRequired;
188 
189     // Set versions of block's predecessor and successor lists.
190     BlockSet Preds, Succs;
191 
192     BBInfo() = default;
193 
194     // Add register to vregsRequired if it belongs there. Return true if
195     // anything changed.
196     bool addRequired(Register Reg) {
197       if (!Reg.isVirtual())
198         return false;
199       if (regsLiveOut.count(Reg))
200         return false;
201       return vregsRequired.insert(Reg).second;
202     }
203 
204     // Same for a full set.
205     bool addRequired(const RegSet &RS) {
206       bool Changed = false;
207       for (Register Reg : RS)
208         Changed |= addRequired(Reg);
209       return Changed;
210     }
211 
212     // Same for a full map.
213     bool addRequired(const RegMap &RM) {
214       bool Changed = false;
215       for (const auto &I : RM)
216         Changed |= addRequired(I.first);
217       return Changed;
218     }
219 
220     // Live-out registers are either in regsLiveOut or vregsPassed.
221     bool isLiveOut(Register Reg) const {
222       return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
223     }
224   };
225 
226   // Extra register info per MBB.
227   DenseMap<const MachineBasicBlock *, BBInfo> MBBInfoMap;
228 
229   bool isReserved(Register Reg) {
230     return Reg.id() < regsReserved.size() && regsReserved.test(Reg.id());
231   }
232 
233   bool isAllocatable(Register Reg) const {
234     return Reg.id() < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
235            !regsReserved.test(Reg.id());
236   }
237 
238   // Analysis information if available
239   LiveVariables *LiveVars = nullptr;
240   LiveIntervals *LiveInts = nullptr;
241   LiveStacks *LiveStks = nullptr;
242   SlotIndexes *Indexes = nullptr;
243 
244   /// A class to track the number of reported error and to guarantee that only
245   /// one error is reported at one time.
246   class ReportedErrors {
247     unsigned NumReported = 0;
248     bool AbortOnError;
249 
250   public:
251     /// \param AbortOnError -- If set, abort after printing the first error.
252     ReportedErrors(bool AbortOnError) : AbortOnError(AbortOnError) {}
253 
254     ~ReportedErrors() {
255       if (!hasError())
256         return;
257       if (AbortOnError)
258         report_fatal_error("Found " + Twine(NumReported) +
259                            " machine code errors.");
260       // Since we haven't aborted, release the lock to allow other threads to
261       // report errors.
262       ReportedErrorsLock->unlock();
263     }
264 
265     /// Increment the number of reported errors.
266     /// \returns true if this is the first reported error.
267     bool increment() {
268       // If this is the first error this thread has encountered, grab the lock
269       // to prevent other threads from reporting errors at the same time.
270       // Otherwise we assume we already have the lock.
271       if (!hasError())
272         ReportedErrorsLock->lock();
273       ++NumReported;
274       return NumReported == 1;
275     }
276 
277     /// \returns true if an error was reported.
278     bool hasError() { return NumReported; }
279   };
280   ReportedErrors ReportedErrs;
281 
282   // This is calculated only when trying to verify convergence control tokens.
283   // Similar to the LLVM IR verifier, we calculate this locally instead of
284   // relying on the pass manager.
285   MachineDominatorTree DT;
286 
287   void visitMachineFunctionBefore();
288   void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
289   void visitMachineBundleBefore(const MachineInstr *MI);
290 
291   /// Verify that all of \p MI's virtual register operands are scalars.
292   /// \returns True if all virtual register operands are scalar. False
293   /// otherwise.
294   bool verifyAllRegOpsScalar(const MachineInstr &MI,
295                              const MachineRegisterInfo &MRI);
296   bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
297 
298   bool verifyGIntrinsicSideEffects(const MachineInstr *MI);
299   bool verifyGIntrinsicConvergence(const MachineInstr *MI);
300   void verifyPreISelGenericInstruction(const MachineInstr *MI);
301 
302   void visitMachineInstrBefore(const MachineInstr *MI);
303   void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
304   void visitMachineBundleAfter(const MachineInstr *MI);
305   void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
306   void visitMachineFunctionAfter();
307 
308   void report(const char *msg, const MachineFunction *MF);
309   void report(const char *msg, const MachineBasicBlock *MBB);
310   void report(const char *msg, const MachineInstr *MI);
311   void report(const char *msg, const MachineOperand *MO, unsigned MONum,
312               LLT MOVRegType = LLT{});
313   void report(const Twine &Msg, const MachineInstr *MI);
314 
315   void report_context(const LiveInterval &LI) const;
316   void report_context(const LiveRange &LR, Register VRegUnit,
317                       LaneBitmask LaneMask) const;
318   void report_context(const LiveRange::Segment &S) const;
319   void report_context(const VNInfo &VNI) const;
320   void report_context(SlotIndex Pos) const;
321   void report_context(MCPhysReg PhysReg) const;
322   void report_context_liverange(const LiveRange &LR) const;
323   void report_context_lanemask(LaneBitmask LaneMask) const;
324   void report_context_vreg(Register VReg) const;
325   void report_context_vreg_regunit(Register VRegOrUnit) const;
326 
327   void verifyInlineAsm(const MachineInstr *MI);
328 
329   void checkLiveness(const MachineOperand *MO, unsigned MONum);
330   void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
331                           SlotIndex UseIdx, const LiveRange &LR,
332                           Register VRegOrUnit,
333                           LaneBitmask LaneMask = LaneBitmask::getNone());
334   void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
335                           SlotIndex DefIdx, const LiveRange &LR,
336                           Register VRegOrUnit, bool SubRangeCheck = false,
337                           LaneBitmask LaneMask = LaneBitmask::getNone());
338 
339   void markReachable(const MachineBasicBlock *MBB);
340   void calcRegsPassed();
341   void checkPHIOps(const MachineBasicBlock &MBB);
342 
343   void calcRegsRequired();
344   void verifyLiveVariables();
345   void verifyLiveIntervals();
346   void verifyLiveInterval(const LiveInterval &);
347   void verifyLiveRangeValue(const LiveRange &, const VNInfo *, Register,
348                             LaneBitmask);
349   void verifyLiveRangeSegment(const LiveRange &,
350                               const LiveRange::const_iterator I, Register,
351                               LaneBitmask);
352   void verifyLiveRange(const LiveRange &, Register,
353                        LaneBitmask LaneMask = LaneBitmask::getNone());
354 
355   void verifyStackFrame();
356 
357   void verifySlotIndexes() const;
358   void verifyProperties(const MachineFunction &MF);
359 };
360 
361 struct MachineVerifierLegacyPass : public MachineFunctionPass {
362   static char ID; // Pass ID, replacement for typeid
363 
364   const std::string Banner;
365 
366   MachineVerifierLegacyPass(std::string banner = std::string())
367       : MachineFunctionPass(ID), Banner(std::move(banner)) {
368     initializeMachineVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
369   }
370 
371   void getAnalysisUsage(AnalysisUsage &AU) const override {
372     AU.addUsedIfAvailable<LiveStacks>();
373     AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
374     AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
375     AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
376     AU.setPreservesAll();
377     MachineFunctionPass::getAnalysisUsage(AU);
378   }
379 
380   bool runOnMachineFunction(MachineFunction &MF) override {
381     // Skip functions that have known verification problems.
382     // FIXME: Remove this mechanism when all problematic passes have been
383     // fixed.
384     if (MF.getProperties().hasProperty(
385             MachineFunctionProperties::Property::FailsVerification))
386       return false;
387 
388     MachineVerifier(this, Banner.c_str(), &errs()).verify(MF);
389     return false;
390   }
391 };
392 
393 } // end anonymous namespace
394 
395 PreservedAnalyses
396 MachineVerifierPass::run(MachineFunction &MF,
397                          MachineFunctionAnalysisManager &MFAM) {
398   // Skip functions that have known verification problems.
399   // FIXME: Remove this mechanism when all problematic passes have been
400   // fixed.
401   if (MF.getProperties().hasProperty(
402           MachineFunctionProperties::Property::FailsVerification))
403     return PreservedAnalyses::all();
404   MachineVerifier(MFAM, Banner.c_str(), &errs()).verify(MF);
405   return PreservedAnalyses::all();
406 }
407 
408 char MachineVerifierLegacyPass::ID = 0;
409 
410 INITIALIZE_PASS(MachineVerifierLegacyPass, "machineverifier",
411                 "Verify generated machine code", false, false)
412 
413 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
414   return new MachineVerifierLegacyPass(Banner);
415 }
416 
417 void llvm::verifyMachineFunction(const std::string &Banner,
418                                  const MachineFunction &MF) {
419   // TODO: Use MFAM after porting below analyses.
420   // LiveVariables *LiveVars;
421   // LiveIntervals *LiveInts;
422   // LiveStacks *LiveStks;
423   // SlotIndexes *Indexes;
424   MachineVerifier(nullptr, Banner.c_str(), &errs()).verify(MF);
425 }
426 
427 bool MachineFunction::verify(Pass *p, const char *Banner, raw_ostream *OS,
428                              bool AbortOnError) const {
429   return MachineVerifier(p, Banner, OS, AbortOnError).verify(*this);
430 }
431 
432 bool MachineFunction::verify(LiveIntervals *LiveInts, SlotIndexes *Indexes,
433                              const char *Banner, raw_ostream *OS,
434                              bool AbortOnError) const {
435   return MachineVerifier(Banner, /*LiveVars=*/nullptr, LiveInts,
436                          /*LiveStks=*/nullptr, Indexes, OS, AbortOnError)
437       .verify(*this);
438 }
439 
440 void MachineVerifier::verifySlotIndexes() const {
441   if (Indexes == nullptr)
442     return;
443 
444   // Ensure the IdxMBB list is sorted by slot indexes.
445   SlotIndex Last;
446   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
447        E = Indexes->MBBIndexEnd(); I != E; ++I) {
448     assert(!Last.isValid() || I->first > Last);
449     Last = I->first;
450   }
451 }
452 
453 void MachineVerifier::verifyProperties(const MachineFunction &MF) {
454   // If a pass has introduced virtual registers without clearing the
455   // NoVRegs property (or set it without allocating the vregs)
456   // then report an error.
457   if (MF.getProperties().hasProperty(
458           MachineFunctionProperties::Property::NoVRegs) &&
459       MRI->getNumVirtRegs())
460     report("Function has NoVRegs property but there are VReg operands", &MF);
461 }
462 
463 bool MachineVerifier::verify(const MachineFunction &MF) {
464   this->MF = &MF;
465   TM = &MF.getTarget();
466   TII = MF.getSubtarget().getInstrInfo();
467   TRI = MF.getSubtarget().getRegisterInfo();
468   RBI = MF.getSubtarget().getRegBankInfo();
469   MRI = &MF.getRegInfo();
470 
471   const bool isFunctionFailedISel = MF.getProperties().hasProperty(
472       MachineFunctionProperties::Property::FailedISel);
473 
474   // If we're mid-GlobalISel and we already triggered the fallback path then
475   // it's expected that the MIR is somewhat broken but that's ok since we'll
476   // reset it and clear the FailedISel attribute in ResetMachineFunctions.
477   if (isFunctionFailedISel)
478     return true;
479 
480   isFunctionRegBankSelected = MF.getProperties().hasProperty(
481       MachineFunctionProperties::Property::RegBankSelected);
482   isFunctionSelected = MF.getProperties().hasProperty(
483       MachineFunctionProperties::Property::Selected);
484   isFunctionTracksDebugUserValues = MF.getProperties().hasProperty(
485       MachineFunctionProperties::Property::TracksDebugUserValues);
486 
487   if (PASS) {
488     auto *LISWrapper = PASS->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
489     LiveInts = LISWrapper ? &LISWrapper->getLIS() : nullptr;
490     // We don't want to verify LiveVariables if LiveIntervals is available.
491     auto *LVWrapper = PASS->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
492     if (!LiveInts)
493       LiveVars = LVWrapper ? &LVWrapper->getLV() : nullptr;
494     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
495     auto *SIWrapper = PASS->getAnalysisIfAvailable<SlotIndexesWrapperPass>();
496     Indexes = SIWrapper ? &SIWrapper->getSI() : nullptr;
497   }
498   if (MFAM) {
499     MachineFunction &Func = const_cast<MachineFunction &>(MF);
500     LiveInts = MFAM->getCachedResult<LiveIntervalsAnalysis>(Func);
501     if (!LiveInts)
502       LiveVars = MFAM->getCachedResult<LiveVariablesAnalysis>(Func);
503     // TODO: LiveStks = MFAM->getCachedResult<LiveStacksAnalysis>(Func);
504     Indexes = MFAM->getCachedResult<SlotIndexesAnalysis>(Func);
505   }
506 
507   verifySlotIndexes();
508 
509   verifyProperties(MF);
510 
511   visitMachineFunctionBefore();
512   for (const MachineBasicBlock &MBB : MF) {
513     visitMachineBasicBlockBefore(&MBB);
514     // Keep track of the current bundle header.
515     const MachineInstr *CurBundle = nullptr;
516     // Do we expect the next instruction to be part of the same bundle?
517     bool InBundle = false;
518 
519     for (const MachineInstr &MI : MBB.instrs()) {
520       if (MI.getParent() != &MBB) {
521         report("Bad instruction parent pointer", &MBB);
522         OS << "Instruction: " << MI;
523         continue;
524       }
525 
526       // Check for consistent bundle flags.
527       if (InBundle && !MI.isBundledWithPred())
528         report("Missing BundledPred flag, "
529                "BundledSucc was set on predecessor",
530                &MI);
531       if (!InBundle && MI.isBundledWithPred())
532         report("BundledPred flag is set, "
533                "but BundledSucc not set on predecessor",
534                &MI);
535 
536       // Is this a bundle header?
537       if (!MI.isInsideBundle()) {
538         if (CurBundle)
539           visitMachineBundleAfter(CurBundle);
540         CurBundle = &MI;
541         visitMachineBundleBefore(CurBundle);
542       } else if (!CurBundle)
543         report("No bundle header", &MI);
544       visitMachineInstrBefore(&MI);
545       for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
546         const MachineOperand &Op = MI.getOperand(I);
547         if (Op.getParent() != &MI) {
548           // Make sure to use correct addOperand / removeOperand / ChangeTo
549           // functions when replacing operands of a MachineInstr.
550           report("Instruction has operand with wrong parent set", &MI);
551         }
552 
553         visitMachineOperand(&Op, I);
554       }
555 
556       // Was this the last bundled instruction?
557       InBundle = MI.isBundledWithSucc();
558     }
559     if (CurBundle)
560       visitMachineBundleAfter(CurBundle);
561     if (InBundle)
562       report("BundledSucc flag set on last instruction in block", &MBB.back());
563     visitMachineBasicBlockAfter(&MBB);
564   }
565   visitMachineFunctionAfter();
566 
567   // Clean up.
568   regsLive.clear();
569   regsDefined.clear();
570   regsDead.clear();
571   regsKilled.clear();
572   regMasks.clear();
573   MBBInfoMap.clear();
574 
575   return !ReportedErrs.hasError();
576 }
577 
578 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
579   assert(MF);
580   OS << '\n';
581   if (ReportedErrs.increment()) {
582     if (Banner)
583       OS << "# " << Banner << '\n';
584 
585     if (LiveInts != nullptr)
586       LiveInts->print(OS);
587     else
588       MF->print(OS, Indexes);
589   }
590 
591   OS << "*** Bad machine code: " << msg << " ***\n"
592      << "- function:    " << MF->getName() << '\n';
593 }
594 
595 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
596   assert(MBB);
597   report(msg, MBB->getParent());
598   OS << "- basic block: " << printMBBReference(*MBB) << ' ' << MBB->getName()
599      << " (" << (const void *)MBB << ')';
600   if (Indexes)
601     OS << " [" << Indexes->getMBBStartIdx(MBB) << ';'
602        << Indexes->getMBBEndIdx(MBB) << ')';
603   OS << '\n';
604 }
605 
606 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
607   assert(MI);
608   report(msg, MI->getParent());
609   OS << "- instruction: ";
610   if (Indexes && Indexes->hasIndex(*MI))
611     OS << Indexes->getInstructionIndex(*MI) << '\t';
612   MI->print(OS, /*IsStandalone=*/true);
613 }
614 
615 void MachineVerifier::report(const char *msg, const MachineOperand *MO,
616                              unsigned MONum, LLT MOVRegType) {
617   assert(MO);
618   report(msg, MO->getParent());
619   OS << "- operand " << MONum << ":   ";
620   MO->print(OS, MOVRegType, TRI);
621   OS << '\n';
622 }
623 
624 void MachineVerifier::report(const Twine &Msg, const MachineInstr *MI) {
625   report(Msg.str().c_str(), MI);
626 }
627 
628 void MachineVerifier::report_context(SlotIndex Pos) const {
629   OS << "- at:          " << Pos << '\n';
630 }
631 
632 void MachineVerifier::report_context(const LiveInterval &LI) const {
633   OS << "- interval:    " << LI << '\n';
634 }
635 
636 void MachineVerifier::report_context(const LiveRange &LR, Register VRegUnit,
637                                      LaneBitmask LaneMask) const {
638   report_context_liverange(LR);
639   report_context_vreg_regunit(VRegUnit);
640   if (LaneMask.any())
641     report_context_lanemask(LaneMask);
642 }
643 
644 void MachineVerifier::report_context(const LiveRange::Segment &S) const {
645   OS << "- segment:     " << S << '\n';
646 }
647 
648 void MachineVerifier::report_context(const VNInfo &VNI) const {
649   OS << "- ValNo:       " << VNI.id << " (def " << VNI.def << ")\n";
650 }
651 
652 void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
653   OS << "- liverange:   " << LR << '\n';
654 }
655 
656 void MachineVerifier::report_context(MCPhysReg PReg) const {
657   OS << "- p. register: " << printReg(PReg, TRI) << '\n';
658 }
659 
660 void MachineVerifier::report_context_vreg(Register VReg) const {
661   OS << "- v. register: " << printReg(VReg, TRI) << '\n';
662 }
663 
664 void MachineVerifier::report_context_vreg_regunit(Register VRegOrUnit) const {
665   if (VRegOrUnit.isVirtual()) {
666     report_context_vreg(VRegOrUnit);
667   } else {
668     OS << "- regunit:     " << printRegUnit(VRegOrUnit, TRI) << '\n';
669   }
670 }
671 
672 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
673   OS << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
674 }
675 
676 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
677   BBInfo &MInfo = MBBInfoMap[MBB];
678   if (!MInfo.reachable) {
679     MInfo.reachable = true;
680     for (const MachineBasicBlock *Succ : MBB->successors())
681       markReachable(Succ);
682   }
683 }
684 
685 void MachineVerifier::visitMachineFunctionBefore() {
686   lastIndex = SlotIndex();
687   regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
688                                            : TRI->getReservedRegs(*MF);
689 
690   if (!MF->empty())
691     markReachable(&MF->front());
692 
693   // Build a set of the basic blocks in the function.
694   FunctionBlocks.clear();
695   for (const auto &MBB : *MF) {
696     FunctionBlocks.insert(&MBB);
697     BBInfo &MInfo = MBBInfoMap[&MBB];
698 
699     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
700     if (MInfo.Preds.size() != MBB.pred_size())
701       report("MBB has duplicate entries in its predecessor list.", &MBB);
702 
703     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
704     if (MInfo.Succs.size() != MBB.succ_size())
705       report("MBB has duplicate entries in its successor list.", &MBB);
706   }
707 
708   // Check that the register use lists are sane.
709   MRI->verifyUseLists();
710 
711   if (!MF->empty())
712     verifyStackFrame();
713 }
714 
715 void
716 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
717   FirstTerminator = nullptr;
718   FirstNonPHI = nullptr;
719 
720   if (!MF->getProperties().hasProperty(
721       MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
722     // If this block has allocatable physical registers live-in, check that
723     // it is an entry block or landing pad.
724     for (const auto &LI : MBB->liveins()) {
725       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
726           MBB->getIterator() != MBB->getParent()->begin() &&
727           !MBB->isInlineAsmBrIndirectTarget()) {
728         report("MBB has allocatable live-in, but isn't entry, landing-pad, or "
729                "inlineasm-br-indirect-target.",
730                MBB);
731         report_context(LI.PhysReg);
732       }
733     }
734   }
735 
736   if (MBB->isIRBlockAddressTaken()) {
737     if (!MBB->getAddressTakenIRBlock()->hasAddressTaken())
738       report("ir-block-address-taken is associated with basic block not used by "
739              "a blockaddress.",
740              MBB);
741   }
742 
743   // Count the number of landing pad successors.
744   SmallPtrSet<const MachineBasicBlock*, 4> LandingPadSuccs;
745   for (const auto *succ : MBB->successors()) {
746     if (succ->isEHPad())
747       LandingPadSuccs.insert(succ);
748     if (!FunctionBlocks.count(succ))
749       report("MBB has successor that isn't part of the function.", MBB);
750     if (!MBBInfoMap[succ].Preds.count(MBB)) {
751       report("Inconsistent CFG", MBB);
752       OS << "MBB is not in the predecessor list of the successor "
753          << printMBBReference(*succ) << ".\n";
754     }
755   }
756 
757   // Check the predecessor list.
758   for (const MachineBasicBlock *Pred : MBB->predecessors()) {
759     if (!FunctionBlocks.count(Pred))
760       report("MBB has predecessor that isn't part of the function.", MBB);
761     if (!MBBInfoMap[Pred].Succs.count(MBB)) {
762       report("Inconsistent CFG", MBB);
763       OS << "MBB is not in the successor list of the predecessor "
764          << printMBBReference(*Pred) << ".\n";
765     }
766   }
767 
768   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
769   const BasicBlock *BB = MBB->getBasicBlock();
770   const Function &F = MF->getFunction();
771   if (LandingPadSuccs.size() > 1 &&
772       !(AsmInfo &&
773         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
774         BB && isa<SwitchInst>(BB->getTerminator())) &&
775       !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
776     report("MBB has more than one landing pad successor", MBB);
777 
778   // Call analyzeBranch. If it succeeds, there several more conditions to check.
779   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
780   SmallVector<MachineOperand, 4> Cond;
781   if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
782                           Cond)) {
783     // Ok, analyzeBranch thinks it knows what's going on with this block. Let's
784     // check whether its answers match up with reality.
785     if (!TBB && !FBB) {
786       // Block falls through to its successor.
787       if (!MBB->empty() && MBB->back().isBarrier() &&
788           !TII->isPredicated(MBB->back())) {
789         report("MBB exits via unconditional fall-through but ends with a "
790                "barrier instruction!", MBB);
791       }
792       if (!Cond.empty()) {
793         report("MBB exits via unconditional fall-through but has a condition!",
794                MBB);
795       }
796     } else if (TBB && !FBB && Cond.empty()) {
797       // Block unconditionally branches somewhere.
798       if (MBB->empty()) {
799         report("MBB exits via unconditional branch but doesn't contain "
800                "any instructions!", MBB);
801       } else if (!MBB->back().isBarrier()) {
802         report("MBB exits via unconditional branch but doesn't end with a "
803                "barrier instruction!", MBB);
804       } else if (!MBB->back().isTerminator()) {
805         report("MBB exits via unconditional branch but the branch isn't a "
806                "terminator instruction!", MBB);
807       }
808     } else if (TBB && !FBB && !Cond.empty()) {
809       // Block conditionally branches somewhere, otherwise falls through.
810       if (MBB->empty()) {
811         report("MBB exits via conditional branch/fall-through but doesn't "
812                "contain any instructions!", MBB);
813       } else if (MBB->back().isBarrier()) {
814         report("MBB exits via conditional branch/fall-through but ends with a "
815                "barrier instruction!", MBB);
816       } else if (!MBB->back().isTerminator()) {
817         report("MBB exits via conditional branch/fall-through but the branch "
818                "isn't a terminator instruction!", MBB);
819       }
820     } else if (TBB && FBB) {
821       // Block conditionally branches somewhere, otherwise branches
822       // somewhere else.
823       if (MBB->empty()) {
824         report("MBB exits via conditional branch/branch but doesn't "
825                "contain any instructions!", MBB);
826       } else if (!MBB->back().isBarrier()) {
827         report("MBB exits via conditional branch/branch but doesn't end with a "
828                "barrier instruction!", MBB);
829       } else if (!MBB->back().isTerminator()) {
830         report("MBB exits via conditional branch/branch but the branch "
831                "isn't a terminator instruction!", MBB);
832       }
833       if (Cond.empty()) {
834         report("MBB exits via conditional branch/branch but there's no "
835                "condition!", MBB);
836       }
837     } else {
838       report("analyzeBranch returned invalid data!", MBB);
839     }
840 
841     // Now check that the successors match up with the answers reported by
842     // analyzeBranch.
843     if (TBB && !MBB->isSuccessor(TBB))
844       report("MBB exits via jump or conditional branch, but its target isn't a "
845              "CFG successor!",
846              MBB);
847     if (FBB && !MBB->isSuccessor(FBB))
848       report("MBB exits via conditional branch, but its target isn't a CFG "
849              "successor!",
850              MBB);
851 
852     // There might be a fallthrough to the next block if there's either no
853     // unconditional true branch, or if there's a condition, and one of the
854     // branches is missing.
855     bool Fallthrough = !TBB || (!Cond.empty() && !FBB);
856 
857     // A conditional fallthrough must be an actual CFG successor, not
858     // unreachable. (Conversely, an unconditional fallthrough might not really
859     // be a successor, because the block might end in unreachable.)
860     if (!Cond.empty() && !FBB) {
861       MachineFunction::const_iterator MBBI = std::next(MBB->getIterator());
862       if (MBBI == MF->end()) {
863         report("MBB conditionally falls through out of function!", MBB);
864       } else if (!MBB->isSuccessor(&*MBBI))
865         report("MBB exits via conditional branch/fall-through but the CFG "
866                "successors don't match the actual successors!",
867                MBB);
868     }
869 
870     // Verify that there aren't any extra un-accounted-for successors.
871     for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
872       // If this successor is one of the branch targets, it's okay.
873       if (SuccMBB == TBB || SuccMBB == FBB)
874         continue;
875       // If we might have a fallthrough, and the successor is the fallthrough
876       // block, that's also ok.
877       if (Fallthrough && SuccMBB == MBB->getNextNode())
878         continue;
879       // Also accept successors which are for exception-handling or might be
880       // inlineasm_br targets.
881       if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget())
882         continue;
883       report("MBB has unexpected successors which are not branch targets, "
884              "fallthrough, EHPads, or inlineasm_br targets.",
885              MBB);
886     }
887   }
888 
889   regsLive.clear();
890   if (MRI->tracksLiveness()) {
891     for (const auto &LI : MBB->liveins()) {
892       if (!Register::isPhysicalRegister(LI.PhysReg)) {
893         report("MBB live-in list contains non-physical register", MBB);
894         continue;
895       }
896       for (const MCPhysReg &SubReg : TRI->subregs_inclusive(LI.PhysReg))
897         regsLive.insert(SubReg);
898     }
899   }
900 
901   const MachineFrameInfo &MFI = MF->getFrameInfo();
902   BitVector PR = MFI.getPristineRegs(*MF);
903   for (unsigned I : PR.set_bits()) {
904     for (const MCPhysReg &SubReg : TRI->subregs_inclusive(I))
905       regsLive.insert(SubReg);
906   }
907 
908   regsKilled.clear();
909   regsDefined.clear();
910 
911   if (Indexes)
912     lastIndex = Indexes->getMBBStartIdx(MBB);
913 }
914 
915 // This function gets called for all bundle headers, including normal
916 // stand-alone unbundled instructions.
917 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
918   if (Indexes && Indexes->hasIndex(*MI)) {
919     SlotIndex idx = Indexes->getInstructionIndex(*MI);
920     if (!(idx > lastIndex)) {
921       report("Instruction index out of order", MI);
922       OS << "Last instruction was at " << lastIndex << '\n';
923     }
924     lastIndex = idx;
925   }
926 
927   // Ensure non-terminators don't follow terminators.
928   if (MI->isTerminator()) {
929     if (!FirstTerminator)
930       FirstTerminator = MI;
931   } else if (FirstTerminator) {
932     // For GlobalISel, G_INVOKE_REGION_START is a terminator that we allow to
933     // precede non-terminators.
934     if (FirstTerminator->getOpcode() != TargetOpcode::G_INVOKE_REGION_START) {
935       report("Non-terminator instruction after the first terminator", MI);
936       OS << "First terminator was:\t" << *FirstTerminator;
937     }
938   }
939 }
940 
941 // The operands on an INLINEASM instruction must follow a template.
942 // Verify that the flag operands make sense.
943 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
944   // The first two operands on INLINEASM are the asm string and global flags.
945   if (MI->getNumOperands() < 2) {
946     report("Too few operands on inline asm", MI);
947     return;
948   }
949   if (!MI->getOperand(0).isSymbol())
950     report("Asm string must be an external symbol", MI);
951   if (!MI->getOperand(1).isImm())
952     report("Asm flags must be an immediate", MI);
953   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
954   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
955   // and Extra_IsConvergent = 32.
956   if (!isUInt<6>(MI->getOperand(1).getImm()))
957     report("Unknown asm flags", &MI->getOperand(1), 1);
958 
959   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
960 
961   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
962   unsigned NumOps;
963   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
964     const MachineOperand &MO = MI->getOperand(OpNo);
965     // There may be implicit ops after the fixed operands.
966     if (!MO.isImm())
967       break;
968     const InlineAsm::Flag F(MO.getImm());
969     NumOps = 1 + F.getNumOperandRegisters();
970   }
971 
972   if (OpNo > MI->getNumOperands())
973     report("Missing operands in last group", MI);
974 
975   // An optional MDNode follows the groups.
976   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
977     ++OpNo;
978 
979   // All trailing operands must be implicit registers.
980   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
981     const MachineOperand &MO = MI->getOperand(OpNo);
982     if (!MO.isReg() || !MO.isImplicit())
983       report("Expected implicit register after groups", &MO, OpNo);
984   }
985 
986   if (MI->getOpcode() == TargetOpcode::INLINEASM_BR) {
987     const MachineBasicBlock *MBB = MI->getParent();
988 
989     for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI->getNumOperands();
990          i != e; ++i) {
991       const MachineOperand &MO = MI->getOperand(i);
992 
993       if (!MO.isMBB())
994         continue;
995 
996       // Check the successor & predecessor lists look ok, assume they are
997       // not. Find the indirect target without going through the successors.
998       const MachineBasicBlock *IndirectTargetMBB = MO.getMBB();
999       if (!IndirectTargetMBB) {
1000         report("INLINEASM_BR indirect target does not exist", &MO, i);
1001         break;
1002       }
1003 
1004       if (!MBB->isSuccessor(IndirectTargetMBB))
1005         report("INLINEASM_BR indirect target missing from successor list", &MO,
1006                i);
1007 
1008       if (!IndirectTargetMBB->isPredecessor(MBB))
1009         report("INLINEASM_BR indirect target predecessor list missing parent",
1010                &MO, i);
1011     }
1012   }
1013 }
1014 
1015 bool MachineVerifier::verifyAllRegOpsScalar(const MachineInstr &MI,
1016                                             const MachineRegisterInfo &MRI) {
1017   if (none_of(MI.explicit_operands(), [&MRI](const MachineOperand &Op) {
1018         if (!Op.isReg())
1019           return false;
1020         const auto Reg = Op.getReg();
1021         if (Reg.isPhysical())
1022           return false;
1023         return !MRI.getType(Reg).isScalar();
1024       }))
1025     return true;
1026   report("All register operands must have scalar types", &MI);
1027   return false;
1028 }
1029 
1030 /// Check that types are consistent when two operands need to have the same
1031 /// number of vector elements.
1032 /// \return true if the types are valid.
1033 bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
1034                                                const MachineInstr *MI) {
1035   if (Ty0.isVector() != Ty1.isVector()) {
1036     report("operand types must be all-vector or all-scalar", MI);
1037     // Generally we try to report as many issues as possible at once, but in
1038     // this case it's not clear what should we be comparing the size of the
1039     // scalar with: the size of the whole vector or its lane. Instead of
1040     // making an arbitrary choice and emitting not so helpful message, let's
1041     // avoid the extra noise and stop here.
1042     return false;
1043   }
1044 
1045   if (Ty0.isVector() && Ty0.getElementCount() != Ty1.getElementCount()) {
1046     report("operand types must preserve number of vector elements", MI);
1047     return false;
1048   }
1049 
1050   return true;
1051 }
1052 
1053 bool MachineVerifier::verifyGIntrinsicSideEffects(const MachineInstr *MI) {
1054   auto Opcode = MI->getOpcode();
1055   bool NoSideEffects = Opcode == TargetOpcode::G_INTRINSIC ||
1056                        Opcode == TargetOpcode::G_INTRINSIC_CONVERGENT;
1057   unsigned IntrID = cast<GIntrinsic>(MI)->getIntrinsicID();
1058   if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1059     AttributeList Attrs = Intrinsic::getAttributes(
1060         MF->getFunction().getContext(), static_cast<Intrinsic::ID>(IntrID));
1061     bool DeclHasSideEffects = !Attrs.getMemoryEffects().doesNotAccessMemory();
1062     if (NoSideEffects && DeclHasSideEffects) {
1063       report(Twine(TII->getName(Opcode),
1064                    " used with intrinsic that accesses memory"),
1065              MI);
1066       return false;
1067     }
1068     if (!NoSideEffects && !DeclHasSideEffects) {
1069       report(Twine(TII->getName(Opcode), " used with readnone intrinsic"), MI);
1070       return false;
1071     }
1072   }
1073 
1074   return true;
1075 }
1076 
1077 bool MachineVerifier::verifyGIntrinsicConvergence(const MachineInstr *MI) {
1078   auto Opcode = MI->getOpcode();
1079   bool NotConvergent = Opcode == TargetOpcode::G_INTRINSIC ||
1080                        Opcode == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS;
1081   unsigned IntrID = cast<GIntrinsic>(MI)->getIntrinsicID();
1082   if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1083     AttributeList Attrs = Intrinsic::getAttributes(
1084         MF->getFunction().getContext(), static_cast<Intrinsic::ID>(IntrID));
1085     bool DeclIsConvergent = Attrs.hasFnAttr(Attribute::Convergent);
1086     if (NotConvergent && DeclIsConvergent) {
1087       report(Twine(TII->getName(Opcode), " used with a convergent intrinsic"),
1088              MI);
1089       return false;
1090     }
1091     if (!NotConvergent && !DeclIsConvergent) {
1092       report(
1093           Twine(TII->getName(Opcode), " used with a non-convergent intrinsic"),
1094           MI);
1095       return false;
1096     }
1097   }
1098 
1099   return true;
1100 }
1101 
1102 void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
1103   if (isFunctionSelected)
1104     report("Unexpected generic instruction in a Selected function", MI);
1105 
1106   const MCInstrDesc &MCID = MI->getDesc();
1107   unsigned NumOps = MI->getNumOperands();
1108 
1109   // Branches must reference a basic block if they are not indirect
1110   if (MI->isBranch() && !MI->isIndirectBranch()) {
1111     bool HasMBB = false;
1112     for (const MachineOperand &Op : MI->operands()) {
1113       if (Op.isMBB()) {
1114         HasMBB = true;
1115         break;
1116       }
1117     }
1118 
1119     if (!HasMBB) {
1120       report("Branch instruction is missing a basic block operand or "
1121              "isIndirectBranch property",
1122              MI);
1123     }
1124   }
1125 
1126   // Check types.
1127   SmallVector<LLT, 4> Types;
1128   for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps);
1129        I != E; ++I) {
1130     if (!MCID.operands()[I].isGenericType())
1131       continue;
1132     // Generic instructions specify type equality constraints between some of
1133     // their operands. Make sure these are consistent.
1134     size_t TypeIdx = MCID.operands()[I].getGenericTypeIndex();
1135     Types.resize(std::max(TypeIdx + 1, Types.size()));
1136 
1137     const MachineOperand *MO = &MI->getOperand(I);
1138     if (!MO->isReg()) {
1139       report("generic instruction must use register operands", MI);
1140       continue;
1141     }
1142 
1143     LLT OpTy = MRI->getType(MO->getReg());
1144     // Don't report a type mismatch if there is no actual mismatch, only a
1145     // type missing, to reduce noise:
1146     if (OpTy.isValid()) {
1147       // Only the first valid type for a type index will be printed: don't
1148       // overwrite it later so it's always clear which type was expected:
1149       if (!Types[TypeIdx].isValid())
1150         Types[TypeIdx] = OpTy;
1151       else if (Types[TypeIdx] != OpTy)
1152         report("Type mismatch in generic instruction", MO, I, OpTy);
1153     } else {
1154       // Generic instructions must have types attached to their operands.
1155       report("Generic instruction is missing a virtual register type", MO, I);
1156     }
1157   }
1158 
1159   // Generic opcodes must not have physical register operands.
1160   for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
1161     const MachineOperand *MO = &MI->getOperand(I);
1162     if (MO->isReg() && MO->getReg().isPhysical())
1163       report("Generic instruction cannot have physical register", MO, I);
1164   }
1165 
1166   // Avoid out of bounds in checks below. This was already reported earlier.
1167   if (MI->getNumOperands() < MCID.getNumOperands())
1168     return;
1169 
1170   StringRef ErrorInfo;
1171   if (!TII->verifyInstruction(*MI, ErrorInfo))
1172     report(ErrorInfo.data(), MI);
1173 
1174   // Verify properties of various specific instruction types
1175   unsigned Opc = MI->getOpcode();
1176   switch (Opc) {
1177   case TargetOpcode::G_ASSERT_SEXT:
1178   case TargetOpcode::G_ASSERT_ZEXT: {
1179     std::string OpcName =
1180         Opc == TargetOpcode::G_ASSERT_ZEXT ? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT";
1181     if (!MI->getOperand(2).isImm()) {
1182       report(Twine(OpcName, " expects an immediate operand #2"), MI);
1183       break;
1184     }
1185 
1186     Register Dst = MI->getOperand(0).getReg();
1187     Register Src = MI->getOperand(1).getReg();
1188     LLT SrcTy = MRI->getType(Src);
1189     int64_t Imm = MI->getOperand(2).getImm();
1190     if (Imm <= 0) {
1191       report(Twine(OpcName, " size must be >= 1"), MI);
1192       break;
1193     }
1194 
1195     if (Imm >= SrcTy.getScalarSizeInBits()) {
1196       report(Twine(OpcName, " size must be less than source bit width"), MI);
1197       break;
1198     }
1199 
1200     const RegisterBank *SrcRB = RBI->getRegBank(Src, *MRI, *TRI);
1201     const RegisterBank *DstRB = RBI->getRegBank(Dst, *MRI, *TRI);
1202 
1203     // Allow only the source bank to be set.
1204     if ((SrcRB && DstRB && SrcRB != DstRB) || (DstRB && !SrcRB)) {
1205       report(Twine(OpcName, " cannot change register bank"), MI);
1206       break;
1207     }
1208 
1209     // Don't allow a class change. Do allow member class->regbank.
1210     const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(Dst);
1211     if (DstRC && DstRC != MRI->getRegClassOrNull(Src)) {
1212       report(
1213           Twine(OpcName, " source and destination register classes must match"),
1214           MI);
1215       break;
1216     }
1217 
1218     break;
1219   }
1220 
1221   case TargetOpcode::G_CONSTANT:
1222   case TargetOpcode::G_FCONSTANT: {
1223     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1224     if (DstTy.isVector())
1225       report("Instruction cannot use a vector result type", MI);
1226 
1227     if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
1228       if (!MI->getOperand(1).isCImm()) {
1229         report("G_CONSTANT operand must be cimm", MI);
1230         break;
1231       }
1232 
1233       const ConstantInt *CI = MI->getOperand(1).getCImm();
1234       if (CI->getBitWidth() != DstTy.getSizeInBits())
1235         report("inconsistent constant size", MI);
1236     } else {
1237       if (!MI->getOperand(1).isFPImm()) {
1238         report("G_FCONSTANT operand must be fpimm", MI);
1239         break;
1240       }
1241       const ConstantFP *CF = MI->getOperand(1).getFPImm();
1242 
1243       if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) !=
1244           DstTy.getSizeInBits()) {
1245         report("inconsistent constant size", MI);
1246       }
1247     }
1248 
1249     break;
1250   }
1251   case TargetOpcode::G_LOAD:
1252   case TargetOpcode::G_STORE:
1253   case TargetOpcode::G_ZEXTLOAD:
1254   case TargetOpcode::G_SEXTLOAD: {
1255     LLT ValTy = MRI->getType(MI->getOperand(0).getReg());
1256     LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1257     if (!PtrTy.isPointer())
1258       report("Generic memory instruction must access a pointer", MI);
1259 
1260     // Generic loads and stores must have a single MachineMemOperand
1261     // describing that access.
1262     if (!MI->hasOneMemOperand()) {
1263       report("Generic instruction accessing memory must have one mem operand",
1264              MI);
1265     } else {
1266       const MachineMemOperand &MMO = **MI->memoperands_begin();
1267       if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD ||
1268           MI->getOpcode() == TargetOpcode::G_SEXTLOAD) {
1269         if (TypeSize::isKnownGE(MMO.getSizeInBits().getValue(),
1270                                 ValTy.getSizeInBits()))
1271           report("Generic extload must have a narrower memory type", MI);
1272       } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
1273         if (TypeSize::isKnownGT(MMO.getSize().getValue(),
1274                                 ValTy.getSizeInBytes()))
1275           report("load memory size cannot exceed result size", MI);
1276       } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
1277         if (TypeSize::isKnownLT(ValTy.getSizeInBytes(),
1278                                 MMO.getSize().getValue()))
1279           report("store memory size cannot exceed value size", MI);
1280       }
1281 
1282       const AtomicOrdering Order = MMO.getSuccessOrdering();
1283       if (Opc == TargetOpcode::G_STORE) {
1284         if (Order == AtomicOrdering::Acquire ||
1285             Order == AtomicOrdering::AcquireRelease)
1286           report("atomic store cannot use acquire ordering", MI);
1287 
1288       } else {
1289         if (Order == AtomicOrdering::Release ||
1290             Order == AtomicOrdering::AcquireRelease)
1291           report("atomic load cannot use release ordering", MI);
1292       }
1293     }
1294 
1295     break;
1296   }
1297   case TargetOpcode::G_PHI: {
1298     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1299     if (!DstTy.isValid() || !all_of(drop_begin(MI->operands()),
1300                                     [this, &DstTy](const MachineOperand &MO) {
1301                                       if (!MO.isReg())
1302                                         return true;
1303                                       LLT Ty = MRI->getType(MO.getReg());
1304                                       if (!Ty.isValid() || (Ty != DstTy))
1305                                         return false;
1306                                       return true;
1307                                     }))
1308       report("Generic Instruction G_PHI has operands with incompatible/missing "
1309              "types",
1310              MI);
1311     break;
1312   }
1313   case TargetOpcode::G_BITCAST: {
1314     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1315     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1316     if (!DstTy.isValid() || !SrcTy.isValid())
1317       break;
1318 
1319     if (SrcTy.isPointer() != DstTy.isPointer())
1320       report("bitcast cannot convert between pointers and other types", MI);
1321 
1322     if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1323       report("bitcast sizes must match", MI);
1324 
1325     if (SrcTy == DstTy)
1326       report("bitcast must change the type", MI);
1327 
1328     break;
1329   }
1330   case TargetOpcode::G_INTTOPTR:
1331   case TargetOpcode::G_PTRTOINT:
1332   case TargetOpcode::G_ADDRSPACE_CAST: {
1333     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1334     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1335     if (!DstTy.isValid() || !SrcTy.isValid())
1336       break;
1337 
1338     verifyVectorElementMatch(DstTy, SrcTy, MI);
1339 
1340     DstTy = DstTy.getScalarType();
1341     SrcTy = SrcTy.getScalarType();
1342 
1343     if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
1344       if (!DstTy.isPointer())
1345         report("inttoptr result type must be a pointer", MI);
1346       if (SrcTy.isPointer())
1347         report("inttoptr source type must not be a pointer", MI);
1348     } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
1349       if (!SrcTy.isPointer())
1350         report("ptrtoint source type must be a pointer", MI);
1351       if (DstTy.isPointer())
1352         report("ptrtoint result type must not be a pointer", MI);
1353     } else {
1354       assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
1355       if (!SrcTy.isPointer() || !DstTy.isPointer())
1356         report("addrspacecast types must be pointers", MI);
1357       else {
1358         if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
1359           report("addrspacecast must convert different address spaces", MI);
1360       }
1361     }
1362 
1363     break;
1364   }
1365   case TargetOpcode::G_PTR_ADD: {
1366     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1367     LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1368     LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg());
1369     if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
1370       break;
1371 
1372     if (!PtrTy.isPointerOrPointerVector())
1373       report("gep first operand must be a pointer", MI);
1374 
1375     if (OffsetTy.isPointerOrPointerVector())
1376       report("gep offset operand must not be a pointer", MI);
1377 
1378     if (PtrTy.isPointerOrPointerVector()) {
1379       const DataLayout &DL = MF->getDataLayout();
1380       unsigned AS = PtrTy.getAddressSpace();
1381       unsigned IndexSizeInBits = DL.getIndexSize(AS) * 8;
1382       if (OffsetTy.getScalarSizeInBits() != IndexSizeInBits) {
1383         report("gep offset operand must match index size for address space",
1384                MI);
1385       }
1386     }
1387 
1388     // TODO: Is the offset allowed to be a scalar with a vector?
1389     break;
1390   }
1391   case TargetOpcode::G_PTRMASK: {
1392     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1393     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1394     LLT MaskTy = MRI->getType(MI->getOperand(2).getReg());
1395     if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid())
1396       break;
1397 
1398     if (!DstTy.isPointerOrPointerVector())
1399       report("ptrmask result type must be a pointer", MI);
1400 
1401     if (!MaskTy.getScalarType().isScalar())
1402       report("ptrmask mask type must be an integer", MI);
1403 
1404     verifyVectorElementMatch(DstTy, MaskTy, MI);
1405     break;
1406   }
1407   case TargetOpcode::G_SEXT:
1408   case TargetOpcode::G_ZEXT:
1409   case TargetOpcode::G_ANYEXT:
1410   case TargetOpcode::G_TRUNC:
1411   case TargetOpcode::G_FPEXT:
1412   case TargetOpcode::G_FPTRUNC: {
1413     // Number of operands and presense of types is already checked (and
1414     // reported in case of any issues), so no need to report them again. As
1415     // we're trying to report as many issues as possible at once, however, the
1416     // instructions aren't guaranteed to have the right number of operands or
1417     // types attached to them at this point
1418     assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1419     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1420     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1421     if (!DstTy.isValid() || !SrcTy.isValid())
1422       break;
1423 
1424     if (DstTy.isPointerOrPointerVector() || SrcTy.isPointerOrPointerVector())
1425       report("Generic extend/truncate can not operate on pointers", MI);
1426 
1427     verifyVectorElementMatch(DstTy, SrcTy, MI);
1428 
1429     unsigned DstSize = DstTy.getScalarSizeInBits();
1430     unsigned SrcSize = SrcTy.getScalarSizeInBits();
1431     switch (MI->getOpcode()) {
1432     default:
1433       if (DstSize <= SrcSize)
1434         report("Generic extend has destination type no larger than source", MI);
1435       break;
1436     case TargetOpcode::G_TRUNC:
1437     case TargetOpcode::G_FPTRUNC:
1438       if (DstSize >= SrcSize)
1439         report("Generic truncate has destination type no smaller than source",
1440                MI);
1441       break;
1442     }
1443     break;
1444   }
1445   case TargetOpcode::G_SELECT: {
1446     LLT SelTy = MRI->getType(MI->getOperand(0).getReg());
1447     LLT CondTy = MRI->getType(MI->getOperand(1).getReg());
1448     if (!SelTy.isValid() || !CondTy.isValid())
1449       break;
1450 
1451     // Scalar condition select on a vector is valid.
1452     if (CondTy.isVector())
1453       verifyVectorElementMatch(SelTy, CondTy, MI);
1454     break;
1455   }
1456   case TargetOpcode::G_MERGE_VALUES: {
1457     // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1458     // e.g. s2N = MERGE sN, sN
1459     // Merging multiple scalars into a vector is not allowed, should use
1460     // G_BUILD_VECTOR for that.
1461     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1462     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1463     if (DstTy.isVector() || SrcTy.isVector())
1464       report("G_MERGE_VALUES cannot operate on vectors", MI);
1465 
1466     const unsigned NumOps = MI->getNumOperands();
1467     if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
1468       report("G_MERGE_VALUES result size is inconsistent", MI);
1469 
1470     for (unsigned I = 2; I != NumOps; ++I) {
1471       if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy)
1472         report("G_MERGE_VALUES source types do not match", MI);
1473     }
1474 
1475     break;
1476   }
1477   case TargetOpcode::G_UNMERGE_VALUES: {
1478     unsigned NumDsts = MI->getNumOperands() - 1;
1479     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1480     for (unsigned i = 1; i < NumDsts; ++i) {
1481       if (MRI->getType(MI->getOperand(i).getReg()) != DstTy) {
1482         report("G_UNMERGE_VALUES destination types do not match", MI);
1483         break;
1484       }
1485     }
1486 
1487     LLT SrcTy = MRI->getType(MI->getOperand(NumDsts).getReg());
1488     if (DstTy.isVector()) {
1489       // This case is the converse of G_CONCAT_VECTORS.
1490       if (!SrcTy.isVector() || SrcTy.getScalarType() != DstTy.getScalarType() ||
1491           SrcTy.isScalableVector() != DstTy.isScalableVector() ||
1492           SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1493         report("G_UNMERGE_VALUES source operand does not match vector "
1494                "destination operands",
1495                MI);
1496     } else if (SrcTy.isVector()) {
1497       // This case is the converse of G_BUILD_VECTOR, but relaxed to allow
1498       // mismatched types as long as the total size matches:
1499       //   %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<4 x s32>)
1500       if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1501         report("G_UNMERGE_VALUES vector source operand does not match scalar "
1502                "destination operands",
1503                MI);
1504     } else {
1505       // This case is the converse of G_MERGE_VALUES.
1506       if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits()) {
1507         report("G_UNMERGE_VALUES scalar source operand does not match scalar "
1508                "destination operands",
1509                MI);
1510       }
1511     }
1512     break;
1513   }
1514   case TargetOpcode::G_BUILD_VECTOR: {
1515     // Source types must be scalars, dest type a vector. Total size of scalars
1516     // must match the dest vector size.
1517     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1518     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1519     if (!DstTy.isVector() || SrcEltTy.isVector()) {
1520       report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1521       break;
1522     }
1523 
1524     if (DstTy.getElementType() != SrcEltTy)
1525       report("G_BUILD_VECTOR result element type must match source type", MI);
1526 
1527     if (DstTy.getNumElements() != MI->getNumOperands() - 1)
1528       report("G_BUILD_VECTOR must have an operand for each elemement", MI);
1529 
1530     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1531       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1532         report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
1533 
1534     break;
1535   }
1536   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1537     // Source types must be scalars, dest type a vector. Scalar types must be
1538     // larger than the dest vector elt type, as this is a truncating operation.
1539     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1540     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1541     if (!DstTy.isVector() || SrcEltTy.isVector())
1542       report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1543              MI);
1544     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1545       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1546         report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1547                MI);
1548     if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1549       report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1550              "dest elt type",
1551              MI);
1552     break;
1553   }
1554   case TargetOpcode::G_CONCAT_VECTORS: {
1555     // Source types should be vectors, and total size should match the dest
1556     // vector size.
1557     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1558     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1559     if (!DstTy.isVector() || !SrcTy.isVector())
1560       report("G_CONCAT_VECTOR requires vector source and destination operands",
1561              MI);
1562 
1563     if (MI->getNumOperands() < 3)
1564       report("G_CONCAT_VECTOR requires at least 2 source operands", MI);
1565 
1566     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1567       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1568         report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1569     if (DstTy.getElementCount() !=
1570         SrcTy.getElementCount() * (MI->getNumOperands() - 1))
1571       report("G_CONCAT_VECTOR num dest and source elements should match", MI);
1572     break;
1573   }
1574   case TargetOpcode::G_ICMP:
1575   case TargetOpcode::G_FCMP: {
1576     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1577     LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
1578 
1579     if ((DstTy.isVector() != SrcTy.isVector()) ||
1580         (DstTy.isVector() &&
1581          DstTy.getElementCount() != SrcTy.getElementCount()))
1582       report("Generic vector icmp/fcmp must preserve number of lanes", MI);
1583 
1584     break;
1585   }
1586   case TargetOpcode::G_SCMP:
1587   case TargetOpcode::G_UCMP: {
1588     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1589     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1590     LLT SrcTy2 = MRI->getType(MI->getOperand(2).getReg());
1591 
1592     if (SrcTy.isPointerOrPointerVector() || SrcTy2.isPointerOrPointerVector()) {
1593       report("Generic scmp/ucmp does not support pointers as operands", MI);
1594       break;
1595     }
1596 
1597     if (DstTy.isPointerOrPointerVector()) {
1598       report("Generic scmp/ucmp does not support pointers as a result", MI);
1599       break;
1600     }
1601 
1602     if ((DstTy.isVector() != SrcTy.isVector()) ||
1603         (DstTy.isVector() &&
1604          DstTy.getElementCount() != SrcTy.getElementCount())) {
1605       report("Generic vector scmp/ucmp must preserve number of lanes", MI);
1606       break;
1607     }
1608 
1609     if (SrcTy != SrcTy2) {
1610       report("Generic scmp/ucmp must have same input types", MI);
1611       break;
1612     }
1613 
1614     break;
1615   }
1616   case TargetOpcode::G_EXTRACT: {
1617     const MachineOperand &SrcOp = MI->getOperand(1);
1618     if (!SrcOp.isReg()) {
1619       report("extract source must be a register", MI);
1620       break;
1621     }
1622 
1623     const MachineOperand &OffsetOp = MI->getOperand(2);
1624     if (!OffsetOp.isImm()) {
1625       report("extract offset must be a constant", MI);
1626       break;
1627     }
1628 
1629     unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1630     unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1631     if (SrcSize == DstSize)
1632       report("extract source must be larger than result", MI);
1633 
1634     if (DstSize + OffsetOp.getImm() > SrcSize)
1635       report("extract reads past end of register", MI);
1636     break;
1637   }
1638   case TargetOpcode::G_INSERT: {
1639     const MachineOperand &SrcOp = MI->getOperand(2);
1640     if (!SrcOp.isReg()) {
1641       report("insert source must be a register", MI);
1642       break;
1643     }
1644 
1645     const MachineOperand &OffsetOp = MI->getOperand(3);
1646     if (!OffsetOp.isImm()) {
1647       report("insert offset must be a constant", MI);
1648       break;
1649     }
1650 
1651     unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1652     unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1653 
1654     if (DstSize <= SrcSize)
1655       report("inserted size must be smaller than total register", MI);
1656 
1657     if (SrcSize + OffsetOp.getImm() > DstSize)
1658       report("insert writes past end of register", MI);
1659 
1660     break;
1661   }
1662   case TargetOpcode::G_JUMP_TABLE: {
1663     if (!MI->getOperand(1).isJTI())
1664       report("G_JUMP_TABLE source operand must be a jump table index", MI);
1665     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1666     if (!DstTy.isPointer())
1667       report("G_JUMP_TABLE dest operand must have a pointer type", MI);
1668     break;
1669   }
1670   case TargetOpcode::G_BRJT: {
1671     if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
1672       report("G_BRJT src operand 0 must be a pointer type", MI);
1673 
1674     if (!MI->getOperand(1).isJTI())
1675       report("G_BRJT src operand 1 must be a jump table index", MI);
1676 
1677     const auto &IdxOp = MI->getOperand(2);
1678     if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
1679       report("G_BRJT src operand 2 must be a scalar reg type", MI);
1680     break;
1681   }
1682   case TargetOpcode::G_INTRINSIC:
1683   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
1684   case TargetOpcode::G_INTRINSIC_CONVERGENT:
1685   case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS: {
1686     // TODO: Should verify number of def and use operands, but the current
1687     // interface requires passing in IR types for mangling.
1688     const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
1689     if (!IntrIDOp.isIntrinsicID()) {
1690       report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
1691       break;
1692     }
1693 
1694     if (!verifyGIntrinsicSideEffects(MI))
1695       break;
1696     if (!verifyGIntrinsicConvergence(MI))
1697       break;
1698 
1699     break;
1700   }
1701   case TargetOpcode::G_SEXT_INREG: {
1702     if (!MI->getOperand(2).isImm()) {
1703       report("G_SEXT_INREG expects an immediate operand #2", MI);
1704       break;
1705     }
1706 
1707     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1708     int64_t Imm = MI->getOperand(2).getImm();
1709     if (Imm <= 0)
1710       report("G_SEXT_INREG size must be >= 1", MI);
1711     if (Imm >= SrcTy.getScalarSizeInBits())
1712       report("G_SEXT_INREG size must be less than source bit width", MI);
1713     break;
1714   }
1715   case TargetOpcode::G_BSWAP: {
1716     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1717     if (DstTy.getScalarSizeInBits() % 16 != 0)
1718       report("G_BSWAP size must be a multiple of 16 bits", MI);
1719     break;
1720   }
1721   case TargetOpcode::G_VSCALE: {
1722     if (!MI->getOperand(1).isCImm()) {
1723       report("G_VSCALE operand must be cimm", MI);
1724       break;
1725     }
1726     if (MI->getOperand(1).getCImm()->isZero()) {
1727       report("G_VSCALE immediate cannot be zero", MI);
1728       break;
1729     }
1730     break;
1731   }
1732   case TargetOpcode::G_INSERT_SUBVECTOR: {
1733     const MachineOperand &Src0Op = MI->getOperand(1);
1734     if (!Src0Op.isReg()) {
1735       report("G_INSERT_SUBVECTOR first source must be a register", MI);
1736       break;
1737     }
1738 
1739     const MachineOperand &Src1Op = MI->getOperand(2);
1740     if (!Src1Op.isReg()) {
1741       report("G_INSERT_SUBVECTOR second source must be a register", MI);
1742       break;
1743     }
1744 
1745     const MachineOperand &IndexOp = MI->getOperand(3);
1746     if (!IndexOp.isImm()) {
1747       report("G_INSERT_SUBVECTOR index must be an immediate", MI);
1748       break;
1749     }
1750 
1751     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1752     LLT Src1Ty = MRI->getType(Src1Op.getReg());
1753 
1754     if (!DstTy.isVector()) {
1755       report("Destination type must be a vector", MI);
1756       break;
1757     }
1758 
1759     if (!Src1Ty.isVector()) {
1760       report("Second source must be a vector", MI);
1761       break;
1762     }
1763 
1764     if (DstTy.getElementType() != Src1Ty.getElementType()) {
1765       report("Element type of vectors must be the same", MI);
1766       break;
1767     }
1768 
1769     if (Src1Ty.isScalable() != DstTy.isScalable()) {
1770       report("Vector types must both be fixed or both be scalable", MI);
1771       break;
1772     }
1773 
1774     if (ElementCount::isKnownGT(Src1Ty.getElementCount(),
1775                                 DstTy.getElementCount())) {
1776       report("Second source must be smaller than destination vector", MI);
1777       break;
1778     }
1779 
1780     uint64_t Idx = IndexOp.getImm();
1781     uint64_t Src1MinLen = Src1Ty.getElementCount().getKnownMinValue();
1782     if (IndexOp.getImm() % Src1MinLen != 0) {
1783       report("Index must be a multiple of the second source vector's "
1784              "minimum vector length",
1785              MI);
1786       break;
1787     }
1788 
1789     uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1790     if (Idx >= DstMinLen || Idx + Src1MinLen > DstMinLen) {
1791       report("Subvector type and index must not cause insert to overrun the "
1792              "vector being inserted into",
1793              MI);
1794       break;
1795     }
1796 
1797     break;
1798   }
1799   case TargetOpcode::G_EXTRACT_SUBVECTOR: {
1800     const MachineOperand &SrcOp = MI->getOperand(1);
1801     if (!SrcOp.isReg()) {
1802       report("G_EXTRACT_SUBVECTOR first source must be a register", MI);
1803       break;
1804     }
1805 
1806     const MachineOperand &IndexOp = MI->getOperand(2);
1807     if (!IndexOp.isImm()) {
1808       report("G_EXTRACT_SUBVECTOR index must be an immediate", MI);
1809       break;
1810     }
1811 
1812     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1813     LLT SrcTy = MRI->getType(SrcOp.getReg());
1814 
1815     if (!DstTy.isVector()) {
1816       report("Destination type must be a vector", MI);
1817       break;
1818     }
1819 
1820     if (!SrcTy.isVector()) {
1821       report("Source must be a vector", MI);
1822       break;
1823     }
1824 
1825     if (DstTy.getElementType() != SrcTy.getElementType()) {
1826       report("Element type of vectors must be the same", MI);
1827       break;
1828     }
1829 
1830     if (SrcTy.isScalable() != DstTy.isScalable()) {
1831       report("Vector types must both be fixed or both be scalable", MI);
1832       break;
1833     }
1834 
1835     if (ElementCount::isKnownGT(DstTy.getElementCount(),
1836                                 SrcTy.getElementCount())) {
1837       report("Destination vector must be smaller than source vector", MI);
1838       break;
1839     }
1840 
1841     uint64_t Idx = IndexOp.getImm();
1842     uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1843     if (Idx % DstMinLen != 0) {
1844       report("Index must be a multiple of the destination vector's minimum "
1845              "vector length",
1846              MI);
1847       break;
1848     }
1849 
1850     uint64_t SrcMinLen = SrcTy.getElementCount().getKnownMinValue();
1851     if (Idx >= SrcMinLen || Idx + DstMinLen > SrcMinLen) {
1852       report("Destination type and index must not cause extract to overrun the "
1853              "source vector",
1854              MI);
1855       break;
1856     }
1857 
1858     break;
1859   }
1860   case TargetOpcode::G_SHUFFLE_VECTOR: {
1861     const MachineOperand &MaskOp = MI->getOperand(3);
1862     if (!MaskOp.isShuffleMask()) {
1863       report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
1864       break;
1865     }
1866 
1867     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1868     LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
1869     LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
1870 
1871     if (Src0Ty != Src1Ty)
1872       report("Source operands must be the same type", MI);
1873 
1874     if (Src0Ty.getScalarType() != DstTy.getScalarType())
1875       report("G_SHUFFLE_VECTOR cannot change element type", MI);
1876 
1877     // Don't check that all operands are vector because scalars are used in
1878     // place of 1 element vectors.
1879     int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1;
1880     int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1;
1881 
1882     ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
1883 
1884     if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
1885       report("Wrong result type for shufflemask", MI);
1886 
1887     for (int Idx : MaskIdxes) {
1888       if (Idx < 0)
1889         continue;
1890 
1891       if (Idx >= 2 * SrcNumElts)
1892         report("Out of bounds shuffle index", MI);
1893     }
1894 
1895     break;
1896   }
1897 
1898   case TargetOpcode::G_SPLAT_VECTOR: {
1899     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1900     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1901 
1902     if (!DstTy.isScalableVector()) {
1903       report("Destination type must be a scalable vector", MI);
1904       break;
1905     }
1906 
1907     if (!SrcTy.isScalar() && !SrcTy.isPointer()) {
1908       report("Source type must be a scalar or pointer", MI);
1909       break;
1910     }
1911 
1912     if (TypeSize::isKnownGT(DstTy.getElementType().getSizeInBits(),
1913                             SrcTy.getSizeInBits())) {
1914       report("Element type of the destination must be the same size or smaller "
1915              "than the source type",
1916              MI);
1917       break;
1918     }
1919 
1920     break;
1921   }
1922   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1923     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1924     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1925     LLT IdxTy = MRI->getType(MI->getOperand(2).getReg());
1926 
1927     if (!DstTy.isScalar() && !DstTy.isPointer()) {
1928       report("Destination type must be a scalar or pointer", MI);
1929       break;
1930     }
1931 
1932     if (!SrcTy.isVector()) {
1933       report("First source must be a vector", MI);
1934       break;
1935     }
1936 
1937     auto TLI = MF->getSubtarget().getTargetLowering();
1938     if (IdxTy.getSizeInBits() !=
1939         TLI->getVectorIdxTy(MF->getDataLayout()).getFixedSizeInBits()) {
1940       report("Index type must match VectorIdxTy", MI);
1941       break;
1942     }
1943 
1944     break;
1945   }
1946   case TargetOpcode::G_INSERT_VECTOR_ELT: {
1947     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1948     LLT VecTy = MRI->getType(MI->getOperand(1).getReg());
1949     LLT ScaTy = MRI->getType(MI->getOperand(2).getReg());
1950     LLT IdxTy = MRI->getType(MI->getOperand(3).getReg());
1951 
1952     if (!DstTy.isVector()) {
1953       report("Destination type must be a vector", MI);
1954       break;
1955     }
1956 
1957     if (VecTy != DstTy) {
1958       report("Destination type and vector type must match", MI);
1959       break;
1960     }
1961 
1962     if (!ScaTy.isScalar() && !ScaTy.isPointer()) {
1963       report("Inserted element must be a scalar or pointer", MI);
1964       break;
1965     }
1966 
1967     auto TLI = MF->getSubtarget().getTargetLowering();
1968     if (IdxTy.getSizeInBits() !=
1969         TLI->getVectorIdxTy(MF->getDataLayout()).getFixedSizeInBits()) {
1970       report("Index type must match VectorIdxTy", MI);
1971       break;
1972     }
1973 
1974     break;
1975   }
1976   case TargetOpcode::G_DYN_STACKALLOC: {
1977     const MachineOperand &DstOp = MI->getOperand(0);
1978     const MachineOperand &AllocOp = MI->getOperand(1);
1979     const MachineOperand &AlignOp = MI->getOperand(2);
1980 
1981     if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
1982       report("dst operand 0 must be a pointer type", MI);
1983       break;
1984     }
1985 
1986     if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
1987       report("src operand 1 must be a scalar reg type", MI);
1988       break;
1989     }
1990 
1991     if (!AlignOp.isImm()) {
1992       report("src operand 2 must be an immediate type", MI);
1993       break;
1994     }
1995     break;
1996   }
1997   case TargetOpcode::G_MEMCPY_INLINE:
1998   case TargetOpcode::G_MEMCPY:
1999   case TargetOpcode::G_MEMMOVE: {
2000     ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2001     if (MMOs.size() != 2) {
2002       report("memcpy/memmove must have 2 memory operands", MI);
2003       break;
2004     }
2005 
2006     if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) ||
2007         (MMOs[1]->isStore() || !MMOs[1]->isLoad())) {
2008       report("wrong memory operand types", MI);
2009       break;
2010     }
2011 
2012     if (MMOs[0]->getSize() != MMOs[1]->getSize())
2013       report("inconsistent memory operand sizes", MI);
2014 
2015     LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2016     LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg());
2017 
2018     if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) {
2019       report("memory instruction operand must be a pointer", MI);
2020       break;
2021     }
2022 
2023     if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2024       report("inconsistent store address space", MI);
2025     if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace())
2026       report("inconsistent load address space", MI);
2027 
2028     if (Opc != TargetOpcode::G_MEMCPY_INLINE)
2029       if (!MI->getOperand(3).isImm() || (MI->getOperand(3).getImm() & ~1LL))
2030         report("'tail' flag (operand 3) must be an immediate 0 or 1", MI);
2031 
2032     break;
2033   }
2034   case TargetOpcode::G_BZERO:
2035   case TargetOpcode::G_MEMSET: {
2036     ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2037     std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset" : "bzero";
2038     if (MMOs.size() != 1) {
2039       report(Twine(Name, " must have 1 memory operand"), MI);
2040       break;
2041     }
2042 
2043     if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) {
2044       report(Twine(Name, " memory operand must be a store"), MI);
2045       break;
2046     }
2047 
2048     LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2049     if (!DstPtrTy.isPointer()) {
2050       report(Twine(Name, " operand must be a pointer"), MI);
2051       break;
2052     }
2053 
2054     if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2055       report("inconsistent " + Twine(Name, " address space"), MI);
2056 
2057     if (!MI->getOperand(MI->getNumOperands() - 1).isImm() ||
2058         (MI->getOperand(MI->getNumOperands() - 1).getImm() & ~1LL))
2059       report("'tail' flag (last operand) must be an immediate 0 or 1", MI);
2060 
2061     break;
2062   }
2063   case TargetOpcode::G_UBSANTRAP: {
2064     const MachineOperand &KindOp = MI->getOperand(0);
2065     if (!MI->getOperand(0).isImm()) {
2066       report("Crash kind must be an immediate", &KindOp, 0);
2067       break;
2068     }
2069     int64_t Kind = MI->getOperand(0).getImm();
2070     if (!isInt<8>(Kind))
2071       report("Crash kind must be 8 bit wide", &KindOp, 0);
2072     break;
2073   }
2074   case TargetOpcode::G_VECREDUCE_SEQ_FADD:
2075   case TargetOpcode::G_VECREDUCE_SEQ_FMUL: {
2076     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2077     LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2078     LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2079     if (!DstTy.isScalar())
2080       report("Vector reduction requires a scalar destination type", MI);
2081     if (!Src1Ty.isScalar())
2082       report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI);
2083     if (!Src2Ty.isVector())
2084       report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI);
2085     break;
2086   }
2087   case TargetOpcode::G_VECREDUCE_FADD:
2088   case TargetOpcode::G_VECREDUCE_FMUL:
2089   case TargetOpcode::G_VECREDUCE_FMAX:
2090   case TargetOpcode::G_VECREDUCE_FMIN:
2091   case TargetOpcode::G_VECREDUCE_FMAXIMUM:
2092   case TargetOpcode::G_VECREDUCE_FMINIMUM:
2093   case TargetOpcode::G_VECREDUCE_ADD:
2094   case TargetOpcode::G_VECREDUCE_MUL:
2095   case TargetOpcode::G_VECREDUCE_AND:
2096   case TargetOpcode::G_VECREDUCE_OR:
2097   case TargetOpcode::G_VECREDUCE_XOR:
2098   case TargetOpcode::G_VECREDUCE_SMAX:
2099   case TargetOpcode::G_VECREDUCE_SMIN:
2100   case TargetOpcode::G_VECREDUCE_UMAX:
2101   case TargetOpcode::G_VECREDUCE_UMIN: {
2102     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2103     if (!DstTy.isScalar())
2104       report("Vector reduction requires a scalar destination type", MI);
2105     break;
2106   }
2107 
2108   case TargetOpcode::G_SBFX:
2109   case TargetOpcode::G_UBFX: {
2110     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2111     if (DstTy.isVector()) {
2112       report("Bitfield extraction is not supported on vectors", MI);
2113       break;
2114     }
2115     break;
2116   }
2117   case TargetOpcode::G_SHL:
2118   case TargetOpcode::G_LSHR:
2119   case TargetOpcode::G_ASHR:
2120   case TargetOpcode::G_ROTR:
2121   case TargetOpcode::G_ROTL: {
2122     LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2123     LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2124     if (Src1Ty.isVector() != Src2Ty.isVector()) {
2125       report("Shifts and rotates require operands to be either all scalars or "
2126              "all vectors",
2127              MI);
2128       break;
2129     }
2130     break;
2131   }
2132   case TargetOpcode::G_LLROUND:
2133   case TargetOpcode::G_LROUND: {
2134     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2135     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2136     if (!DstTy.isValid() || !SrcTy.isValid())
2137       break;
2138     if (SrcTy.isPointer() || DstTy.isPointer()) {
2139       StringRef Op = SrcTy.isPointer() ? "Source" : "Destination";
2140       report(Twine(Op, " operand must not be a pointer type"), MI);
2141     } else if (SrcTy.isScalar()) {
2142       verifyAllRegOpsScalar(*MI, *MRI);
2143       break;
2144     } else if (SrcTy.isVector()) {
2145       verifyVectorElementMatch(SrcTy, DstTy, MI);
2146       break;
2147     }
2148     break;
2149   }
2150   case TargetOpcode::G_IS_FPCLASS: {
2151     LLT DestTy = MRI->getType(MI->getOperand(0).getReg());
2152     LLT DestEltTy = DestTy.getScalarType();
2153     if (!DestEltTy.isScalar()) {
2154       report("Destination must be a scalar or vector of scalars", MI);
2155       break;
2156     }
2157     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2158     LLT SrcEltTy = SrcTy.getScalarType();
2159     if (!SrcEltTy.isScalar()) {
2160       report("Source must be a scalar or vector of scalars", MI);
2161       break;
2162     }
2163     if (!verifyVectorElementMatch(DestTy, SrcTy, MI))
2164       break;
2165     const MachineOperand &TestMO = MI->getOperand(2);
2166     if (!TestMO.isImm()) {
2167       report("floating-point class set (operand 2) must be an immediate", MI);
2168       break;
2169     }
2170     int64_t Test = TestMO.getImm();
2171     if (Test < 0 || Test > fcAllFlags) {
2172       report("Incorrect floating-point class set (operand 2)", MI);
2173       break;
2174     }
2175     break;
2176   }
2177   case TargetOpcode::G_PREFETCH: {
2178     const MachineOperand &AddrOp = MI->getOperand(0);
2179     if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer()) {
2180       report("addr operand must be a pointer", &AddrOp, 0);
2181       break;
2182     }
2183     const MachineOperand &RWOp = MI->getOperand(1);
2184     if (!RWOp.isImm() || (uint64_t)RWOp.getImm() >= 2) {
2185       report("rw operand must be an immediate 0-1", &RWOp, 1);
2186       break;
2187     }
2188     const MachineOperand &LocalityOp = MI->getOperand(2);
2189     if (!LocalityOp.isImm() || (uint64_t)LocalityOp.getImm() >= 4) {
2190       report("locality operand must be an immediate 0-3", &LocalityOp, 2);
2191       break;
2192     }
2193     const MachineOperand &CacheTypeOp = MI->getOperand(3);
2194     if (!CacheTypeOp.isImm() || (uint64_t)CacheTypeOp.getImm() >= 2) {
2195       report("cache type operand must be an immediate 0-1", &CacheTypeOp, 3);
2196       break;
2197     }
2198     break;
2199   }
2200   case TargetOpcode::G_ASSERT_ALIGN: {
2201     if (MI->getOperand(2).getImm() < 1)
2202       report("alignment immediate must be >= 1", MI);
2203     break;
2204   }
2205   case TargetOpcode::G_CONSTANT_POOL: {
2206     if (!MI->getOperand(1).isCPI())
2207       report("Src operand 1 must be a constant pool index", MI);
2208     if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
2209       report("Dst operand 0 must be a pointer", MI);
2210     break;
2211   }
2212   case TargetOpcode::G_PTRAUTH_GLOBAL_VALUE: {
2213     const MachineOperand &AddrOp = MI->getOperand(1);
2214     if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer())
2215       report("addr operand must be a pointer", &AddrOp, 1);
2216     break;
2217   }
2218   default:
2219     break;
2220   }
2221 }
2222 
2223 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
2224   const MCInstrDesc &MCID = MI->getDesc();
2225   if (MI->getNumOperands() < MCID.getNumOperands()) {
2226     report("Too few operands", MI);
2227     OS << MCID.getNumOperands() << " operands expected, but "
2228        << MI->getNumOperands() << " given.\n";
2229   }
2230 
2231   if (MI->getFlag(MachineInstr::NoConvergent) && !MCID.isConvergent())
2232     report("NoConvergent flag expected only on convergent instructions.", MI);
2233 
2234   if (MI->isPHI()) {
2235     if (MF->getProperties().hasProperty(
2236             MachineFunctionProperties::Property::NoPHIs))
2237       report("Found PHI instruction with NoPHIs property set", MI);
2238 
2239     if (FirstNonPHI)
2240       report("Found PHI instruction after non-PHI", MI);
2241   } else if (FirstNonPHI == nullptr)
2242     FirstNonPHI = MI;
2243 
2244   // Check the tied operands.
2245   if (MI->isInlineAsm())
2246     verifyInlineAsm(MI);
2247 
2248   // Check that unspillable terminators define a reg and have at most one use.
2249   if (TII->isUnspillableTerminator(MI)) {
2250     if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef())
2251       report("Unspillable Terminator does not define a reg", MI);
2252     Register Def = MI->getOperand(0).getReg();
2253     if (Def.isVirtual() &&
2254         !MF->getProperties().hasProperty(
2255             MachineFunctionProperties::Property::NoPHIs) &&
2256         std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1)
2257       report("Unspillable Terminator expected to have at most one use!", MI);
2258   }
2259 
2260   // A fully-formed DBG_VALUE must have a location. Ignore partially formed
2261   // DBG_VALUEs: these are convenient to use in tests, but should never get
2262   // generated.
2263   if (MI->isDebugValue() && MI->getNumOperands() == 4)
2264     if (!MI->getDebugLoc())
2265       report("Missing DebugLoc for debug instruction", MI);
2266 
2267   // Meta instructions should never be the subject of debug value tracking,
2268   // they don't create a value in the output program at all.
2269   if (MI->isMetaInstruction() && MI->peekDebugInstrNum())
2270     report("Metadata instruction should not have a value tracking number", MI);
2271 
2272   // Check the MachineMemOperands for basic consistency.
2273   for (MachineMemOperand *Op : MI->memoperands()) {
2274     if (Op->isLoad() && !MI->mayLoad())
2275       report("Missing mayLoad flag", MI);
2276     if (Op->isStore() && !MI->mayStore())
2277       report("Missing mayStore flag", MI);
2278   }
2279 
2280   // Debug values must not have a slot index.
2281   // Other instructions must have one, unless they are inside a bundle.
2282   if (LiveInts) {
2283     bool mapped = !LiveInts->isNotInMIMap(*MI);
2284     if (MI->isDebugOrPseudoInstr()) {
2285       if (mapped)
2286         report("Debug instruction has a slot index", MI);
2287     } else if (MI->isInsideBundle()) {
2288       if (mapped)
2289         report("Instruction inside bundle has a slot index", MI);
2290     } else {
2291       if (!mapped)
2292         report("Missing slot index", MI);
2293     }
2294   }
2295 
2296   unsigned Opc = MCID.getOpcode();
2297   if (isPreISelGenericOpcode(Opc) || isPreISelGenericOptimizationHint(Opc)) {
2298     verifyPreISelGenericInstruction(MI);
2299     return;
2300   }
2301 
2302   StringRef ErrorInfo;
2303   if (!TII->verifyInstruction(*MI, ErrorInfo))
2304     report(ErrorInfo.data(), MI);
2305 
2306   // Verify properties of various specific instruction types
2307   switch (MI->getOpcode()) {
2308   case TargetOpcode::COPY: {
2309     const MachineOperand &DstOp = MI->getOperand(0);
2310     const MachineOperand &SrcOp = MI->getOperand(1);
2311     const Register SrcReg = SrcOp.getReg();
2312     const Register DstReg = DstOp.getReg();
2313 
2314     LLT DstTy = MRI->getType(DstReg);
2315     LLT SrcTy = MRI->getType(SrcReg);
2316     if (SrcTy.isValid() && DstTy.isValid()) {
2317       // If both types are valid, check that the types are the same.
2318       if (SrcTy != DstTy) {
2319         report("Copy Instruction is illegal with mismatching types", MI);
2320         OS << "Def = " << DstTy << ", Src = " << SrcTy << '\n';
2321       }
2322 
2323       break;
2324     }
2325 
2326     if (!SrcTy.isValid() && !DstTy.isValid())
2327       break;
2328 
2329     // If we have only one valid type, this is likely a copy between a virtual
2330     // and physical register.
2331     TypeSize SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
2332     TypeSize DstSize = TRI->getRegSizeInBits(DstReg, *MRI);
2333     if (SrcReg.isPhysical() && DstTy.isValid()) {
2334       const TargetRegisterClass *SrcRC =
2335           TRI->getMinimalPhysRegClassLLT(SrcReg, DstTy);
2336       if (SrcRC)
2337         SrcSize = TRI->getRegSizeInBits(*SrcRC);
2338     }
2339 
2340     if (DstReg.isPhysical() && SrcTy.isValid()) {
2341       const TargetRegisterClass *DstRC =
2342           TRI->getMinimalPhysRegClassLLT(DstReg, SrcTy);
2343       if (DstRC)
2344         DstSize = TRI->getRegSizeInBits(*DstRC);
2345     }
2346 
2347     // The next two checks allow COPY between physical and virtual registers,
2348     // when the virtual register has a scalable size and the physical register
2349     // has a fixed size. These checks allow COPY between *potentialy* mismatched
2350     // sizes. However, once RegisterBankSelection occurs, MachineVerifier should
2351     // be able to resolve a fixed size for the scalable vector, and at that
2352     // point this function will know for sure whether the sizes are mismatched
2353     // and correctly report a size mismatch.
2354     if (SrcReg.isPhysical() && DstReg.isVirtual() && DstSize.isScalable() &&
2355         !SrcSize.isScalable())
2356       break;
2357     if (SrcReg.isVirtual() && DstReg.isPhysical() && SrcSize.isScalable() &&
2358         !DstSize.isScalable())
2359       break;
2360 
2361     if (SrcSize.isNonZero() && DstSize.isNonZero() && SrcSize != DstSize) {
2362       if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
2363         report("Copy Instruction is illegal with mismatching sizes", MI);
2364         OS << "Def Size = " << DstSize << ", Src Size = " << SrcSize << '\n';
2365       }
2366     }
2367     break;
2368   }
2369   case TargetOpcode::STATEPOINT: {
2370     StatepointOpers SO(MI);
2371     if (!MI->getOperand(SO.getIDPos()).isImm() ||
2372         !MI->getOperand(SO.getNBytesPos()).isImm() ||
2373         !MI->getOperand(SO.getNCallArgsPos()).isImm()) {
2374       report("meta operands to STATEPOINT not constant!", MI);
2375       break;
2376     }
2377 
2378     auto VerifyStackMapConstant = [&](unsigned Offset) {
2379       if (Offset >= MI->getNumOperands()) {
2380         report("stack map constant to STATEPOINT is out of range!", MI);
2381         return;
2382       }
2383       if (!MI->getOperand(Offset - 1).isImm() ||
2384           MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp ||
2385           !MI->getOperand(Offset).isImm())
2386         report("stack map constant to STATEPOINT not well formed!", MI);
2387     };
2388     VerifyStackMapConstant(SO.getCCIdx());
2389     VerifyStackMapConstant(SO.getFlagsIdx());
2390     VerifyStackMapConstant(SO.getNumDeoptArgsIdx());
2391     VerifyStackMapConstant(SO.getNumGCPtrIdx());
2392     VerifyStackMapConstant(SO.getNumAllocaIdx());
2393     VerifyStackMapConstant(SO.getNumGcMapEntriesIdx());
2394 
2395     // Verify that all explicit statepoint defs are tied to gc operands as
2396     // they are expected to be a relocation of gc operands.
2397     unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx();
2398     unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2;
2399     for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) {
2400       unsigned UseOpIdx;
2401       if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) {
2402         report("STATEPOINT defs expected to be tied", MI);
2403         break;
2404       }
2405       if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) {
2406         report("STATEPOINT def tied to non-gc operand", MI);
2407         break;
2408       }
2409     }
2410 
2411     // TODO: verify we have properly encoded deopt arguments
2412   } break;
2413   case TargetOpcode::INSERT_SUBREG: {
2414     unsigned InsertedSize;
2415     if (unsigned SubIdx = MI->getOperand(2).getSubReg())
2416       InsertedSize = TRI->getSubRegIdxSize(SubIdx);
2417     else
2418       InsertedSize = TRI->getRegSizeInBits(MI->getOperand(2).getReg(), *MRI);
2419     unsigned SubRegSize = TRI->getSubRegIdxSize(MI->getOperand(3).getImm());
2420     if (SubRegSize < InsertedSize) {
2421       report("INSERT_SUBREG expected inserted value to have equal or lesser "
2422              "size than the subreg it was inserted into", MI);
2423       break;
2424     }
2425   } break;
2426   case TargetOpcode::REG_SEQUENCE: {
2427     unsigned NumOps = MI->getNumOperands();
2428     if (!(NumOps & 1)) {
2429       report("Invalid number of operands for REG_SEQUENCE", MI);
2430       break;
2431     }
2432 
2433     for (unsigned I = 1; I != NumOps; I += 2) {
2434       const MachineOperand &RegOp = MI->getOperand(I);
2435       const MachineOperand &SubRegOp = MI->getOperand(I + 1);
2436 
2437       if (!RegOp.isReg())
2438         report("Invalid register operand for REG_SEQUENCE", &RegOp, I);
2439 
2440       if (!SubRegOp.isImm() || SubRegOp.getImm() == 0 ||
2441           SubRegOp.getImm() >= TRI->getNumSubRegIndices()) {
2442         report("Invalid subregister index operand for REG_SEQUENCE",
2443                &SubRegOp, I + 1);
2444       }
2445     }
2446 
2447     Register DstReg = MI->getOperand(0).getReg();
2448     if (DstReg.isPhysical())
2449       report("REG_SEQUENCE does not support physical register results", MI);
2450 
2451     if (MI->getOperand(0).getSubReg())
2452       report("Invalid subreg result for REG_SEQUENCE", MI);
2453 
2454     break;
2455   }
2456   }
2457 }
2458 
2459 void
2460 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
2461   const MachineInstr *MI = MO->getParent();
2462   const MCInstrDesc &MCID = MI->getDesc();
2463   unsigned NumDefs = MCID.getNumDefs();
2464   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
2465     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
2466 
2467   // The first MCID.NumDefs operands must be explicit register defines
2468   if (MONum < NumDefs) {
2469     const MCOperandInfo &MCOI = MCID.operands()[MONum];
2470     if (!MO->isReg())
2471       report("Explicit definition must be a register", MO, MONum);
2472     else if (!MO->isDef() && !MCOI.isOptionalDef())
2473       report("Explicit definition marked as use", MO, MONum);
2474     else if (MO->isImplicit())
2475       report("Explicit definition marked as implicit", MO, MONum);
2476   } else if (MONum < MCID.getNumOperands()) {
2477     const MCOperandInfo &MCOI = MCID.operands()[MONum];
2478     // Don't check if it's the last operand in a variadic instruction. See,
2479     // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
2480     bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
2481     if (!IsOptional) {
2482       if (MO->isReg()) {
2483         if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs())
2484           report("Explicit operand marked as def", MO, MONum);
2485         if (MO->isImplicit())
2486           report("Explicit operand marked as implicit", MO, MONum);
2487       }
2488 
2489       // Check that an instruction has register operands only as expected.
2490       if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
2491           !MO->isReg() && !MO->isFI())
2492         report("Expected a register operand.", MO, MONum);
2493       if (MO->isReg()) {
2494         if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
2495             (MCOI.OperandType == MCOI::OPERAND_PCREL &&
2496              !TII->isPCRelRegisterOperandLegal(*MO)))
2497           report("Expected a non-register operand.", MO, MONum);
2498       }
2499     }
2500 
2501     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
2502     if (TiedTo != -1) {
2503       if (!MO->isReg())
2504         report("Tied use must be a register", MO, MONum);
2505       else if (!MO->isTied())
2506         report("Operand should be tied", MO, MONum);
2507       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
2508         report("Tied def doesn't match MCInstrDesc", MO, MONum);
2509       else if (MO->getReg().isPhysical()) {
2510         const MachineOperand &MOTied = MI->getOperand(TiedTo);
2511         if (!MOTied.isReg())
2512           report("Tied counterpart must be a register", &MOTied, TiedTo);
2513         else if (MOTied.getReg().isPhysical() &&
2514                  MO->getReg() != MOTied.getReg())
2515           report("Tied physical registers must match.", &MOTied, TiedTo);
2516       }
2517     } else if (MO->isReg() && MO->isTied())
2518       report("Explicit operand should not be tied", MO, MONum);
2519   } else if (!MI->isVariadic()) {
2520     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
2521     if (!MO->isValidExcessOperand())
2522       report("Extra explicit operand on non-variadic instruction", MO, MONum);
2523   }
2524 
2525   switch (MO->getType()) {
2526   case MachineOperand::MO_Register: {
2527     // Verify debug flag on debug instructions. Check this first because reg0
2528     // indicates an undefined debug value.
2529     if (MI->isDebugInstr() && MO->isUse()) {
2530       if (!MO->isDebug())
2531         report("Register operand must be marked debug", MO, MONum);
2532     } else if (MO->isDebug()) {
2533       report("Register operand must not be marked debug", MO, MONum);
2534     }
2535 
2536     const Register Reg = MO->getReg();
2537     if (!Reg)
2538       return;
2539     if (MRI->tracksLiveness() && !MI->isDebugInstr())
2540       checkLiveness(MO, MONum);
2541 
2542     if (MO->isDef() && MO->isUndef() && !MO->getSubReg() &&
2543         MO->getReg().isVirtual()) // TODO: Apply to physregs too
2544       report("Undef virtual register def operands require a subregister", MO, MONum);
2545 
2546     // Verify the consistency of tied operands.
2547     if (MO->isTied()) {
2548       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
2549       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
2550       if (!OtherMO.isReg())
2551         report("Must be tied to a register", MO, MONum);
2552       if (!OtherMO.isTied())
2553         report("Missing tie flags on tied operand", MO, MONum);
2554       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
2555         report("Inconsistent tie links", MO, MONum);
2556       if (MONum < MCID.getNumDefs()) {
2557         if (OtherIdx < MCID.getNumOperands()) {
2558           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
2559             report("Explicit def tied to explicit use without tie constraint",
2560                    MO, MONum);
2561         } else {
2562           if (!OtherMO.isImplicit())
2563             report("Explicit def should be tied to implicit use", MO, MONum);
2564         }
2565       }
2566     }
2567 
2568     // Verify two-address constraints after the twoaddressinstruction pass.
2569     // Both twoaddressinstruction pass and phi-node-elimination pass call
2570     // MRI->leaveSSA() to set MF as not IsSSA, we should do the verification
2571     // after twoaddressinstruction pass not after phi-node-elimination pass. So
2572     // we shouldn't use the IsSSA as the condition, we should based on
2573     // TiedOpsRewritten property to verify two-address constraints, this
2574     // property will be set in twoaddressinstruction pass.
2575     unsigned DefIdx;
2576     if (MF->getProperties().hasProperty(
2577             MachineFunctionProperties::Property::TiedOpsRewritten) &&
2578         MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
2579         Reg != MI->getOperand(DefIdx).getReg())
2580       report("Two-address instruction operands must be identical", MO, MONum);
2581 
2582     // Check register classes.
2583     unsigned SubIdx = MO->getSubReg();
2584 
2585     if (Reg.isPhysical()) {
2586       if (SubIdx) {
2587         report("Illegal subregister index for physical register", MO, MONum);
2588         return;
2589       }
2590       if (MONum < MCID.getNumOperands()) {
2591         if (const TargetRegisterClass *DRC =
2592               TII->getRegClass(MCID, MONum, TRI, *MF)) {
2593           if (!DRC->contains(Reg)) {
2594             report("Illegal physical register for instruction", MO, MONum);
2595             OS << printReg(Reg, TRI) << " is not a "
2596                << TRI->getRegClassName(DRC) << " register.\n";
2597           }
2598         }
2599       }
2600       if (MO->isRenamable()) {
2601         if (MRI->isReserved(Reg)) {
2602           report("isRenamable set on reserved register", MO, MONum);
2603           return;
2604         }
2605       }
2606     } else {
2607       // Virtual register.
2608       const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
2609       if (!RC) {
2610         // This is a generic virtual register.
2611 
2612         // Do not allow undef uses for generic virtual registers. This ensures
2613         // getVRegDef can never fail and return null on a generic register.
2614         //
2615         // FIXME: This restriction should probably be broadened to all SSA
2616         // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
2617         // run on the SSA function just before phi elimination.
2618         if (MO->isUndef())
2619           report("Generic virtual register use cannot be undef", MO, MONum);
2620 
2621         // Debug value instruction is permitted to use undefined vregs.
2622         // This is a performance measure to skip the overhead of immediately
2623         // pruning unused debug operands. The final undef substitution occurs
2624         // when debug values are allocated in LDVImpl::handleDebugValue, so
2625         // these verifications always apply after this pass.
2626         if (isFunctionTracksDebugUserValues || !MO->isUse() ||
2627             !MI->isDebugValue() || !MRI->def_empty(Reg)) {
2628           // If we're post-Select, we can't have gvregs anymore.
2629           if (isFunctionSelected) {
2630             report("Generic virtual register invalid in a Selected function",
2631                    MO, MONum);
2632             return;
2633           }
2634 
2635           // The gvreg must have a type and it must not have a SubIdx.
2636           LLT Ty = MRI->getType(Reg);
2637           if (!Ty.isValid()) {
2638             report("Generic virtual register must have a valid type", MO,
2639                    MONum);
2640             return;
2641           }
2642 
2643           const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
2644           const RegisterBankInfo *RBI = MF->getSubtarget().getRegBankInfo();
2645 
2646           // If we're post-RegBankSelect, the gvreg must have a bank.
2647           if (!RegBank && isFunctionRegBankSelected) {
2648             report("Generic virtual register must have a bank in a "
2649                    "RegBankSelected function",
2650                    MO, MONum);
2651             return;
2652           }
2653 
2654           // Make sure the register fits into its register bank if any.
2655           if (RegBank && Ty.isValid() && !Ty.isScalableVector() &&
2656               RBI->getMaximumSize(RegBank->getID()) < Ty.getSizeInBits()) {
2657             report("Register bank is too small for virtual register", MO,
2658                    MONum);
2659             OS << "Register bank " << RegBank->getName() << " too small("
2660                << RBI->getMaximumSize(RegBank->getID()) << ") to fit "
2661                << Ty.getSizeInBits() << "-bits\n";
2662             return;
2663           }
2664         }
2665 
2666         if (SubIdx)  {
2667           report("Generic virtual register does not allow subregister index", MO,
2668                  MONum);
2669           return;
2670         }
2671 
2672         // If this is a target specific instruction and this operand
2673         // has register class constraint, the virtual register must
2674         // comply to it.
2675         if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
2676             MONum < MCID.getNumOperands() &&
2677             TII->getRegClass(MCID, MONum, TRI, *MF)) {
2678           report("Virtual register does not match instruction constraint", MO,
2679                  MONum);
2680           OS << "Expect register class "
2681              << TRI->getRegClassName(TII->getRegClass(MCID, MONum, TRI, *MF))
2682              << " but got nothing\n";
2683           return;
2684         }
2685 
2686         break;
2687       }
2688       if (SubIdx) {
2689         const TargetRegisterClass *SRC =
2690           TRI->getSubClassWithSubReg(RC, SubIdx);
2691         if (!SRC) {
2692           report("Invalid subregister index for virtual register", MO, MONum);
2693           OS << "Register class " << TRI->getRegClassName(RC)
2694              << " does not support subreg index " << SubIdx << '\n';
2695           return;
2696         }
2697         if (RC != SRC) {
2698           report("Invalid register class for subregister index", MO, MONum);
2699           OS << "Register class " << TRI->getRegClassName(RC)
2700              << " does not fully support subreg index " << SubIdx << '\n';
2701           return;
2702         }
2703       }
2704       if (MONum < MCID.getNumOperands()) {
2705         if (const TargetRegisterClass *DRC =
2706               TII->getRegClass(MCID, MONum, TRI, *MF)) {
2707           if (SubIdx) {
2708             const TargetRegisterClass *SuperRC =
2709                 TRI->getLargestLegalSuperClass(RC, *MF);
2710             if (!SuperRC) {
2711               report("No largest legal super class exists.", MO, MONum);
2712               return;
2713             }
2714             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
2715             if (!DRC) {
2716               report("No matching super-reg register class.", MO, MONum);
2717               return;
2718             }
2719           }
2720           if (!RC->hasSuperClassEq(DRC)) {
2721             report("Illegal virtual register for instruction", MO, MONum);
2722             OS << "Expected a " << TRI->getRegClassName(DRC)
2723                << " register, but got a " << TRI->getRegClassName(RC)
2724                << " register\n";
2725           }
2726         }
2727       }
2728     }
2729     break;
2730   }
2731 
2732   case MachineOperand::MO_RegisterMask:
2733     regMasks.push_back(MO->getRegMask());
2734     break;
2735 
2736   case MachineOperand::MO_MachineBasicBlock:
2737     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
2738       report("PHI operand is not in the CFG", MO, MONum);
2739     break;
2740 
2741   case MachineOperand::MO_FrameIndex:
2742     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
2743         LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2744       int FI = MO->getIndex();
2745       LiveInterval &LI = LiveStks->getInterval(FI);
2746       SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
2747 
2748       bool stores = MI->mayStore();
2749       bool loads = MI->mayLoad();
2750       // For a memory-to-memory move, we need to check if the frame
2751       // index is used for storing or loading, by inspecting the
2752       // memory operands.
2753       if (stores && loads) {
2754         for (auto *MMO : MI->memoperands()) {
2755           const PseudoSourceValue *PSV = MMO->getPseudoValue();
2756           if (PSV == nullptr) continue;
2757           const FixedStackPseudoSourceValue *Value =
2758             dyn_cast<FixedStackPseudoSourceValue>(PSV);
2759           if (Value == nullptr) continue;
2760           if (Value->getFrameIndex() != FI) continue;
2761 
2762           if (MMO->isStore())
2763             loads = false;
2764           else
2765             stores = false;
2766           break;
2767         }
2768         if (loads == stores)
2769           report("Missing fixed stack memoperand.", MI);
2770       }
2771       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
2772         report("Instruction loads from dead spill slot", MO, MONum);
2773         OS << "Live stack: " << LI << '\n';
2774       }
2775       if (stores && !LI.liveAt(Idx.getRegSlot())) {
2776         report("Instruction stores to dead spill slot", MO, MONum);
2777         OS << "Live stack: " << LI << '\n';
2778       }
2779     }
2780     break;
2781 
2782   case MachineOperand::MO_CFIIndex:
2783     if (MO->getCFIIndex() >= MF->getFrameInstructions().size())
2784       report("CFI instruction has invalid index", MO, MONum);
2785     break;
2786 
2787   default:
2788     break;
2789   }
2790 }
2791 
2792 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
2793                                          unsigned MONum, SlotIndex UseIdx,
2794                                          const LiveRange &LR,
2795                                          Register VRegOrUnit,
2796                                          LaneBitmask LaneMask) {
2797   const MachineInstr *MI = MO->getParent();
2798 
2799   if (!LR.verify()) {
2800     report("invalid live range", MO, MONum);
2801     report_context_liverange(LR);
2802     report_context_vreg_regunit(VRegOrUnit);
2803     report_context(UseIdx);
2804     return;
2805   }
2806 
2807   LiveQueryResult LRQ = LR.Query(UseIdx);
2808   bool HasValue = LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut());
2809   // Check if we have a segment at the use, note however that we only need one
2810   // live subregister range, the others may be dead.
2811   if (!HasValue && LaneMask.none()) {
2812     report("No live segment at use", MO, MONum);
2813     report_context_liverange(LR);
2814     report_context_vreg_regunit(VRegOrUnit);
2815     report_context(UseIdx);
2816   }
2817   if (MO->isKill() && !LRQ.isKill()) {
2818     report("Live range continues after kill flag", MO, MONum);
2819     report_context_liverange(LR);
2820     report_context_vreg_regunit(VRegOrUnit);
2821     if (LaneMask.any())
2822       report_context_lanemask(LaneMask);
2823     report_context(UseIdx);
2824   }
2825 }
2826 
2827 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
2828                                          unsigned MONum, SlotIndex DefIdx,
2829                                          const LiveRange &LR,
2830                                          Register VRegOrUnit,
2831                                          bool SubRangeCheck,
2832                                          LaneBitmask LaneMask) {
2833   if (!LR.verify()) {
2834     report("invalid live range", MO, MONum);
2835     report_context_liverange(LR);
2836     report_context_vreg_regunit(VRegOrUnit);
2837     if (LaneMask.any())
2838       report_context_lanemask(LaneMask);
2839     report_context(DefIdx);
2840   }
2841 
2842   if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
2843     // The LR can correspond to the whole reg and its def slot is not obliged
2844     // to be the same as the MO' def slot. E.g. when we check here "normal"
2845     // subreg MO but there is other EC subreg MO in the same instruction so the
2846     // whole reg has EC def slot and differs from the currently checked MO' def
2847     // slot. For example:
2848     // %0 [16e,32r:0) 0@16e  L..3 [16e,32r:0) 0@16e  L..C [16r,32r:0) 0@16r
2849     // Check that there is an early-clobber def of the same superregister
2850     // somewhere is performed in visitMachineFunctionAfter()
2851     if (((SubRangeCheck || MO->getSubReg() == 0) && VNI->def != DefIdx) ||
2852         !SlotIndex::isSameInstr(VNI->def, DefIdx) ||
2853         (VNI->def != DefIdx &&
2854          (!VNI->def.isEarlyClobber() || !DefIdx.isRegister()))) {
2855       report("Inconsistent valno->def", MO, MONum);
2856       report_context_liverange(LR);
2857       report_context_vreg_regunit(VRegOrUnit);
2858       if (LaneMask.any())
2859         report_context_lanemask(LaneMask);
2860       report_context(*VNI);
2861       report_context(DefIdx);
2862     }
2863   } else {
2864     report("No live segment at def", MO, MONum);
2865     report_context_liverange(LR);
2866     report_context_vreg_regunit(VRegOrUnit);
2867     if (LaneMask.any())
2868       report_context_lanemask(LaneMask);
2869     report_context(DefIdx);
2870   }
2871   // Check that, if the dead def flag is present, LiveInts agree.
2872   if (MO->isDead()) {
2873     LiveQueryResult LRQ = LR.Query(DefIdx);
2874     if (!LRQ.isDeadDef()) {
2875       assert(VRegOrUnit.isVirtual() && "Expecting a virtual register.");
2876       // A dead subreg def only tells us that the specific subreg is dead. There
2877       // could be other non-dead defs of other subregs, or we could have other
2878       // parts of the register being live through the instruction. So unless we
2879       // are checking liveness for a subrange it is ok for the live range to
2880       // continue, given that we have a dead def of a subregister.
2881       if (SubRangeCheck || MO->getSubReg() == 0) {
2882         report("Live range continues after dead def flag", MO, MONum);
2883         report_context_liverange(LR);
2884         report_context_vreg_regunit(VRegOrUnit);
2885         if (LaneMask.any())
2886           report_context_lanemask(LaneMask);
2887       }
2888     }
2889   }
2890 }
2891 
2892 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
2893   const MachineInstr *MI = MO->getParent();
2894   const Register Reg = MO->getReg();
2895   const unsigned SubRegIdx = MO->getSubReg();
2896 
2897   const LiveInterval *LI = nullptr;
2898   if (LiveInts && Reg.isVirtual()) {
2899     if (LiveInts->hasInterval(Reg)) {
2900       LI = &LiveInts->getInterval(Reg);
2901       if (SubRegIdx != 0 && (MO->isDef() || !MO->isUndef()) && !LI->empty() &&
2902           !LI->hasSubRanges() && MRI->shouldTrackSubRegLiveness(Reg))
2903         report("Live interval for subreg operand has no subranges", MO, MONum);
2904     } else {
2905       report("Virtual register has no live interval", MO, MONum);
2906     }
2907   }
2908 
2909   // Both use and def operands can read a register.
2910   if (MO->readsReg()) {
2911     if (MO->isKill())
2912       addRegWithSubRegs(regsKilled, Reg);
2913 
2914     // Check that LiveVars knows this kill (unless we are inside a bundle, in
2915     // which case we have already checked that LiveVars knows any kills on the
2916     // bundle header instead).
2917     if (LiveVars && Reg.isVirtual() && MO->isKill() &&
2918         !MI->isBundledWithPred()) {
2919       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
2920       if (!is_contained(VI.Kills, MI))
2921         report("Kill missing from LiveVariables", MO, MONum);
2922     }
2923 
2924     // Check LiveInts liveness and kill.
2925     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2926       SlotIndex UseIdx;
2927       if (MI->isPHI()) {
2928         // PHI use occurs on the edge, so check for live out here instead.
2929         UseIdx = LiveInts->getMBBEndIdx(
2930           MI->getOperand(MONum + 1).getMBB()).getPrevSlot();
2931       } else {
2932         UseIdx = LiveInts->getInstructionIndex(*MI);
2933       }
2934       // Check the cached regunit intervals.
2935       if (Reg.isPhysical() && !isReserved(Reg)) {
2936         for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
2937           if (MRI->isReservedRegUnit(Unit))
2938             continue;
2939           if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
2940             checkLivenessAtUse(MO, MONum, UseIdx, *LR, Unit);
2941         }
2942       }
2943 
2944       if (Reg.isVirtual()) {
2945         // This is a virtual register interval.
2946         checkLivenessAtUse(MO, MONum, UseIdx, *LI, Reg);
2947 
2948         if (LI->hasSubRanges() && !MO->isDef()) {
2949           LaneBitmask MOMask = SubRegIdx != 0
2950                                    ? TRI->getSubRegIndexLaneMask(SubRegIdx)
2951                                    : MRI->getMaxLaneMaskForVReg(Reg);
2952           LaneBitmask LiveInMask;
2953           for (const LiveInterval::SubRange &SR : LI->subranges()) {
2954             if ((MOMask & SR.LaneMask).none())
2955               continue;
2956             checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
2957             LiveQueryResult LRQ = SR.Query(UseIdx);
2958             if (LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut()))
2959               LiveInMask |= SR.LaneMask;
2960           }
2961           // At least parts of the register has to be live at the use.
2962           if ((LiveInMask & MOMask).none()) {
2963             report("No live subrange at use", MO, MONum);
2964             report_context(*LI);
2965             report_context(UseIdx);
2966           }
2967           // For PHIs all lanes should be live
2968           if (MI->isPHI() && LiveInMask != MOMask) {
2969             report("Not all lanes of PHI source live at use", MO, MONum);
2970             report_context(*LI);
2971             report_context(UseIdx);
2972           }
2973         }
2974       }
2975     }
2976 
2977     // Use of a dead register.
2978     if (!regsLive.count(Reg)) {
2979       if (Reg.isPhysical()) {
2980         // Reserved registers may be used even when 'dead'.
2981         bool Bad = !isReserved(Reg);
2982         // We are fine if just any subregister has a defined value.
2983         if (Bad) {
2984 
2985           for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
2986             if (regsLive.count(SubReg)) {
2987               Bad = false;
2988               break;
2989             }
2990           }
2991         }
2992         // If there is an additional implicit-use of a super register we stop
2993         // here. By definition we are fine if the super register is not
2994         // (completely) dead, if the complete super register is dead we will
2995         // get a report for its operand.
2996         if (Bad) {
2997           for (const MachineOperand &MOP : MI->uses()) {
2998             if (!MOP.isReg() || !MOP.isImplicit())
2999               continue;
3000 
3001             if (!MOP.getReg().isPhysical())
3002               continue;
3003 
3004             if (llvm::is_contained(TRI->subregs(MOP.getReg()), Reg))
3005               Bad = false;
3006           }
3007         }
3008         if (Bad)
3009           report("Using an undefined physical register", MO, MONum);
3010       } else if (MRI->def_empty(Reg)) {
3011         report("Reading virtual register without a def", MO, MONum);
3012       } else {
3013         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3014         // We don't know which virtual registers are live in, so only complain
3015         // if vreg was killed in this MBB. Otherwise keep track of vregs that
3016         // must be live in. PHI instructions are handled separately.
3017         if (MInfo.regsKilled.count(Reg))
3018           report("Using a killed virtual register", MO, MONum);
3019         else if (!MI->isPHI())
3020           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
3021       }
3022     }
3023   }
3024 
3025   if (MO->isDef()) {
3026     // Register defined.
3027     // TODO: verify that earlyclobber ops are not used.
3028     if (MO->isDead())
3029       addRegWithSubRegs(regsDead, Reg);
3030     else
3031       addRegWithSubRegs(regsDefined, Reg);
3032 
3033     // Verify SSA form.
3034     if (MRI->isSSA() && Reg.isVirtual() &&
3035         std::next(MRI->def_begin(Reg)) != MRI->def_end())
3036       report("Multiple virtual register defs in SSA form", MO, MONum);
3037 
3038     // Check LiveInts for a live segment, but only for virtual registers.
3039     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
3040       SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
3041       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
3042 
3043       if (Reg.isVirtual()) {
3044         checkLivenessAtDef(MO, MONum, DefIdx, *LI, Reg);
3045 
3046         if (LI->hasSubRanges()) {
3047           LaneBitmask MOMask = SubRegIdx != 0
3048                                    ? TRI->getSubRegIndexLaneMask(SubRegIdx)
3049                                    : MRI->getMaxLaneMaskForVReg(Reg);
3050           for (const LiveInterval::SubRange &SR : LI->subranges()) {
3051             if ((SR.LaneMask & MOMask).none())
3052               continue;
3053             checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
3054           }
3055         }
3056       }
3057     }
3058   }
3059 }
3060 
3061 // This function gets called after visiting all instructions in a bundle. The
3062 // argument points to the bundle header.
3063 // Normal stand-alone instructions are also considered 'bundles', and this
3064 // function is called for all of them.
3065 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
3066   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3067   set_union(MInfo.regsKilled, regsKilled);
3068   set_subtract(regsLive, regsKilled); regsKilled.clear();
3069   // Kill any masked registers.
3070   while (!regMasks.empty()) {
3071     const uint32_t *Mask = regMasks.pop_back_val();
3072     for (Register Reg : regsLive)
3073       if (Reg.isPhysical() &&
3074           MachineOperand::clobbersPhysReg(Mask, Reg.asMCReg()))
3075         regsDead.push_back(Reg);
3076   }
3077   set_subtract(regsLive, regsDead);   regsDead.clear();
3078   set_union(regsLive, regsDefined);   regsDefined.clear();
3079 }
3080 
3081 void
3082 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
3083   MBBInfoMap[MBB].regsLiveOut = regsLive;
3084   regsLive.clear();
3085 
3086   if (Indexes) {
3087     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
3088     if (!(stop > lastIndex)) {
3089       report("Block ends before last instruction index", MBB);
3090       OS << "Block ends at " << stop << " last instruction was at " << lastIndex
3091          << '\n';
3092     }
3093     lastIndex = stop;
3094   }
3095 }
3096 
3097 namespace {
3098 // This implements a set of registers that serves as a filter: can filter other
3099 // sets by passing through elements not in the filter and blocking those that
3100 // are. Any filter implicitly includes the full set of physical registers upon
3101 // creation, thus filtering them all out. The filter itself as a set only grows,
3102 // and needs to be as efficient as possible.
3103 struct VRegFilter {
3104   // Add elements to the filter itself. \pre Input set \p FromRegSet must have
3105   // no duplicates. Both virtual and physical registers are fine.
3106   template <typename RegSetT> void add(const RegSetT &FromRegSet) {
3107     SmallVector<Register, 0> VRegsBuffer;
3108     filterAndAdd(FromRegSet, VRegsBuffer);
3109   }
3110   // Filter \p FromRegSet through the filter and append passed elements into \p
3111   // ToVRegs. All elements appended are then added to the filter itself.
3112   // \returns true if anything changed.
3113   template <typename RegSetT>
3114   bool filterAndAdd(const RegSetT &FromRegSet,
3115                     SmallVectorImpl<Register> &ToVRegs) {
3116     unsigned SparseUniverse = Sparse.size();
3117     unsigned NewSparseUniverse = SparseUniverse;
3118     unsigned NewDenseSize = Dense.size();
3119     size_t Begin = ToVRegs.size();
3120     for (Register Reg : FromRegSet) {
3121       if (!Reg.isVirtual())
3122         continue;
3123       unsigned Index = Register::virtReg2Index(Reg);
3124       if (Index < SparseUniverseMax) {
3125         if (Index < SparseUniverse && Sparse.test(Index))
3126           continue;
3127         NewSparseUniverse = std::max(NewSparseUniverse, Index + 1);
3128       } else {
3129         if (Dense.count(Reg))
3130           continue;
3131         ++NewDenseSize;
3132       }
3133       ToVRegs.push_back(Reg);
3134     }
3135     size_t End = ToVRegs.size();
3136     if (Begin == End)
3137       return false;
3138     // Reserving space in sets once performs better than doing so continuously
3139     // and pays easily for double look-ups (even in Dense with SparseUniverseMax
3140     // tuned all the way down) and double iteration (the second one is over a
3141     // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
3142     Sparse.resize(NewSparseUniverse);
3143     Dense.reserve(NewDenseSize);
3144     for (unsigned I = Begin; I < End; ++I) {
3145       Register Reg = ToVRegs[I];
3146       unsigned Index = Register::virtReg2Index(Reg);
3147       if (Index < SparseUniverseMax)
3148         Sparse.set(Index);
3149       else
3150         Dense.insert(Reg);
3151     }
3152     return true;
3153   }
3154 
3155 private:
3156   static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8;
3157   // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound
3158   // are tracked by Dense. The only purpose of the threashold and the Dense set
3159   // is to have a reasonably growing memory usage in pathological cases (large
3160   // number of very sparse VRegFilter instances live at the same time). In
3161   // practice even in the worst-by-execution time cases having all elements
3162   // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
3163   // space efficient than if tracked by Dense. The threashold is set to keep the
3164   // worst-case memory usage within 2x of figures determined empirically for
3165   // "all Dense" scenario in such worst-by-execution-time cases.
3166   BitVector Sparse;
3167   DenseSet<unsigned> Dense;
3168 };
3169 
3170 // Implements both a transfer function and a (binary, in-place) join operator
3171 // for a dataflow over register sets with set union join and filtering transfer
3172 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
3173 // Maintains out_b as its state, allowing for O(n) iteration over it at any
3174 // time, where n is the size of the set (as opposed to O(U) where U is the
3175 // universe). filter_b implicitly contains all physical registers at all times.
3176 class FilteringVRegSet {
3177   VRegFilter Filter;
3178   SmallVector<Register, 0> VRegs;
3179 
3180 public:
3181   // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
3182   // Both virtual and physical registers are fine.
3183   template <typename RegSetT> void addToFilter(const RegSetT &RS) {
3184     Filter.add(RS);
3185   }
3186   // Passes \p RS through the filter_b (transfer function) and adds what's left
3187   // to itself (out_b).
3188   template <typename RegSetT> bool add(const RegSetT &RS) {
3189     // Double-duty the Filter: to maintain VRegs a set (and the join operation
3190     // a set union) just add everything being added here to the Filter as well.
3191     return Filter.filterAndAdd(RS, VRegs);
3192   }
3193   using const_iterator = decltype(VRegs)::const_iterator;
3194   const_iterator begin() const { return VRegs.begin(); }
3195   const_iterator end() const { return VRegs.end(); }
3196   size_t size() const { return VRegs.size(); }
3197 };
3198 } // namespace
3199 
3200 // Calculate the largest possible vregsPassed sets. These are the registers that
3201 // can pass through an MBB live, but may not be live every time. It is assumed
3202 // that all vregsPassed sets are empty before the call.
3203 void MachineVerifier::calcRegsPassed() {
3204   if (MF->empty())
3205     // ReversePostOrderTraversal doesn't handle empty functions.
3206     return;
3207 
3208   for (const MachineBasicBlock *MB :
3209        ReversePostOrderTraversal<const MachineFunction *>(MF)) {
3210     FilteringVRegSet VRegs;
3211     BBInfo &Info = MBBInfoMap[MB];
3212     assert(Info.reachable);
3213 
3214     VRegs.addToFilter(Info.regsKilled);
3215     VRegs.addToFilter(Info.regsLiveOut);
3216     for (const MachineBasicBlock *Pred : MB->predecessors()) {
3217       const BBInfo &PredInfo = MBBInfoMap[Pred];
3218       if (!PredInfo.reachable)
3219         continue;
3220 
3221       VRegs.add(PredInfo.regsLiveOut);
3222       VRegs.add(PredInfo.vregsPassed);
3223     }
3224     Info.vregsPassed.reserve(VRegs.size());
3225     Info.vregsPassed.insert(VRegs.begin(), VRegs.end());
3226   }
3227 }
3228 
3229 // Calculate the set of virtual registers that must be passed through each basic
3230 // block in order to satisfy the requirements of successor blocks. This is very
3231 // similar to calcRegsPassed, only backwards.
3232 void MachineVerifier::calcRegsRequired() {
3233   // First push live-in regs to predecessors' vregsRequired.
3234   SmallPtrSet<const MachineBasicBlock*, 8> todo;
3235   for (const auto &MBB : *MF) {
3236     BBInfo &MInfo = MBBInfoMap[&MBB];
3237     for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3238       BBInfo &PInfo = MBBInfoMap[Pred];
3239       if (PInfo.addRequired(MInfo.vregsLiveIn))
3240         todo.insert(Pred);
3241     }
3242 
3243     // Handle the PHI node.
3244     for (const MachineInstr &MI : MBB.phis()) {
3245       for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3246         // Skip those Operands which are undef regs or not regs.
3247         if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg())
3248           continue;
3249 
3250         // Get register and predecessor for one PHI edge.
3251         Register Reg = MI.getOperand(i).getReg();
3252         const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB();
3253 
3254         BBInfo &PInfo = MBBInfoMap[Pred];
3255         if (PInfo.addRequired(Reg))
3256           todo.insert(Pred);
3257       }
3258     }
3259   }
3260 
3261   // Iteratively push vregsRequired to predecessors. This will converge to the
3262   // same final state regardless of DenseSet iteration order.
3263   while (!todo.empty()) {
3264     const MachineBasicBlock *MBB = *todo.begin();
3265     todo.erase(MBB);
3266     BBInfo &MInfo = MBBInfoMap[MBB];
3267     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3268       if (Pred == MBB)
3269         continue;
3270       BBInfo &SInfo = MBBInfoMap[Pred];
3271       if (SInfo.addRequired(MInfo.vregsRequired))
3272         todo.insert(Pred);
3273     }
3274   }
3275 }
3276 
3277 // Check PHI instructions at the beginning of MBB. It is assumed that
3278 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
3279 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
3280   BBInfo &MInfo = MBBInfoMap[&MBB];
3281 
3282   SmallPtrSet<const MachineBasicBlock*, 8> seen;
3283   for (const MachineInstr &Phi : MBB) {
3284     if (!Phi.isPHI())
3285       break;
3286     seen.clear();
3287 
3288     const MachineOperand &MODef = Phi.getOperand(0);
3289     if (!MODef.isReg() || !MODef.isDef()) {
3290       report("Expected first PHI operand to be a register def", &MODef, 0);
3291       continue;
3292     }
3293     if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
3294         MODef.isEarlyClobber() || MODef.isDebug())
3295       report("Unexpected flag on PHI operand", &MODef, 0);
3296     Register DefReg = MODef.getReg();
3297     if (!DefReg.isVirtual())
3298       report("Expected first PHI operand to be a virtual register", &MODef, 0);
3299 
3300     for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
3301       const MachineOperand &MO0 = Phi.getOperand(I);
3302       if (!MO0.isReg()) {
3303         report("Expected PHI operand to be a register", &MO0, I);
3304         continue;
3305       }
3306       if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
3307           MO0.isDebug() || MO0.isTied())
3308         report("Unexpected flag on PHI operand", &MO0, I);
3309 
3310       const MachineOperand &MO1 = Phi.getOperand(I + 1);
3311       if (!MO1.isMBB()) {
3312         report("Expected PHI operand to be a basic block", &MO1, I + 1);
3313         continue;
3314       }
3315 
3316       const MachineBasicBlock &Pre = *MO1.getMBB();
3317       if (!Pre.isSuccessor(&MBB)) {
3318         report("PHI input is not a predecessor block", &MO1, I + 1);
3319         continue;
3320       }
3321 
3322       if (MInfo.reachable) {
3323         seen.insert(&Pre);
3324         BBInfo &PrInfo = MBBInfoMap[&Pre];
3325         if (!MO0.isUndef() && PrInfo.reachable &&
3326             !PrInfo.isLiveOut(MO0.getReg()))
3327           report("PHI operand is not live-out from predecessor", &MO0, I);
3328       }
3329     }
3330 
3331     // Did we see all predecessors?
3332     if (MInfo.reachable) {
3333       for (MachineBasicBlock *Pred : MBB.predecessors()) {
3334         if (!seen.count(Pred)) {
3335           report("Missing PHI operand", &Phi);
3336           OS << printMBBReference(*Pred)
3337              << " is a predecessor according to the CFG.\n";
3338         }
3339       }
3340     }
3341   }
3342 }
3343 
3344 static void
3345 verifyConvergenceControl(const MachineFunction &MF, MachineDominatorTree &DT,
3346                          std::function<void(const Twine &Message)> FailureCB,
3347                          raw_ostream &OS) {
3348   MachineConvergenceVerifier CV;
3349   CV.initialize(&OS, FailureCB, MF);
3350 
3351   for (const auto &MBB : MF) {
3352     CV.visit(MBB);
3353     for (const auto &MI : MBB.instrs())
3354       CV.visit(MI);
3355   }
3356 
3357   if (CV.sawTokens()) {
3358     DT.recalculate(const_cast<MachineFunction &>(MF));
3359     CV.verify(DT);
3360   }
3361 }
3362 
3363 void MachineVerifier::visitMachineFunctionAfter() {
3364   auto FailureCB = [this](const Twine &Message) {
3365     report(Message.str().c_str(), MF);
3366   };
3367   verifyConvergenceControl(*MF, DT, FailureCB, OS);
3368 
3369   calcRegsPassed();
3370 
3371   for (const MachineBasicBlock &MBB : *MF)
3372     checkPHIOps(MBB);
3373 
3374   // Now check liveness info if available
3375   calcRegsRequired();
3376 
3377   // Check for killed virtual registers that should be live out.
3378   for (const auto &MBB : *MF) {
3379     BBInfo &MInfo = MBBInfoMap[&MBB];
3380     for (Register VReg : MInfo.vregsRequired)
3381       if (MInfo.regsKilled.count(VReg)) {
3382         report("Virtual register killed in block, but needed live out.", &MBB);
3383         OS << "Virtual register " << printReg(VReg)
3384            << " is used after the block.\n";
3385       }
3386   }
3387 
3388   if (!MF->empty()) {
3389     BBInfo &MInfo = MBBInfoMap[&MF->front()];
3390     for (Register VReg : MInfo.vregsRequired) {
3391       report("Virtual register defs don't dominate all uses.", MF);
3392       report_context_vreg(VReg);
3393     }
3394   }
3395 
3396   if (LiveVars)
3397     verifyLiveVariables();
3398   if (LiveInts)
3399     verifyLiveIntervals();
3400 
3401   // Check live-in list of each MBB. If a register is live into MBB, check
3402   // that the register is in regsLiveOut of each predecessor block. Since
3403   // this must come from a definition in the predecesssor or its live-in
3404   // list, this will catch a live-through case where the predecessor does not
3405   // have the register in its live-in list.  This currently only checks
3406   // registers that have no aliases, are not allocatable and are not
3407   // reserved, which could mean a condition code register for instance.
3408   if (MRI->tracksLiveness())
3409     for (const auto &MBB : *MF)
3410       for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
3411         MCPhysReg LiveInReg = P.PhysReg;
3412         bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
3413         if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg))
3414           continue;
3415         for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3416           BBInfo &PInfo = MBBInfoMap[Pred];
3417           if (!PInfo.regsLiveOut.count(LiveInReg)) {
3418             report("Live in register not found to be live out from predecessor.",
3419                    &MBB);
3420             OS << TRI->getName(LiveInReg) << " not found to be live out from "
3421                << printMBBReference(*Pred) << '\n';
3422           }
3423         }
3424       }
3425 
3426   for (auto CSInfo : MF->getCallSitesInfo())
3427     if (!CSInfo.first->isCall())
3428       report("Call site info referencing instruction that is not call", MF);
3429 
3430   // If there's debug-info, check that we don't have any duplicate value
3431   // tracking numbers.
3432   if (MF->getFunction().getSubprogram()) {
3433     DenseSet<unsigned> SeenNumbers;
3434     for (const auto &MBB : *MF) {
3435       for (const auto &MI : MBB) {
3436         if (auto Num = MI.peekDebugInstrNum()) {
3437           auto Result = SeenNumbers.insert((unsigned)Num);
3438           if (!Result.second)
3439             report("Instruction has a duplicated value tracking number", &MI);
3440         }
3441       }
3442     }
3443   }
3444 }
3445 
3446 void MachineVerifier::verifyLiveVariables() {
3447   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
3448   for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3449     Register Reg = Register::index2VirtReg(I);
3450     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
3451     for (const auto &MBB : *MF) {
3452       BBInfo &MInfo = MBBInfoMap[&MBB];
3453 
3454       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
3455       if (MInfo.vregsRequired.count(Reg)) {
3456         if (!VI.AliveBlocks.test(MBB.getNumber())) {
3457           report("LiveVariables: Block missing from AliveBlocks", &MBB);
3458           OS << "Virtual register " << printReg(Reg)
3459              << " must be live through the block.\n";
3460         }
3461       } else {
3462         if (VI.AliveBlocks.test(MBB.getNumber())) {
3463           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
3464           OS << "Virtual register " << printReg(Reg)
3465              << " is not needed live through the block.\n";
3466         }
3467       }
3468     }
3469   }
3470 }
3471 
3472 void MachineVerifier::verifyLiveIntervals() {
3473   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
3474   for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3475     Register Reg = Register::index2VirtReg(I);
3476 
3477     // Spilling and splitting may leave unused registers around. Skip them.
3478     if (MRI->reg_nodbg_empty(Reg))
3479       continue;
3480 
3481     if (!LiveInts->hasInterval(Reg)) {
3482       report("Missing live interval for virtual register", MF);
3483       OS << printReg(Reg, TRI) << " still has defs or uses\n";
3484       continue;
3485     }
3486 
3487     const LiveInterval &LI = LiveInts->getInterval(Reg);
3488     assert(Reg == LI.reg() && "Invalid reg to interval mapping");
3489     verifyLiveInterval(LI);
3490   }
3491 
3492   // Verify all the cached regunit intervals.
3493   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
3494     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
3495       verifyLiveRange(*LR, i);
3496 }
3497 
3498 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
3499                                            const VNInfo *VNI, Register Reg,
3500                                            LaneBitmask LaneMask) {
3501   if (VNI->isUnused())
3502     return;
3503 
3504   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
3505 
3506   if (!DefVNI) {
3507     report("Value not live at VNInfo def and not marked unused", MF);
3508     report_context(LR, Reg, LaneMask);
3509     report_context(*VNI);
3510     return;
3511   }
3512 
3513   if (DefVNI != VNI) {
3514     report("Live segment at def has different VNInfo", MF);
3515     report_context(LR, Reg, LaneMask);
3516     report_context(*VNI);
3517     return;
3518   }
3519 
3520   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
3521   if (!MBB) {
3522     report("Invalid VNInfo definition index", MF);
3523     report_context(LR, Reg, LaneMask);
3524     report_context(*VNI);
3525     return;
3526   }
3527 
3528   if (VNI->isPHIDef()) {
3529     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
3530       report("PHIDef VNInfo is not defined at MBB start", MBB);
3531       report_context(LR, Reg, LaneMask);
3532       report_context(*VNI);
3533     }
3534     return;
3535   }
3536 
3537   // Non-PHI def.
3538   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
3539   if (!MI) {
3540     report("No instruction at VNInfo def index", MBB);
3541     report_context(LR, Reg, LaneMask);
3542     report_context(*VNI);
3543     return;
3544   }
3545 
3546   if (Reg != 0) {
3547     bool hasDef = false;
3548     bool isEarlyClobber = false;
3549     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3550       if (!MOI->isReg() || !MOI->isDef())
3551         continue;
3552       if (Reg.isVirtual()) {
3553         if (MOI->getReg() != Reg)
3554           continue;
3555       } else {
3556         if (!MOI->getReg().isPhysical() || !TRI->hasRegUnit(MOI->getReg(), Reg))
3557           continue;
3558       }
3559       if (LaneMask.any() &&
3560           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
3561         continue;
3562       hasDef = true;
3563       if (MOI->isEarlyClobber())
3564         isEarlyClobber = true;
3565     }
3566 
3567     if (!hasDef) {
3568       report("Defining instruction does not modify register", MI);
3569       report_context(LR, Reg, LaneMask);
3570       report_context(*VNI);
3571     }
3572 
3573     // Early clobber defs begin at USE slots, but other defs must begin at
3574     // DEF slots.
3575     if (isEarlyClobber) {
3576       if (!VNI->def.isEarlyClobber()) {
3577         report("Early clobber def must be at an early-clobber slot", MBB);
3578         report_context(LR, Reg, LaneMask);
3579         report_context(*VNI);
3580       }
3581     } else if (!VNI->def.isRegister()) {
3582       report("Non-PHI, non-early clobber def must be at a register slot", MBB);
3583       report_context(LR, Reg, LaneMask);
3584       report_context(*VNI);
3585     }
3586   }
3587 }
3588 
3589 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
3590                                              const LiveRange::const_iterator I,
3591                                              Register Reg,
3592                                              LaneBitmask LaneMask) {
3593   const LiveRange::Segment &S = *I;
3594   const VNInfo *VNI = S.valno;
3595   assert(VNI && "Live segment has no valno");
3596 
3597   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
3598     report("Foreign valno in live segment", MF);
3599     report_context(LR, Reg, LaneMask);
3600     report_context(S);
3601     report_context(*VNI);
3602   }
3603 
3604   if (VNI->isUnused()) {
3605     report("Live segment valno is marked unused", MF);
3606     report_context(LR, Reg, LaneMask);
3607     report_context(S);
3608   }
3609 
3610   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
3611   if (!MBB) {
3612     report("Bad start of live segment, no basic block", MF);
3613     report_context(LR, Reg, LaneMask);
3614     report_context(S);
3615     return;
3616   }
3617   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
3618   if (S.start != MBBStartIdx && S.start != VNI->def) {
3619     report("Live segment must begin at MBB entry or valno def", MBB);
3620     report_context(LR, Reg, LaneMask);
3621     report_context(S);
3622   }
3623 
3624   const MachineBasicBlock *EndMBB =
3625     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
3626   if (!EndMBB) {
3627     report("Bad end of live segment, no basic block", MF);
3628     report_context(LR, Reg, LaneMask);
3629     report_context(S);
3630     return;
3631   }
3632 
3633   // Checks for non-live-out segments.
3634   if (S.end != LiveInts->getMBBEndIdx(EndMBB)) {
3635     // RegUnit intervals are allowed dead phis.
3636     if (!Reg.isVirtual() && VNI->isPHIDef() && S.start == VNI->def &&
3637         S.end == VNI->def.getDeadSlot())
3638       return;
3639 
3640     // The live segment is ending inside EndMBB
3641     const MachineInstr *MI =
3642         LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
3643     if (!MI) {
3644       report("Live segment doesn't end at a valid instruction", EndMBB);
3645       report_context(LR, Reg, LaneMask);
3646       report_context(S);
3647       return;
3648     }
3649 
3650     // The block slot must refer to a basic block boundary.
3651     if (S.end.isBlock()) {
3652       report("Live segment ends at B slot of an instruction", EndMBB);
3653       report_context(LR, Reg, LaneMask);
3654       report_context(S);
3655     }
3656 
3657     if (S.end.isDead()) {
3658       // Segment ends on the dead slot.
3659       // That means there must be a dead def.
3660       if (!SlotIndex::isSameInstr(S.start, S.end)) {
3661         report("Live segment ending at dead slot spans instructions", EndMBB);
3662         report_context(LR, Reg, LaneMask);
3663         report_context(S);
3664       }
3665     }
3666 
3667     // After tied operands are rewritten, a live segment can only end at an
3668     // early-clobber slot if it is being redefined by an early-clobber def.
3669     // TODO: Before tied operands are rewritten, a live segment can only end at
3670     // an early-clobber slot if the last use is tied to an early-clobber def.
3671     if (MF->getProperties().hasProperty(
3672             MachineFunctionProperties::Property::TiedOpsRewritten) &&
3673         S.end.isEarlyClobber()) {
3674       if (I + 1 == LR.end() || (I + 1)->start != S.end) {
3675         report("Live segment ending at early clobber slot must be "
3676                "redefined by an EC def in the same instruction",
3677                EndMBB);
3678         report_context(LR, Reg, LaneMask);
3679         report_context(S);
3680       }
3681     }
3682 
3683     // The following checks only apply to virtual registers. Physreg liveness
3684     // is too weird to check.
3685     if (Reg.isVirtual()) {
3686       // A live segment can end with either a redefinition, a kill flag on a
3687       // use, or a dead flag on a def.
3688       bool hasRead = false;
3689       bool hasSubRegDef = false;
3690       bool hasDeadDef = false;
3691       for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3692         if (!MOI->isReg() || MOI->getReg() != Reg)
3693           continue;
3694         unsigned Sub = MOI->getSubReg();
3695         LaneBitmask SLM =
3696             Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) : LaneBitmask::getAll();
3697         if (MOI->isDef()) {
3698           if (Sub != 0) {
3699             hasSubRegDef = true;
3700             // An operand %0:sub0 reads %0:sub1..n. Invert the lane
3701             // mask for subregister defs. Read-undef defs will be handled by
3702             // readsReg below.
3703             SLM = ~SLM;
3704           }
3705           if (MOI->isDead())
3706             hasDeadDef = true;
3707         }
3708         if (LaneMask.any() && (LaneMask & SLM).none())
3709           continue;
3710         if (MOI->readsReg())
3711           hasRead = true;
3712       }
3713       if (S.end.isDead()) {
3714         // Make sure that the corresponding machine operand for a "dead" live
3715         // range has the dead flag. We cannot perform this check for subregister
3716         // liveranges as partially dead values are allowed.
3717         if (LaneMask.none() && !hasDeadDef) {
3718           report(
3719               "Instruction ending live segment on dead slot has no dead flag",
3720               MI);
3721           report_context(LR, Reg, LaneMask);
3722           report_context(S);
3723         }
3724       } else {
3725         if (!hasRead) {
3726           // When tracking subregister liveness, the main range must start new
3727           // values on partial register writes, even if there is no read.
3728           if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
3729               !hasSubRegDef) {
3730             report("Instruction ending live segment doesn't read the register",
3731                    MI);
3732             report_context(LR, Reg, LaneMask);
3733             report_context(S);
3734           }
3735         }
3736       }
3737     }
3738   }
3739 
3740   // Now check all the basic blocks in this live segment.
3741   MachineFunction::const_iterator MFI = MBB->getIterator();
3742   // Is this live segment the beginning of a non-PHIDef VN?
3743   if (S.start == VNI->def && !VNI->isPHIDef()) {
3744     // Not live-in to any blocks.
3745     if (MBB == EndMBB)
3746       return;
3747     // Skip this block.
3748     ++MFI;
3749   }
3750 
3751   SmallVector<SlotIndex, 4> Undefs;
3752   if (LaneMask.any()) {
3753     LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
3754     OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
3755   }
3756 
3757   while (true) {
3758     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
3759     // We don't know how to track physregs into a landing pad.
3760     if (!Reg.isVirtual() && MFI->isEHPad()) {
3761       if (&*MFI == EndMBB)
3762         break;
3763       ++MFI;
3764       continue;
3765     }
3766 
3767     // Is VNI a PHI-def in the current block?
3768     bool IsPHI = VNI->isPHIDef() &&
3769       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
3770 
3771     // Check that VNI is live-out of all predecessors.
3772     for (const MachineBasicBlock *Pred : MFI->predecessors()) {
3773       SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred);
3774       // Predecessor of landing pad live-out on last call.
3775       if (MFI->isEHPad()) {
3776         for (const MachineInstr &MI : llvm::reverse(*Pred)) {
3777           if (MI.isCall()) {
3778             PEnd = Indexes->getInstructionIndex(MI).getBoundaryIndex();
3779             break;
3780           }
3781         }
3782       }
3783       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
3784 
3785       // All predecessors must have a live-out value. However for a phi
3786       // instruction with subregister intervals
3787       // only one of the subregisters (not necessarily the current one) needs to
3788       // be defined.
3789       if (!PVNI && (LaneMask.none() || !IsPHI)) {
3790         if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes))
3791           continue;
3792         report("Register not marked live out of predecessor", Pred);
3793         report_context(LR, Reg, LaneMask);
3794         report_context(*VNI);
3795         OS << " live into " << printMBBReference(*MFI) << '@'
3796            << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " << PEnd
3797            << '\n';
3798         continue;
3799       }
3800 
3801       // Only PHI-defs can take different predecessor values.
3802       if (!IsPHI && PVNI != VNI) {
3803         report("Different value live out of predecessor", Pred);
3804         report_context(LR, Reg, LaneMask);
3805         OS << "Valno #" << PVNI->id << " live out of "
3806            << printMBBReference(*Pred) << '@' << PEnd << "\nValno #" << VNI->id
3807            << " live into " << printMBBReference(*MFI) << '@'
3808            << LiveInts->getMBBStartIdx(&*MFI) << '\n';
3809       }
3810     }
3811     if (&*MFI == EndMBB)
3812       break;
3813     ++MFI;
3814   }
3815 }
3816 
3817 void MachineVerifier::verifyLiveRange(const LiveRange &LR, Register Reg,
3818                                       LaneBitmask LaneMask) {
3819   for (const VNInfo *VNI : LR.valnos)
3820     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
3821 
3822   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
3823     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
3824 }
3825 
3826 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
3827   Register Reg = LI.reg();
3828   assert(Reg.isVirtual());
3829   verifyLiveRange(LI, Reg);
3830 
3831   if (LI.hasSubRanges()) {
3832     LaneBitmask Mask;
3833     LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
3834     for (const LiveInterval::SubRange &SR : LI.subranges()) {
3835       if ((Mask & SR.LaneMask).any()) {
3836         report("Lane masks of sub ranges overlap in live interval", MF);
3837         report_context(LI);
3838       }
3839       if ((SR.LaneMask & ~MaxMask).any()) {
3840         report("Subrange lanemask is invalid", MF);
3841         report_context(LI);
3842       }
3843       if (SR.empty()) {
3844         report("Subrange must not be empty", MF);
3845         report_context(SR, LI.reg(), SR.LaneMask);
3846       }
3847       Mask |= SR.LaneMask;
3848       verifyLiveRange(SR, LI.reg(), SR.LaneMask);
3849       if (!LI.covers(SR)) {
3850         report("A Subrange is not covered by the main range", MF);
3851         report_context(LI);
3852       }
3853     }
3854   }
3855 
3856   // Check the LI only has one connected component.
3857   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
3858   unsigned NumComp = ConEQ.Classify(LI);
3859   if (NumComp > 1) {
3860     report("Multiple connected components in live interval", MF);
3861     report_context(LI);
3862     for (unsigned comp = 0; comp != NumComp; ++comp) {
3863       OS << comp << ": valnos";
3864       for (const VNInfo *I : LI.valnos)
3865         if (comp == ConEQ.getEqClass(I))
3866           OS << ' ' << I->id;
3867       OS << '\n';
3868     }
3869   }
3870 }
3871 
3872 namespace {
3873 
3874   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
3875   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
3876   // value is zero.
3877   // We use a bool plus an integer to capture the stack state.
3878 struct StackStateOfBB {
3879   StackStateOfBB() = default;
3880   StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup)
3881       : EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
3882         ExitIsSetup(ExitSetup) {}
3883 
3884   // Can be negative, which means we are setting up a frame.
3885   int EntryValue = 0;
3886   int ExitValue = 0;
3887   bool EntryIsSetup = false;
3888   bool ExitIsSetup = false;
3889 };
3890 
3891 } // end anonymous namespace
3892 
3893 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
3894 /// by a FrameDestroy <n>, stack adjustments are identical on all
3895 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
3896 void MachineVerifier::verifyStackFrame() {
3897   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
3898   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
3899   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
3900     return;
3901 
3902   SmallVector<StackStateOfBB, 8> SPState;
3903   SPState.resize(MF->getNumBlockIDs());
3904   df_iterator_default_set<const MachineBasicBlock*> Reachable;
3905 
3906   // Visit the MBBs in DFS order.
3907   for (df_ext_iterator<const MachineFunction *,
3908                        df_iterator_default_set<const MachineBasicBlock *>>
3909        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
3910        DFI != DFE; ++DFI) {
3911     const MachineBasicBlock *MBB = *DFI;
3912 
3913     StackStateOfBB BBState;
3914     // Check the exit state of the DFS stack predecessor.
3915     if (DFI.getPathLength() >= 2) {
3916       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
3917       assert(Reachable.count(StackPred) &&
3918              "DFS stack predecessor is already visited.\n");
3919       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
3920       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
3921       BBState.ExitValue = BBState.EntryValue;
3922       BBState.ExitIsSetup = BBState.EntryIsSetup;
3923     }
3924 
3925     if ((int)MBB->getCallFrameSize() != -BBState.EntryValue) {
3926       report("Call frame size on entry does not match value computed from "
3927              "predecessor",
3928              MBB);
3929       OS << "Call frame size on entry " << MBB->getCallFrameSize()
3930          << " does not match value computed from predecessor "
3931          << -BBState.EntryValue << '\n';
3932     }
3933 
3934     // Update stack state by checking contents of MBB.
3935     for (const auto &I : *MBB) {
3936       if (I.getOpcode() == FrameSetupOpcode) {
3937         if (BBState.ExitIsSetup)
3938           report("FrameSetup is after another FrameSetup", &I);
3939         if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
3940           report("AdjustsStack not set in presence of a frame pseudo "
3941                  "instruction.", &I);
3942         BBState.ExitValue -= TII->getFrameTotalSize(I);
3943         BBState.ExitIsSetup = true;
3944       }
3945 
3946       if (I.getOpcode() == FrameDestroyOpcode) {
3947         int Size = TII->getFrameTotalSize(I);
3948         if (!BBState.ExitIsSetup)
3949           report("FrameDestroy is not after a FrameSetup", &I);
3950         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
3951                                                BBState.ExitValue;
3952         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
3953           report("FrameDestroy <n> is after FrameSetup <m>", &I);
3954           OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
3955              << AbsSPAdj << ">.\n";
3956         }
3957         if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
3958           report("AdjustsStack not set in presence of a frame pseudo "
3959                  "instruction.", &I);
3960         BBState.ExitValue += Size;
3961         BBState.ExitIsSetup = false;
3962       }
3963     }
3964     SPState[MBB->getNumber()] = BBState;
3965 
3966     // Make sure the exit state of any predecessor is consistent with the entry
3967     // state.
3968     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3969       if (Reachable.count(Pred) &&
3970           (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue ||
3971            SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
3972         report("The exit stack state of a predecessor is inconsistent.", MBB);
3973         OS << "Predecessor " << printMBBReference(*Pred) << " has exit state ("
3974            << SPState[Pred->getNumber()].ExitValue << ", "
3975            << SPState[Pred->getNumber()].ExitIsSetup << "), while "
3976            << printMBBReference(*MBB) << " has entry state ("
3977            << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
3978       }
3979     }
3980 
3981     // Make sure the entry state of any successor is consistent with the exit
3982     // state.
3983     for (const MachineBasicBlock *Succ : MBB->successors()) {
3984       if (Reachable.count(Succ) &&
3985           (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue ||
3986            SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
3987         report("The entry stack state of a successor is inconsistent.", MBB);
3988         OS << "Successor " << printMBBReference(*Succ) << " has entry state ("
3989            << SPState[Succ->getNumber()].EntryValue << ", "
3990            << SPState[Succ->getNumber()].EntryIsSetup << "), while "
3991            << printMBBReference(*MBB) << " has exit state ("
3992            << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
3993       }
3994     }
3995 
3996     // Make sure a basic block with return ends with zero stack adjustment.
3997     if (!MBB->empty() && MBB->back().isReturn()) {
3998       if (BBState.ExitIsSetup)
3999         report("A return block ends with a FrameSetup.", MBB);
4000       if (BBState.ExitValue)
4001         report("A return block ends with a nonzero stack adjustment.", MBB);
4002     }
4003   }
4004 }
4005