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