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