xref: /llvm-project/llvm/lib/CodeGen/MachineVerifier.cpp (revision e8ce76f1a67e99e2eba54a3c8a85a0fd214e3606)
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() ||
1491           (SrcTy.getScalarType() != DstTy.getScalarType() &&
1492            !SrcTy.isPointerVector()) ||
1493           SrcTy.isScalableVector() != DstTy.isScalableVector() ||
1494           SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1495         report("G_UNMERGE_VALUES source operand does not match vector "
1496                "destination operands",
1497                MI);
1498     } else if (SrcTy.isVector()) {
1499       // This case is the converse of G_BUILD_VECTOR, but relaxed to allow
1500       // mismatched types as long as the total size matches:
1501       //   %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<4 x s32>)
1502       if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1503         report("G_UNMERGE_VALUES vector source operand does not match scalar "
1504                "destination operands",
1505                MI);
1506     } else {
1507       // This case is the converse of G_MERGE_VALUES.
1508       if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits()) {
1509         report("G_UNMERGE_VALUES scalar source operand does not match scalar "
1510                "destination operands",
1511                MI);
1512       }
1513     }
1514     break;
1515   }
1516   case TargetOpcode::G_BUILD_VECTOR: {
1517     // Source types must be scalars, dest type a vector. Total size of scalars
1518     // must match the dest vector size.
1519     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1520     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1521     if (!DstTy.isVector() || SrcEltTy.isVector()) {
1522       report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1523       break;
1524     }
1525 
1526     if (DstTy.getElementType() != SrcEltTy)
1527       report("G_BUILD_VECTOR result element type must match source type", MI);
1528 
1529     if (DstTy.getNumElements() != MI->getNumOperands() - 1)
1530       report("G_BUILD_VECTOR must have an operand for each elemement", MI);
1531 
1532     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1533       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1534         report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
1535 
1536     break;
1537   }
1538   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1539     // Source types must be scalars, dest type a vector. Scalar types must be
1540     // larger than the dest vector elt type, as this is a truncating operation.
1541     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1542     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1543     if (!DstTy.isVector() || SrcEltTy.isVector())
1544       report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1545              MI);
1546     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1547       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1548         report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1549                MI);
1550     if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1551       report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1552              "dest elt type",
1553              MI);
1554     break;
1555   }
1556   case TargetOpcode::G_CONCAT_VECTORS: {
1557     // Source types should be vectors, and total size should match the dest
1558     // vector size.
1559     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1560     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1561     if (!DstTy.isVector() || !SrcTy.isVector())
1562       report("G_CONCAT_VECTOR requires vector source and destination operands",
1563              MI);
1564 
1565     if (MI->getNumOperands() < 3)
1566       report("G_CONCAT_VECTOR requires at least 2 source operands", MI);
1567 
1568     for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1569       if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1570         report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1571     if (DstTy.getElementCount() !=
1572         SrcTy.getElementCount() * (MI->getNumOperands() - 1))
1573       report("G_CONCAT_VECTOR num dest and source elements should match", MI);
1574     break;
1575   }
1576   case TargetOpcode::G_ICMP:
1577   case TargetOpcode::G_FCMP: {
1578     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1579     LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
1580 
1581     if ((DstTy.isVector() != SrcTy.isVector()) ||
1582         (DstTy.isVector() &&
1583          DstTy.getElementCount() != SrcTy.getElementCount()))
1584       report("Generic vector icmp/fcmp must preserve number of lanes", MI);
1585 
1586     break;
1587   }
1588   case TargetOpcode::G_SCMP:
1589   case TargetOpcode::G_UCMP: {
1590     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1591     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1592     LLT SrcTy2 = MRI->getType(MI->getOperand(2).getReg());
1593 
1594     if (SrcTy.isPointerOrPointerVector() || SrcTy2.isPointerOrPointerVector()) {
1595       report("Generic scmp/ucmp does not support pointers as operands", MI);
1596       break;
1597     }
1598 
1599     if (DstTy.isPointerOrPointerVector()) {
1600       report("Generic scmp/ucmp does not support pointers as a result", MI);
1601       break;
1602     }
1603 
1604     if ((DstTy.isVector() != SrcTy.isVector()) ||
1605         (DstTy.isVector() &&
1606          DstTy.getElementCount() != SrcTy.getElementCount())) {
1607       report("Generic vector scmp/ucmp must preserve number of lanes", MI);
1608       break;
1609     }
1610 
1611     if (SrcTy != SrcTy2) {
1612       report("Generic scmp/ucmp must have same input types", MI);
1613       break;
1614     }
1615 
1616     break;
1617   }
1618   case TargetOpcode::G_EXTRACT: {
1619     const MachineOperand &SrcOp = MI->getOperand(1);
1620     if (!SrcOp.isReg()) {
1621       report("extract source must be a register", MI);
1622       break;
1623     }
1624 
1625     const MachineOperand &OffsetOp = MI->getOperand(2);
1626     if (!OffsetOp.isImm()) {
1627       report("extract offset must be a constant", MI);
1628       break;
1629     }
1630 
1631     unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1632     unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1633     if (SrcSize == DstSize)
1634       report("extract source must be larger than result", MI);
1635 
1636     if (DstSize + OffsetOp.getImm() > SrcSize)
1637       report("extract reads past end of register", MI);
1638     break;
1639   }
1640   case TargetOpcode::G_INSERT: {
1641     const MachineOperand &SrcOp = MI->getOperand(2);
1642     if (!SrcOp.isReg()) {
1643       report("insert source must be a register", MI);
1644       break;
1645     }
1646 
1647     const MachineOperand &OffsetOp = MI->getOperand(3);
1648     if (!OffsetOp.isImm()) {
1649       report("insert offset must be a constant", MI);
1650       break;
1651     }
1652 
1653     unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1654     unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1655 
1656     if (DstSize <= SrcSize)
1657       report("inserted size must be smaller than total register", MI);
1658 
1659     if (SrcSize + OffsetOp.getImm() > DstSize)
1660       report("insert writes past end of register", MI);
1661 
1662     break;
1663   }
1664   case TargetOpcode::G_JUMP_TABLE: {
1665     if (!MI->getOperand(1).isJTI())
1666       report("G_JUMP_TABLE source operand must be a jump table index", MI);
1667     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1668     if (!DstTy.isPointer())
1669       report("G_JUMP_TABLE dest operand must have a pointer type", MI);
1670     break;
1671   }
1672   case TargetOpcode::G_BRJT: {
1673     if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
1674       report("G_BRJT src operand 0 must be a pointer type", MI);
1675 
1676     if (!MI->getOperand(1).isJTI())
1677       report("G_BRJT src operand 1 must be a jump table index", MI);
1678 
1679     const auto &IdxOp = MI->getOperand(2);
1680     if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
1681       report("G_BRJT src operand 2 must be a scalar reg type", MI);
1682     break;
1683   }
1684   case TargetOpcode::G_INTRINSIC:
1685   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
1686   case TargetOpcode::G_INTRINSIC_CONVERGENT:
1687   case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS: {
1688     // TODO: Should verify number of def and use operands, but the current
1689     // interface requires passing in IR types for mangling.
1690     const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
1691     if (!IntrIDOp.isIntrinsicID()) {
1692       report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
1693       break;
1694     }
1695 
1696     if (!verifyGIntrinsicSideEffects(MI))
1697       break;
1698     if (!verifyGIntrinsicConvergence(MI))
1699       break;
1700 
1701     break;
1702   }
1703   case TargetOpcode::G_SEXT_INREG: {
1704     if (!MI->getOperand(2).isImm()) {
1705       report("G_SEXT_INREG expects an immediate operand #2", MI);
1706       break;
1707     }
1708 
1709     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1710     int64_t Imm = MI->getOperand(2).getImm();
1711     if (Imm <= 0)
1712       report("G_SEXT_INREG size must be >= 1", MI);
1713     if (Imm >= SrcTy.getScalarSizeInBits())
1714       report("G_SEXT_INREG size must be less than source bit width", MI);
1715     break;
1716   }
1717   case TargetOpcode::G_BSWAP: {
1718     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1719     if (DstTy.getScalarSizeInBits() % 16 != 0)
1720       report("G_BSWAP size must be a multiple of 16 bits", MI);
1721     break;
1722   }
1723   case TargetOpcode::G_VSCALE: {
1724     if (!MI->getOperand(1).isCImm()) {
1725       report("G_VSCALE operand must be cimm", MI);
1726       break;
1727     }
1728     if (MI->getOperand(1).getCImm()->isZero()) {
1729       report("G_VSCALE immediate cannot be zero", MI);
1730       break;
1731     }
1732     break;
1733   }
1734   case TargetOpcode::G_INSERT_SUBVECTOR: {
1735     const MachineOperand &Src0Op = MI->getOperand(1);
1736     if (!Src0Op.isReg()) {
1737       report("G_INSERT_SUBVECTOR first source must be a register", MI);
1738       break;
1739     }
1740 
1741     const MachineOperand &Src1Op = MI->getOperand(2);
1742     if (!Src1Op.isReg()) {
1743       report("G_INSERT_SUBVECTOR second source must be a register", MI);
1744       break;
1745     }
1746 
1747     const MachineOperand &IndexOp = MI->getOperand(3);
1748     if (!IndexOp.isImm()) {
1749       report("G_INSERT_SUBVECTOR index must be an immediate", MI);
1750       break;
1751     }
1752 
1753     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1754     LLT Src1Ty = MRI->getType(Src1Op.getReg());
1755 
1756     if (!DstTy.isVector()) {
1757       report("Destination type must be a vector", MI);
1758       break;
1759     }
1760 
1761     if (!Src1Ty.isVector()) {
1762       report("Second source must be a vector", MI);
1763       break;
1764     }
1765 
1766     if (DstTy.getElementType() != Src1Ty.getElementType()) {
1767       report("Element type of vectors must be the same", MI);
1768       break;
1769     }
1770 
1771     if (Src1Ty.isScalable() != DstTy.isScalable()) {
1772       report("Vector types must both be fixed or both be scalable", MI);
1773       break;
1774     }
1775 
1776     if (ElementCount::isKnownGT(Src1Ty.getElementCount(),
1777                                 DstTy.getElementCount())) {
1778       report("Second source must be smaller than destination vector", MI);
1779       break;
1780     }
1781 
1782     uint64_t Idx = IndexOp.getImm();
1783     uint64_t Src1MinLen = Src1Ty.getElementCount().getKnownMinValue();
1784     if (IndexOp.getImm() % Src1MinLen != 0) {
1785       report("Index must be a multiple of the second source vector's "
1786              "minimum vector length",
1787              MI);
1788       break;
1789     }
1790 
1791     uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1792     if (Idx >= DstMinLen || Idx + Src1MinLen > DstMinLen) {
1793       report("Subvector type and index must not cause insert to overrun the "
1794              "vector being inserted into",
1795              MI);
1796       break;
1797     }
1798 
1799     break;
1800   }
1801   case TargetOpcode::G_EXTRACT_SUBVECTOR: {
1802     const MachineOperand &SrcOp = MI->getOperand(1);
1803     if (!SrcOp.isReg()) {
1804       report("G_EXTRACT_SUBVECTOR first source must be a register", MI);
1805       break;
1806     }
1807 
1808     const MachineOperand &IndexOp = MI->getOperand(2);
1809     if (!IndexOp.isImm()) {
1810       report("G_EXTRACT_SUBVECTOR index must be an immediate", MI);
1811       break;
1812     }
1813 
1814     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1815     LLT SrcTy = MRI->getType(SrcOp.getReg());
1816 
1817     if (!DstTy.isVector()) {
1818       report("Destination type must be a vector", MI);
1819       break;
1820     }
1821 
1822     if (!SrcTy.isVector()) {
1823       report("Source must be a vector", MI);
1824       break;
1825     }
1826 
1827     if (DstTy.getElementType() != SrcTy.getElementType()) {
1828       report("Element type of vectors must be the same", MI);
1829       break;
1830     }
1831 
1832     if (SrcTy.isScalable() != DstTy.isScalable()) {
1833       report("Vector types must both be fixed or both be scalable", MI);
1834       break;
1835     }
1836 
1837     if (ElementCount::isKnownGT(DstTy.getElementCount(),
1838                                 SrcTy.getElementCount())) {
1839       report("Destination vector must be smaller than source vector", MI);
1840       break;
1841     }
1842 
1843     uint64_t Idx = IndexOp.getImm();
1844     uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1845     if (Idx % DstMinLen != 0) {
1846       report("Index must be a multiple of the destination vector's minimum "
1847              "vector length",
1848              MI);
1849       break;
1850     }
1851 
1852     uint64_t SrcMinLen = SrcTy.getElementCount().getKnownMinValue();
1853     if (Idx >= SrcMinLen || Idx + DstMinLen > SrcMinLen) {
1854       report("Destination type and index must not cause extract to overrun the "
1855              "source vector",
1856              MI);
1857       break;
1858     }
1859 
1860     break;
1861   }
1862   case TargetOpcode::G_SHUFFLE_VECTOR: {
1863     const MachineOperand &MaskOp = MI->getOperand(3);
1864     if (!MaskOp.isShuffleMask()) {
1865       report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
1866       break;
1867     }
1868 
1869     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1870     LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
1871     LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
1872 
1873     if (Src0Ty != Src1Ty)
1874       report("Source operands must be the same type", MI);
1875 
1876     if (Src0Ty.getScalarType() != DstTy.getScalarType())
1877       report("G_SHUFFLE_VECTOR cannot change element type", MI);
1878 
1879     // Don't check that all operands are vector because scalars are used in
1880     // place of 1 element vectors.
1881     int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1;
1882     int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1;
1883 
1884     ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
1885 
1886     if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
1887       report("Wrong result type for shufflemask", MI);
1888 
1889     for (int Idx : MaskIdxes) {
1890       if (Idx < 0)
1891         continue;
1892 
1893       if (Idx >= 2 * SrcNumElts)
1894         report("Out of bounds shuffle index", MI);
1895     }
1896 
1897     break;
1898   }
1899 
1900   case TargetOpcode::G_SPLAT_VECTOR: {
1901     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1902     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1903 
1904     if (!DstTy.isScalableVector()) {
1905       report("Destination type must be a scalable vector", MI);
1906       break;
1907     }
1908 
1909     if (!SrcTy.isScalar() && !SrcTy.isPointer()) {
1910       report("Source type must be a scalar or pointer", MI);
1911       break;
1912     }
1913 
1914     if (TypeSize::isKnownGT(DstTy.getElementType().getSizeInBits(),
1915                             SrcTy.getSizeInBits())) {
1916       report("Element type of the destination must be the same size or smaller "
1917              "than the source type",
1918              MI);
1919       break;
1920     }
1921 
1922     break;
1923   }
1924   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1925     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1926     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1927     LLT IdxTy = MRI->getType(MI->getOperand(2).getReg());
1928 
1929     if (!DstTy.isScalar() && !DstTy.isPointer()) {
1930       report("Destination type must be a scalar or pointer", MI);
1931       break;
1932     }
1933 
1934     if (!SrcTy.isVector()) {
1935       report("First source must be a vector", MI);
1936       break;
1937     }
1938 
1939     auto TLI = MF->getSubtarget().getTargetLowering();
1940     if (IdxTy.getSizeInBits() !=
1941         TLI->getVectorIdxTy(MF->getDataLayout()).getFixedSizeInBits()) {
1942       report("Index type must match VectorIdxTy", MI);
1943       break;
1944     }
1945 
1946     break;
1947   }
1948   case TargetOpcode::G_INSERT_VECTOR_ELT: {
1949     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1950     LLT VecTy = MRI->getType(MI->getOperand(1).getReg());
1951     LLT ScaTy = MRI->getType(MI->getOperand(2).getReg());
1952     LLT IdxTy = MRI->getType(MI->getOperand(3).getReg());
1953 
1954     if (!DstTy.isVector()) {
1955       report("Destination type must be a vector", MI);
1956       break;
1957     }
1958 
1959     if (VecTy != DstTy) {
1960       report("Destination type and vector type must match", MI);
1961       break;
1962     }
1963 
1964     if (!ScaTy.isScalar() && !ScaTy.isPointer()) {
1965       report("Inserted element must be a scalar or pointer", MI);
1966       break;
1967     }
1968 
1969     auto TLI = MF->getSubtarget().getTargetLowering();
1970     if (IdxTy.getSizeInBits() !=
1971         TLI->getVectorIdxTy(MF->getDataLayout()).getFixedSizeInBits()) {
1972       report("Index type must match VectorIdxTy", MI);
1973       break;
1974     }
1975 
1976     break;
1977   }
1978   case TargetOpcode::G_DYN_STACKALLOC: {
1979     const MachineOperand &DstOp = MI->getOperand(0);
1980     const MachineOperand &AllocOp = MI->getOperand(1);
1981     const MachineOperand &AlignOp = MI->getOperand(2);
1982 
1983     if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
1984       report("dst operand 0 must be a pointer type", MI);
1985       break;
1986     }
1987 
1988     if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
1989       report("src operand 1 must be a scalar reg type", MI);
1990       break;
1991     }
1992 
1993     if (!AlignOp.isImm()) {
1994       report("src operand 2 must be an immediate type", MI);
1995       break;
1996     }
1997     break;
1998   }
1999   case TargetOpcode::G_MEMCPY_INLINE:
2000   case TargetOpcode::G_MEMCPY:
2001   case TargetOpcode::G_MEMMOVE: {
2002     ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2003     if (MMOs.size() != 2) {
2004       report("memcpy/memmove must have 2 memory operands", MI);
2005       break;
2006     }
2007 
2008     if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) ||
2009         (MMOs[1]->isStore() || !MMOs[1]->isLoad())) {
2010       report("wrong memory operand types", MI);
2011       break;
2012     }
2013 
2014     if (MMOs[0]->getSize() != MMOs[1]->getSize())
2015       report("inconsistent memory operand sizes", MI);
2016 
2017     LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2018     LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg());
2019 
2020     if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) {
2021       report("memory instruction operand must be a pointer", MI);
2022       break;
2023     }
2024 
2025     if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2026       report("inconsistent store address space", MI);
2027     if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace())
2028       report("inconsistent load address space", MI);
2029 
2030     if (Opc != TargetOpcode::G_MEMCPY_INLINE)
2031       if (!MI->getOperand(3).isImm() || (MI->getOperand(3).getImm() & ~1LL))
2032         report("'tail' flag (operand 3) must be an immediate 0 or 1", MI);
2033 
2034     break;
2035   }
2036   case TargetOpcode::G_BZERO:
2037   case TargetOpcode::G_MEMSET: {
2038     ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2039     std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset" : "bzero";
2040     if (MMOs.size() != 1) {
2041       report(Twine(Name, " must have 1 memory operand"), MI);
2042       break;
2043     }
2044 
2045     if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) {
2046       report(Twine(Name, " memory operand must be a store"), MI);
2047       break;
2048     }
2049 
2050     LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2051     if (!DstPtrTy.isPointer()) {
2052       report(Twine(Name, " operand must be a pointer"), MI);
2053       break;
2054     }
2055 
2056     if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2057       report("inconsistent " + Twine(Name, " address space"), MI);
2058 
2059     if (!MI->getOperand(MI->getNumOperands() - 1).isImm() ||
2060         (MI->getOperand(MI->getNumOperands() - 1).getImm() & ~1LL))
2061       report("'tail' flag (last operand) must be an immediate 0 or 1", MI);
2062 
2063     break;
2064   }
2065   case TargetOpcode::G_UBSANTRAP: {
2066     const MachineOperand &KindOp = MI->getOperand(0);
2067     if (!MI->getOperand(0).isImm()) {
2068       report("Crash kind must be an immediate", &KindOp, 0);
2069       break;
2070     }
2071     int64_t Kind = MI->getOperand(0).getImm();
2072     if (!isInt<8>(Kind))
2073       report("Crash kind must be 8 bit wide", &KindOp, 0);
2074     break;
2075   }
2076   case TargetOpcode::G_VECREDUCE_SEQ_FADD:
2077   case TargetOpcode::G_VECREDUCE_SEQ_FMUL: {
2078     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2079     LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2080     LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2081     if (!DstTy.isScalar())
2082       report("Vector reduction requires a scalar destination type", MI);
2083     if (!Src1Ty.isScalar())
2084       report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI);
2085     if (!Src2Ty.isVector())
2086       report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI);
2087     break;
2088   }
2089   case TargetOpcode::G_VECREDUCE_FADD:
2090   case TargetOpcode::G_VECREDUCE_FMUL:
2091   case TargetOpcode::G_VECREDUCE_FMAX:
2092   case TargetOpcode::G_VECREDUCE_FMIN:
2093   case TargetOpcode::G_VECREDUCE_FMAXIMUM:
2094   case TargetOpcode::G_VECREDUCE_FMINIMUM:
2095   case TargetOpcode::G_VECREDUCE_ADD:
2096   case TargetOpcode::G_VECREDUCE_MUL:
2097   case TargetOpcode::G_VECREDUCE_AND:
2098   case TargetOpcode::G_VECREDUCE_OR:
2099   case TargetOpcode::G_VECREDUCE_XOR:
2100   case TargetOpcode::G_VECREDUCE_SMAX:
2101   case TargetOpcode::G_VECREDUCE_SMIN:
2102   case TargetOpcode::G_VECREDUCE_UMAX:
2103   case TargetOpcode::G_VECREDUCE_UMIN: {
2104     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2105     if (!DstTy.isScalar())
2106       report("Vector reduction requires a scalar destination type", MI);
2107     break;
2108   }
2109 
2110   case TargetOpcode::G_SBFX:
2111   case TargetOpcode::G_UBFX: {
2112     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2113     if (DstTy.isVector()) {
2114       report("Bitfield extraction is not supported on vectors", MI);
2115       break;
2116     }
2117     break;
2118   }
2119   case TargetOpcode::G_SHL:
2120   case TargetOpcode::G_LSHR:
2121   case TargetOpcode::G_ASHR:
2122   case TargetOpcode::G_ROTR:
2123   case TargetOpcode::G_ROTL: {
2124     LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2125     LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2126     if (Src1Ty.isVector() != Src2Ty.isVector()) {
2127       report("Shifts and rotates require operands to be either all scalars or "
2128              "all vectors",
2129              MI);
2130       break;
2131     }
2132     break;
2133   }
2134   case TargetOpcode::G_LLROUND:
2135   case TargetOpcode::G_LROUND: {
2136     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2137     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2138     if (!DstTy.isValid() || !SrcTy.isValid())
2139       break;
2140     if (SrcTy.isPointer() || DstTy.isPointer()) {
2141       StringRef Op = SrcTy.isPointer() ? "Source" : "Destination";
2142       report(Twine(Op, " operand must not be a pointer type"), MI);
2143     } else if (SrcTy.isScalar()) {
2144       verifyAllRegOpsScalar(*MI, *MRI);
2145       break;
2146     } else if (SrcTy.isVector()) {
2147       verifyVectorElementMatch(SrcTy, DstTy, MI);
2148       break;
2149     }
2150     break;
2151   }
2152   case TargetOpcode::G_IS_FPCLASS: {
2153     LLT DestTy = MRI->getType(MI->getOperand(0).getReg());
2154     LLT DestEltTy = DestTy.getScalarType();
2155     if (!DestEltTy.isScalar()) {
2156       report("Destination must be a scalar or vector of scalars", MI);
2157       break;
2158     }
2159     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2160     LLT SrcEltTy = SrcTy.getScalarType();
2161     if (!SrcEltTy.isScalar()) {
2162       report("Source must be a scalar or vector of scalars", MI);
2163       break;
2164     }
2165     if (!verifyVectorElementMatch(DestTy, SrcTy, MI))
2166       break;
2167     const MachineOperand &TestMO = MI->getOperand(2);
2168     if (!TestMO.isImm()) {
2169       report("floating-point class set (operand 2) must be an immediate", MI);
2170       break;
2171     }
2172     int64_t Test = TestMO.getImm();
2173     if (Test < 0 || Test > fcAllFlags) {
2174       report("Incorrect floating-point class set (operand 2)", MI);
2175       break;
2176     }
2177     break;
2178   }
2179   case TargetOpcode::G_PREFETCH: {
2180     const MachineOperand &AddrOp = MI->getOperand(0);
2181     if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer()) {
2182       report("addr operand must be a pointer", &AddrOp, 0);
2183       break;
2184     }
2185     const MachineOperand &RWOp = MI->getOperand(1);
2186     if (!RWOp.isImm() || (uint64_t)RWOp.getImm() >= 2) {
2187       report("rw operand must be an immediate 0-1", &RWOp, 1);
2188       break;
2189     }
2190     const MachineOperand &LocalityOp = MI->getOperand(2);
2191     if (!LocalityOp.isImm() || (uint64_t)LocalityOp.getImm() >= 4) {
2192       report("locality operand must be an immediate 0-3", &LocalityOp, 2);
2193       break;
2194     }
2195     const MachineOperand &CacheTypeOp = MI->getOperand(3);
2196     if (!CacheTypeOp.isImm() || (uint64_t)CacheTypeOp.getImm() >= 2) {
2197       report("cache type operand must be an immediate 0-1", &CacheTypeOp, 3);
2198       break;
2199     }
2200     break;
2201   }
2202   case TargetOpcode::G_ASSERT_ALIGN: {
2203     if (MI->getOperand(2).getImm() < 1)
2204       report("alignment immediate must be >= 1", MI);
2205     break;
2206   }
2207   case TargetOpcode::G_CONSTANT_POOL: {
2208     if (!MI->getOperand(1).isCPI())
2209       report("Src operand 1 must be a constant pool index", MI);
2210     if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
2211       report("Dst operand 0 must be a pointer", MI);
2212     break;
2213   }
2214   case TargetOpcode::G_PTRAUTH_GLOBAL_VALUE: {
2215     const MachineOperand &AddrOp = MI->getOperand(1);
2216     if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer())
2217       report("addr operand must be a pointer", &AddrOp, 1);
2218     break;
2219   }
2220   default:
2221     break;
2222   }
2223 }
2224 
2225 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
2226   const MCInstrDesc &MCID = MI->getDesc();
2227   if (MI->getNumOperands() < MCID.getNumOperands()) {
2228     report("Too few operands", MI);
2229     OS << MCID.getNumOperands() << " operands expected, but "
2230        << MI->getNumOperands() << " given.\n";
2231   }
2232 
2233   if (MI->getFlag(MachineInstr::NoConvergent) && !MCID.isConvergent())
2234     report("NoConvergent flag expected only on convergent instructions.", MI);
2235 
2236   if (MI->isPHI()) {
2237     if (MF->getProperties().hasProperty(
2238             MachineFunctionProperties::Property::NoPHIs))
2239       report("Found PHI instruction with NoPHIs property set", MI);
2240 
2241     if (FirstNonPHI)
2242       report("Found PHI instruction after non-PHI", MI);
2243   } else if (FirstNonPHI == nullptr)
2244     FirstNonPHI = MI;
2245 
2246   // Check the tied operands.
2247   if (MI->isInlineAsm())
2248     verifyInlineAsm(MI);
2249 
2250   // Check that unspillable terminators define a reg and have at most one use.
2251   if (TII->isUnspillableTerminator(MI)) {
2252     if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef())
2253       report("Unspillable Terminator does not define a reg", MI);
2254     Register Def = MI->getOperand(0).getReg();
2255     if (Def.isVirtual() &&
2256         !MF->getProperties().hasProperty(
2257             MachineFunctionProperties::Property::NoPHIs) &&
2258         std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1)
2259       report("Unspillable Terminator expected to have at most one use!", MI);
2260   }
2261 
2262   // A fully-formed DBG_VALUE must have a location. Ignore partially formed
2263   // DBG_VALUEs: these are convenient to use in tests, but should never get
2264   // generated.
2265   if (MI->isDebugValue() && MI->getNumOperands() == 4)
2266     if (!MI->getDebugLoc())
2267       report("Missing DebugLoc for debug instruction", MI);
2268 
2269   // Meta instructions should never be the subject of debug value tracking,
2270   // they don't create a value in the output program at all.
2271   if (MI->isMetaInstruction() && MI->peekDebugInstrNum())
2272     report("Metadata instruction should not have a value tracking number", MI);
2273 
2274   // Check the MachineMemOperands for basic consistency.
2275   for (MachineMemOperand *Op : MI->memoperands()) {
2276     if (Op->isLoad() && !MI->mayLoad())
2277       report("Missing mayLoad flag", MI);
2278     if (Op->isStore() && !MI->mayStore())
2279       report("Missing mayStore flag", MI);
2280   }
2281 
2282   // Debug values must not have a slot index.
2283   // Other instructions must have one, unless they are inside a bundle.
2284   if (LiveInts) {
2285     bool mapped = !LiveInts->isNotInMIMap(*MI);
2286     if (MI->isDebugOrPseudoInstr()) {
2287       if (mapped)
2288         report("Debug instruction has a slot index", MI);
2289     } else if (MI->isInsideBundle()) {
2290       if (mapped)
2291         report("Instruction inside bundle has a slot index", MI);
2292     } else {
2293       if (!mapped)
2294         report("Missing slot index", MI);
2295     }
2296   }
2297 
2298   unsigned Opc = MCID.getOpcode();
2299   if (isPreISelGenericOpcode(Opc) || isPreISelGenericOptimizationHint(Opc)) {
2300     verifyPreISelGenericInstruction(MI);
2301     return;
2302   }
2303 
2304   StringRef ErrorInfo;
2305   if (!TII->verifyInstruction(*MI, ErrorInfo))
2306     report(ErrorInfo.data(), MI);
2307 
2308   // Verify properties of various specific instruction types
2309   switch (MI->getOpcode()) {
2310   case TargetOpcode::COPY: {
2311     const MachineOperand &DstOp = MI->getOperand(0);
2312     const MachineOperand &SrcOp = MI->getOperand(1);
2313     const Register SrcReg = SrcOp.getReg();
2314     const Register DstReg = DstOp.getReg();
2315 
2316     LLT DstTy = MRI->getType(DstReg);
2317     LLT SrcTy = MRI->getType(SrcReg);
2318     if (SrcTy.isValid() && DstTy.isValid()) {
2319       // If both types are valid, check that the types are the same.
2320       if (SrcTy != DstTy) {
2321         report("Copy Instruction is illegal with mismatching types", MI);
2322         OS << "Def = " << DstTy << ", Src = " << SrcTy << '\n';
2323       }
2324 
2325       break;
2326     }
2327 
2328     if (!SrcTy.isValid() && !DstTy.isValid())
2329       break;
2330 
2331     // If we have only one valid type, this is likely a copy between a virtual
2332     // and physical register.
2333     TypeSize SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
2334     TypeSize DstSize = TRI->getRegSizeInBits(DstReg, *MRI);
2335     if (SrcReg.isPhysical() && DstTy.isValid()) {
2336       const TargetRegisterClass *SrcRC =
2337           TRI->getMinimalPhysRegClassLLT(SrcReg, DstTy);
2338       if (SrcRC)
2339         SrcSize = TRI->getRegSizeInBits(*SrcRC);
2340     }
2341 
2342     if (DstReg.isPhysical() && SrcTy.isValid()) {
2343       const TargetRegisterClass *DstRC =
2344           TRI->getMinimalPhysRegClassLLT(DstReg, SrcTy);
2345       if (DstRC)
2346         DstSize = TRI->getRegSizeInBits(*DstRC);
2347     }
2348 
2349     // The next two checks allow COPY between physical and virtual registers,
2350     // when the virtual register has a scalable size and the physical register
2351     // has a fixed size. These checks allow COPY between *potentialy* mismatched
2352     // sizes. However, once RegisterBankSelection occurs, MachineVerifier should
2353     // be able to resolve a fixed size for the scalable vector, and at that
2354     // point this function will know for sure whether the sizes are mismatched
2355     // and correctly report a size mismatch.
2356     if (SrcReg.isPhysical() && DstReg.isVirtual() && DstSize.isScalable() &&
2357         !SrcSize.isScalable())
2358       break;
2359     if (SrcReg.isVirtual() && DstReg.isPhysical() && SrcSize.isScalable() &&
2360         !DstSize.isScalable())
2361       break;
2362 
2363     if (SrcSize.isNonZero() && DstSize.isNonZero() && SrcSize != DstSize) {
2364       if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
2365         report("Copy Instruction is illegal with mismatching sizes", MI);
2366         OS << "Def Size = " << DstSize << ", Src Size = " << SrcSize << '\n';
2367       }
2368     }
2369     break;
2370   }
2371   case TargetOpcode::STATEPOINT: {
2372     StatepointOpers SO(MI);
2373     if (!MI->getOperand(SO.getIDPos()).isImm() ||
2374         !MI->getOperand(SO.getNBytesPos()).isImm() ||
2375         !MI->getOperand(SO.getNCallArgsPos()).isImm()) {
2376       report("meta operands to STATEPOINT not constant!", MI);
2377       break;
2378     }
2379 
2380     auto VerifyStackMapConstant = [&](unsigned Offset) {
2381       if (Offset >= MI->getNumOperands()) {
2382         report("stack map constant to STATEPOINT is out of range!", MI);
2383         return;
2384       }
2385       if (!MI->getOperand(Offset - 1).isImm() ||
2386           MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp ||
2387           !MI->getOperand(Offset).isImm())
2388         report("stack map constant to STATEPOINT not well formed!", MI);
2389     };
2390     VerifyStackMapConstant(SO.getCCIdx());
2391     VerifyStackMapConstant(SO.getFlagsIdx());
2392     VerifyStackMapConstant(SO.getNumDeoptArgsIdx());
2393     VerifyStackMapConstant(SO.getNumGCPtrIdx());
2394     VerifyStackMapConstant(SO.getNumAllocaIdx());
2395     VerifyStackMapConstant(SO.getNumGcMapEntriesIdx());
2396 
2397     // Verify that all explicit statepoint defs are tied to gc operands as
2398     // they are expected to be a relocation of gc operands.
2399     unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx();
2400     unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2;
2401     for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) {
2402       unsigned UseOpIdx;
2403       if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) {
2404         report("STATEPOINT defs expected to be tied", MI);
2405         break;
2406       }
2407       if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) {
2408         report("STATEPOINT def tied to non-gc operand", MI);
2409         break;
2410       }
2411     }
2412 
2413     // TODO: verify we have properly encoded deopt arguments
2414   } break;
2415   case TargetOpcode::INSERT_SUBREG: {
2416     unsigned InsertedSize;
2417     if (unsigned SubIdx = MI->getOperand(2).getSubReg())
2418       InsertedSize = TRI->getSubRegIdxSize(SubIdx);
2419     else
2420       InsertedSize = TRI->getRegSizeInBits(MI->getOperand(2).getReg(), *MRI);
2421     unsigned SubRegSize = TRI->getSubRegIdxSize(MI->getOperand(3).getImm());
2422     if (SubRegSize < InsertedSize) {
2423       report("INSERT_SUBREG expected inserted value to have equal or lesser "
2424              "size than the subreg it was inserted into", MI);
2425       break;
2426     }
2427   } break;
2428   case TargetOpcode::REG_SEQUENCE: {
2429     unsigned NumOps = MI->getNumOperands();
2430     if (!(NumOps & 1)) {
2431       report("Invalid number of operands for REG_SEQUENCE", MI);
2432       break;
2433     }
2434 
2435     for (unsigned I = 1; I != NumOps; I += 2) {
2436       const MachineOperand &RegOp = MI->getOperand(I);
2437       const MachineOperand &SubRegOp = MI->getOperand(I + 1);
2438 
2439       if (!RegOp.isReg())
2440         report("Invalid register operand for REG_SEQUENCE", &RegOp, I);
2441 
2442       if (!SubRegOp.isImm() || SubRegOp.getImm() == 0 ||
2443           SubRegOp.getImm() >= TRI->getNumSubRegIndices()) {
2444         report("Invalid subregister index operand for REG_SEQUENCE",
2445                &SubRegOp, I + 1);
2446       }
2447     }
2448 
2449     Register DstReg = MI->getOperand(0).getReg();
2450     if (DstReg.isPhysical())
2451       report("REG_SEQUENCE does not support physical register results", MI);
2452 
2453     if (MI->getOperand(0).getSubReg())
2454       report("Invalid subreg result for REG_SEQUENCE", MI);
2455 
2456     break;
2457   }
2458   }
2459 }
2460 
2461 void
2462 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
2463   const MachineInstr *MI = MO->getParent();
2464   const MCInstrDesc &MCID = MI->getDesc();
2465   unsigned NumDefs = MCID.getNumDefs();
2466   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
2467     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
2468 
2469   // The first MCID.NumDefs operands must be explicit register defines
2470   if (MONum < NumDefs) {
2471     const MCOperandInfo &MCOI = MCID.operands()[MONum];
2472     if (!MO->isReg())
2473       report("Explicit definition must be a register", MO, MONum);
2474     else if (!MO->isDef() && !MCOI.isOptionalDef())
2475       report("Explicit definition marked as use", MO, MONum);
2476     else if (MO->isImplicit())
2477       report("Explicit definition marked as implicit", MO, MONum);
2478   } else if (MONum < MCID.getNumOperands()) {
2479     const MCOperandInfo &MCOI = MCID.operands()[MONum];
2480     // Don't check if it's the last operand in a variadic instruction. See,
2481     // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
2482     bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
2483     if (!IsOptional) {
2484       if (MO->isReg()) {
2485         if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs())
2486           report("Explicit operand marked as def", MO, MONum);
2487         if (MO->isImplicit())
2488           report("Explicit operand marked as implicit", MO, MONum);
2489       }
2490 
2491       // Check that an instruction has register operands only as expected.
2492       if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
2493           !MO->isReg() && !MO->isFI())
2494         report("Expected a register operand.", MO, MONum);
2495       if (MO->isReg()) {
2496         if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
2497             (MCOI.OperandType == MCOI::OPERAND_PCREL &&
2498              !TII->isPCRelRegisterOperandLegal(*MO)))
2499           report("Expected a non-register operand.", MO, MONum);
2500       }
2501     }
2502 
2503     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
2504     if (TiedTo != -1) {
2505       if (!MO->isReg())
2506         report("Tied use must be a register", MO, MONum);
2507       else if (!MO->isTied())
2508         report("Operand should be tied", MO, MONum);
2509       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
2510         report("Tied def doesn't match MCInstrDesc", MO, MONum);
2511       else if (MO->getReg().isPhysical()) {
2512         const MachineOperand &MOTied = MI->getOperand(TiedTo);
2513         if (!MOTied.isReg())
2514           report("Tied counterpart must be a register", &MOTied, TiedTo);
2515         else if (MOTied.getReg().isPhysical() &&
2516                  MO->getReg() != MOTied.getReg())
2517           report("Tied physical registers must match.", &MOTied, TiedTo);
2518       }
2519     } else if (MO->isReg() && MO->isTied())
2520       report("Explicit operand should not be tied", MO, MONum);
2521   } else if (!MI->isVariadic()) {
2522     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
2523     if (!MO->isValidExcessOperand())
2524       report("Extra explicit operand on non-variadic instruction", MO, MONum);
2525   }
2526 
2527   switch (MO->getType()) {
2528   case MachineOperand::MO_Register: {
2529     // Verify debug flag on debug instructions. Check this first because reg0
2530     // indicates an undefined debug value.
2531     if (MI->isDebugInstr() && MO->isUse()) {
2532       if (!MO->isDebug())
2533         report("Register operand must be marked debug", MO, MONum);
2534     } else if (MO->isDebug()) {
2535       report("Register operand must not be marked debug", MO, MONum);
2536     }
2537 
2538     const Register Reg = MO->getReg();
2539     if (!Reg)
2540       return;
2541     if (MRI->tracksLiveness() && !MI->isDebugInstr())
2542       checkLiveness(MO, MONum);
2543 
2544     if (MO->isDef() && MO->isUndef() && !MO->getSubReg() &&
2545         MO->getReg().isVirtual()) // TODO: Apply to physregs too
2546       report("Undef virtual register def operands require a subregister", MO, MONum);
2547 
2548     // Verify the consistency of tied operands.
2549     if (MO->isTied()) {
2550       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
2551       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
2552       if (!OtherMO.isReg())
2553         report("Must be tied to a register", MO, MONum);
2554       if (!OtherMO.isTied())
2555         report("Missing tie flags on tied operand", MO, MONum);
2556       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
2557         report("Inconsistent tie links", MO, MONum);
2558       if (MONum < MCID.getNumDefs()) {
2559         if (OtherIdx < MCID.getNumOperands()) {
2560           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
2561             report("Explicit def tied to explicit use without tie constraint",
2562                    MO, MONum);
2563         } else {
2564           if (!OtherMO.isImplicit())
2565             report("Explicit def should be tied to implicit use", MO, MONum);
2566         }
2567       }
2568     }
2569 
2570     // Verify two-address constraints after the twoaddressinstruction pass.
2571     // Both twoaddressinstruction pass and phi-node-elimination pass call
2572     // MRI->leaveSSA() to set MF as not IsSSA, we should do the verification
2573     // after twoaddressinstruction pass not after phi-node-elimination pass. So
2574     // we shouldn't use the IsSSA as the condition, we should based on
2575     // TiedOpsRewritten property to verify two-address constraints, this
2576     // property will be set in twoaddressinstruction pass.
2577     unsigned DefIdx;
2578     if (MF->getProperties().hasProperty(
2579             MachineFunctionProperties::Property::TiedOpsRewritten) &&
2580         MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
2581         Reg != MI->getOperand(DefIdx).getReg())
2582       report("Two-address instruction operands must be identical", MO, MONum);
2583 
2584     // Check register classes.
2585     unsigned SubIdx = MO->getSubReg();
2586 
2587     if (Reg.isPhysical()) {
2588       if (SubIdx) {
2589         report("Illegal subregister index for physical register", MO, MONum);
2590         return;
2591       }
2592       if (MONum < MCID.getNumOperands()) {
2593         if (const TargetRegisterClass *DRC =
2594               TII->getRegClass(MCID, MONum, TRI, *MF)) {
2595           if (!DRC->contains(Reg)) {
2596             report("Illegal physical register for instruction", MO, MONum);
2597             OS << printReg(Reg, TRI) << " is not a "
2598                << TRI->getRegClassName(DRC) << " register.\n";
2599           }
2600         }
2601       }
2602       if (MO->isRenamable()) {
2603         if (MRI->isReserved(Reg)) {
2604           report("isRenamable set on reserved register", MO, MONum);
2605           return;
2606         }
2607       }
2608     } else {
2609       // Virtual register.
2610       const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
2611       if (!RC) {
2612         // This is a generic virtual register.
2613 
2614         // Do not allow undef uses for generic virtual registers. This ensures
2615         // getVRegDef can never fail and return null on a generic register.
2616         //
2617         // FIXME: This restriction should probably be broadened to all SSA
2618         // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
2619         // run on the SSA function just before phi elimination.
2620         if (MO->isUndef())
2621           report("Generic virtual register use cannot be undef", MO, MONum);
2622 
2623         // Debug value instruction is permitted to use undefined vregs.
2624         // This is a performance measure to skip the overhead of immediately
2625         // pruning unused debug operands. The final undef substitution occurs
2626         // when debug values are allocated in LDVImpl::handleDebugValue, so
2627         // these verifications always apply after this pass.
2628         if (isFunctionTracksDebugUserValues || !MO->isUse() ||
2629             !MI->isDebugValue() || !MRI->def_empty(Reg)) {
2630           // If we're post-Select, we can't have gvregs anymore.
2631           if (isFunctionSelected) {
2632             report("Generic virtual register invalid in a Selected function",
2633                    MO, MONum);
2634             return;
2635           }
2636 
2637           // The gvreg must have a type and it must not have a SubIdx.
2638           LLT Ty = MRI->getType(Reg);
2639           if (!Ty.isValid()) {
2640             report("Generic virtual register must have a valid type", MO,
2641                    MONum);
2642             return;
2643           }
2644 
2645           const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
2646           const RegisterBankInfo *RBI = MF->getSubtarget().getRegBankInfo();
2647 
2648           // If we're post-RegBankSelect, the gvreg must have a bank.
2649           if (!RegBank && isFunctionRegBankSelected) {
2650             report("Generic virtual register must have a bank in a "
2651                    "RegBankSelected function",
2652                    MO, MONum);
2653             return;
2654           }
2655 
2656           // Make sure the register fits into its register bank if any.
2657           if (RegBank && Ty.isValid() && !Ty.isScalableVector() &&
2658               RBI->getMaximumSize(RegBank->getID()) < Ty.getSizeInBits()) {
2659             report("Register bank is too small for virtual register", MO,
2660                    MONum);
2661             OS << "Register bank " << RegBank->getName() << " too small("
2662                << RBI->getMaximumSize(RegBank->getID()) << ") to fit "
2663                << Ty.getSizeInBits() << "-bits\n";
2664             return;
2665           }
2666         }
2667 
2668         if (SubIdx)  {
2669           report("Generic virtual register does not allow subregister index", MO,
2670                  MONum);
2671           return;
2672         }
2673 
2674         // If this is a target specific instruction and this operand
2675         // has register class constraint, the virtual register must
2676         // comply to it.
2677         if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
2678             MONum < MCID.getNumOperands() &&
2679             TII->getRegClass(MCID, MONum, TRI, *MF)) {
2680           report("Virtual register does not match instruction constraint", MO,
2681                  MONum);
2682           OS << "Expect register class "
2683              << TRI->getRegClassName(TII->getRegClass(MCID, MONum, TRI, *MF))
2684              << " but got nothing\n";
2685           return;
2686         }
2687 
2688         break;
2689       }
2690       if (SubIdx) {
2691         const TargetRegisterClass *SRC =
2692           TRI->getSubClassWithSubReg(RC, SubIdx);
2693         if (!SRC) {
2694           report("Invalid subregister index for virtual register", MO, MONum);
2695           OS << "Register class " << TRI->getRegClassName(RC)
2696              << " does not support subreg index " << SubIdx << '\n';
2697           return;
2698         }
2699         if (RC != SRC) {
2700           report("Invalid register class for subregister index", MO, MONum);
2701           OS << "Register class " << TRI->getRegClassName(RC)
2702              << " does not fully support subreg index " << SubIdx << '\n';
2703           return;
2704         }
2705       }
2706       if (MONum < MCID.getNumOperands()) {
2707         if (const TargetRegisterClass *DRC =
2708               TII->getRegClass(MCID, MONum, TRI, *MF)) {
2709           if (SubIdx) {
2710             const TargetRegisterClass *SuperRC =
2711                 TRI->getLargestLegalSuperClass(RC, *MF);
2712             if (!SuperRC) {
2713               report("No largest legal super class exists.", MO, MONum);
2714               return;
2715             }
2716             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
2717             if (!DRC) {
2718               report("No matching super-reg register class.", MO, MONum);
2719               return;
2720             }
2721           }
2722           if (!RC->hasSuperClassEq(DRC)) {
2723             report("Illegal virtual register for instruction", MO, MONum);
2724             OS << "Expected a " << TRI->getRegClassName(DRC)
2725                << " register, but got a " << TRI->getRegClassName(RC)
2726                << " register\n";
2727           }
2728         }
2729       }
2730     }
2731     break;
2732   }
2733 
2734   case MachineOperand::MO_RegisterMask:
2735     regMasks.push_back(MO->getRegMask());
2736     break;
2737 
2738   case MachineOperand::MO_MachineBasicBlock:
2739     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
2740       report("PHI operand is not in the CFG", MO, MONum);
2741     break;
2742 
2743   case MachineOperand::MO_FrameIndex:
2744     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
2745         LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2746       int FI = MO->getIndex();
2747       LiveInterval &LI = LiveStks->getInterval(FI);
2748       SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
2749 
2750       bool stores = MI->mayStore();
2751       bool loads = MI->mayLoad();
2752       // For a memory-to-memory move, we need to check if the frame
2753       // index is used for storing or loading, by inspecting the
2754       // memory operands.
2755       if (stores && loads) {
2756         for (auto *MMO : MI->memoperands()) {
2757           const PseudoSourceValue *PSV = MMO->getPseudoValue();
2758           if (PSV == nullptr) continue;
2759           const FixedStackPseudoSourceValue *Value =
2760             dyn_cast<FixedStackPseudoSourceValue>(PSV);
2761           if (Value == nullptr) continue;
2762           if (Value->getFrameIndex() != FI) continue;
2763 
2764           if (MMO->isStore())
2765             loads = false;
2766           else
2767             stores = false;
2768           break;
2769         }
2770         if (loads == stores)
2771           report("Missing fixed stack memoperand.", MI);
2772       }
2773       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
2774         report("Instruction loads from dead spill slot", MO, MONum);
2775         OS << "Live stack: " << LI << '\n';
2776       }
2777       if (stores && !LI.liveAt(Idx.getRegSlot())) {
2778         report("Instruction stores to dead spill slot", MO, MONum);
2779         OS << "Live stack: " << LI << '\n';
2780       }
2781     }
2782     break;
2783 
2784   case MachineOperand::MO_CFIIndex:
2785     if (MO->getCFIIndex() >= MF->getFrameInstructions().size())
2786       report("CFI instruction has invalid index", MO, MONum);
2787     break;
2788 
2789   default:
2790     break;
2791   }
2792 }
2793 
2794 void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
2795                                          unsigned MONum, SlotIndex UseIdx,
2796                                          const LiveRange &LR,
2797                                          Register VRegOrUnit,
2798                                          LaneBitmask LaneMask) {
2799   const MachineInstr *MI = MO->getParent();
2800 
2801   if (!LR.verify()) {
2802     report("invalid live range", MO, MONum);
2803     report_context_liverange(LR);
2804     report_context_vreg_regunit(VRegOrUnit);
2805     report_context(UseIdx);
2806     return;
2807   }
2808 
2809   LiveQueryResult LRQ = LR.Query(UseIdx);
2810   bool HasValue = LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut());
2811   // Check if we have a segment at the use, note however that we only need one
2812   // live subregister range, the others may be dead.
2813   if (!HasValue && LaneMask.none()) {
2814     report("No live segment at use", MO, MONum);
2815     report_context_liverange(LR);
2816     report_context_vreg_regunit(VRegOrUnit);
2817     report_context(UseIdx);
2818   }
2819   if (MO->isKill() && !LRQ.isKill()) {
2820     report("Live range continues after kill flag", MO, MONum);
2821     report_context_liverange(LR);
2822     report_context_vreg_regunit(VRegOrUnit);
2823     if (LaneMask.any())
2824       report_context_lanemask(LaneMask);
2825     report_context(UseIdx);
2826   }
2827 }
2828 
2829 void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
2830                                          unsigned MONum, SlotIndex DefIdx,
2831                                          const LiveRange &LR,
2832                                          Register VRegOrUnit,
2833                                          bool SubRangeCheck,
2834                                          LaneBitmask LaneMask) {
2835   if (!LR.verify()) {
2836     report("invalid live range", MO, MONum);
2837     report_context_liverange(LR);
2838     report_context_vreg_regunit(VRegOrUnit);
2839     if (LaneMask.any())
2840       report_context_lanemask(LaneMask);
2841     report_context(DefIdx);
2842   }
2843 
2844   if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
2845     // The LR can correspond to the whole reg and its def slot is not obliged
2846     // to be the same as the MO' def slot. E.g. when we check here "normal"
2847     // subreg MO but there is other EC subreg MO in the same instruction so the
2848     // whole reg has EC def slot and differs from the currently checked MO' def
2849     // slot. For example:
2850     // %0 [16e,32r:0) 0@16e  L..3 [16e,32r:0) 0@16e  L..C [16r,32r:0) 0@16r
2851     // Check that there is an early-clobber def of the same superregister
2852     // somewhere is performed in visitMachineFunctionAfter()
2853     if (((SubRangeCheck || MO->getSubReg() == 0) && VNI->def != DefIdx) ||
2854         !SlotIndex::isSameInstr(VNI->def, DefIdx) ||
2855         (VNI->def != DefIdx &&
2856          (!VNI->def.isEarlyClobber() || !DefIdx.isRegister()))) {
2857       report("Inconsistent valno->def", MO, MONum);
2858       report_context_liverange(LR);
2859       report_context_vreg_regunit(VRegOrUnit);
2860       if (LaneMask.any())
2861         report_context_lanemask(LaneMask);
2862       report_context(*VNI);
2863       report_context(DefIdx);
2864     }
2865   } else {
2866     report("No live segment at def", MO, MONum);
2867     report_context_liverange(LR);
2868     report_context_vreg_regunit(VRegOrUnit);
2869     if (LaneMask.any())
2870       report_context_lanemask(LaneMask);
2871     report_context(DefIdx);
2872   }
2873   // Check that, if the dead def flag is present, LiveInts agree.
2874   if (MO->isDead()) {
2875     LiveQueryResult LRQ = LR.Query(DefIdx);
2876     if (!LRQ.isDeadDef()) {
2877       assert(VRegOrUnit.isVirtual() && "Expecting a virtual register.");
2878       // A dead subreg def only tells us that the specific subreg is dead. There
2879       // could be other non-dead defs of other subregs, or we could have other
2880       // parts of the register being live through the instruction. So unless we
2881       // are checking liveness for a subrange it is ok for the live range to
2882       // continue, given that we have a dead def of a subregister.
2883       if (SubRangeCheck || MO->getSubReg() == 0) {
2884         report("Live range continues after dead def flag", MO, MONum);
2885         report_context_liverange(LR);
2886         report_context_vreg_regunit(VRegOrUnit);
2887         if (LaneMask.any())
2888           report_context_lanemask(LaneMask);
2889       }
2890     }
2891   }
2892 }
2893 
2894 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
2895   const MachineInstr *MI = MO->getParent();
2896   const Register Reg = MO->getReg();
2897   const unsigned SubRegIdx = MO->getSubReg();
2898 
2899   const LiveInterval *LI = nullptr;
2900   if (LiveInts && Reg.isVirtual()) {
2901     if (LiveInts->hasInterval(Reg)) {
2902       LI = &LiveInts->getInterval(Reg);
2903       if (SubRegIdx != 0 && (MO->isDef() || !MO->isUndef()) && !LI->empty() &&
2904           !LI->hasSubRanges() && MRI->shouldTrackSubRegLiveness(Reg))
2905         report("Live interval for subreg operand has no subranges", MO, MONum);
2906     } else {
2907       report("Virtual register has no live interval", MO, MONum);
2908     }
2909   }
2910 
2911   // Both use and def operands can read a register.
2912   if (MO->readsReg()) {
2913     if (MO->isKill())
2914       addRegWithSubRegs(regsKilled, Reg);
2915 
2916     // Check that LiveVars knows this kill (unless we are inside a bundle, in
2917     // which case we have already checked that LiveVars knows any kills on the
2918     // bundle header instead).
2919     if (LiveVars && Reg.isVirtual() && MO->isKill() &&
2920         !MI->isBundledWithPred()) {
2921       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
2922       if (!is_contained(VI.Kills, MI))
2923         report("Kill missing from LiveVariables", MO, MONum);
2924     }
2925 
2926     // Check LiveInts liveness and kill.
2927     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2928       SlotIndex UseIdx;
2929       if (MI->isPHI()) {
2930         // PHI use occurs on the edge, so check for live out here instead.
2931         UseIdx = LiveInts->getMBBEndIdx(
2932           MI->getOperand(MONum + 1).getMBB()).getPrevSlot();
2933       } else {
2934         UseIdx = LiveInts->getInstructionIndex(*MI);
2935       }
2936       // Check the cached regunit intervals.
2937       if (Reg.isPhysical() && !isReserved(Reg)) {
2938         for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
2939           if (MRI->isReservedRegUnit(Unit))
2940             continue;
2941           if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
2942             checkLivenessAtUse(MO, MONum, UseIdx, *LR, Unit);
2943         }
2944       }
2945 
2946       if (Reg.isVirtual()) {
2947         // This is a virtual register interval.
2948         checkLivenessAtUse(MO, MONum, UseIdx, *LI, Reg);
2949 
2950         if (LI->hasSubRanges() && !MO->isDef()) {
2951           LaneBitmask MOMask = SubRegIdx != 0
2952                                    ? TRI->getSubRegIndexLaneMask(SubRegIdx)
2953                                    : MRI->getMaxLaneMaskForVReg(Reg);
2954           LaneBitmask LiveInMask;
2955           for (const LiveInterval::SubRange &SR : LI->subranges()) {
2956             if ((MOMask & SR.LaneMask).none())
2957               continue;
2958             checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
2959             LiveQueryResult LRQ = SR.Query(UseIdx);
2960             if (LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut()))
2961               LiveInMask |= SR.LaneMask;
2962           }
2963           // At least parts of the register has to be live at the use.
2964           if ((LiveInMask & MOMask).none()) {
2965             report("No live subrange at use", MO, MONum);
2966             report_context(*LI);
2967             report_context(UseIdx);
2968           }
2969           // For PHIs all lanes should be live
2970           if (MI->isPHI() && LiveInMask != MOMask) {
2971             report("Not all lanes of PHI source live at use", MO, MONum);
2972             report_context(*LI);
2973             report_context(UseIdx);
2974           }
2975         }
2976       }
2977     }
2978 
2979     // Use of a dead register.
2980     if (!regsLive.count(Reg)) {
2981       if (Reg.isPhysical()) {
2982         // Reserved registers may be used even when 'dead'.
2983         bool Bad = !isReserved(Reg);
2984         // We are fine if just any subregister has a defined value.
2985         if (Bad) {
2986 
2987           for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
2988             if (regsLive.count(SubReg)) {
2989               Bad = false;
2990               break;
2991             }
2992           }
2993         }
2994         // If there is an additional implicit-use of a super register we stop
2995         // here. By definition we are fine if the super register is not
2996         // (completely) dead, if the complete super register is dead we will
2997         // get a report for its operand.
2998         if (Bad) {
2999           for (const MachineOperand &MOP : MI->uses()) {
3000             if (!MOP.isReg() || !MOP.isImplicit())
3001               continue;
3002 
3003             if (!MOP.getReg().isPhysical())
3004               continue;
3005 
3006             if (llvm::is_contained(TRI->subregs(MOP.getReg()), Reg))
3007               Bad = false;
3008           }
3009         }
3010         if (Bad)
3011           report("Using an undefined physical register", MO, MONum);
3012       } else if (MRI->def_empty(Reg)) {
3013         report("Reading virtual register without a def", MO, MONum);
3014       } else {
3015         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3016         // We don't know which virtual registers are live in, so only complain
3017         // if vreg was killed in this MBB. Otherwise keep track of vregs that
3018         // must be live in. PHI instructions are handled separately.
3019         if (MInfo.regsKilled.count(Reg))
3020           report("Using a killed virtual register", MO, MONum);
3021         else if (!MI->isPHI())
3022           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
3023       }
3024     }
3025   }
3026 
3027   if (MO->isDef()) {
3028     // Register defined.
3029     // TODO: verify that earlyclobber ops are not used.
3030     if (MO->isDead())
3031       addRegWithSubRegs(regsDead, Reg);
3032     else
3033       addRegWithSubRegs(regsDefined, Reg);
3034 
3035     // Verify SSA form.
3036     if (MRI->isSSA() && Reg.isVirtual() &&
3037         std::next(MRI->def_begin(Reg)) != MRI->def_end())
3038       report("Multiple virtual register defs in SSA form", MO, MONum);
3039 
3040     // Check LiveInts for a live segment, but only for virtual registers.
3041     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
3042       SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
3043       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
3044 
3045       if (Reg.isVirtual()) {
3046         checkLivenessAtDef(MO, MONum, DefIdx, *LI, Reg);
3047 
3048         if (LI->hasSubRanges()) {
3049           LaneBitmask MOMask = SubRegIdx != 0
3050                                    ? TRI->getSubRegIndexLaneMask(SubRegIdx)
3051                                    : MRI->getMaxLaneMaskForVReg(Reg);
3052           for (const LiveInterval::SubRange &SR : LI->subranges()) {
3053             if ((SR.LaneMask & MOMask).none())
3054               continue;
3055             checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
3056           }
3057         }
3058       }
3059     }
3060   }
3061 }
3062 
3063 // This function gets called after visiting all instructions in a bundle. The
3064 // argument points to the bundle header.
3065 // Normal stand-alone instructions are also considered 'bundles', and this
3066 // function is called for all of them.
3067 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
3068   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3069   set_union(MInfo.regsKilled, regsKilled);
3070   set_subtract(regsLive, regsKilled); regsKilled.clear();
3071   // Kill any masked registers.
3072   while (!regMasks.empty()) {
3073     const uint32_t *Mask = regMasks.pop_back_val();
3074     for (Register Reg : regsLive)
3075       if (Reg.isPhysical() &&
3076           MachineOperand::clobbersPhysReg(Mask, Reg.asMCReg()))
3077         regsDead.push_back(Reg);
3078   }
3079   set_subtract(regsLive, regsDead);   regsDead.clear();
3080   set_union(regsLive, regsDefined);   regsDefined.clear();
3081 }
3082 
3083 void
3084 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
3085   MBBInfoMap[MBB].regsLiveOut = regsLive;
3086   regsLive.clear();
3087 
3088   if (Indexes) {
3089     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
3090     if (!(stop > lastIndex)) {
3091       report("Block ends before last instruction index", MBB);
3092       OS << "Block ends at " << stop << " last instruction was at " << lastIndex
3093          << '\n';
3094     }
3095     lastIndex = stop;
3096   }
3097 }
3098 
3099 namespace {
3100 // This implements a set of registers that serves as a filter: can filter other
3101 // sets by passing through elements not in the filter and blocking those that
3102 // are. Any filter implicitly includes the full set of physical registers upon
3103 // creation, thus filtering them all out. The filter itself as a set only grows,
3104 // and needs to be as efficient as possible.
3105 struct VRegFilter {
3106   // Add elements to the filter itself. \pre Input set \p FromRegSet must have
3107   // no duplicates. Both virtual and physical registers are fine.
3108   template <typename RegSetT> void add(const RegSetT &FromRegSet) {
3109     SmallVector<Register, 0> VRegsBuffer;
3110     filterAndAdd(FromRegSet, VRegsBuffer);
3111   }
3112   // Filter \p FromRegSet through the filter and append passed elements into \p
3113   // ToVRegs. All elements appended are then added to the filter itself.
3114   // \returns true if anything changed.
3115   template <typename RegSetT>
3116   bool filterAndAdd(const RegSetT &FromRegSet,
3117                     SmallVectorImpl<Register> &ToVRegs) {
3118     unsigned SparseUniverse = Sparse.size();
3119     unsigned NewSparseUniverse = SparseUniverse;
3120     unsigned NewDenseSize = Dense.size();
3121     size_t Begin = ToVRegs.size();
3122     for (Register Reg : FromRegSet) {
3123       if (!Reg.isVirtual())
3124         continue;
3125       unsigned Index = Register::virtReg2Index(Reg);
3126       if (Index < SparseUniverseMax) {
3127         if (Index < SparseUniverse && Sparse.test(Index))
3128           continue;
3129         NewSparseUniverse = std::max(NewSparseUniverse, Index + 1);
3130       } else {
3131         if (Dense.count(Reg))
3132           continue;
3133         ++NewDenseSize;
3134       }
3135       ToVRegs.push_back(Reg);
3136     }
3137     size_t End = ToVRegs.size();
3138     if (Begin == End)
3139       return false;
3140     // Reserving space in sets once performs better than doing so continuously
3141     // and pays easily for double look-ups (even in Dense with SparseUniverseMax
3142     // tuned all the way down) and double iteration (the second one is over a
3143     // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
3144     Sparse.resize(NewSparseUniverse);
3145     Dense.reserve(NewDenseSize);
3146     for (unsigned I = Begin; I < End; ++I) {
3147       Register Reg = ToVRegs[I];
3148       unsigned Index = Register::virtReg2Index(Reg);
3149       if (Index < SparseUniverseMax)
3150         Sparse.set(Index);
3151       else
3152         Dense.insert(Reg);
3153     }
3154     return true;
3155   }
3156 
3157 private:
3158   static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8;
3159   // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound
3160   // are tracked by Dense. The only purpose of the threashold and the Dense set
3161   // is to have a reasonably growing memory usage in pathological cases (large
3162   // number of very sparse VRegFilter instances live at the same time). In
3163   // practice even in the worst-by-execution time cases having all elements
3164   // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
3165   // space efficient than if tracked by Dense. The threashold is set to keep the
3166   // worst-case memory usage within 2x of figures determined empirically for
3167   // "all Dense" scenario in such worst-by-execution-time cases.
3168   BitVector Sparse;
3169   DenseSet<unsigned> Dense;
3170 };
3171 
3172 // Implements both a transfer function and a (binary, in-place) join operator
3173 // for a dataflow over register sets with set union join and filtering transfer
3174 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
3175 // Maintains out_b as its state, allowing for O(n) iteration over it at any
3176 // time, where n is the size of the set (as opposed to O(U) where U is the
3177 // universe). filter_b implicitly contains all physical registers at all times.
3178 class FilteringVRegSet {
3179   VRegFilter Filter;
3180   SmallVector<Register, 0> VRegs;
3181 
3182 public:
3183   // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
3184   // Both virtual and physical registers are fine.
3185   template <typename RegSetT> void addToFilter(const RegSetT &RS) {
3186     Filter.add(RS);
3187   }
3188   // Passes \p RS through the filter_b (transfer function) and adds what's left
3189   // to itself (out_b).
3190   template <typename RegSetT> bool add(const RegSetT &RS) {
3191     // Double-duty the Filter: to maintain VRegs a set (and the join operation
3192     // a set union) just add everything being added here to the Filter as well.
3193     return Filter.filterAndAdd(RS, VRegs);
3194   }
3195   using const_iterator = decltype(VRegs)::const_iterator;
3196   const_iterator begin() const { return VRegs.begin(); }
3197   const_iterator end() const { return VRegs.end(); }
3198   size_t size() const { return VRegs.size(); }
3199 };
3200 } // namespace
3201 
3202 // Calculate the largest possible vregsPassed sets. These are the registers that
3203 // can pass through an MBB live, but may not be live every time. It is assumed
3204 // that all vregsPassed sets are empty before the call.
3205 void MachineVerifier::calcRegsPassed() {
3206   if (MF->empty())
3207     // ReversePostOrderTraversal doesn't handle empty functions.
3208     return;
3209 
3210   for (const MachineBasicBlock *MB :
3211        ReversePostOrderTraversal<const MachineFunction *>(MF)) {
3212     FilteringVRegSet VRegs;
3213     BBInfo &Info = MBBInfoMap[MB];
3214     assert(Info.reachable);
3215 
3216     VRegs.addToFilter(Info.regsKilled);
3217     VRegs.addToFilter(Info.regsLiveOut);
3218     for (const MachineBasicBlock *Pred : MB->predecessors()) {
3219       const BBInfo &PredInfo = MBBInfoMap[Pred];
3220       if (!PredInfo.reachable)
3221         continue;
3222 
3223       VRegs.add(PredInfo.regsLiveOut);
3224       VRegs.add(PredInfo.vregsPassed);
3225     }
3226     Info.vregsPassed.reserve(VRegs.size());
3227     Info.vregsPassed.insert(VRegs.begin(), VRegs.end());
3228   }
3229 }
3230 
3231 // Calculate the set of virtual registers that must be passed through each basic
3232 // block in order to satisfy the requirements of successor blocks. This is very
3233 // similar to calcRegsPassed, only backwards.
3234 void MachineVerifier::calcRegsRequired() {
3235   // First push live-in regs to predecessors' vregsRequired.
3236   SmallPtrSet<const MachineBasicBlock*, 8> todo;
3237   for (const auto &MBB : *MF) {
3238     BBInfo &MInfo = MBBInfoMap[&MBB];
3239     for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3240       BBInfo &PInfo = MBBInfoMap[Pred];
3241       if (PInfo.addRequired(MInfo.vregsLiveIn))
3242         todo.insert(Pred);
3243     }
3244 
3245     // Handle the PHI node.
3246     for (const MachineInstr &MI : MBB.phis()) {
3247       for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3248         // Skip those Operands which are undef regs or not regs.
3249         if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg())
3250           continue;
3251 
3252         // Get register and predecessor for one PHI edge.
3253         Register Reg = MI.getOperand(i).getReg();
3254         const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB();
3255 
3256         BBInfo &PInfo = MBBInfoMap[Pred];
3257         if (PInfo.addRequired(Reg))
3258           todo.insert(Pred);
3259       }
3260     }
3261   }
3262 
3263   // Iteratively push vregsRequired to predecessors. This will converge to the
3264   // same final state regardless of DenseSet iteration order.
3265   while (!todo.empty()) {
3266     const MachineBasicBlock *MBB = *todo.begin();
3267     todo.erase(MBB);
3268     BBInfo &MInfo = MBBInfoMap[MBB];
3269     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3270       if (Pred == MBB)
3271         continue;
3272       BBInfo &SInfo = MBBInfoMap[Pred];
3273       if (SInfo.addRequired(MInfo.vregsRequired))
3274         todo.insert(Pred);
3275     }
3276   }
3277 }
3278 
3279 // Check PHI instructions at the beginning of MBB. It is assumed that
3280 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
3281 void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
3282   BBInfo &MInfo = MBBInfoMap[&MBB];
3283 
3284   SmallPtrSet<const MachineBasicBlock*, 8> seen;
3285   for (const MachineInstr &Phi : MBB) {
3286     if (!Phi.isPHI())
3287       break;
3288     seen.clear();
3289 
3290     const MachineOperand &MODef = Phi.getOperand(0);
3291     if (!MODef.isReg() || !MODef.isDef()) {
3292       report("Expected first PHI operand to be a register def", &MODef, 0);
3293       continue;
3294     }
3295     if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
3296         MODef.isEarlyClobber() || MODef.isDebug())
3297       report("Unexpected flag on PHI operand", &MODef, 0);
3298     Register DefReg = MODef.getReg();
3299     if (!DefReg.isVirtual())
3300       report("Expected first PHI operand to be a virtual register", &MODef, 0);
3301 
3302     for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
3303       const MachineOperand &MO0 = Phi.getOperand(I);
3304       if (!MO0.isReg()) {
3305         report("Expected PHI operand to be a register", &MO0, I);
3306         continue;
3307       }
3308       if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
3309           MO0.isDebug() || MO0.isTied())
3310         report("Unexpected flag on PHI operand", &MO0, I);
3311 
3312       const MachineOperand &MO1 = Phi.getOperand(I + 1);
3313       if (!MO1.isMBB()) {
3314         report("Expected PHI operand to be a basic block", &MO1, I + 1);
3315         continue;
3316       }
3317 
3318       const MachineBasicBlock &Pre = *MO1.getMBB();
3319       if (!Pre.isSuccessor(&MBB)) {
3320         report("PHI input is not a predecessor block", &MO1, I + 1);
3321         continue;
3322       }
3323 
3324       if (MInfo.reachable) {
3325         seen.insert(&Pre);
3326         BBInfo &PrInfo = MBBInfoMap[&Pre];
3327         if (!MO0.isUndef() && PrInfo.reachable &&
3328             !PrInfo.isLiveOut(MO0.getReg()))
3329           report("PHI operand is not live-out from predecessor", &MO0, I);
3330       }
3331     }
3332 
3333     // Did we see all predecessors?
3334     if (MInfo.reachable) {
3335       for (MachineBasicBlock *Pred : MBB.predecessors()) {
3336         if (!seen.count(Pred)) {
3337           report("Missing PHI operand", &Phi);
3338           OS << printMBBReference(*Pred)
3339              << " is a predecessor according to the CFG.\n";
3340         }
3341       }
3342     }
3343   }
3344 }
3345 
3346 static void
3347 verifyConvergenceControl(const MachineFunction &MF, MachineDominatorTree &DT,
3348                          std::function<void(const Twine &Message)> FailureCB,
3349                          raw_ostream &OS) {
3350   MachineConvergenceVerifier CV;
3351   CV.initialize(&OS, FailureCB, MF);
3352 
3353   for (const auto &MBB : MF) {
3354     CV.visit(MBB);
3355     for (const auto &MI : MBB.instrs())
3356       CV.visit(MI);
3357   }
3358 
3359   if (CV.sawTokens()) {
3360     DT.recalculate(const_cast<MachineFunction &>(MF));
3361     CV.verify(DT);
3362   }
3363 }
3364 
3365 void MachineVerifier::visitMachineFunctionAfter() {
3366   auto FailureCB = [this](const Twine &Message) {
3367     report(Message.str().c_str(), MF);
3368   };
3369   verifyConvergenceControl(*MF, DT, FailureCB, OS);
3370 
3371   calcRegsPassed();
3372 
3373   for (const MachineBasicBlock &MBB : *MF)
3374     checkPHIOps(MBB);
3375 
3376   // Now check liveness info if available
3377   calcRegsRequired();
3378 
3379   // Check for killed virtual registers that should be live out.
3380   for (const auto &MBB : *MF) {
3381     BBInfo &MInfo = MBBInfoMap[&MBB];
3382     for (Register VReg : MInfo.vregsRequired)
3383       if (MInfo.regsKilled.count(VReg)) {
3384         report("Virtual register killed in block, but needed live out.", &MBB);
3385         OS << "Virtual register " << printReg(VReg)
3386            << " is used after the block.\n";
3387       }
3388   }
3389 
3390   if (!MF->empty()) {
3391     BBInfo &MInfo = MBBInfoMap[&MF->front()];
3392     for (Register VReg : MInfo.vregsRequired) {
3393       report("Virtual register defs don't dominate all uses.", MF);
3394       report_context_vreg(VReg);
3395     }
3396   }
3397 
3398   if (LiveVars)
3399     verifyLiveVariables();
3400   if (LiveInts)
3401     verifyLiveIntervals();
3402 
3403   // Check live-in list of each MBB. If a register is live into MBB, check
3404   // that the register is in regsLiveOut of each predecessor block. Since
3405   // this must come from a definition in the predecesssor or its live-in
3406   // list, this will catch a live-through case where the predecessor does not
3407   // have the register in its live-in list.  This currently only checks
3408   // registers that have no aliases, are not allocatable and are not
3409   // reserved, which could mean a condition code register for instance.
3410   if (MRI->tracksLiveness())
3411     for (const auto &MBB : *MF)
3412       for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
3413         MCPhysReg LiveInReg = P.PhysReg;
3414         bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
3415         if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg))
3416           continue;
3417         for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3418           BBInfo &PInfo = MBBInfoMap[Pred];
3419           if (!PInfo.regsLiveOut.count(LiveInReg)) {
3420             report("Live in register not found to be live out from predecessor.",
3421                    &MBB);
3422             OS << TRI->getName(LiveInReg) << " not found to be live out from "
3423                << printMBBReference(*Pred) << '\n';
3424           }
3425         }
3426       }
3427 
3428   for (auto CSInfo : MF->getCallSitesInfo())
3429     if (!CSInfo.first->isCall())
3430       report("Call site info referencing instruction that is not call", MF);
3431 
3432   // If there's debug-info, check that we don't have any duplicate value
3433   // tracking numbers.
3434   if (MF->getFunction().getSubprogram()) {
3435     DenseSet<unsigned> SeenNumbers;
3436     for (const auto &MBB : *MF) {
3437       for (const auto &MI : MBB) {
3438         if (auto Num = MI.peekDebugInstrNum()) {
3439           auto Result = SeenNumbers.insert((unsigned)Num);
3440           if (!Result.second)
3441             report("Instruction has a duplicated value tracking number", &MI);
3442         }
3443       }
3444     }
3445   }
3446 }
3447 
3448 void MachineVerifier::verifyLiveVariables() {
3449   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
3450   for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3451     Register Reg = Register::index2VirtReg(I);
3452     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
3453     for (const auto &MBB : *MF) {
3454       BBInfo &MInfo = MBBInfoMap[&MBB];
3455 
3456       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
3457       if (MInfo.vregsRequired.count(Reg)) {
3458         if (!VI.AliveBlocks.test(MBB.getNumber())) {
3459           report("LiveVariables: Block missing from AliveBlocks", &MBB);
3460           OS << "Virtual register " << printReg(Reg)
3461              << " must be live through the block.\n";
3462         }
3463       } else {
3464         if (VI.AliveBlocks.test(MBB.getNumber())) {
3465           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
3466           OS << "Virtual register " << printReg(Reg)
3467              << " is not needed live through the block.\n";
3468         }
3469       }
3470     }
3471   }
3472 }
3473 
3474 void MachineVerifier::verifyLiveIntervals() {
3475   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
3476   for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3477     Register Reg = Register::index2VirtReg(I);
3478 
3479     // Spilling and splitting may leave unused registers around. Skip them.
3480     if (MRI->reg_nodbg_empty(Reg))
3481       continue;
3482 
3483     if (!LiveInts->hasInterval(Reg)) {
3484       report("Missing live interval for virtual register", MF);
3485       OS << printReg(Reg, TRI) << " still has defs or uses\n";
3486       continue;
3487     }
3488 
3489     const LiveInterval &LI = LiveInts->getInterval(Reg);
3490     assert(Reg == LI.reg() && "Invalid reg to interval mapping");
3491     verifyLiveInterval(LI);
3492   }
3493 
3494   // Verify all the cached regunit intervals.
3495   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
3496     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
3497       verifyLiveRange(*LR, i);
3498 }
3499 
3500 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
3501                                            const VNInfo *VNI, Register Reg,
3502                                            LaneBitmask LaneMask) {
3503   if (VNI->isUnused())
3504     return;
3505 
3506   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
3507 
3508   if (!DefVNI) {
3509     report("Value not live at VNInfo def and not marked unused", MF);
3510     report_context(LR, Reg, LaneMask);
3511     report_context(*VNI);
3512     return;
3513   }
3514 
3515   if (DefVNI != VNI) {
3516     report("Live segment at def has different VNInfo", MF);
3517     report_context(LR, Reg, LaneMask);
3518     report_context(*VNI);
3519     return;
3520   }
3521 
3522   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
3523   if (!MBB) {
3524     report("Invalid VNInfo definition index", MF);
3525     report_context(LR, Reg, LaneMask);
3526     report_context(*VNI);
3527     return;
3528   }
3529 
3530   if (VNI->isPHIDef()) {
3531     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
3532       report("PHIDef VNInfo is not defined at MBB start", MBB);
3533       report_context(LR, Reg, LaneMask);
3534       report_context(*VNI);
3535     }
3536     return;
3537   }
3538 
3539   // Non-PHI def.
3540   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
3541   if (!MI) {
3542     report("No instruction at VNInfo def index", MBB);
3543     report_context(LR, Reg, LaneMask);
3544     report_context(*VNI);
3545     return;
3546   }
3547 
3548   if (Reg != 0) {
3549     bool hasDef = false;
3550     bool isEarlyClobber = false;
3551     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3552       if (!MOI->isReg() || !MOI->isDef())
3553         continue;
3554       if (Reg.isVirtual()) {
3555         if (MOI->getReg() != Reg)
3556           continue;
3557       } else {
3558         if (!MOI->getReg().isPhysical() || !TRI->hasRegUnit(MOI->getReg(), Reg))
3559           continue;
3560       }
3561       if (LaneMask.any() &&
3562           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
3563         continue;
3564       hasDef = true;
3565       if (MOI->isEarlyClobber())
3566         isEarlyClobber = true;
3567     }
3568 
3569     if (!hasDef) {
3570       report("Defining instruction does not modify register", MI);
3571       report_context(LR, Reg, LaneMask);
3572       report_context(*VNI);
3573     }
3574 
3575     // Early clobber defs begin at USE slots, but other defs must begin at
3576     // DEF slots.
3577     if (isEarlyClobber) {
3578       if (!VNI->def.isEarlyClobber()) {
3579         report("Early clobber def must be at an early-clobber slot", MBB);
3580         report_context(LR, Reg, LaneMask);
3581         report_context(*VNI);
3582       }
3583     } else if (!VNI->def.isRegister()) {
3584       report("Non-PHI, non-early clobber def must be at a register slot", MBB);
3585       report_context(LR, Reg, LaneMask);
3586       report_context(*VNI);
3587     }
3588   }
3589 }
3590 
3591 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
3592                                              const LiveRange::const_iterator I,
3593                                              Register Reg,
3594                                              LaneBitmask LaneMask) {
3595   const LiveRange::Segment &S = *I;
3596   const VNInfo *VNI = S.valno;
3597   assert(VNI && "Live segment has no valno");
3598 
3599   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
3600     report("Foreign valno in live segment", MF);
3601     report_context(LR, Reg, LaneMask);
3602     report_context(S);
3603     report_context(*VNI);
3604   }
3605 
3606   if (VNI->isUnused()) {
3607     report("Live segment valno is marked unused", MF);
3608     report_context(LR, Reg, LaneMask);
3609     report_context(S);
3610   }
3611 
3612   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
3613   if (!MBB) {
3614     report("Bad start of live segment, no basic block", MF);
3615     report_context(LR, Reg, LaneMask);
3616     report_context(S);
3617     return;
3618   }
3619   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
3620   if (S.start != MBBStartIdx && S.start != VNI->def) {
3621     report("Live segment must begin at MBB entry or valno def", MBB);
3622     report_context(LR, Reg, LaneMask);
3623     report_context(S);
3624   }
3625 
3626   const MachineBasicBlock *EndMBB =
3627     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
3628   if (!EndMBB) {
3629     report("Bad end of live segment, no basic block", MF);
3630     report_context(LR, Reg, LaneMask);
3631     report_context(S);
3632     return;
3633   }
3634 
3635   // Checks for non-live-out segments.
3636   if (S.end != LiveInts->getMBBEndIdx(EndMBB)) {
3637     // RegUnit intervals are allowed dead phis.
3638     if (!Reg.isVirtual() && VNI->isPHIDef() && S.start == VNI->def &&
3639         S.end == VNI->def.getDeadSlot())
3640       return;
3641 
3642     // The live segment is ending inside EndMBB
3643     const MachineInstr *MI =
3644         LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
3645     if (!MI) {
3646       report("Live segment doesn't end at a valid instruction", EndMBB);
3647       report_context(LR, Reg, LaneMask);
3648       report_context(S);
3649       return;
3650     }
3651 
3652     // The block slot must refer to a basic block boundary.
3653     if (S.end.isBlock()) {
3654       report("Live segment ends at B slot of an instruction", EndMBB);
3655       report_context(LR, Reg, LaneMask);
3656       report_context(S);
3657     }
3658 
3659     if (S.end.isDead()) {
3660       // Segment ends on the dead slot.
3661       // That means there must be a dead def.
3662       if (!SlotIndex::isSameInstr(S.start, S.end)) {
3663         report("Live segment ending at dead slot spans instructions", EndMBB);
3664         report_context(LR, Reg, LaneMask);
3665         report_context(S);
3666       }
3667     }
3668 
3669     // After tied operands are rewritten, a live segment can only end at an
3670     // early-clobber slot if it is being redefined by an early-clobber def.
3671     // TODO: Before tied operands are rewritten, a live segment can only end at
3672     // an early-clobber slot if the last use is tied to an early-clobber def.
3673     if (MF->getProperties().hasProperty(
3674             MachineFunctionProperties::Property::TiedOpsRewritten) &&
3675         S.end.isEarlyClobber()) {
3676       if (I + 1 == LR.end() || (I + 1)->start != S.end) {
3677         report("Live segment ending at early clobber slot must be "
3678                "redefined by an EC def in the same instruction",
3679                EndMBB);
3680         report_context(LR, Reg, LaneMask);
3681         report_context(S);
3682       }
3683     }
3684 
3685     // The following checks only apply to virtual registers. Physreg liveness
3686     // is too weird to check.
3687     if (Reg.isVirtual()) {
3688       // A live segment can end with either a redefinition, a kill flag on a
3689       // use, or a dead flag on a def.
3690       bool hasRead = false;
3691       bool hasSubRegDef = false;
3692       bool hasDeadDef = false;
3693       for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3694         if (!MOI->isReg() || MOI->getReg() != Reg)
3695           continue;
3696         unsigned Sub = MOI->getSubReg();
3697         LaneBitmask SLM =
3698             Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) : LaneBitmask::getAll();
3699         if (MOI->isDef()) {
3700           if (Sub != 0) {
3701             hasSubRegDef = true;
3702             // An operand %0:sub0 reads %0:sub1..n. Invert the lane
3703             // mask for subregister defs. Read-undef defs will be handled by
3704             // readsReg below.
3705             SLM = ~SLM;
3706           }
3707           if (MOI->isDead())
3708             hasDeadDef = true;
3709         }
3710         if (LaneMask.any() && (LaneMask & SLM).none())
3711           continue;
3712         if (MOI->readsReg())
3713           hasRead = true;
3714       }
3715       if (S.end.isDead()) {
3716         // Make sure that the corresponding machine operand for a "dead" live
3717         // range has the dead flag. We cannot perform this check for subregister
3718         // liveranges as partially dead values are allowed.
3719         if (LaneMask.none() && !hasDeadDef) {
3720           report(
3721               "Instruction ending live segment on dead slot has no dead flag",
3722               MI);
3723           report_context(LR, Reg, LaneMask);
3724           report_context(S);
3725         }
3726       } else {
3727         if (!hasRead) {
3728           // When tracking subregister liveness, the main range must start new
3729           // values on partial register writes, even if there is no read.
3730           if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
3731               !hasSubRegDef) {
3732             report("Instruction ending live segment doesn't read the register",
3733                    MI);
3734             report_context(LR, Reg, LaneMask);
3735             report_context(S);
3736           }
3737         }
3738       }
3739     }
3740   }
3741 
3742   // Now check all the basic blocks in this live segment.
3743   MachineFunction::const_iterator MFI = MBB->getIterator();
3744   // Is this live segment the beginning of a non-PHIDef VN?
3745   if (S.start == VNI->def && !VNI->isPHIDef()) {
3746     // Not live-in to any blocks.
3747     if (MBB == EndMBB)
3748       return;
3749     // Skip this block.
3750     ++MFI;
3751   }
3752 
3753   SmallVector<SlotIndex, 4> Undefs;
3754   if (LaneMask.any()) {
3755     LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
3756     OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
3757   }
3758 
3759   while (true) {
3760     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
3761     // We don't know how to track physregs into a landing pad.
3762     if (!Reg.isVirtual() && MFI->isEHPad()) {
3763       if (&*MFI == EndMBB)
3764         break;
3765       ++MFI;
3766       continue;
3767     }
3768 
3769     // Is VNI a PHI-def in the current block?
3770     bool IsPHI = VNI->isPHIDef() &&
3771       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
3772 
3773     // Check that VNI is live-out of all predecessors.
3774     for (const MachineBasicBlock *Pred : MFI->predecessors()) {
3775       SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred);
3776       // Predecessor of landing pad live-out on last call.
3777       if (MFI->isEHPad()) {
3778         for (const MachineInstr &MI : llvm::reverse(*Pred)) {
3779           if (MI.isCall()) {
3780             PEnd = Indexes->getInstructionIndex(MI).getBoundaryIndex();
3781             break;
3782           }
3783         }
3784       }
3785       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
3786 
3787       // All predecessors must have a live-out value. However for a phi
3788       // instruction with subregister intervals
3789       // only one of the subregisters (not necessarily the current one) needs to
3790       // be defined.
3791       if (!PVNI && (LaneMask.none() || !IsPHI)) {
3792         if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes))
3793           continue;
3794         report("Register not marked live out of predecessor", Pred);
3795         report_context(LR, Reg, LaneMask);
3796         report_context(*VNI);
3797         OS << " live into " << printMBBReference(*MFI) << '@'
3798            << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " << PEnd
3799            << '\n';
3800         continue;
3801       }
3802 
3803       // Only PHI-defs can take different predecessor values.
3804       if (!IsPHI && PVNI != VNI) {
3805         report("Different value live out of predecessor", Pred);
3806         report_context(LR, Reg, LaneMask);
3807         OS << "Valno #" << PVNI->id << " live out of "
3808            << printMBBReference(*Pred) << '@' << PEnd << "\nValno #" << VNI->id
3809            << " live into " << printMBBReference(*MFI) << '@'
3810            << LiveInts->getMBBStartIdx(&*MFI) << '\n';
3811       }
3812     }
3813     if (&*MFI == EndMBB)
3814       break;
3815     ++MFI;
3816   }
3817 }
3818 
3819 void MachineVerifier::verifyLiveRange(const LiveRange &LR, Register Reg,
3820                                       LaneBitmask LaneMask) {
3821   for (const VNInfo *VNI : LR.valnos)
3822     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
3823 
3824   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
3825     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
3826 }
3827 
3828 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
3829   Register Reg = LI.reg();
3830   assert(Reg.isVirtual());
3831   verifyLiveRange(LI, Reg);
3832 
3833   if (LI.hasSubRanges()) {
3834     LaneBitmask Mask;
3835     LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
3836     for (const LiveInterval::SubRange &SR : LI.subranges()) {
3837       if ((Mask & SR.LaneMask).any()) {
3838         report("Lane masks of sub ranges overlap in live interval", MF);
3839         report_context(LI);
3840       }
3841       if ((SR.LaneMask & ~MaxMask).any()) {
3842         report("Subrange lanemask is invalid", MF);
3843         report_context(LI);
3844       }
3845       if (SR.empty()) {
3846         report("Subrange must not be empty", MF);
3847         report_context(SR, LI.reg(), SR.LaneMask);
3848       }
3849       Mask |= SR.LaneMask;
3850       verifyLiveRange(SR, LI.reg(), SR.LaneMask);
3851       if (!LI.covers(SR)) {
3852         report("A Subrange is not covered by the main range", MF);
3853         report_context(LI);
3854       }
3855     }
3856   }
3857 
3858   // Check the LI only has one connected component.
3859   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
3860   unsigned NumComp = ConEQ.Classify(LI);
3861   if (NumComp > 1) {
3862     report("Multiple connected components in live interval", MF);
3863     report_context(LI);
3864     for (unsigned comp = 0; comp != NumComp; ++comp) {
3865       OS << comp << ": valnos";
3866       for (const VNInfo *I : LI.valnos)
3867         if (comp == ConEQ.getEqClass(I))
3868           OS << ' ' << I->id;
3869       OS << '\n';
3870     }
3871   }
3872 }
3873 
3874 namespace {
3875 
3876   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
3877   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
3878   // value is zero.
3879   // We use a bool plus an integer to capture the stack state.
3880 struct StackStateOfBB {
3881   StackStateOfBB() = default;
3882   StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup)
3883       : EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
3884         ExitIsSetup(ExitSetup) {}
3885 
3886   // Can be negative, which means we are setting up a frame.
3887   int EntryValue = 0;
3888   int ExitValue = 0;
3889   bool EntryIsSetup = false;
3890   bool ExitIsSetup = false;
3891 };
3892 
3893 } // end anonymous namespace
3894 
3895 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
3896 /// by a FrameDestroy <n>, stack adjustments are identical on all
3897 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
3898 void MachineVerifier::verifyStackFrame() {
3899   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
3900   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
3901   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
3902     return;
3903 
3904   SmallVector<StackStateOfBB, 8> SPState;
3905   SPState.resize(MF->getNumBlockIDs());
3906   df_iterator_default_set<const MachineBasicBlock*> Reachable;
3907 
3908   // Visit the MBBs in DFS order.
3909   for (df_ext_iterator<const MachineFunction *,
3910                        df_iterator_default_set<const MachineBasicBlock *>>
3911        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
3912        DFI != DFE; ++DFI) {
3913     const MachineBasicBlock *MBB = *DFI;
3914 
3915     StackStateOfBB BBState;
3916     // Check the exit state of the DFS stack predecessor.
3917     if (DFI.getPathLength() >= 2) {
3918       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
3919       assert(Reachable.count(StackPred) &&
3920              "DFS stack predecessor is already visited.\n");
3921       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
3922       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
3923       BBState.ExitValue = BBState.EntryValue;
3924       BBState.ExitIsSetup = BBState.EntryIsSetup;
3925     }
3926 
3927     if ((int)MBB->getCallFrameSize() != -BBState.EntryValue) {
3928       report("Call frame size on entry does not match value computed from "
3929              "predecessor",
3930              MBB);
3931       OS << "Call frame size on entry " << MBB->getCallFrameSize()
3932          << " does not match value computed from predecessor "
3933          << -BBState.EntryValue << '\n';
3934     }
3935 
3936     // Update stack state by checking contents of MBB.
3937     for (const auto &I : *MBB) {
3938       if (I.getOpcode() == FrameSetupOpcode) {
3939         if (BBState.ExitIsSetup)
3940           report("FrameSetup is after another FrameSetup", &I);
3941         if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
3942           report("AdjustsStack not set in presence of a frame pseudo "
3943                  "instruction.", &I);
3944         BBState.ExitValue -= TII->getFrameTotalSize(I);
3945         BBState.ExitIsSetup = true;
3946       }
3947 
3948       if (I.getOpcode() == FrameDestroyOpcode) {
3949         int Size = TII->getFrameTotalSize(I);
3950         if (!BBState.ExitIsSetup)
3951           report("FrameDestroy is not after a FrameSetup", &I);
3952         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
3953                                                BBState.ExitValue;
3954         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
3955           report("FrameDestroy <n> is after FrameSetup <m>", &I);
3956           OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
3957              << AbsSPAdj << ">.\n";
3958         }
3959         if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
3960           report("AdjustsStack not set in presence of a frame pseudo "
3961                  "instruction.", &I);
3962         BBState.ExitValue += Size;
3963         BBState.ExitIsSetup = false;
3964       }
3965     }
3966     SPState[MBB->getNumber()] = BBState;
3967 
3968     // Make sure the exit state of any predecessor is consistent with the entry
3969     // state.
3970     for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3971       if (Reachable.count(Pred) &&
3972           (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue ||
3973            SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
3974         report("The exit stack state of a predecessor is inconsistent.", MBB);
3975         OS << "Predecessor " << printMBBReference(*Pred) << " has exit state ("
3976            << SPState[Pred->getNumber()].ExitValue << ", "
3977            << SPState[Pred->getNumber()].ExitIsSetup << "), while "
3978            << printMBBReference(*MBB) << " has entry state ("
3979            << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
3980       }
3981     }
3982 
3983     // Make sure the entry state of any successor is consistent with the exit
3984     // state.
3985     for (const MachineBasicBlock *Succ : MBB->successors()) {
3986       if (Reachable.count(Succ) &&
3987           (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue ||
3988            SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
3989         report("The entry stack state of a successor is inconsistent.", MBB);
3990         OS << "Successor " << printMBBReference(*Succ) << " has entry state ("
3991            << SPState[Succ->getNumber()].EntryValue << ", "
3992            << SPState[Succ->getNumber()].EntryIsSetup << "), while "
3993            << printMBBReference(*MBB) << " has exit state ("
3994            << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
3995       }
3996     }
3997 
3998     // Make sure a basic block with return ends with zero stack adjustment.
3999     if (!MBB->empty() && MBB->back().isReturn()) {
4000       if (BBState.ExitIsSetup)
4001         report("A return block ends with a FrameSetup.", MBB);
4002       if (BBState.ExitValue)
4003         report("A return block ends with a nonzero stack adjustment.", MBB);
4004     }
4005   }
4006 }
4007