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