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