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