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