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