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