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