12cab237bSDimitry Andric //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // Pass to verify generated machine code. The following is checked:
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky // Operand counts: All explicit operands must be present.
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky // Register classes: All physical and virtual register operands must be
15f22ef01cSRoman Divacky // compatible with the register class required by the instruction descriptor.
16f22ef01cSRoman Divacky //
17f22ef01cSRoman Divacky // Register live intervals: Registers must be defined only once, and must be
18f22ef01cSRoman Divacky // defined before use.
19f22ef01cSRoman Divacky //
20f22ef01cSRoman Divacky // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21f22ef01cSRoman Divacky // command-line option -verify-machineinstrs, or by defining the environment
22f22ef01cSRoman Divacky // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23f22ef01cSRoman Divacky // the verifier errors.
24f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
25f22ef01cSRoman Divacky 
26*b5893f02SDimitry Andric #include "LiveRangeCalc.h"
272cab237bSDimitry Andric #include "llvm/ADT/BitVector.h"
282cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
29f22ef01cSRoman Divacky #include "llvm/ADT/DenseSet.h"
30f785676fSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
312cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
32f22ef01cSRoman Divacky #include "llvm/ADT/SetOperations.h"
332cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
34f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h"
352cab237bSDimitry Andric #include "llvm/ADT/StringRef.h"
362cab237bSDimitry Andric #include "llvm/ADT/Twine.h"
377d523365SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
382cab237bSDimitry Andric #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
392cab237bSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
402cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
41da09e106SDimitry Andric #include "llvm/CodeGen/LiveStacks.h"
42139f7f9bSDimitry Andric #include "llvm/CodeGen/LiveVariables.h"
432cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
44139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
452cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
46139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
472cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
482cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
49139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
502cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
51139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
522cab237bSDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
532cab237bSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
546d97bb29SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
552cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
562cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
572cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
582cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
59139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
602cab237bSDimitry Andric #include "llvm/IR/Function.h"
61139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h"
62139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
632cab237bSDimitry Andric #include "llvm/MC/LaneBitmask.h"
64139f7f9bSDimitry Andric #include "llvm/MC/MCAsmInfo.h"
652cab237bSDimitry Andric #include "llvm/MC/MCInstrDesc.h"
662cab237bSDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
672cab237bSDimitry Andric #include "llvm/MC/MCTargetOptions.h"
682cab237bSDimitry Andric #include "llvm/Pass.h"
692cab237bSDimitry Andric #include "llvm/Support/Casting.h"
70f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
712cab237bSDimitry Andric #include "llvm/Support/LowLevelTypeImpl.h"
722cab237bSDimitry Andric #include "llvm/Support/MathExtras.h"
73f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
74139f7f9bSDimitry Andric #include "llvm/Target/TargetMachine.h"
752cab237bSDimitry Andric #include <algorithm>
762cab237bSDimitry Andric #include <cassert>
772cab237bSDimitry Andric #include <cstddef>
782cab237bSDimitry Andric #include <cstdint>
792cab237bSDimitry Andric #include <iterator>
802cab237bSDimitry Andric #include <string>
812cab237bSDimitry Andric #include <utility>
822cab237bSDimitry Andric 
83f22ef01cSRoman Divacky using namespace llvm;
84f22ef01cSRoman Divacky 
85f22ef01cSRoman Divacky namespace {
86f22ef01cSRoman Divacky 
872cab237bSDimitry Andric   struct MachineVerifier {
MachineVerifier__anon68d9c28a0111::MachineVerifier882cab237bSDimitry Andric     MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
89f22ef01cSRoman Divacky 
903ca95b02SDimitry Andric     unsigned verify(MachineFunction &MF);
91f22ef01cSRoman Divacky 
92f22ef01cSRoman Divacky     Pass *const PASS;
932754fe60SDimitry Andric     const char *Banner;
94f22ef01cSRoman Divacky     const MachineFunction *MF;
95f22ef01cSRoman Divacky     const TargetMachine *TM;
9617a519f9SDimitry Andric     const TargetInstrInfo *TII;
97f22ef01cSRoman Divacky     const TargetRegisterInfo *TRI;
98f22ef01cSRoman Divacky     const MachineRegisterInfo *MRI;
99f22ef01cSRoman Divacky 
100f22ef01cSRoman Divacky     unsigned foundErrors;
101f22ef01cSRoman Divacky 
102d88c1a5aSDimitry Andric     // Avoid querying the MachineFunctionProperties for each operand.
103d88c1a5aSDimitry Andric     bool isFunctionRegBankSelected;
104d88c1a5aSDimitry Andric     bool isFunctionSelected;
105d88c1a5aSDimitry Andric 
1062cab237bSDimitry Andric     using RegVector = SmallVector<unsigned, 16>;
1072cab237bSDimitry Andric     using RegMaskVector = SmallVector<const uint32_t *, 4>;
1082cab237bSDimitry Andric     using RegSet = DenseSet<unsigned>;
1092cab237bSDimitry Andric     using RegMap = DenseMap<unsigned, const MachineInstr *>;
1102cab237bSDimitry Andric     using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
111f22ef01cSRoman Divacky 
112*b5893f02SDimitry Andric     const MachineInstr *FirstNonPHI;
1136122f3e6SDimitry Andric     const MachineInstr *FirstTerminator;
1143861d79fSDimitry Andric     BlockSet FunctionBlocks;
1156122f3e6SDimitry Andric 
116f22ef01cSRoman Divacky     BitVector regsReserved;
117f22ef01cSRoman Divacky     RegSet regsLive;
118f22ef01cSRoman Divacky     RegVector regsDefined, regsDead, regsKilled;
119dff0c46cSDimitry Andric     RegMaskVector regMasks;
120f22ef01cSRoman Divacky 
1212754fe60SDimitry Andric     SlotIndex lastIndex;
1222754fe60SDimitry Andric 
123f22ef01cSRoman Divacky     // Add Reg and any sub-registers to RV
addRegWithSubRegs__anon68d9c28a0111::MachineVerifier124f22ef01cSRoman Divacky     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
125f22ef01cSRoman Divacky       RV.push_back(Reg);
126f22ef01cSRoman Divacky       if (TargetRegisterInfo::isPhysicalRegister(Reg))
1277ae0e2c9SDimitry Andric         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1287ae0e2c9SDimitry Andric           RV.push_back(*SubRegs);
129f22ef01cSRoman Divacky     }
130f22ef01cSRoman Divacky 
131f22ef01cSRoman Divacky     struct BBInfo {
132f22ef01cSRoman Divacky       // Is this MBB reachable from the MF entry point?
1332cab237bSDimitry Andric       bool reachable = false;
134f22ef01cSRoman Divacky 
135f22ef01cSRoman Divacky       // Vregs that must be live in because they are used without being
136f22ef01cSRoman Divacky       // defined. Map value is the user.
137f22ef01cSRoman Divacky       RegMap vregsLiveIn;
138f22ef01cSRoman Divacky 
139f22ef01cSRoman Divacky       // Regs killed in MBB. They may be defined again, and will then be in both
140f22ef01cSRoman Divacky       // regsKilled and regsLiveOut.
141f22ef01cSRoman Divacky       RegSet regsKilled;
142f22ef01cSRoman Divacky 
143f22ef01cSRoman Divacky       // Regs defined in MBB and live out. Note that vregs passing through may
144f22ef01cSRoman Divacky       // be live out without being mentioned here.
145f22ef01cSRoman Divacky       RegSet regsLiveOut;
146f22ef01cSRoman Divacky 
147f22ef01cSRoman Divacky       // Vregs that pass through MBB untouched. This set is disjoint from
148f22ef01cSRoman Divacky       // regsKilled and regsLiveOut.
149f22ef01cSRoman Divacky       RegSet vregsPassed;
150f22ef01cSRoman Divacky 
151f22ef01cSRoman Divacky       // Vregs that must pass through MBB because they are needed by a successor
152f22ef01cSRoman Divacky       // block. This set is disjoint from regsLiveOut.
153f22ef01cSRoman Divacky       RegSet vregsRequired;
154f22ef01cSRoman Divacky 
1553861d79fSDimitry Andric       // Set versions of block's predecessor and successor lists.
1563861d79fSDimitry Andric       BlockSet Preds, Succs;
1573861d79fSDimitry Andric 
1582cab237bSDimitry Andric       BBInfo() = default;
159f22ef01cSRoman Divacky 
160f22ef01cSRoman Divacky       // Add register to vregsPassed if it belongs there. Return true if
161f22ef01cSRoman Divacky       // anything changed.
addPassed__anon68d9c28a0111::MachineVerifier::BBInfo162f22ef01cSRoman Divacky       bool addPassed(unsigned Reg) {
163f22ef01cSRoman Divacky         if (!TargetRegisterInfo::isVirtualRegister(Reg))
164f22ef01cSRoman Divacky           return false;
165f22ef01cSRoman Divacky         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
166f22ef01cSRoman Divacky           return false;
167f22ef01cSRoman Divacky         return vregsPassed.insert(Reg).second;
168f22ef01cSRoman Divacky       }
169f22ef01cSRoman Divacky 
170f22ef01cSRoman Divacky       // Same for a full set.
addPassed__anon68d9c28a0111::MachineVerifier::BBInfo171f22ef01cSRoman Divacky       bool addPassed(const RegSet &RS) {
172f22ef01cSRoman Divacky         bool changed = false;
173f22ef01cSRoman Divacky         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
174f22ef01cSRoman Divacky           if (addPassed(*I))
175f22ef01cSRoman Divacky             changed = true;
176f22ef01cSRoman Divacky         return changed;
177f22ef01cSRoman Divacky       }
178f22ef01cSRoman Divacky 
179f22ef01cSRoman Divacky       // Add register to vregsRequired if it belongs there. Return true if
180f22ef01cSRoman Divacky       // anything changed.
addRequired__anon68d9c28a0111::MachineVerifier::BBInfo181f22ef01cSRoman Divacky       bool addRequired(unsigned Reg) {
182f22ef01cSRoman Divacky         if (!TargetRegisterInfo::isVirtualRegister(Reg))
183f22ef01cSRoman Divacky           return false;
184f22ef01cSRoman Divacky         if (regsLiveOut.count(Reg))
185f22ef01cSRoman Divacky           return false;
186f22ef01cSRoman Divacky         return vregsRequired.insert(Reg).second;
187f22ef01cSRoman Divacky       }
188f22ef01cSRoman Divacky 
189f22ef01cSRoman Divacky       // Same for a full set.
addRequired__anon68d9c28a0111::MachineVerifier::BBInfo190f22ef01cSRoman Divacky       bool addRequired(const RegSet &RS) {
191f22ef01cSRoman Divacky         bool changed = false;
192f22ef01cSRoman Divacky         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
193f22ef01cSRoman Divacky           if (addRequired(*I))
194f22ef01cSRoman Divacky             changed = true;
195f22ef01cSRoman Divacky         return changed;
196f22ef01cSRoman Divacky       }
197f22ef01cSRoman Divacky 
198f22ef01cSRoman Divacky       // Same for a full map.
addRequired__anon68d9c28a0111::MachineVerifier::BBInfo199f22ef01cSRoman Divacky       bool addRequired(const RegMap &RM) {
200f22ef01cSRoman Divacky         bool changed = false;
201f22ef01cSRoman Divacky         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
202f22ef01cSRoman Divacky           if (addRequired(I->first))
203f22ef01cSRoman Divacky             changed = true;
204f22ef01cSRoman Divacky         return changed;
205f22ef01cSRoman Divacky       }
206f22ef01cSRoman Divacky 
207f22ef01cSRoman Divacky       // Live-out registers are either in regsLiveOut or vregsPassed.
isLiveOut__anon68d9c28a0111::MachineVerifier::BBInfo208f22ef01cSRoman Divacky       bool isLiveOut(unsigned Reg) const {
209f22ef01cSRoman Divacky         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
210f22ef01cSRoman Divacky       }
211f22ef01cSRoman Divacky     };
212f22ef01cSRoman Divacky 
213f22ef01cSRoman Divacky     // Extra register info per MBB.
214f22ef01cSRoman Divacky     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
215f22ef01cSRoman Divacky 
isReserved__anon68d9c28a0111::MachineVerifier216f22ef01cSRoman Divacky     bool isReserved(unsigned Reg) {
217f22ef01cSRoman Divacky       return Reg < regsReserved.size() && regsReserved.test(Reg);
218f22ef01cSRoman Divacky     }
219f22ef01cSRoman Divacky 
isAllocatable__anon68d9c28a0111::MachineVerifier2200f5676f4SDimitry Andric     bool isAllocatable(unsigned Reg) const {
2210f5676f4SDimitry Andric       return Reg < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
2220f5676f4SDimitry Andric         !regsReserved.test(Reg);
223dff0c46cSDimitry Andric     }
224dff0c46cSDimitry Andric 
225f22ef01cSRoman Divacky     // Analysis information if available
226f22ef01cSRoman Divacky     LiveVariables *LiveVars;
2272754fe60SDimitry Andric     LiveIntervals *LiveInts;
2282754fe60SDimitry Andric     LiveStacks *LiveStks;
2292754fe60SDimitry Andric     SlotIndexes *Indexes;
230f22ef01cSRoman Divacky 
231f22ef01cSRoman Divacky     void visitMachineFunctionBefore();
232f22ef01cSRoman Divacky     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
2337ae0e2c9SDimitry Andric     void visitMachineBundleBefore(const MachineInstr *MI);
234f22ef01cSRoman Divacky     void visitMachineInstrBefore(const MachineInstr *MI);
235f22ef01cSRoman Divacky     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
236f22ef01cSRoman Divacky     void visitMachineInstrAfter(const MachineInstr *MI);
2377ae0e2c9SDimitry Andric     void visitMachineBundleAfter(const MachineInstr *MI);
238f22ef01cSRoman Divacky     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
239f22ef01cSRoman Divacky     void visitMachineFunctionAfter();
240f22ef01cSRoman Divacky 
241f22ef01cSRoman Divacky     void report(const char *msg, const MachineFunction *MF);
242f22ef01cSRoman Divacky     void report(const char *msg, const MachineBasicBlock *MBB);
243f22ef01cSRoman Divacky     void report(const char *msg, const MachineInstr *MI);
2444ba319b5SDimitry Andric     void report(const char *msg, const MachineOperand *MO, unsigned MONum,
2454ba319b5SDimitry Andric                 LLT MOVRegType = LLT{});
2467d523365SDimitry Andric 
2477d523365SDimitry Andric     void report_context(const LiveInterval &LI) const;
248d88c1a5aSDimitry Andric     void report_context(const LiveRange &LR, unsigned VRegUnit,
2497d523365SDimitry Andric                         LaneBitmask LaneMask) const;
2507d523365SDimitry Andric     void report_context(const LiveRange::Segment &S) const;
2517d523365SDimitry Andric     void report_context(const VNInfo &VNI) const;
2523ca95b02SDimitry Andric     void report_context(SlotIndex Pos) const;
253*b5893f02SDimitry Andric     void report_context(MCPhysReg PhysReg) const;
2543ca95b02SDimitry Andric     void report_context_liverange(const LiveRange &LR) const;
2553ca95b02SDimitry Andric     void report_context_lanemask(LaneBitmask LaneMask) const;
2563ca95b02SDimitry Andric     void report_context_vreg(unsigned VReg) const;
2574ba319b5SDimitry Andric     void report_context_vreg_regunit(unsigned VRegOrUnit) const;
258f22ef01cSRoman Divacky 
2593861d79fSDimitry Andric     void verifyInlineAsm(const MachineInstr *MI);
2603861d79fSDimitry Andric 
261dff0c46cSDimitry Andric     void checkLiveness(const MachineOperand *MO, unsigned MONum);
2623ca95b02SDimitry Andric     void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
2634ba319b5SDimitry Andric                             SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
264d88c1a5aSDimitry Andric                             LaneBitmask LaneMask = LaneBitmask::getNone());
2653ca95b02SDimitry Andric     void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
2664ba319b5SDimitry Andric                             SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
267*b5893f02SDimitry Andric                             bool SubRangeCheck = false,
268d88c1a5aSDimitry Andric                             LaneBitmask LaneMask = LaneBitmask::getNone());
2693ca95b02SDimitry Andric 
270f22ef01cSRoman Divacky     void markReachable(const MachineBasicBlock *MBB);
271f22ef01cSRoman Divacky     void calcRegsPassed();
2722cab237bSDimitry Andric     void checkPHIOps(const MachineBasicBlock &MBB);
273f22ef01cSRoman Divacky 
274f22ef01cSRoman Divacky     void calcRegsRequired();
275f22ef01cSRoman Divacky     void verifyLiveVariables();
276e580952dSDimitry Andric     void verifyLiveIntervals();
2777ae0e2c9SDimitry Andric     void verifyLiveInterval(const LiveInterval&);
27839d628a0SDimitry Andric     void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
279d88c1a5aSDimitry Andric                               LaneBitmask);
280f785676fSDimitry Andric     void verifyLiveRangeSegment(const LiveRange&,
28139d628a0SDimitry Andric                                 const LiveRange::const_iterator I, unsigned,
282d88c1a5aSDimitry Andric                                 LaneBitmask);
283d88c1a5aSDimitry Andric     void verifyLiveRange(const LiveRange&, unsigned,
284d88c1a5aSDimitry Andric                          LaneBitmask LaneMask = LaneBitmask::getNone());
285f785676fSDimitry Andric 
286f785676fSDimitry Andric     void verifyStackFrame();
2877d523365SDimitry Andric 
2887d523365SDimitry Andric     void verifySlotIndexes() const;
2893ca95b02SDimitry Andric     void verifyProperties(const MachineFunction &MF);
290f22ef01cSRoman Divacky   };
291f22ef01cSRoman Divacky 
292f22ef01cSRoman Divacky   struct MachineVerifierPass : public MachineFunctionPass {
293f22ef01cSRoman Divacky     static char ID; // Pass ID, replacement for typeid
2942cab237bSDimitry Andric 
29539d628a0SDimitry Andric     const std::string Banner;
296f22ef01cSRoman Divacky 
MachineVerifierPass__anon68d9c28a0111::MachineVerifierPass2977a7e6055SDimitry Andric     MachineVerifierPass(std::string banner = std::string())
2987a7e6055SDimitry Andric       : MachineFunctionPass(ID), Banner(std::move(banner)) {
2992754fe60SDimitry Andric         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
3002754fe60SDimitry Andric       }
301f22ef01cSRoman Divacky 
getAnalysisUsage__anon68d9c28a0111::MachineVerifierPass30291bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
303f22ef01cSRoman Divacky       AU.setPreservesAll();
304f22ef01cSRoman Divacky       MachineFunctionPass::getAnalysisUsage(AU);
305f22ef01cSRoman Divacky     }
306f22ef01cSRoman Divacky 
runOnMachineFunction__anon68d9c28a0111::MachineVerifierPass30791bc56edSDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override {
3083ca95b02SDimitry Andric       unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
3093ca95b02SDimitry Andric       if (FoundErrors)
3103ca95b02SDimitry Andric         report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
311f22ef01cSRoman Divacky       return false;
312f22ef01cSRoman Divacky     }
313f22ef01cSRoman Divacky   };
314f22ef01cSRoman Divacky 
3152cab237bSDimitry Andric } // end anonymous namespace
316f22ef01cSRoman Divacky 
317f22ef01cSRoman Divacky char MachineVerifierPass::ID = 0;
3182cab237bSDimitry Andric 
319e580952dSDimitry Andric INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
3202754fe60SDimitry Andric                 "Verify generated machine code", false, false)
321f22ef01cSRoman Divacky 
createMachineVerifierPass(const std::string & Banner)32239d628a0SDimitry Andric FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
3232754fe60SDimitry Andric   return new MachineVerifierPass(Banner);
324f22ef01cSRoman Divacky }
325f22ef01cSRoman Divacky 
verify(Pass * p,const char * Banner,bool AbortOnErrors) const3263ca95b02SDimitry Andric bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
3273ca95b02SDimitry Andric     const {
3283ca95b02SDimitry Andric   MachineFunction &MF = const_cast<MachineFunction&>(*this);
3293ca95b02SDimitry Andric   unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
3303ca95b02SDimitry Andric   if (AbortOnErrors && FoundErrors)
3313ca95b02SDimitry Andric     report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
3323ca95b02SDimitry Andric   return FoundErrors == 0;
333f22ef01cSRoman Divacky }
334f22ef01cSRoman Divacky 
verifySlotIndexes() const3357d523365SDimitry Andric void MachineVerifier::verifySlotIndexes() const {
3367d523365SDimitry Andric   if (Indexes == nullptr)
3377d523365SDimitry Andric     return;
3387d523365SDimitry Andric 
3397d523365SDimitry Andric   // Ensure the IdxMBB list is sorted by slot indexes.
3407d523365SDimitry Andric   SlotIndex Last;
3417d523365SDimitry Andric   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
3427d523365SDimitry Andric        E = Indexes->MBBIndexEnd(); I != E; ++I) {
3437d523365SDimitry Andric     assert(!Last.isValid() || I->first > Last);
3447d523365SDimitry Andric     Last = I->first;
3457d523365SDimitry Andric   }
3467d523365SDimitry Andric }
3477d523365SDimitry Andric 
verifyProperties(const MachineFunction & MF)3483ca95b02SDimitry Andric void MachineVerifier::verifyProperties(const MachineFunction &MF) {
3493ca95b02SDimitry Andric   // If a pass has introduced virtual registers without clearing the
350d88c1a5aSDimitry Andric   // NoVRegs property (or set it without allocating the vregs)
3513ca95b02SDimitry Andric   // then report an error.
3523ca95b02SDimitry Andric   if (MF.getProperties().hasProperty(
353d88c1a5aSDimitry Andric           MachineFunctionProperties::Property::NoVRegs) &&
354d88c1a5aSDimitry Andric       MRI->getNumVirtRegs())
355d88c1a5aSDimitry Andric     report("Function has NoVRegs property but there are VReg operands", &MF);
3563ca95b02SDimitry Andric }
3573ca95b02SDimitry Andric 
verify(MachineFunction & MF)3583ca95b02SDimitry Andric unsigned MachineVerifier::verify(MachineFunction &MF) {
359f22ef01cSRoman Divacky   foundErrors = 0;
360f22ef01cSRoman Divacky 
361f22ef01cSRoman Divacky   this->MF = &MF;
362f22ef01cSRoman Divacky   TM = &MF.getTarget();
36339d628a0SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
36439d628a0SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
365f22ef01cSRoman Divacky   MRI = &MF.getRegInfo();
366f22ef01cSRoman Divacky 
3674ba319b5SDimitry Andric   const bool isFunctionFailedISel = MF.getProperties().hasProperty(
3684ba319b5SDimitry Andric       MachineFunctionProperties::Property::FailedISel);
369*b5893f02SDimitry Andric 
370*b5893f02SDimitry Andric   // If we're mid-GlobalISel and we already triggered the fallback path then
371*b5893f02SDimitry Andric   // it's expected that the MIR is somewhat broken but that's ok since we'll
372*b5893f02SDimitry Andric   // reset it and clear the FailedISel attribute in ResetMachineFunctions.
373*b5893f02SDimitry Andric   if (isFunctionFailedISel)
374*b5893f02SDimitry Andric     return foundErrors;
375*b5893f02SDimitry Andric 
3764ba319b5SDimitry Andric   isFunctionRegBankSelected =
3774ba319b5SDimitry Andric       !isFunctionFailedISel &&
3784ba319b5SDimitry Andric       MF.getProperties().hasProperty(
379d88c1a5aSDimitry Andric           MachineFunctionProperties::Property::RegBankSelected);
3804ba319b5SDimitry Andric   isFunctionSelected = !isFunctionFailedISel &&
3814ba319b5SDimitry Andric                        MF.getProperties().hasProperty(
382d88c1a5aSDimitry Andric                            MachineFunctionProperties::Property::Selected);
38391bc56edSDimitry Andric   LiveVars = nullptr;
38491bc56edSDimitry Andric   LiveInts = nullptr;
38591bc56edSDimitry Andric   LiveStks = nullptr;
38691bc56edSDimitry Andric   Indexes = nullptr;
387e580952dSDimitry Andric   if (PASS) {
388e580952dSDimitry Andric     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
389e580952dSDimitry Andric     // We don't want to verify LiveVariables if LiveIntervals is available.
390e580952dSDimitry Andric     if (!LiveInts)
391e580952dSDimitry Andric       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
3922754fe60SDimitry Andric     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
3932754fe60SDimitry Andric     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
394f22ef01cSRoman Divacky   }
395f22ef01cSRoman Divacky 
3967d523365SDimitry Andric   verifySlotIndexes();
3977d523365SDimitry Andric 
3983ca95b02SDimitry Andric   verifyProperties(MF);
3993ca95b02SDimitry Andric 
400f22ef01cSRoman Divacky   visitMachineFunctionBefore();
401f22ef01cSRoman Divacky   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
402f22ef01cSRoman Divacky        MFI!=MFE; ++MFI) {
4037d523365SDimitry Andric     visitMachineBasicBlockBefore(&*MFI);
4047ae0e2c9SDimitry Andric     // Keep track of the current bundle header.
40591bc56edSDimitry Andric     const MachineInstr *CurBundle = nullptr;
406139f7f9bSDimitry Andric     // Do we expect the next instruction to be part of the same bundle?
407139f7f9bSDimitry Andric     bool InBundle = false;
408139f7f9bSDimitry Andric 
409dff0c46cSDimitry Andric     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
410dff0c46cSDimitry Andric            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
4117d523365SDimitry Andric       if (MBBI->getParent() != &*MFI) {
412d88c1a5aSDimitry Andric         report("Bad instruction parent pointer", &*MFI);
413ff0cc061SDimitry Andric         errs() << "Instruction: " << *MBBI;
4142754fe60SDimitry Andric         continue;
4152754fe60SDimitry Andric       }
416139f7f9bSDimitry Andric 
417139f7f9bSDimitry Andric       // Check for consistent bundle flags.
418139f7f9bSDimitry Andric       if (InBundle && !MBBI->isBundledWithPred())
419139f7f9bSDimitry Andric         report("Missing BundledPred flag, "
4207d523365SDimitry Andric                "BundledSucc was set on predecessor",
4217d523365SDimitry Andric                &*MBBI);
422139f7f9bSDimitry Andric       if (!InBundle && MBBI->isBundledWithPred())
423139f7f9bSDimitry Andric         report("BundledPred flag is set, "
4247d523365SDimitry Andric                "but BundledSucc not set on predecessor",
4257d523365SDimitry Andric                &*MBBI);
426139f7f9bSDimitry Andric 
4277ae0e2c9SDimitry Andric       // Is this a bundle header?
4287ae0e2c9SDimitry Andric       if (!MBBI->isInsideBundle()) {
4297ae0e2c9SDimitry Andric         if (CurBundle)
4307ae0e2c9SDimitry Andric           visitMachineBundleAfter(CurBundle);
4317d523365SDimitry Andric         CurBundle = &*MBBI;
4327ae0e2c9SDimitry Andric         visitMachineBundleBefore(CurBundle);
4337ae0e2c9SDimitry Andric       } else if (!CurBundle)
434d88c1a5aSDimitry Andric         report("No bundle header", &*MBBI);
4357d523365SDimitry Andric       visitMachineInstrBefore(&*MBBI);
436ff0cc061SDimitry Andric       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
437ff0cc061SDimitry Andric         const MachineInstr &MI = *MBBI;
438ff0cc061SDimitry Andric         const MachineOperand &Op = MI.getOperand(I);
439ff0cc061SDimitry Andric         if (Op.getParent() != &MI) {
440ff0cc061SDimitry Andric           // Make sure to use correct addOperand / RemoveOperand / ChangeTo
441ff0cc061SDimitry Andric           // functions when replacing operands of a MachineInstr.
442ff0cc061SDimitry Andric           report("Instruction has operand with wrong parent set", &MI);
443ff0cc061SDimitry Andric         }
444ff0cc061SDimitry Andric 
445ff0cc061SDimitry Andric         visitMachineOperand(&Op, I);
446ff0cc061SDimitry Andric       }
447ff0cc061SDimitry Andric 
4487d523365SDimitry Andric       visitMachineInstrAfter(&*MBBI);
449139f7f9bSDimitry Andric 
450139f7f9bSDimitry Andric       // Was this the last bundled instruction?
451139f7f9bSDimitry Andric       InBundle = MBBI->isBundledWithSucc();
452f22ef01cSRoman Divacky     }
4537ae0e2c9SDimitry Andric     if (CurBundle)
4547ae0e2c9SDimitry Andric       visitMachineBundleAfter(CurBundle);
455139f7f9bSDimitry Andric     if (InBundle)
456139f7f9bSDimitry Andric       report("BundledSucc flag set on last instruction in block", &MFI->back());
4577d523365SDimitry Andric     visitMachineBasicBlockAfter(&*MFI);
458f22ef01cSRoman Divacky   }
459f22ef01cSRoman Divacky   visitMachineFunctionAfter();
460f22ef01cSRoman Divacky 
461f22ef01cSRoman Divacky   // Clean up.
462f22ef01cSRoman Divacky   regsLive.clear();
463f22ef01cSRoman Divacky   regsDefined.clear();
464f22ef01cSRoman Divacky   regsDead.clear();
465f22ef01cSRoman Divacky   regsKilled.clear();
466dff0c46cSDimitry Andric   regMasks.clear();
467f22ef01cSRoman Divacky   MBBInfoMap.clear();
468f22ef01cSRoman Divacky 
4693ca95b02SDimitry Andric   return foundErrors;
470f22ef01cSRoman Divacky }
471f22ef01cSRoman Divacky 
report(const char * msg,const MachineFunction * MF)472f22ef01cSRoman Divacky void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
473f22ef01cSRoman Divacky   assert(MF);
474ff0cc061SDimitry Andric   errs() << '\n';
4752754fe60SDimitry Andric   if (!foundErrors++) {
4762754fe60SDimitry Andric     if (Banner)
477ff0cc061SDimitry Andric       errs() << "# " << Banner << '\n';
4787d523365SDimitry Andric     if (LiveInts != nullptr)
4797d523365SDimitry Andric       LiveInts->print(errs());
4807d523365SDimitry Andric     else
481ff0cc061SDimitry Andric       MF->print(errs(), Indexes);
4822754fe60SDimitry Andric   }
483ff0cc061SDimitry Andric   errs() << "*** Bad machine code: " << msg << " ***\n"
4843861d79fSDimitry Andric       << "- function:    " << MF->getName() << "\n";
485f22ef01cSRoman Divacky }
486f22ef01cSRoman Divacky 
report(const char * msg,const MachineBasicBlock * MBB)487f22ef01cSRoman Divacky void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
488f22ef01cSRoman Divacky   assert(MBB);
489f22ef01cSRoman Divacky   report(msg, MBB->getParent());
4902cab237bSDimitry Andric   errs() << "- basic block: " << printMBBReference(*MBB) << ' '
4912cab237bSDimitry Andric          << MBB->getName() << " (" << (const void *)MBB << ')';
4922754fe60SDimitry Andric   if (Indexes)
493ff0cc061SDimitry Andric     errs() << " [" << Indexes->getMBBStartIdx(MBB)
4942754fe60SDimitry Andric         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
495ff0cc061SDimitry Andric   errs() << '\n';
496f22ef01cSRoman Divacky }
497f22ef01cSRoman Divacky 
report(const char * msg,const MachineInstr * MI)498f22ef01cSRoman Divacky void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
499f22ef01cSRoman Divacky   assert(MI);
500f22ef01cSRoman Divacky   report(msg, MI->getParent());
501ff0cc061SDimitry Andric   errs() << "- instruction: ";
5023ca95b02SDimitry Andric   if (Indexes && Indexes->hasIndex(*MI))
5033ca95b02SDimitry Andric     errs() << Indexes->getInstructionIndex(*MI) << '\t';
5047d523365SDimitry Andric   MI->print(errs(), /*SkipOpers=*/true);
505f22ef01cSRoman Divacky }
506f22ef01cSRoman Divacky 
report(const char * msg,const MachineOperand * MO,unsigned MONum,LLT MOVRegType)5074ba319b5SDimitry Andric void MachineVerifier::report(const char *msg, const MachineOperand *MO,
5084ba319b5SDimitry Andric                              unsigned MONum, LLT MOVRegType) {
509f22ef01cSRoman Divacky   assert(MO);
510f22ef01cSRoman Divacky   report(msg, MO->getParent());
511ff0cc061SDimitry Andric   errs() << "- operand " << MONum << ":   ";
5124ba319b5SDimitry Andric   MO->print(errs(), MOVRegType, TRI);
513ff0cc061SDimitry Andric   errs() << "\n";
514f22ef01cSRoman Divacky }
515f22ef01cSRoman Divacky 
report_context(SlotIndex Pos) const5163ca95b02SDimitry Andric void MachineVerifier::report_context(SlotIndex Pos) const {
5173ca95b02SDimitry Andric   errs() << "- at:          " << Pos << '\n';
5183ca95b02SDimitry Andric }
5193ca95b02SDimitry Andric 
report_context(const LiveInterval & LI) const5207d523365SDimitry Andric void MachineVerifier::report_context(const LiveInterval &LI) const {
521ff0cc061SDimitry Andric   errs() << "- interval:    " << LI << '\n';
5227ae0e2c9SDimitry Andric }
5237ae0e2c9SDimitry Andric 
report_context(const LiveRange & LR,unsigned VRegUnit,LaneBitmask LaneMask) const524d88c1a5aSDimitry Andric void MachineVerifier::report_context(const LiveRange &LR, unsigned VRegUnit,
5257d523365SDimitry Andric                                      LaneBitmask LaneMask) const {
5263ca95b02SDimitry Andric   report_context_liverange(LR);
527d88c1a5aSDimitry Andric   report_context_vreg_regunit(VRegUnit);
528d88c1a5aSDimitry Andric   if (LaneMask.any())
5293ca95b02SDimitry Andric     report_context_lanemask(LaneMask);
530f785676fSDimitry Andric }
531f785676fSDimitry Andric 
report_context(const LiveRange::Segment & S) const5327d523365SDimitry Andric void MachineVerifier::report_context(const LiveRange::Segment &S) const {
5337d523365SDimitry Andric   errs() << "- segment:     " << S << '\n';
5347d523365SDimitry Andric }
5357d523365SDimitry Andric 
report_context(const VNInfo & VNI) const5367d523365SDimitry Andric void MachineVerifier::report_context(const VNInfo &VNI) const {
5377d523365SDimitry Andric   errs() << "- ValNo:       " << VNI.id << " (def " << VNI.def << ")\n";
5387ae0e2c9SDimitry Andric }
5397ae0e2c9SDimitry Andric 
report_context_liverange(const LiveRange & LR) const5403ca95b02SDimitry Andric void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
5413ca95b02SDimitry Andric   errs() << "- liverange:   " << LR << '\n';
5423ca95b02SDimitry Andric }
5433ca95b02SDimitry Andric 
report_context(MCPhysReg PReg) const544*b5893f02SDimitry Andric void MachineVerifier::report_context(MCPhysReg PReg) const {
545*b5893f02SDimitry Andric   errs() << "- p. register: " << printReg(PReg, TRI) << '\n';
546*b5893f02SDimitry Andric }
547*b5893f02SDimitry Andric 
report_context_vreg(unsigned VReg) const5483ca95b02SDimitry Andric void MachineVerifier::report_context_vreg(unsigned VReg) const {
5492cab237bSDimitry Andric   errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
5503ca95b02SDimitry Andric }
5513ca95b02SDimitry Andric 
report_context_vreg_regunit(unsigned VRegOrUnit) const5523ca95b02SDimitry Andric void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit) const {
5533ca95b02SDimitry Andric   if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit)) {
5543ca95b02SDimitry Andric     report_context_vreg(VRegOrUnit);
5553ca95b02SDimitry Andric   } else {
5562cab237bSDimitry Andric     errs() << "- regunit:     " << printRegUnit(VRegOrUnit, TRI) << '\n';
5573ca95b02SDimitry Andric   }
5583ca95b02SDimitry Andric }
5593ca95b02SDimitry Andric 
report_context_lanemask(LaneBitmask LaneMask) const5603ca95b02SDimitry Andric void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
5613ca95b02SDimitry Andric   errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
5623ca95b02SDimitry Andric }
5633ca95b02SDimitry Andric 
markReachable(const MachineBasicBlock * MBB)564f22ef01cSRoman Divacky void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
565f22ef01cSRoman Divacky   BBInfo &MInfo = MBBInfoMap[MBB];
566f22ef01cSRoman Divacky   if (!MInfo.reachable) {
567f22ef01cSRoman Divacky     MInfo.reachable = true;
568f22ef01cSRoman Divacky     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
569f22ef01cSRoman Divacky            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
570f22ef01cSRoman Divacky       markReachable(*SuI);
571f22ef01cSRoman Divacky   }
572f22ef01cSRoman Divacky }
573f22ef01cSRoman Divacky 
visitMachineFunctionBefore()574f22ef01cSRoman Divacky void MachineVerifier::visitMachineFunctionBefore() {
5752754fe60SDimitry Andric   lastIndex = SlotIndex();
5760f5676f4SDimitry Andric   regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
5770f5676f4SDimitry Andric                                            : TRI->getReservedRegs(*MF);
578f22ef01cSRoman Divacky 
5797a7e6055SDimitry Andric   if (!MF->empty())
580f22ef01cSRoman Divacky     markReachable(&MF->front());
5813861d79fSDimitry Andric 
5823861d79fSDimitry Andric   // Build a set of the basic blocks in the function.
5833861d79fSDimitry Andric   FunctionBlocks.clear();
58491bc56edSDimitry Andric   for (const auto &MBB : *MF) {
58591bc56edSDimitry Andric     FunctionBlocks.insert(&MBB);
58691bc56edSDimitry Andric     BBInfo &MInfo = MBBInfoMap[&MBB];
5873861d79fSDimitry Andric 
58891bc56edSDimitry Andric     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
58991bc56edSDimitry Andric     if (MInfo.Preds.size() != MBB.pred_size())
59091bc56edSDimitry Andric       report("MBB has duplicate entries in its predecessor list.", &MBB);
5913861d79fSDimitry Andric 
59291bc56edSDimitry Andric     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
59391bc56edSDimitry Andric     if (MInfo.Succs.size() != MBB.succ_size())
59491bc56edSDimitry Andric       report("MBB has duplicate entries in its successor list.", &MBB);
5953861d79fSDimitry Andric   }
596284c1978SDimitry Andric 
597284c1978SDimitry Andric   // Check that the register use lists are sane.
598284c1978SDimitry Andric   MRI->verifyUseLists();
599f785676fSDimitry Andric 
6007a7e6055SDimitry Andric   if (!MF->empty())
601f785676fSDimitry Andric     verifyStackFrame();
602f22ef01cSRoman Divacky }
603f22ef01cSRoman Divacky 
604f22ef01cSRoman Divacky // Does iterator point to a and b as the first two elements?
matchPair(MachineBasicBlock::const_succ_iterator i,const MachineBasicBlock * a,const MachineBasicBlock * b)605f22ef01cSRoman Divacky static bool matchPair(MachineBasicBlock::const_succ_iterator i,
606f22ef01cSRoman Divacky                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
607f22ef01cSRoman Divacky   if (*i == a)
608f22ef01cSRoman Divacky     return *++i == b;
609f22ef01cSRoman Divacky   if (*i == b)
610f22ef01cSRoman Divacky     return *++i == a;
611f22ef01cSRoman Divacky   return false;
612f22ef01cSRoman Divacky }
613f22ef01cSRoman Divacky 
614f22ef01cSRoman Divacky void
visitMachineBasicBlockBefore(const MachineBasicBlock * MBB)615f22ef01cSRoman Divacky MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
61691bc56edSDimitry Andric   FirstTerminator = nullptr;
617*b5893f02SDimitry Andric   FirstNonPHI = nullptr;
6186122f3e6SDimitry Andric 
619d88c1a5aSDimitry Andric   if (!MF->getProperties().hasProperty(
62095ec533aSDimitry Andric       MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
621dff0c46cSDimitry Andric     // If this block has allocatable physical registers live-in, check that
622dff0c46cSDimitry Andric     // it is an entry block or landing pad.
6237d523365SDimitry Andric     for (const auto &LI : MBB->liveins()) {
6247d523365SDimitry Andric       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
6253ca95b02SDimitry Andric           MBB->getIterator() != MBB->getParent()->begin()) {
6267a7e6055SDimitry Andric         report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
627*b5893f02SDimitry Andric         report_context(LI.PhysReg);
628dff0c46cSDimitry Andric       }
629dff0c46cSDimitry Andric     }
630dff0c46cSDimitry Andric   }
631dff0c46cSDimitry Andric 
6322754fe60SDimitry Andric   // Count the number of landing pad successors.
6332754fe60SDimitry Andric   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
6342754fe60SDimitry Andric   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
6352754fe60SDimitry Andric        E = MBB->succ_end(); I != E; ++I) {
6367d523365SDimitry Andric     if ((*I)->isEHPad())
6372754fe60SDimitry Andric       LandingPadSuccs.insert(*I);
6383861d79fSDimitry Andric     if (!FunctionBlocks.count(*I))
6393861d79fSDimitry Andric       report("MBB has successor that isn't part of the function.", MBB);
6403861d79fSDimitry Andric     if (!MBBInfoMap[*I].Preds.count(MBB)) {
6413861d79fSDimitry Andric       report("Inconsistent CFG", MBB);
6422cab237bSDimitry Andric       errs() << "MBB is not in the predecessor list of the successor "
6432cab237bSDimitry Andric              << printMBBReference(*(*I)) << ".\n";
6443861d79fSDimitry Andric     }
6453861d79fSDimitry Andric   }
6463861d79fSDimitry Andric 
6473861d79fSDimitry Andric   // Check the predecessor list.
6483861d79fSDimitry Andric   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
6493861d79fSDimitry Andric        E = MBB->pred_end(); I != E; ++I) {
6503861d79fSDimitry Andric     if (!FunctionBlocks.count(*I))
6513861d79fSDimitry Andric       report("MBB has predecessor that isn't part of the function.", MBB);
6523861d79fSDimitry Andric     if (!MBBInfoMap[*I].Succs.count(MBB)) {
6533861d79fSDimitry Andric       report("Inconsistent CFG", MBB);
6542cab237bSDimitry Andric       errs() << "MBB is not in the successor list of the predecessor "
6552cab237bSDimitry Andric              << printMBBReference(*(*I)) << ".\n";
6563861d79fSDimitry Andric     }
6572754fe60SDimitry Andric   }
658bd5abe19SDimitry Andric 
659bd5abe19SDimitry Andric   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
660bd5abe19SDimitry Andric   const BasicBlock *BB = MBB->getBasicBlock();
6612cab237bSDimitry Andric   const Function &F = MF->getFunction();
662bd5abe19SDimitry Andric   if (LandingPadSuccs.size() > 1 &&
663bd5abe19SDimitry Andric       !(AsmInfo &&
664bd5abe19SDimitry Andric         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
6657d523365SDimitry Andric         BB && isa<SwitchInst>(BB->getTerminator())) &&
6664ba319b5SDimitry Andric       !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
6672754fe60SDimitry Andric     report("MBB has more than one landing pad successor", MBB);
6682754fe60SDimitry Andric 
669f22ef01cSRoman Divacky   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
67091bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
671f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
6723ca95b02SDimitry Andric   if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
6733ca95b02SDimitry Andric                           Cond)) {
674f22ef01cSRoman Divacky     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
675f22ef01cSRoman Divacky     // check whether its answers match up with reality.
676f22ef01cSRoman Divacky     if (!TBB && !FBB) {
677f22ef01cSRoman Divacky       // Block falls through to its successor.
6787d523365SDimitry Andric       MachineFunction::const_iterator MBBI = MBB->getIterator();
679f22ef01cSRoman Divacky       ++MBBI;
680f22ef01cSRoman Divacky       if (MBBI == MF->end()) {
681f22ef01cSRoman Divacky         // It's possible that the block legitimately ends with a noreturn
682f22ef01cSRoman Divacky         // call or an unreachable, in which case it won't actually fall
683f22ef01cSRoman Divacky         // out the bottom of the function.
6842754fe60SDimitry Andric       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
685f22ef01cSRoman Divacky         // It's possible that the block legitimately ends with a noreturn
686*b5893f02SDimitry Andric         // call or an unreachable, in which case it won't actually fall
687f22ef01cSRoman Divacky         // out of the block.
6882754fe60SDimitry Andric       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
689f22ef01cSRoman Divacky         report("MBB exits via unconditional fall-through but doesn't have "
690f22ef01cSRoman Divacky                "exactly one CFG successor!", MBB);
6917d523365SDimitry Andric       } else if (!MBB->isSuccessor(&*MBBI)) {
692f22ef01cSRoman Divacky         report("MBB exits via unconditional fall-through but its successor "
693f22ef01cSRoman Divacky                "differs from its CFG successor!", MBB);
694f22ef01cSRoman Divacky       }
69591bc56edSDimitry Andric       if (!MBB->empty() && MBB->back().isBarrier() &&
6963ca95b02SDimitry Andric           !TII->isPredicated(MBB->back())) {
697f22ef01cSRoman Divacky         report("MBB exits via unconditional fall-through but ends with a "
698f22ef01cSRoman Divacky                "barrier instruction!", MBB);
699f22ef01cSRoman Divacky       }
700f22ef01cSRoman Divacky       if (!Cond.empty()) {
701f22ef01cSRoman Divacky         report("MBB exits via unconditional fall-through but has a condition!",
702f22ef01cSRoman Divacky                MBB);
703f22ef01cSRoman Divacky       }
704f22ef01cSRoman Divacky     } else if (TBB && !FBB && Cond.empty()) {
705f22ef01cSRoman Divacky       // Block unconditionally branches somewhere.
70639d628a0SDimitry Andric       // If the block has exactly one successor, that happens to be a
70739d628a0SDimitry Andric       // landingpad, accept it as valid control flow.
70839d628a0SDimitry Andric       if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
70939d628a0SDimitry Andric           (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
71039d628a0SDimitry Andric            *MBB->succ_begin() != *LandingPadSuccs.begin())) {
711f22ef01cSRoman Divacky         report("MBB exits via unconditional branch but doesn't have "
712f22ef01cSRoman Divacky                "exactly one CFG successor!", MBB);
7132754fe60SDimitry Andric       } else if (!MBB->isSuccessor(TBB)) {
714f22ef01cSRoman Divacky         report("MBB exits via unconditional branch but the CFG "
715f22ef01cSRoman Divacky                "successor doesn't match the actual successor!", MBB);
716f22ef01cSRoman Divacky       }
717f22ef01cSRoman Divacky       if (MBB->empty()) {
718f22ef01cSRoman Divacky         report("MBB exits via unconditional branch but doesn't contain "
719f22ef01cSRoman Divacky                "any instructions!", MBB);
72091bc56edSDimitry Andric       } else if (!MBB->back().isBarrier()) {
721f22ef01cSRoman Divacky         report("MBB exits via unconditional branch but doesn't end with a "
722f22ef01cSRoman Divacky                "barrier instruction!", MBB);
72391bc56edSDimitry Andric       } else if (!MBB->back().isTerminator()) {
724f22ef01cSRoman Divacky         report("MBB exits via unconditional branch but the branch isn't a "
725f22ef01cSRoman Divacky                "terminator instruction!", MBB);
726f22ef01cSRoman Divacky       }
727f22ef01cSRoman Divacky     } else if (TBB && !FBB && !Cond.empty()) {
728f22ef01cSRoman Divacky       // Block conditionally branches somewhere, otherwise falls through.
7297d523365SDimitry Andric       MachineFunction::const_iterator MBBI = MBB->getIterator();
730f22ef01cSRoman Divacky       ++MBBI;
731f22ef01cSRoman Divacky       if (MBBI == MF->end()) {
732f22ef01cSRoman Divacky         report("MBB conditionally falls through out of function!", MBB);
733139f7f9bSDimitry Andric       } else if (MBB->succ_size() == 1) {
7343861d79fSDimitry Andric         // A conditional branch with only one successor is weird, but allowed.
7353861d79fSDimitry Andric         if (&*MBBI != TBB)
7363861d79fSDimitry Andric           report("MBB exits via conditional branch/fall-through but only has "
7373861d79fSDimitry Andric                  "one CFG successor!", MBB);
7383861d79fSDimitry Andric         else if (TBB != *MBB->succ_begin())
7393861d79fSDimitry Andric           report("MBB exits via conditional branch/fall-through but the CFG "
7403861d79fSDimitry Andric                  "successor don't match the actual successor!", MBB);
7413861d79fSDimitry Andric       } else if (MBB->succ_size() != 2) {
742f22ef01cSRoman Divacky         report("MBB exits via conditional branch/fall-through but doesn't have "
743f22ef01cSRoman Divacky                "exactly two CFG successors!", MBB);
7447d523365SDimitry Andric       } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
745f22ef01cSRoman Divacky         report("MBB exits via conditional branch/fall-through but the CFG "
746f22ef01cSRoman Divacky                "successors don't match the actual successors!", MBB);
747f22ef01cSRoman Divacky       }
748f22ef01cSRoman Divacky       if (MBB->empty()) {
749f22ef01cSRoman Divacky         report("MBB exits via conditional branch/fall-through but doesn't "
750f22ef01cSRoman Divacky                "contain any instructions!", MBB);
75191bc56edSDimitry Andric       } else if (MBB->back().isBarrier()) {
752f22ef01cSRoman Divacky         report("MBB exits via conditional branch/fall-through but ends with a "
753f22ef01cSRoman Divacky                "barrier instruction!", MBB);
75491bc56edSDimitry Andric       } else if (!MBB->back().isTerminator()) {
755f22ef01cSRoman Divacky         report("MBB exits via conditional branch/fall-through but the branch "
756f22ef01cSRoman Divacky                "isn't a terminator instruction!", MBB);
757f22ef01cSRoman Divacky       }
758f22ef01cSRoman Divacky     } else if (TBB && FBB) {
759f22ef01cSRoman Divacky       // Block conditionally branches somewhere, otherwise branches
760f22ef01cSRoman Divacky       // somewhere else.
7613861d79fSDimitry Andric       if (MBB->succ_size() == 1) {
7623861d79fSDimitry Andric         // A conditional branch with only one successor is weird, but allowed.
7633861d79fSDimitry Andric         if (FBB != TBB)
7643861d79fSDimitry Andric           report("MBB exits via conditional branch/branch through but only has "
7653861d79fSDimitry Andric                  "one CFG successor!", MBB);
7663861d79fSDimitry Andric         else if (TBB != *MBB->succ_begin())
7673861d79fSDimitry Andric           report("MBB exits via conditional branch/branch through but the CFG "
7683861d79fSDimitry Andric                  "successor don't match the actual successor!", MBB);
7693861d79fSDimitry Andric       } else if (MBB->succ_size() != 2) {
770f22ef01cSRoman Divacky         report("MBB exits via conditional branch/branch but doesn't have "
771f22ef01cSRoman Divacky                "exactly two CFG successors!", MBB);
772f22ef01cSRoman Divacky       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
773f22ef01cSRoman Divacky         report("MBB exits via conditional branch/branch but the CFG "
774f22ef01cSRoman Divacky                "successors don't match the actual successors!", MBB);
775f22ef01cSRoman Divacky       }
776f22ef01cSRoman Divacky       if (MBB->empty()) {
777f22ef01cSRoman Divacky         report("MBB exits via conditional branch/branch but doesn't "
778f22ef01cSRoman Divacky                "contain any instructions!", MBB);
77991bc56edSDimitry Andric       } else if (!MBB->back().isBarrier()) {
780f22ef01cSRoman Divacky         report("MBB exits via conditional branch/branch but doesn't end with a "
781f22ef01cSRoman Divacky                "barrier instruction!", MBB);
78291bc56edSDimitry Andric       } else if (!MBB->back().isTerminator()) {
783f22ef01cSRoman Divacky         report("MBB exits via conditional branch/branch but the branch "
784f22ef01cSRoman Divacky                "isn't a terminator instruction!", MBB);
785f22ef01cSRoman Divacky       }
786f22ef01cSRoman Divacky       if (Cond.empty()) {
787*b5893f02SDimitry Andric         report("MBB exits via conditional branch/branch but there's no "
788f22ef01cSRoman Divacky                "condition!", MBB);
789f22ef01cSRoman Divacky       }
790f22ef01cSRoman Divacky     } else {
791f22ef01cSRoman Divacky       report("AnalyzeBranch returned invalid data!", MBB);
792f22ef01cSRoman Divacky     }
793f22ef01cSRoman Divacky   }
794f22ef01cSRoman Divacky 
795f22ef01cSRoman Divacky   regsLive.clear();
79695ec533aSDimitry Andric   if (MRI->tracksLiveness()) {
7977d523365SDimitry Andric     for (const auto &LI : MBB->liveins()) {
7987d523365SDimitry Andric       if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
799f22ef01cSRoman Divacky         report("MBB live-in list contains non-physical register", MBB);
800f22ef01cSRoman Divacky         continue;
801f22ef01cSRoman Divacky       }
8027d523365SDimitry Andric       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
803f785676fSDimitry Andric            SubRegs.isValid(); ++SubRegs)
8047ae0e2c9SDimitry Andric         regsLive.insert(*SubRegs);
805f22ef01cSRoman Divacky     }
80695ec533aSDimitry Andric   }
807f22ef01cSRoman Divacky 
808d88c1a5aSDimitry Andric   const MachineFrameInfo &MFI = MF->getFrameInfo();
809d88c1a5aSDimitry Andric   BitVector PR = MFI.getPristineRegs(*MF);
81060ff8e32SDimitry Andric   for (unsigned I : PR.set_bits()) {
811f785676fSDimitry Andric     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
812f785676fSDimitry Andric          SubRegs.isValid(); ++SubRegs)
8137ae0e2c9SDimitry Andric       regsLive.insert(*SubRegs);
814f22ef01cSRoman Divacky   }
815f22ef01cSRoman Divacky 
816f22ef01cSRoman Divacky   regsKilled.clear();
817f22ef01cSRoman Divacky   regsDefined.clear();
8182754fe60SDimitry Andric 
8192754fe60SDimitry Andric   if (Indexes)
8202754fe60SDimitry Andric     lastIndex = Indexes->getMBBStartIdx(MBB);
821f22ef01cSRoman Divacky }
822f22ef01cSRoman Divacky 
8237ae0e2c9SDimitry Andric // This function gets called for all bundle headers, including normal
8247ae0e2c9SDimitry Andric // stand-alone unbundled instructions.
visitMachineBundleBefore(const MachineInstr * MI)8257ae0e2c9SDimitry Andric void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
8263ca95b02SDimitry Andric   if (Indexes && Indexes->hasIndex(*MI)) {
8273ca95b02SDimitry Andric     SlotIndex idx = Indexes->getInstructionIndex(*MI);
8287ae0e2c9SDimitry Andric     if (!(idx > lastIndex)) {
8297ae0e2c9SDimitry Andric       report("Instruction index out of order", MI);
830ff0cc061SDimitry Andric       errs() << "Last instruction was at " << lastIndex << '\n';
8317ae0e2c9SDimitry Andric     }
8327ae0e2c9SDimitry Andric     lastIndex = idx;
8337ae0e2c9SDimitry Andric   }
8347ae0e2c9SDimitry Andric 
8357ae0e2c9SDimitry Andric   // Ensure non-terminators don't follow terminators.
8367ae0e2c9SDimitry Andric   // Ignore predicated terminators formed by if conversion.
8377ae0e2c9SDimitry Andric   // FIXME: If conversion shouldn't need to violate this rule.
8383ca95b02SDimitry Andric   if (MI->isTerminator() && !TII->isPredicated(*MI)) {
8397ae0e2c9SDimitry Andric     if (!FirstTerminator)
8407ae0e2c9SDimitry Andric       FirstTerminator = MI;
8417ae0e2c9SDimitry Andric   } else if (FirstTerminator) {
8427ae0e2c9SDimitry Andric     report("Non-terminator instruction after the first terminator", MI);
843ff0cc061SDimitry Andric     errs() << "First terminator was:\t" << *FirstTerminator;
8447ae0e2c9SDimitry Andric   }
8457ae0e2c9SDimitry Andric }
8467ae0e2c9SDimitry Andric 
8473861d79fSDimitry Andric // The operands on an INLINEASM instruction must follow a template.
8483861d79fSDimitry Andric // Verify that the flag operands make sense.
verifyInlineAsm(const MachineInstr * MI)8493861d79fSDimitry Andric void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
8503861d79fSDimitry Andric   // The first two operands on INLINEASM are the asm string and global flags.
8513861d79fSDimitry Andric   if (MI->getNumOperands() < 2) {
8523861d79fSDimitry Andric     report("Too few operands on inline asm", MI);
8533861d79fSDimitry Andric     return;
8543861d79fSDimitry Andric   }
8553861d79fSDimitry Andric   if (!MI->getOperand(0).isSymbol())
8563861d79fSDimitry Andric     report("Asm string must be an external symbol", MI);
8573861d79fSDimitry Andric   if (!MI->getOperand(1).isImm())
8583861d79fSDimitry Andric     report("Asm flags must be an immediate", MI);
8593861d79fSDimitry Andric   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
8603ca95b02SDimitry Andric   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
8613ca95b02SDimitry Andric   // and Extra_IsConvergent = 32.
8623ca95b02SDimitry Andric   if (!isUInt<6>(MI->getOperand(1).getImm()))
8633861d79fSDimitry Andric     report("Unknown asm flags", &MI->getOperand(1), 1);
8643861d79fSDimitry Andric 
865ff0cc061SDimitry Andric   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
8663861d79fSDimitry Andric 
8673861d79fSDimitry Andric   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
8683861d79fSDimitry Andric   unsigned NumOps;
8693861d79fSDimitry Andric   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
8703861d79fSDimitry Andric     const MachineOperand &MO = MI->getOperand(OpNo);
8713861d79fSDimitry Andric     // There may be implicit ops after the fixed operands.
8723861d79fSDimitry Andric     if (!MO.isImm())
8733861d79fSDimitry Andric       break;
8743861d79fSDimitry Andric     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
8753861d79fSDimitry Andric   }
8763861d79fSDimitry Andric 
8773861d79fSDimitry Andric   if (OpNo > MI->getNumOperands())
8783861d79fSDimitry Andric     report("Missing operands in last group", MI);
8793861d79fSDimitry Andric 
8803861d79fSDimitry Andric   // An optional MDNode follows the groups.
8813861d79fSDimitry Andric   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
8823861d79fSDimitry Andric     ++OpNo;
8833861d79fSDimitry Andric 
8843861d79fSDimitry Andric   // All trailing operands must be implicit registers.
8853861d79fSDimitry Andric   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
8863861d79fSDimitry Andric     const MachineOperand &MO = MI->getOperand(OpNo);
8873861d79fSDimitry Andric     if (!MO.isReg() || !MO.isImplicit())
8883861d79fSDimitry Andric       report("Expected implicit register after groups", &MO, OpNo);
8893861d79fSDimitry Andric   }
8903861d79fSDimitry Andric }
8913861d79fSDimitry Andric 
visitMachineInstrBefore(const MachineInstr * MI)892f22ef01cSRoman Divacky void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
89317a519f9SDimitry Andric   const MCInstrDesc &MCID = MI->getDesc();
89417a519f9SDimitry Andric   if (MI->getNumOperands() < MCID.getNumOperands()) {
895f22ef01cSRoman Divacky     report("Too few operands", MI);
896ff0cc061SDimitry Andric     errs() << MCID.getNumOperands() << " operands expected, but "
897f785676fSDimitry Andric            << MI->getNumOperands() << " given.\n";
898f22ef01cSRoman Divacky   }
899f22ef01cSRoman Divacky 
900*b5893f02SDimitry Andric   if (MI->isPHI()) {
901*b5893f02SDimitry Andric     if (MF->getProperties().hasProperty(
902d88c1a5aSDimitry Andric             MachineFunctionProperties::Property::NoPHIs))
903d88c1a5aSDimitry Andric       report("Found PHI instruction with NoPHIs property set", MI);
904d88c1a5aSDimitry Andric 
905*b5893f02SDimitry Andric     if (FirstNonPHI)
906*b5893f02SDimitry Andric       report("Found PHI instruction after non-PHI", MI);
907*b5893f02SDimitry Andric   } else if (FirstNonPHI == nullptr)
908*b5893f02SDimitry Andric     FirstNonPHI = MI;
909*b5893f02SDimitry Andric 
9103861d79fSDimitry Andric   // Check the tied operands.
9113861d79fSDimitry Andric   if (MI->isInlineAsm())
9123861d79fSDimitry Andric     verifyInlineAsm(MI);
9133861d79fSDimitry Andric 
914f22ef01cSRoman Divacky   // Check the MachineMemOperands for basic consistency.
915f22ef01cSRoman Divacky   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
9164ba319b5SDimitry Andric                                   E = MI->memoperands_end();
9174ba319b5SDimitry Andric        I != E; ++I) {
918dff0c46cSDimitry Andric     if ((*I)->isLoad() && !MI->mayLoad())
919f22ef01cSRoman Divacky       report("Missing mayLoad flag", MI);
920dff0c46cSDimitry Andric     if ((*I)->isStore() && !MI->mayStore())
921f22ef01cSRoman Divacky       report("Missing mayStore flag", MI);
922f22ef01cSRoman Divacky   }
923e580952dSDimitry Andric 
924e580952dSDimitry Andric   // Debug values must not have a slot index.
925dff0c46cSDimitry Andric   // Other instructions must have one, unless they are inside a bundle.
926e580952dSDimitry Andric   if (LiveInts) {
9273ca95b02SDimitry Andric     bool mapped = !LiveInts->isNotInMIMap(*MI);
9284ba319b5SDimitry Andric     if (MI->isDebugInstr()) {
929e580952dSDimitry Andric       if (mapped)
930e580952dSDimitry Andric         report("Debug instruction has a slot index", MI);
931dff0c46cSDimitry Andric     } else if (MI->isInsideBundle()) {
932dff0c46cSDimitry Andric       if (mapped)
933dff0c46cSDimitry Andric         report("Instruction inside bundle has a slot index", MI);
934e580952dSDimitry Andric     } else {
935e580952dSDimitry Andric       if (!mapped)
936e580952dSDimitry Andric         report("Missing slot index", MI);
937e580952dSDimitry Andric     }
938e580952dSDimitry Andric   }
939e580952dSDimitry Andric 
940d88c1a5aSDimitry Andric   if (isPreISelGenericOpcode(MCID.getOpcode())) {
941d88c1a5aSDimitry Andric     if (isFunctionSelected)
942d88c1a5aSDimitry Andric       report("Unexpected generic instruction in a Selected function", MI);
943d88c1a5aSDimitry Andric 
9444ba319b5SDimitry Andric     // Check types.
945d88c1a5aSDimitry Andric     SmallVector<LLT, 4> Types;
9464ba319b5SDimitry Andric     for (unsigned I = 0; I < MCID.getNumOperands(); ++I) {
9474ba319b5SDimitry Andric       if (!MCID.OpInfo[I].isGenericType())
948d88c1a5aSDimitry Andric         continue;
9494ba319b5SDimitry Andric       // Generic instructions specify type equality constraints between some of
9504ba319b5SDimitry Andric       // their operands. Make sure these are consistent.
9514ba319b5SDimitry Andric       size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex();
952d88c1a5aSDimitry Andric       Types.resize(std::max(TypeIdx + 1, Types.size()));
953d88c1a5aSDimitry Andric 
9544ba319b5SDimitry Andric       const MachineOperand *MO = &MI->getOperand(I);
9554ba319b5SDimitry Andric       LLT OpTy = MRI->getType(MO->getReg());
9564ba319b5SDimitry Andric       // Don't report a type mismatch if there is no actual mismatch, only a
9574ba319b5SDimitry Andric       // type missing, to reduce noise:
9584ba319b5SDimitry Andric       if (OpTy.isValid()) {
9594ba319b5SDimitry Andric         // Only the first valid type for a type index will be printed: don't
9604ba319b5SDimitry Andric         // overwrite it later so it's always clear which type was expected:
9614ba319b5SDimitry Andric         if (!Types[TypeIdx].isValid())
962d88c1a5aSDimitry Andric           Types[TypeIdx] = OpTy;
9634ba319b5SDimitry Andric         else if (Types[TypeIdx] != OpTy)
9644ba319b5SDimitry Andric           report("Type mismatch in generic instruction", MO, I, OpTy);
9654ba319b5SDimitry Andric       } else {
9664ba319b5SDimitry Andric         // Generic instructions must have types attached to their operands.
9674ba319b5SDimitry Andric         report("Generic instruction is missing a virtual register type", MO, I);
968d88c1a5aSDimitry Andric       }
969d88c1a5aSDimitry Andric     }
970d88c1a5aSDimitry Andric 
971d88c1a5aSDimitry Andric     // Generic opcodes must not have physical register operands.
9724ba319b5SDimitry Andric     for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
9734ba319b5SDimitry Andric       const MachineOperand *MO = &MI->getOperand(I);
9744ba319b5SDimitry Andric       if (MO->isReg() && TargetRegisterInfo::isPhysicalRegister(MO->getReg()))
9754ba319b5SDimitry Andric         report("Generic instruction cannot have physical register", MO, I);
976d88c1a5aSDimitry Andric     }
977d88c1a5aSDimitry Andric   }
978d88c1a5aSDimitry Andric 
9796122f3e6SDimitry Andric   StringRef ErrorInfo;
9803ca95b02SDimitry Andric   if (!TII->verifyInstruction(*MI, ErrorInfo))
9816122f3e6SDimitry Andric     report(ErrorInfo.data(), MI);
9826d97bb29SDimitry Andric 
9836d97bb29SDimitry Andric   // Verify properties of various specific instruction types
9846d97bb29SDimitry Andric   switch(MI->getOpcode()) {
9856d97bb29SDimitry Andric   default:
9866d97bb29SDimitry Andric     break;
9876d97bb29SDimitry Andric   case TargetOpcode::G_LOAD:
9886d97bb29SDimitry Andric   case TargetOpcode::G_STORE:
9896d97bb29SDimitry Andric     // Generic loads and stores must have a single MachineMemOperand
9906d97bb29SDimitry Andric     // describing that access.
9916d97bb29SDimitry Andric     if (!MI->hasOneMemOperand())
9926d97bb29SDimitry Andric       report("Generic instruction accessing memory must have one mem operand",
9936d97bb29SDimitry Andric              MI);
9946d97bb29SDimitry Andric     break;
9952cab237bSDimitry Andric   case TargetOpcode::G_PHI: {
9962cab237bSDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
9972cab237bSDimitry Andric     if (!DstTy.isValid() ||
9982cab237bSDimitry Andric         !std::all_of(MI->operands_begin() + 1, MI->operands_end(),
9992cab237bSDimitry Andric                      [this, &DstTy](const MachineOperand &MO) {
10002cab237bSDimitry Andric                        if (!MO.isReg())
10012cab237bSDimitry Andric                          return true;
10022cab237bSDimitry Andric                        LLT Ty = MRI->getType(MO.getReg());
10032cab237bSDimitry Andric                        if (!Ty.isValid() || (Ty != DstTy))
10042cab237bSDimitry Andric                          return false;
10052cab237bSDimitry Andric                        return true;
10062cab237bSDimitry Andric                      }))
10072cab237bSDimitry Andric       report("Generic Instruction G_PHI has operands with incompatible/missing "
10082cab237bSDimitry Andric              "types",
10092cab237bSDimitry Andric              MI);
10102cab237bSDimitry Andric     break;
10112cab237bSDimitry Andric   }
10124ba319b5SDimitry Andric   case TargetOpcode::G_SEXT:
10134ba319b5SDimitry Andric   case TargetOpcode::G_ZEXT:
10144ba319b5SDimitry Andric   case TargetOpcode::G_ANYEXT:
10154ba319b5SDimitry Andric   case TargetOpcode::G_TRUNC:
10164ba319b5SDimitry Andric   case TargetOpcode::G_FPEXT:
10174ba319b5SDimitry Andric   case TargetOpcode::G_FPTRUNC: {
10184ba319b5SDimitry Andric     // Number of operands and presense of types is already checked (and
10194ba319b5SDimitry Andric     // reported in case of any issues), so no need to report them again. As
10204ba319b5SDimitry Andric     // we're trying to report as many issues as possible at once, however, the
10214ba319b5SDimitry Andric     // instructions aren't guaranteed to have the right number of operands or
10224ba319b5SDimitry Andric     // types attached to them at this point
10234ba319b5SDimitry Andric     assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
10244ba319b5SDimitry Andric     if (MI->getNumOperands() < MCID.getNumOperands())
10254ba319b5SDimitry Andric       break;
10264ba319b5SDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
10274ba319b5SDimitry Andric     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
10284ba319b5SDimitry Andric     if (!DstTy.isValid() || !SrcTy.isValid())
10294ba319b5SDimitry Andric       break;
10304ba319b5SDimitry Andric 
10314ba319b5SDimitry Andric     LLT DstElTy = DstTy.isVector() ? DstTy.getElementType() : DstTy;
10324ba319b5SDimitry Andric     LLT SrcElTy = SrcTy.isVector() ? SrcTy.getElementType() : SrcTy;
10334ba319b5SDimitry Andric     if (DstElTy.isPointer() || SrcElTy.isPointer())
10344ba319b5SDimitry Andric       report("Generic extend/truncate can not operate on pointers", MI);
10354ba319b5SDimitry Andric 
10364ba319b5SDimitry Andric     if (DstTy.isVector() != SrcTy.isVector()) {
10374ba319b5SDimitry Andric       report("Generic extend/truncate must be all-vector or all-scalar", MI);
10384ba319b5SDimitry Andric       // Generally we try to report as many issues as possible at once, but in
10394ba319b5SDimitry Andric       // this case it's not clear what should we be comparing the size of the
10404ba319b5SDimitry Andric       // scalar with: the size of the whole vector or its lane. Instead of
10414ba319b5SDimitry Andric       // making an arbitrary choice and emitting not so helpful message, let's
10424ba319b5SDimitry Andric       // avoid the extra noise and stop here.
10434ba319b5SDimitry Andric       break;
10444ba319b5SDimitry Andric     }
10454ba319b5SDimitry Andric     if (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements())
10464ba319b5SDimitry Andric       report("Generic vector extend/truncate must preserve number of lanes",
10474ba319b5SDimitry Andric              MI);
10484ba319b5SDimitry Andric     unsigned DstSize = DstElTy.getSizeInBits();
10494ba319b5SDimitry Andric     unsigned SrcSize = SrcElTy.getSizeInBits();
10504ba319b5SDimitry Andric     switch (MI->getOpcode()) {
10514ba319b5SDimitry Andric     default:
10524ba319b5SDimitry Andric       if (DstSize <= SrcSize)
10534ba319b5SDimitry Andric         report("Generic extend has destination type no larger than source", MI);
10544ba319b5SDimitry Andric       break;
10554ba319b5SDimitry Andric     case TargetOpcode::G_TRUNC:
10564ba319b5SDimitry Andric     case TargetOpcode::G_FPTRUNC:
10574ba319b5SDimitry Andric       if (DstSize >= SrcSize)
10584ba319b5SDimitry Andric         report("Generic truncate has destination type no smaller than source",
10594ba319b5SDimitry Andric                MI);
10604ba319b5SDimitry Andric       break;
10614ba319b5SDimitry Andric     }
10624ba319b5SDimitry Andric     break;
10634ba319b5SDimitry Andric   }
1064*b5893f02SDimitry Andric   case TargetOpcode::G_MERGE_VALUES: {
1065*b5893f02SDimitry Andric     // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1066*b5893f02SDimitry Andric     // e.g. s2N = MERGE sN, sN
1067*b5893f02SDimitry Andric     // Merging multiple scalars into a vector is not allowed, should use
1068*b5893f02SDimitry Andric     // G_BUILD_VECTOR for that.
1069*b5893f02SDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1070*b5893f02SDimitry Andric     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1071*b5893f02SDimitry Andric     if (DstTy.isVector() || SrcTy.isVector())
1072*b5893f02SDimitry Andric       report("G_MERGE_VALUES cannot operate on vectors", MI);
1073*b5893f02SDimitry Andric     break;
1074*b5893f02SDimitry Andric   }
1075*b5893f02SDimitry Andric   case TargetOpcode::G_UNMERGE_VALUES: {
1076*b5893f02SDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1077*b5893f02SDimitry Andric     LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg());
1078*b5893f02SDimitry Andric     // For now G_UNMERGE can split vectors.
1079*b5893f02SDimitry Andric     for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) {
1080*b5893f02SDimitry Andric       if (MRI->getType(MI->getOperand(i).getReg()) != DstTy)
1081*b5893f02SDimitry Andric         report("G_UNMERGE_VALUES destination types do not match", MI);
1082*b5893f02SDimitry Andric     }
1083*b5893f02SDimitry Andric     if (SrcTy.getSizeInBits() !=
1084*b5893f02SDimitry Andric         (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) {
1085*b5893f02SDimitry Andric       report("G_UNMERGE_VALUES source operand does not cover dest operands",
1086*b5893f02SDimitry Andric              MI);
1087*b5893f02SDimitry Andric     }
1088*b5893f02SDimitry Andric     break;
1089*b5893f02SDimitry Andric   }
1090*b5893f02SDimitry Andric   case TargetOpcode::G_BUILD_VECTOR: {
1091*b5893f02SDimitry Andric     // Source types must be scalars, dest type a vector. Total size of scalars
1092*b5893f02SDimitry Andric     // must match the dest vector size.
1093*b5893f02SDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1094*b5893f02SDimitry Andric     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1095*b5893f02SDimitry Andric     if (!DstTy.isVector() || SrcEltTy.isVector())
1096*b5893f02SDimitry Andric       report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1097*b5893f02SDimitry Andric     for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
1098*b5893f02SDimitry Andric       if (MRI->getType(MI->getOperand(1).getReg()) !=
1099*b5893f02SDimitry Andric           MRI->getType(MI->getOperand(i).getReg()))
1100*b5893f02SDimitry Andric         report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
1101*b5893f02SDimitry Andric     }
1102*b5893f02SDimitry Andric     if (DstTy.getSizeInBits() !=
1103*b5893f02SDimitry Andric         SrcEltTy.getSizeInBits() * (MI->getNumOperands() - 1))
1104*b5893f02SDimitry Andric       report("G_BUILD_VECTOR src operands total size don't match dest "
1105*b5893f02SDimitry Andric              "size.",
1106*b5893f02SDimitry Andric              MI);
1107*b5893f02SDimitry Andric     break;
1108*b5893f02SDimitry Andric   }
1109*b5893f02SDimitry Andric   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1110*b5893f02SDimitry Andric     // Source types must be scalars, dest type a vector. Scalar types must be
1111*b5893f02SDimitry Andric     // larger than the dest vector elt type, as this is a truncating operation.
1112*b5893f02SDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1113*b5893f02SDimitry Andric     LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1114*b5893f02SDimitry Andric     if (!DstTy.isVector() || SrcEltTy.isVector())
1115*b5893f02SDimitry Andric       report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1116*b5893f02SDimitry Andric              MI);
1117*b5893f02SDimitry Andric     for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
1118*b5893f02SDimitry Andric       if (MRI->getType(MI->getOperand(1).getReg()) !=
1119*b5893f02SDimitry Andric           MRI->getType(MI->getOperand(i).getReg()))
1120*b5893f02SDimitry Andric         report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1121*b5893f02SDimitry Andric                MI);
1122*b5893f02SDimitry Andric     }
1123*b5893f02SDimitry Andric     if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1124*b5893f02SDimitry Andric       report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1125*b5893f02SDimitry Andric              "dest elt type",
1126*b5893f02SDimitry Andric              MI);
1127*b5893f02SDimitry Andric     break;
1128*b5893f02SDimitry Andric   }
1129*b5893f02SDimitry Andric   case TargetOpcode::G_CONCAT_VECTORS: {
1130*b5893f02SDimitry Andric     // Source types should be vectors, and total size should match the dest
1131*b5893f02SDimitry Andric     // vector size.
1132*b5893f02SDimitry Andric     LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1133*b5893f02SDimitry Andric     LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1134*b5893f02SDimitry Andric     if (!DstTy.isVector() || !SrcTy.isVector())
1135*b5893f02SDimitry Andric       report("G_CONCAT_VECTOR requires vector source and destination operands",
1136*b5893f02SDimitry Andric              MI);
1137*b5893f02SDimitry Andric     for (unsigned i = 2; i < MI->getNumOperands(); ++i) {
1138*b5893f02SDimitry Andric       if (MRI->getType(MI->getOperand(1).getReg()) !=
1139*b5893f02SDimitry Andric           MRI->getType(MI->getOperand(i).getReg()))
1140*b5893f02SDimitry Andric         report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1141*b5893f02SDimitry Andric     }
1142*b5893f02SDimitry Andric     if (DstTy.getNumElements() !=
1143*b5893f02SDimitry Andric         SrcTy.getNumElements() * (MI->getNumOperands() - 1))
1144*b5893f02SDimitry Andric       report("G_CONCAT_VECTOR num dest and source elements should match", MI);
1145*b5893f02SDimitry Andric     break;
1146*b5893f02SDimitry Andric   }
11474ba319b5SDimitry Andric   case TargetOpcode::COPY: {
11484ba319b5SDimitry Andric     if (foundErrors)
11494ba319b5SDimitry Andric       break;
11504ba319b5SDimitry Andric     const MachineOperand &DstOp = MI->getOperand(0);
11514ba319b5SDimitry Andric     const MachineOperand &SrcOp = MI->getOperand(1);
11524ba319b5SDimitry Andric     LLT DstTy = MRI->getType(DstOp.getReg());
11534ba319b5SDimitry Andric     LLT SrcTy = MRI->getType(SrcOp.getReg());
11544ba319b5SDimitry Andric     if (SrcTy.isValid() && DstTy.isValid()) {
11554ba319b5SDimitry Andric       // If both types are valid, check that the types are the same.
11564ba319b5SDimitry Andric       if (SrcTy != DstTy) {
11574ba319b5SDimitry Andric         report("Copy Instruction is illegal with mismatching types", MI);
11584ba319b5SDimitry Andric         errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
11594ba319b5SDimitry Andric       }
11604ba319b5SDimitry Andric     }
11614ba319b5SDimitry Andric     if (SrcTy.isValid() || DstTy.isValid()) {
11624ba319b5SDimitry Andric       // If one of them have valid types, let's just check they have the same
11634ba319b5SDimitry Andric       // size.
11644ba319b5SDimitry Andric       unsigned SrcSize = TRI->getRegSizeInBits(SrcOp.getReg(), *MRI);
11654ba319b5SDimitry Andric       unsigned DstSize = TRI->getRegSizeInBits(DstOp.getReg(), *MRI);
11664ba319b5SDimitry Andric       assert(SrcSize && "Expecting size here");
11674ba319b5SDimitry Andric       assert(DstSize && "Expecting size here");
11684ba319b5SDimitry Andric       if (SrcSize != DstSize)
11694ba319b5SDimitry Andric         if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
11704ba319b5SDimitry Andric           report("Copy Instruction is illegal with mismatching sizes", MI);
11714ba319b5SDimitry Andric           errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
11724ba319b5SDimitry Andric                  << "\n";
11734ba319b5SDimitry Andric         }
11744ba319b5SDimitry Andric     }
11754ba319b5SDimitry Andric     break;
11764ba319b5SDimitry Andric   }
11776d97bb29SDimitry Andric   case TargetOpcode::STATEPOINT:
11786d97bb29SDimitry Andric     if (!MI->getOperand(StatepointOpers::IDPos).isImm() ||
11796d97bb29SDimitry Andric         !MI->getOperand(StatepointOpers::NBytesPos).isImm() ||
11806d97bb29SDimitry Andric         !MI->getOperand(StatepointOpers::NCallArgsPos).isImm())
11816d97bb29SDimitry Andric       report("meta operands to STATEPOINT not constant!", MI);
11826d97bb29SDimitry Andric     break;
11836d97bb29SDimitry Andric 
11846d97bb29SDimitry Andric     auto VerifyStackMapConstant = [&](unsigned Offset) {
11856d97bb29SDimitry Andric       if (!MI->getOperand(Offset).isImm() ||
11866d97bb29SDimitry Andric           MI->getOperand(Offset).getImm() != StackMaps::ConstantOp ||
11876d97bb29SDimitry Andric           !MI->getOperand(Offset + 1).isImm())
11886d97bb29SDimitry Andric         report("stack map constant to STATEPOINT not well formed!", MI);
11896d97bb29SDimitry Andric     };
11906d97bb29SDimitry Andric     const unsigned VarStart = StatepointOpers(MI).getVarIdx();
11916d97bb29SDimitry Andric     VerifyStackMapConstant(VarStart + StatepointOpers::CCOffset);
11926d97bb29SDimitry Andric     VerifyStackMapConstant(VarStart + StatepointOpers::FlagsOffset);
11936d97bb29SDimitry Andric     VerifyStackMapConstant(VarStart + StatepointOpers::NumDeoptOperandsOffset);
11946d97bb29SDimitry Andric 
11956d97bb29SDimitry Andric     // TODO: verify we have properly encoded deopt arguments
11966d97bb29SDimitry Andric   };
1197f22ef01cSRoman Divacky }
1198f22ef01cSRoman Divacky 
1199f22ef01cSRoman Divacky void
visitMachineOperand(const MachineOperand * MO,unsigned MONum)1200f22ef01cSRoman Divacky MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
1201f22ef01cSRoman Divacky   const MachineInstr *MI = MO->getParent();
120217a519f9SDimitry Andric   const MCInstrDesc &MCID = MI->getDesc();
12037d523365SDimitry Andric   unsigned NumDefs = MCID.getNumDefs();
12047d523365SDimitry Andric   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
12057d523365SDimitry Andric     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
1206f22ef01cSRoman Divacky 
120717a519f9SDimitry Andric   // The first MCID.NumDefs operands must be explicit register defines
12087d523365SDimitry Andric   if (MONum < NumDefs) {
12097ae0e2c9SDimitry Andric     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
1210f22ef01cSRoman Divacky     if (!MO->isReg())
1211f22ef01cSRoman Divacky       report("Explicit definition must be a register", MO, MONum);
12127ae0e2c9SDimitry Andric     else if (!MO->isDef() && !MCOI.isOptionalDef())
1213f22ef01cSRoman Divacky       report("Explicit definition marked as use", MO, MONum);
1214f22ef01cSRoman Divacky     else if (MO->isImplicit())
1215f22ef01cSRoman Divacky       report("Explicit definition marked as implicit", MO, MONum);
121617a519f9SDimitry Andric   } else if (MONum < MCID.getNumOperands()) {
12177ae0e2c9SDimitry Andric     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
12182754fe60SDimitry Andric     // Don't check if it's the last operand in a variadic instruction. See,
12192754fe60SDimitry Andric     // e.g., LDM_RET in the arm back end.
122017a519f9SDimitry Andric     if (MO->isReg() &&
1221dff0c46cSDimitry Andric         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
122217a519f9SDimitry Andric       if (MO->isDef() && !MCOI.isOptionalDef())
1223f22ef01cSRoman Divacky         report("Explicit operand marked as def", MO, MONum);
1224f22ef01cSRoman Divacky       if (MO->isImplicit())
1225f22ef01cSRoman Divacky         report("Explicit operand marked as implicit", MO, MONum);
1226f22ef01cSRoman Divacky     }
12273861d79fSDimitry Andric 
12283861d79fSDimitry Andric     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
12293861d79fSDimitry Andric     if (TiedTo != -1) {
12303861d79fSDimitry Andric       if (!MO->isReg())
12313861d79fSDimitry Andric         report("Tied use must be a register", MO, MONum);
12323861d79fSDimitry Andric       else if (!MO->isTied())
12333861d79fSDimitry Andric         report("Operand should be tied", MO, MONum);
12343861d79fSDimitry Andric       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
12353861d79fSDimitry Andric         report("Tied def doesn't match MCInstrDesc", MO, MONum);
1236c4394386SDimitry Andric       else if (TargetRegisterInfo::isPhysicalRegister(MO->getReg())) {
1237c4394386SDimitry Andric         const MachineOperand &MOTied = MI->getOperand(TiedTo);
1238c4394386SDimitry Andric         if (!MOTied.isReg())
1239c4394386SDimitry Andric           report("Tied counterpart must be a register", &MOTied, TiedTo);
1240c4394386SDimitry Andric         else if (TargetRegisterInfo::isPhysicalRegister(MOTied.getReg()) &&
1241c4394386SDimitry Andric                  MO->getReg() != MOTied.getReg())
1242c4394386SDimitry Andric           report("Tied physical registers must match.", &MOTied, TiedTo);
1243c4394386SDimitry Andric       }
12443861d79fSDimitry Andric     } else if (MO->isReg() && MO->isTied())
12453861d79fSDimitry Andric       report("Explicit operand should not be tied", MO, MONum);
1246f22ef01cSRoman Divacky   } else {
1247f22ef01cSRoman Divacky     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1248dff0c46cSDimitry Andric     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
1249f22ef01cSRoman Divacky       report("Extra explicit operand on non-variadic instruction", MO, MONum);
1250f22ef01cSRoman Divacky   }
1251f22ef01cSRoman Divacky 
1252f22ef01cSRoman Divacky   switch (MO->getType()) {
1253f22ef01cSRoman Divacky   case MachineOperand::MO_Register: {
1254f22ef01cSRoman Divacky     const unsigned Reg = MO->getReg();
1255f22ef01cSRoman Divacky     if (!Reg)
1256f22ef01cSRoman Divacky       return;
1257dff0c46cSDimitry Andric     if (MRI->tracksLiveness() && !MI->isDebugValue())
1258dff0c46cSDimitry Andric       checkLiveness(MO, MONum);
1259f22ef01cSRoman Divacky 
12603861d79fSDimitry Andric     // Verify the consistency of tied operands.
12613861d79fSDimitry Andric     if (MO->isTied()) {
12623861d79fSDimitry Andric       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
12633861d79fSDimitry Andric       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
12643861d79fSDimitry Andric       if (!OtherMO.isReg())
12653861d79fSDimitry Andric         report("Must be tied to a register", MO, MONum);
12663861d79fSDimitry Andric       if (!OtherMO.isTied())
12673861d79fSDimitry Andric         report("Missing tie flags on tied operand", MO, MONum);
12683861d79fSDimitry Andric       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
12693861d79fSDimitry Andric         report("Inconsistent tie links", MO, MONum);
12703861d79fSDimitry Andric       if (MONum < MCID.getNumDefs()) {
12713861d79fSDimitry Andric         if (OtherIdx < MCID.getNumOperands()) {
12723861d79fSDimitry Andric           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
12733861d79fSDimitry Andric             report("Explicit def tied to explicit use without tie constraint",
12743861d79fSDimitry Andric                    MO, MONum);
12753861d79fSDimitry Andric         } else {
12763861d79fSDimitry Andric           if (!OtherMO.isImplicit())
12773861d79fSDimitry Andric             report("Explicit def should be tied to implicit use", MO, MONum);
12783861d79fSDimitry Andric         }
12793861d79fSDimitry Andric       }
12803861d79fSDimitry Andric     }
12813861d79fSDimitry Andric 
12827ae0e2c9SDimitry Andric     // Verify two-address constraints after leaving SSA form.
12837ae0e2c9SDimitry Andric     unsigned DefIdx;
12847ae0e2c9SDimitry Andric     if (!MRI->isSSA() && MO->isUse() &&
12857ae0e2c9SDimitry Andric         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
12867ae0e2c9SDimitry Andric         Reg != MI->getOperand(DefIdx).getReg())
12877ae0e2c9SDimitry Andric       report("Two-address instruction operands must be identical", MO, MONum);
1288f22ef01cSRoman Divacky 
1289f22ef01cSRoman Divacky     // Check register classes.
1290f22ef01cSRoman Divacky     unsigned SubIdx = MO->getSubReg();
1291f22ef01cSRoman Divacky 
1292f22ef01cSRoman Divacky     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1293f22ef01cSRoman Divacky       if (SubIdx) {
12946122f3e6SDimitry Andric         report("Illegal subregister index for physical register", MO, MONum);
1295f22ef01cSRoman Divacky         return;
1296f22ef01cSRoman Divacky       }
12972cab237bSDimitry Andric       if (MONum < MCID.getNumOperands()) {
12987ae0e2c9SDimitry Andric         if (const TargetRegisterClass *DRC =
12997ae0e2c9SDimitry Andric               TII->getRegClass(MCID, MONum, TRI, *MF)) {
13006122f3e6SDimitry Andric           if (!DRC->contains(Reg)) {
1301f22ef01cSRoman Divacky             report("Illegal physical register for instruction", MO, MONum);
13022cab237bSDimitry Andric             errs() << printReg(Reg, TRI) << " is not a "
130339d628a0SDimitry Andric                    << TRI->getRegClassName(DRC) << " register.\n";
1304f22ef01cSRoman Divacky           }
1305f22ef01cSRoman Divacky         }
13062cab237bSDimitry Andric       }
13074ba319b5SDimitry Andric       if (MO->isRenamable()) {
13084ba319b5SDimitry Andric         if (MRI->isReserved(Reg)) {
13094ba319b5SDimitry Andric           report("isRenamable set on reserved register", MO, MONum);
13104ba319b5SDimitry Andric           return;
13114ba319b5SDimitry Andric         }
13124ba319b5SDimitry Andric       }
13134ba319b5SDimitry Andric       if (MI->isDebugValue() && MO->isUse() && !MO->isDebug()) {
13144ba319b5SDimitry Andric         report("Use-reg is not IsDebug in a DBG_VALUE", MO, MONum);
13152cab237bSDimitry Andric         return;
13162cab237bSDimitry Andric       }
1317f22ef01cSRoman Divacky     } else {
1318f22ef01cSRoman Divacky       // Virtual register.
13193ca95b02SDimitry Andric       const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
13203ca95b02SDimitry Andric       if (!RC) {
13213ca95b02SDimitry Andric         // This is a generic virtual register.
1322d88c1a5aSDimitry Andric 
1323d88c1a5aSDimitry Andric         // If we're post-Select, we can't have gvregs anymore.
1324d88c1a5aSDimitry Andric         if (isFunctionSelected) {
1325d88c1a5aSDimitry Andric           report("Generic virtual register invalid in a Selected function",
1326d88c1a5aSDimitry Andric                  MO, MONum);
13273ca95b02SDimitry Andric           return;
13283ca95b02SDimitry Andric         }
1329d88c1a5aSDimitry Andric 
1330d88c1a5aSDimitry Andric         // The gvreg must have a type and it must not have a SubIdx.
1331d88c1a5aSDimitry Andric         LLT Ty = MRI->getType(Reg);
1332d88c1a5aSDimitry Andric         if (!Ty.isValid()) {
1333d88c1a5aSDimitry Andric           report("Generic virtual register must have a valid type", MO,
1334d88c1a5aSDimitry Andric                  MONum);
1335d88c1a5aSDimitry Andric           return;
1336d88c1a5aSDimitry Andric         }
1337d88c1a5aSDimitry Andric 
13383ca95b02SDimitry Andric         const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
1339d88c1a5aSDimitry Andric 
1340d88c1a5aSDimitry Andric         // If we're post-RegBankSelect, the gvreg must have a bank.
1341d88c1a5aSDimitry Andric         if (!RegBank && isFunctionRegBankSelected) {
1342d88c1a5aSDimitry Andric           report("Generic virtual register must have a bank in a "
1343d88c1a5aSDimitry Andric                  "RegBankSelected function",
1344d88c1a5aSDimitry Andric                  MO, MONum);
1345d88c1a5aSDimitry Andric           return;
1346d88c1a5aSDimitry Andric         }
1347d88c1a5aSDimitry Andric 
1348d88c1a5aSDimitry Andric         // Make sure the register fits into its register bank if any.
1349d88c1a5aSDimitry Andric         if (RegBank && Ty.isValid() &&
1350d88c1a5aSDimitry Andric             RegBank->getSize() < Ty.getSizeInBits()) {
13513ca95b02SDimitry Andric           report("Register bank is too small for virtual register", MO,
13523ca95b02SDimitry Andric                  MONum);
13533ca95b02SDimitry Andric           errs() << "Register bank " << RegBank->getName() << " too small("
1354d88c1a5aSDimitry Andric                  << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
1355d88c1a5aSDimitry Andric                  << "-bits\n";
13563ca95b02SDimitry Andric           return;
13573ca95b02SDimitry Andric         }
13583ca95b02SDimitry Andric         if (SubIdx)  {
1359d88c1a5aSDimitry Andric           report("Generic virtual register does not subregister index", MO,
1360d88c1a5aSDimitry Andric                  MONum);
13613ca95b02SDimitry Andric           return;
13623ca95b02SDimitry Andric         }
1363d88c1a5aSDimitry Andric 
1364d88c1a5aSDimitry Andric         // If this is a target specific instruction and this operand
1365d88c1a5aSDimitry Andric         // has register class constraint, the virtual register must
1366d88c1a5aSDimitry Andric         // comply to it.
1367d88c1a5aSDimitry Andric         if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
13682cab237bSDimitry Andric             MONum < MCID.getNumOperands() &&
1369d88c1a5aSDimitry Andric             TII->getRegClass(MCID, MONum, TRI, *MF)) {
1370d88c1a5aSDimitry Andric           report("Virtual register does not match instruction constraint", MO,
1371d88c1a5aSDimitry Andric                  MONum);
1372d88c1a5aSDimitry Andric           errs() << "Expect register class "
1373d88c1a5aSDimitry Andric                  << TRI->getRegClassName(
1374d88c1a5aSDimitry Andric                         TII->getRegClass(MCID, MONum, TRI, *MF))
1375d88c1a5aSDimitry Andric                  << " but got nothing\n";
1376d88c1a5aSDimitry Andric           return;
1377d88c1a5aSDimitry Andric         }
1378d88c1a5aSDimitry Andric 
13793ca95b02SDimitry Andric         break;
13803ca95b02SDimitry Andric       }
1381f22ef01cSRoman Divacky       if (SubIdx) {
13826122f3e6SDimitry Andric         const TargetRegisterClass *SRC =
13836122f3e6SDimitry Andric           TRI->getSubClassWithSubReg(RC, SubIdx);
1384f22ef01cSRoman Divacky         if (!SRC) {
1385f22ef01cSRoman Divacky           report("Invalid subregister index for virtual register", MO, MONum);
1386ff0cc061SDimitry Andric           errs() << "Register class " << TRI->getRegClassName(RC)
1387f22ef01cSRoman Divacky               << " does not support subreg index " << SubIdx << "\n";
1388f22ef01cSRoman Divacky           return;
1389f22ef01cSRoman Divacky         }
13906122f3e6SDimitry Andric         if (RC != SRC) {
13916122f3e6SDimitry Andric           report("Invalid register class for subregister index", MO, MONum);
1392ff0cc061SDimitry Andric           errs() << "Register class " << TRI->getRegClassName(RC)
13936122f3e6SDimitry Andric               << " does not fully support subreg index " << SubIdx << "\n";
13946122f3e6SDimitry Andric           return;
13956122f3e6SDimitry Andric         }
1396f22ef01cSRoman Divacky       }
13972cab237bSDimitry Andric       if (MONum < MCID.getNumOperands()) {
13987ae0e2c9SDimitry Andric         if (const TargetRegisterClass *DRC =
13997ae0e2c9SDimitry Andric               TII->getRegClass(MCID, MONum, TRI, *MF)) {
14006122f3e6SDimitry Andric           if (SubIdx) {
14016122f3e6SDimitry Andric             const TargetRegisterClass *SuperRC =
1402ff0cc061SDimitry Andric                 TRI->getLargestLegalSuperClass(RC, *MF);
14036122f3e6SDimitry Andric             if (!SuperRC) {
14046122f3e6SDimitry Andric               report("No largest legal super class exists.", MO, MONum);
14056122f3e6SDimitry Andric               return;
14066122f3e6SDimitry Andric             }
14076122f3e6SDimitry Andric             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
14086122f3e6SDimitry Andric             if (!DRC) {
14096122f3e6SDimitry Andric               report("No matching super-reg register class.", MO, MONum);
14106122f3e6SDimitry Andric               return;
14116122f3e6SDimitry Andric             }
14126122f3e6SDimitry Andric           }
1413bd5abe19SDimitry Andric           if (!RC->hasSuperClassEq(DRC)) {
1414f22ef01cSRoman Divacky             report("Illegal virtual register for instruction", MO, MONum);
1415ff0cc061SDimitry Andric             errs() << "Expected a " << TRI->getRegClassName(DRC)
141639d628a0SDimitry Andric                 << " register, but got a " << TRI->getRegClassName(RC)
141739d628a0SDimitry Andric                 << " register\n";
1418f22ef01cSRoman Divacky           }
1419f22ef01cSRoman Divacky         }
1420f22ef01cSRoman Divacky       }
1421f22ef01cSRoman Divacky     }
1422f22ef01cSRoman Divacky     break;
1423f22ef01cSRoman Divacky   }
1424f22ef01cSRoman Divacky 
1425dff0c46cSDimitry Andric   case MachineOperand::MO_RegisterMask:
1426dff0c46cSDimitry Andric     regMasks.push_back(MO->getRegMask());
1427dff0c46cSDimitry Andric     break;
1428dff0c46cSDimitry Andric 
1429f22ef01cSRoman Divacky   case MachineOperand::MO_MachineBasicBlock:
1430f22ef01cSRoman Divacky     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
1431f22ef01cSRoman Divacky       report("PHI operand is not in the CFG", MO, MONum);
1432f22ef01cSRoman Divacky     break;
1433f22ef01cSRoman Divacky 
14342754fe60SDimitry Andric   case MachineOperand::MO_FrameIndex:
14352754fe60SDimitry Andric     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
14363ca95b02SDimitry Andric         LiveInts && !LiveInts->isNotInMIMap(*MI)) {
14377d523365SDimitry Andric       int FI = MO->getIndex();
14387d523365SDimitry Andric       LiveInterval &LI = LiveStks->getInterval(FI);
14393ca95b02SDimitry Andric       SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
14407d523365SDimitry Andric 
14417d523365SDimitry Andric       bool stores = MI->mayStore();
14427d523365SDimitry Andric       bool loads = MI->mayLoad();
14437d523365SDimitry Andric       // For a memory-to-memory move, we need to check if the frame
14447d523365SDimitry Andric       // index is used for storing or loading, by inspecting the
14457d523365SDimitry Andric       // memory operands.
14467d523365SDimitry Andric       if (stores && loads) {
14477d523365SDimitry Andric         for (auto *MMO : MI->memoperands()) {
14487d523365SDimitry Andric           const PseudoSourceValue *PSV = MMO->getPseudoValue();
14497d523365SDimitry Andric           if (PSV == nullptr) continue;
14507d523365SDimitry Andric           const FixedStackPseudoSourceValue *Value =
14517d523365SDimitry Andric             dyn_cast<FixedStackPseudoSourceValue>(PSV);
14527d523365SDimitry Andric           if (Value == nullptr) continue;
14537d523365SDimitry Andric           if (Value->getFrameIndex() != FI) continue;
14547d523365SDimitry Andric 
14557d523365SDimitry Andric           if (MMO->isStore())
14567d523365SDimitry Andric             loads = false;
14577d523365SDimitry Andric           else
14587d523365SDimitry Andric             stores = false;
14597d523365SDimitry Andric           break;
14607d523365SDimitry Andric         }
14617d523365SDimitry Andric         if (loads == stores)
14627d523365SDimitry Andric           report("Missing fixed stack memoperand.", MI);
14637d523365SDimitry Andric       }
14647d523365SDimitry Andric       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
14652754fe60SDimitry Andric         report("Instruction loads from dead spill slot", MO, MONum);
1466ff0cc061SDimitry Andric         errs() << "Live stack: " << LI << '\n';
14672754fe60SDimitry Andric       }
14687d523365SDimitry Andric       if (stores && !LI.liveAt(Idx.getRegSlot())) {
14692754fe60SDimitry Andric         report("Instruction stores to dead spill slot", MO, MONum);
1470ff0cc061SDimitry Andric         errs() << "Live stack: " << LI << '\n';
14712754fe60SDimitry Andric       }
14722754fe60SDimitry Andric     }
14732754fe60SDimitry Andric     break;
14742754fe60SDimitry Andric 
1475f22ef01cSRoman Divacky   default:
1476f22ef01cSRoman Divacky     break;
1477f22ef01cSRoman Divacky   }
1478f22ef01cSRoman Divacky }
1479f22ef01cSRoman Divacky 
checkLivenessAtUse(const MachineOperand * MO,unsigned MONum,SlotIndex UseIdx,const LiveRange & LR,unsigned VRegOrUnit,LaneBitmask LaneMask)14803ca95b02SDimitry Andric void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
14813ca95b02SDimitry Andric     unsigned MONum, SlotIndex UseIdx, const LiveRange &LR, unsigned VRegOrUnit,
14823ca95b02SDimitry Andric     LaneBitmask LaneMask) {
14833ca95b02SDimitry Andric   LiveQueryResult LRQ = LR.Query(UseIdx);
14843ca95b02SDimitry Andric   // Check if we have a segment at the use, note however that we only need one
14853ca95b02SDimitry Andric   // live subregister range, the others may be dead.
1486d88c1a5aSDimitry Andric   if (!LRQ.valueIn() && LaneMask.none()) {
14873ca95b02SDimitry Andric     report("No live segment at use", MO, MONum);
14883ca95b02SDimitry Andric     report_context_liverange(LR);
14893ca95b02SDimitry Andric     report_context_vreg_regunit(VRegOrUnit);
14903ca95b02SDimitry Andric     report_context(UseIdx);
14913ca95b02SDimitry Andric   }
14923ca95b02SDimitry Andric   if (MO->isKill() && !LRQ.isKill()) {
14933ca95b02SDimitry Andric     report("Live range continues after kill flag", MO, MONum);
14943ca95b02SDimitry Andric     report_context_liverange(LR);
14953ca95b02SDimitry Andric     report_context_vreg_regunit(VRegOrUnit);
1496d88c1a5aSDimitry Andric     if (LaneMask.any())
14973ca95b02SDimitry Andric       report_context_lanemask(LaneMask);
14983ca95b02SDimitry Andric     report_context(UseIdx);
14993ca95b02SDimitry Andric   }
15003ca95b02SDimitry Andric }
15013ca95b02SDimitry Andric 
checkLivenessAtDef(const MachineOperand * MO,unsigned MONum,SlotIndex DefIdx,const LiveRange & LR,unsigned VRegOrUnit,bool SubRangeCheck,LaneBitmask LaneMask)15023ca95b02SDimitry Andric void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
15033ca95b02SDimitry Andric     unsigned MONum, SlotIndex DefIdx, const LiveRange &LR, unsigned VRegOrUnit,
1504*b5893f02SDimitry Andric     bool SubRangeCheck, LaneBitmask LaneMask) {
15053ca95b02SDimitry Andric   if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
15063ca95b02SDimitry Andric     assert(VNI && "NULL valno is not allowed");
15073ca95b02SDimitry Andric     if (VNI->def != DefIdx) {
15083ca95b02SDimitry Andric       report("Inconsistent valno->def", MO, MONum);
15093ca95b02SDimitry Andric       report_context_liverange(LR);
15103ca95b02SDimitry Andric       report_context_vreg_regunit(VRegOrUnit);
1511d88c1a5aSDimitry Andric       if (LaneMask.any())
15123ca95b02SDimitry Andric         report_context_lanemask(LaneMask);
15133ca95b02SDimitry Andric       report_context(*VNI);
15143ca95b02SDimitry Andric       report_context(DefIdx);
15153ca95b02SDimitry Andric     }
15163ca95b02SDimitry Andric   } else {
15173ca95b02SDimitry Andric     report("No live segment at def", MO, MONum);
15183ca95b02SDimitry Andric     report_context_liverange(LR);
15193ca95b02SDimitry Andric     report_context_vreg_regunit(VRegOrUnit);
1520d88c1a5aSDimitry Andric     if (LaneMask.any())
15213ca95b02SDimitry Andric       report_context_lanemask(LaneMask);
15223ca95b02SDimitry Andric     report_context(DefIdx);
15233ca95b02SDimitry Andric   }
15243ca95b02SDimitry Andric   // Check that, if the dead def flag is present, LiveInts agree.
15253ca95b02SDimitry Andric   if (MO->isDead()) {
15263ca95b02SDimitry Andric     LiveQueryResult LRQ = LR.Query(DefIdx);
15273ca95b02SDimitry Andric     if (!LRQ.isDeadDef()) {
1528*b5893f02SDimitry Andric       assert(TargetRegisterInfo::isVirtualRegister(VRegOrUnit) &&
1529*b5893f02SDimitry Andric              "Expecting a virtual register.");
1530*b5893f02SDimitry Andric       // A dead subreg def only tells us that the specific subreg is dead. There
1531*b5893f02SDimitry Andric       // could be other non-dead defs of other subregs, or we could have other
1532*b5893f02SDimitry Andric       // parts of the register being live through the instruction. So unless we
1533*b5893f02SDimitry Andric       // are checking liveness for a subrange it is ok for the live range to
1534*b5893f02SDimitry Andric       // continue, given that we have a dead def of a subregister.
1535*b5893f02SDimitry Andric       if (SubRangeCheck || MO->getSubReg() == 0) {
15363ca95b02SDimitry Andric         report("Live range continues after dead def flag", MO, MONum);
15373ca95b02SDimitry Andric         report_context_liverange(LR);
15383ca95b02SDimitry Andric         report_context_vreg_regunit(VRegOrUnit);
1539d88c1a5aSDimitry Andric         if (LaneMask.any())
15403ca95b02SDimitry Andric           report_context_lanemask(LaneMask);
15413ca95b02SDimitry Andric       }
15423ca95b02SDimitry Andric     }
15433ca95b02SDimitry Andric   }
15443ca95b02SDimitry Andric }
15453ca95b02SDimitry Andric 
checkLiveness(const MachineOperand * MO,unsigned MONum)1546dff0c46cSDimitry Andric void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1547dff0c46cSDimitry Andric   const MachineInstr *MI = MO->getParent();
1548dff0c46cSDimitry Andric   const unsigned Reg = MO->getReg();
1549dff0c46cSDimitry Andric 
1550dff0c46cSDimitry Andric   // Both use and def operands can read a register.
1551dff0c46cSDimitry Andric   if (MO->readsReg()) {
15527ae0e2c9SDimitry Andric     if (MO->isKill())
1553dff0c46cSDimitry Andric       addRegWithSubRegs(regsKilled, Reg);
1554dff0c46cSDimitry Andric 
1555dff0c46cSDimitry Andric     // Check that LiveVars knows this kill.
1556dff0c46cSDimitry Andric     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1557dff0c46cSDimitry Andric         MO->isKill()) {
1558dff0c46cSDimitry Andric       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1559d88c1a5aSDimitry Andric       if (!is_contained(VI.Kills, MI))
1560dff0c46cSDimitry Andric         report("Kill missing from LiveVariables", MO, MONum);
1561dff0c46cSDimitry Andric     }
1562dff0c46cSDimitry Andric 
1563dff0c46cSDimitry Andric     // Check LiveInts liveness and kill.
15643ca95b02SDimitry Andric     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
15653ca95b02SDimitry Andric       SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
15667ae0e2c9SDimitry Andric       // Check the cached regunit intervals.
15677ae0e2c9SDimitry Andric       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
15687ae0e2c9SDimitry Andric         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1569d4419f6fSDimitry Andric           if (MRI->isReservedRegUnit(*Units))
1570d4419f6fSDimitry Andric             continue;
15713ca95b02SDimitry Andric           if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
15723ca95b02SDimitry Andric             checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
15737ae0e2c9SDimitry Andric         }
15747ae0e2c9SDimitry Andric       }
15757ae0e2c9SDimitry Andric 
15767ae0e2c9SDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1577dff0c46cSDimitry Andric         if (LiveInts->hasInterval(Reg)) {
15787ae0e2c9SDimitry Andric           // This is a virtual register interval.
1579dff0c46cSDimitry Andric           const LiveInterval &LI = LiveInts->getInterval(Reg);
15803ca95b02SDimitry Andric           checkLivenessAtUse(MO, MONum, UseIdx, LI, Reg);
15813ca95b02SDimitry Andric 
15823ca95b02SDimitry Andric           if (LI.hasSubRanges() && !MO->isDef()) {
15833ca95b02SDimitry Andric             unsigned SubRegIdx = MO->getSubReg();
15843ca95b02SDimitry Andric             LaneBitmask MOMask = SubRegIdx != 0
15853ca95b02SDimitry Andric                                ? TRI->getSubRegIndexLaneMask(SubRegIdx)
15863ca95b02SDimitry Andric                                : MRI->getMaxLaneMaskForVReg(Reg);
1587d88c1a5aSDimitry Andric             LaneBitmask LiveInMask;
15883ca95b02SDimitry Andric             for (const LiveInterval::SubRange &SR : LI.subranges()) {
1589d88c1a5aSDimitry Andric               if ((MOMask & SR.LaneMask).none())
15903ca95b02SDimitry Andric                 continue;
15913ca95b02SDimitry Andric               checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
15923ca95b02SDimitry Andric               LiveQueryResult LRQ = SR.Query(UseIdx);
15933ca95b02SDimitry Andric               if (LRQ.valueIn())
15943ca95b02SDimitry Andric                 LiveInMask |= SR.LaneMask;
1595dff0c46cSDimitry Andric             }
15963ca95b02SDimitry Andric             // At least parts of the register has to be live at the use.
1597d88c1a5aSDimitry Andric             if ((LiveInMask & MOMask).none()) {
15983ca95b02SDimitry Andric               report("No live subrange at use", MO, MONum);
15993ca95b02SDimitry Andric               report_context(LI);
16003ca95b02SDimitry Andric               report_context(UseIdx);
16013ca95b02SDimitry Andric             }
1602dff0c46cSDimitry Andric           }
1603dff0c46cSDimitry Andric         } else {
16047ae0e2c9SDimitry Andric           report("Virtual register has no live interval", MO, MONum);
16057ae0e2c9SDimitry Andric         }
1606dff0c46cSDimitry Andric       }
1607dff0c46cSDimitry Andric     }
1608dff0c46cSDimitry Andric 
1609dff0c46cSDimitry Andric     // Use of a dead register.
1610dff0c46cSDimitry Andric     if (!regsLive.count(Reg)) {
1611dff0c46cSDimitry Andric       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1612dff0c46cSDimitry Andric         // Reserved registers may be used even when 'dead'.
161339d628a0SDimitry Andric         bool Bad = !isReserved(Reg);
161439d628a0SDimitry Andric         // We are fine if just any subregister has a defined value.
161539d628a0SDimitry Andric         if (Bad) {
161639d628a0SDimitry Andric           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
161739d628a0SDimitry Andric                ++SubRegs) {
161839d628a0SDimitry Andric             if (regsLive.count(*SubRegs)) {
161939d628a0SDimitry Andric               Bad = false;
162039d628a0SDimitry Andric               break;
162139d628a0SDimitry Andric             }
162239d628a0SDimitry Andric           }
162339d628a0SDimitry Andric         }
1624ff0cc061SDimitry Andric         // If there is an additional implicit-use of a super register we stop
1625ff0cc061SDimitry Andric         // here. By definition we are fine if the super register is not
1626ff0cc061SDimitry Andric         // (completely) dead, if the complete super register is dead we will
1627ff0cc061SDimitry Andric         // get a report for its operand.
1628ff0cc061SDimitry Andric         if (Bad) {
1629ff0cc061SDimitry Andric           for (const MachineOperand &MOP : MI->uses()) {
1630*b5893f02SDimitry Andric             if (!MOP.isReg() || !MOP.isImplicit())
1631ff0cc061SDimitry Andric               continue;
1632*b5893f02SDimitry Andric 
1633*b5893f02SDimitry Andric             if (!TargetRegisterInfo::isPhysicalRegister(MOP.getReg()))
1634ff0cc061SDimitry Andric               continue;
1635*b5893f02SDimitry Andric 
1636ff0cc061SDimitry Andric             for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1637ff0cc061SDimitry Andric                  ++SubRegs) {
1638ff0cc061SDimitry Andric               if (*SubRegs == Reg) {
1639ff0cc061SDimitry Andric                 Bad = false;
1640ff0cc061SDimitry Andric                 break;
1641ff0cc061SDimitry Andric               }
1642ff0cc061SDimitry Andric             }
1643ff0cc061SDimitry Andric           }
1644ff0cc061SDimitry Andric         }
164539d628a0SDimitry Andric         if (Bad)
1646dff0c46cSDimitry Andric           report("Using an undefined physical register", MO, MONum);
16477ae0e2c9SDimitry Andric       } else if (MRI->def_empty(Reg)) {
16487ae0e2c9SDimitry Andric         report("Reading virtual register without a def", MO, MONum);
1649dff0c46cSDimitry Andric       } else {
1650dff0c46cSDimitry Andric         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1651dff0c46cSDimitry Andric         // We don't know which virtual registers are live in, so only complain
1652dff0c46cSDimitry Andric         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1653dff0c46cSDimitry Andric         // must be live in. PHI instructions are handled separately.
1654dff0c46cSDimitry Andric         if (MInfo.regsKilled.count(Reg))
1655dff0c46cSDimitry Andric           report("Using a killed virtual register", MO, MONum);
1656dff0c46cSDimitry Andric         else if (!MI->isPHI())
1657dff0c46cSDimitry Andric           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1658dff0c46cSDimitry Andric       }
1659dff0c46cSDimitry Andric     }
1660dff0c46cSDimitry Andric   }
1661dff0c46cSDimitry Andric 
1662dff0c46cSDimitry Andric   if (MO->isDef()) {
1663dff0c46cSDimitry Andric     // Register defined.
1664dff0c46cSDimitry Andric     // TODO: verify that earlyclobber ops are not used.
1665dff0c46cSDimitry Andric     if (MO->isDead())
1666dff0c46cSDimitry Andric       addRegWithSubRegs(regsDead, Reg);
1667dff0c46cSDimitry Andric     else
1668dff0c46cSDimitry Andric       addRegWithSubRegs(regsDefined, Reg);
1669dff0c46cSDimitry Andric 
1670dff0c46cSDimitry Andric     // Verify SSA form.
1671dff0c46cSDimitry Andric     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
167291bc56edSDimitry Andric         std::next(MRI->def_begin(Reg)) != MRI->def_end())
1673dff0c46cSDimitry Andric       report("Multiple virtual register defs in SSA form", MO, MONum);
1674dff0c46cSDimitry Andric 
1675f785676fSDimitry Andric     // Check LiveInts for a live segment, but only for virtual registers.
16763ca95b02SDimitry Andric     if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
16773ca95b02SDimitry Andric       SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
16787ae0e2c9SDimitry Andric       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
16793ca95b02SDimitry Andric 
16803ca95b02SDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1681dff0c46cSDimitry Andric         if (LiveInts->hasInterval(Reg)) {
1682dff0c46cSDimitry Andric           const LiveInterval &LI = LiveInts->getInterval(Reg);
16833ca95b02SDimitry Andric           checkLivenessAtDef(MO, MONum, DefIdx, LI, Reg);
16843ca95b02SDimitry Andric 
16853ca95b02SDimitry Andric           if (LI.hasSubRanges()) {
16863ca95b02SDimitry Andric             unsigned SubRegIdx = MO->getSubReg();
16873ca95b02SDimitry Andric             LaneBitmask MOMask = SubRegIdx != 0
16883ca95b02SDimitry Andric               ? TRI->getSubRegIndexLaneMask(SubRegIdx)
16893ca95b02SDimitry Andric               : MRI->getMaxLaneMaskForVReg(Reg);
16903ca95b02SDimitry Andric             for (const LiveInterval::SubRange &SR : LI.subranges()) {
1691d88c1a5aSDimitry Andric               if ((SR.LaneMask & MOMask).none())
16923ca95b02SDimitry Andric                 continue;
1693*b5893f02SDimitry Andric               checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
1694f785676fSDimitry Andric             }
1695f785676fSDimitry Andric           }
1696dff0c46cSDimitry Andric         } else {
1697dff0c46cSDimitry Andric           report("Virtual register has no Live interval", MO, MONum);
1698dff0c46cSDimitry Andric         }
1699dff0c46cSDimitry Andric       }
1700dff0c46cSDimitry Andric     }
1701dff0c46cSDimitry Andric   }
17023ca95b02SDimitry Andric }
1703dff0c46cSDimitry Andric 
visitMachineInstrAfter(const MachineInstr * MI)17042cab237bSDimitry Andric void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {}
17057ae0e2c9SDimitry Andric 
17067ae0e2c9SDimitry Andric // This function gets called after visiting all instructions in a bundle. The
17077ae0e2c9SDimitry Andric // argument points to the bundle header.
17087ae0e2c9SDimitry Andric // Normal stand-alone instructions are also considered 'bundles', and this
17097ae0e2c9SDimitry Andric // function is called for all of them.
visitMachineBundleAfter(const MachineInstr * MI)17107ae0e2c9SDimitry Andric void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1711f22ef01cSRoman Divacky   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1712f22ef01cSRoman Divacky   set_union(MInfo.regsKilled, regsKilled);
1713e580952dSDimitry Andric   set_subtract(regsLive, regsKilled); regsKilled.clear();
1714dff0c46cSDimitry Andric   // Kill any masked registers.
1715dff0c46cSDimitry Andric   while (!regMasks.empty()) {
1716dff0c46cSDimitry Andric     const uint32_t *Mask = regMasks.pop_back_val();
1717dff0c46cSDimitry Andric     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1718dff0c46cSDimitry Andric       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1719dff0c46cSDimitry Andric           MachineOperand::clobbersPhysReg(Mask, *I))
1720dff0c46cSDimitry Andric         regsDead.push_back(*I);
1721dff0c46cSDimitry Andric   }
1722f22ef01cSRoman Divacky   set_subtract(regsLive, regsDead);   regsDead.clear();
1723f22ef01cSRoman Divacky   set_union(regsLive, regsDefined);   regsDefined.clear();
1724f22ef01cSRoman Divacky }
1725f22ef01cSRoman Divacky 
1726f22ef01cSRoman Divacky void
visitMachineBasicBlockAfter(const MachineBasicBlock * MBB)1727f22ef01cSRoman Divacky MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1728f22ef01cSRoman Divacky   MBBInfoMap[MBB].regsLiveOut = regsLive;
1729f22ef01cSRoman Divacky   regsLive.clear();
17302754fe60SDimitry Andric 
17312754fe60SDimitry Andric   if (Indexes) {
17322754fe60SDimitry Andric     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
17332754fe60SDimitry Andric     if (!(stop > lastIndex)) {
17342754fe60SDimitry Andric       report("Block ends before last instruction index", MBB);
1735ff0cc061SDimitry Andric       errs() << "Block ends at " << stop
17362754fe60SDimitry Andric           << " last instruction was at " << lastIndex << '\n';
17372754fe60SDimitry Andric     }
17382754fe60SDimitry Andric     lastIndex = stop;
17392754fe60SDimitry Andric   }
1740f22ef01cSRoman Divacky }
1741f22ef01cSRoman Divacky 
1742f22ef01cSRoman Divacky // Calculate the largest possible vregsPassed sets. These are the registers that
1743f22ef01cSRoman Divacky // can pass through an MBB live, but may not be live every time. It is assumed
1744f22ef01cSRoman Divacky // that all vregsPassed sets are empty before the call.
calcRegsPassed()1745f22ef01cSRoman Divacky void MachineVerifier::calcRegsPassed() {
1746f22ef01cSRoman Divacky   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1747f22ef01cSRoman Divacky   // have any vregsPassed.
1748dff0c46cSDimitry Andric   SmallPtrSet<const MachineBasicBlock*, 8> todo;
174991bc56edSDimitry Andric   for (const auto &MBB : *MF) {
1750f22ef01cSRoman Divacky     BBInfo &MInfo = MBBInfoMap[&MBB];
1751f22ef01cSRoman Divacky     if (!MInfo.reachable)
1752f22ef01cSRoman Divacky       continue;
1753f22ef01cSRoman Divacky     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1754f22ef01cSRoman Divacky            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1755f22ef01cSRoman Divacky       BBInfo &SInfo = MBBInfoMap[*SuI];
1756f22ef01cSRoman Divacky       if (SInfo.addPassed(MInfo.regsLiveOut))
1757f22ef01cSRoman Divacky         todo.insert(*SuI);
1758f22ef01cSRoman Divacky     }
1759f22ef01cSRoman Divacky   }
1760f22ef01cSRoman Divacky 
1761f22ef01cSRoman Divacky   // Iteratively push vregsPassed to successors. This will converge to the same
1762f22ef01cSRoman Divacky   // final state regardless of DenseSet iteration order.
1763f22ef01cSRoman Divacky   while (!todo.empty()) {
1764f22ef01cSRoman Divacky     const MachineBasicBlock *MBB = *todo.begin();
1765f22ef01cSRoman Divacky     todo.erase(MBB);
1766f22ef01cSRoman Divacky     BBInfo &MInfo = MBBInfoMap[MBB];
1767f22ef01cSRoman Divacky     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1768f22ef01cSRoman Divacky            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1769f22ef01cSRoman Divacky       if (*SuI == MBB)
1770f22ef01cSRoman Divacky         continue;
1771f22ef01cSRoman Divacky       BBInfo &SInfo = MBBInfoMap[*SuI];
1772f22ef01cSRoman Divacky       if (SInfo.addPassed(MInfo.vregsPassed))
1773f22ef01cSRoman Divacky         todo.insert(*SuI);
1774f22ef01cSRoman Divacky     }
1775f22ef01cSRoman Divacky   }
1776f22ef01cSRoman Divacky }
1777f22ef01cSRoman Divacky 
1778f22ef01cSRoman Divacky // Calculate the set of virtual registers that must be passed through each basic
1779f22ef01cSRoman Divacky // block in order to satisfy the requirements of successor blocks. This is very
1780f22ef01cSRoman Divacky // similar to calcRegsPassed, only backwards.
calcRegsRequired()1781f22ef01cSRoman Divacky void MachineVerifier::calcRegsRequired() {
1782f22ef01cSRoman Divacky   // First push live-in regs to predecessors' vregsRequired.
1783dff0c46cSDimitry Andric   SmallPtrSet<const MachineBasicBlock*, 8> todo;
178491bc56edSDimitry Andric   for (const auto &MBB : *MF) {
1785f22ef01cSRoman Divacky     BBInfo &MInfo = MBBInfoMap[&MBB];
1786f22ef01cSRoman Divacky     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1787f22ef01cSRoman Divacky            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1788f22ef01cSRoman Divacky       BBInfo &PInfo = MBBInfoMap[*PrI];
1789f22ef01cSRoman Divacky       if (PInfo.addRequired(MInfo.vregsLiveIn))
1790f22ef01cSRoman Divacky         todo.insert(*PrI);
1791f22ef01cSRoman Divacky     }
1792f22ef01cSRoman Divacky   }
1793f22ef01cSRoman Divacky 
1794f22ef01cSRoman Divacky   // Iteratively push vregsRequired to predecessors. This will converge to the
1795f22ef01cSRoman Divacky   // same final state regardless of DenseSet iteration order.
1796f22ef01cSRoman Divacky   while (!todo.empty()) {
1797f22ef01cSRoman Divacky     const MachineBasicBlock *MBB = *todo.begin();
1798f22ef01cSRoman Divacky     todo.erase(MBB);
1799f22ef01cSRoman Divacky     BBInfo &MInfo = MBBInfoMap[MBB];
1800f22ef01cSRoman Divacky     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1801f22ef01cSRoman Divacky            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1802f22ef01cSRoman Divacky       if (*PrI == MBB)
1803f22ef01cSRoman Divacky         continue;
1804f22ef01cSRoman Divacky       BBInfo &SInfo = MBBInfoMap[*PrI];
1805f22ef01cSRoman Divacky       if (SInfo.addRequired(MInfo.vregsRequired))
1806f22ef01cSRoman Divacky         todo.insert(*PrI);
1807f22ef01cSRoman Divacky     }
1808f22ef01cSRoman Divacky   }
1809f22ef01cSRoman Divacky }
1810f22ef01cSRoman Divacky 
1811f22ef01cSRoman Divacky // Check PHI instructions at the beginning of MBB. It is assumed that
1812f22ef01cSRoman Divacky // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
checkPHIOps(const MachineBasicBlock & MBB)18132cab237bSDimitry Andric void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
18142cab237bSDimitry Andric   BBInfo &MInfo = MBBInfoMap[&MBB];
18152cab237bSDimitry Andric 
1816dff0c46cSDimitry Andric   SmallPtrSet<const MachineBasicBlock*, 8> seen;
18172cab237bSDimitry Andric   for (const MachineInstr &Phi : MBB) {
18182cab237bSDimitry Andric     if (!Phi.isPHI())
181991bc56edSDimitry Andric       break;
1820dff0c46cSDimitry Andric     seen.clear();
1821f22ef01cSRoman Divacky 
18222cab237bSDimitry Andric     const MachineOperand &MODef = Phi.getOperand(0);
18232cab237bSDimitry Andric     if (!MODef.isReg() || !MODef.isDef()) {
18242cab237bSDimitry Andric       report("Expected first PHI operand to be a register def", &MODef, 0);
1825f22ef01cSRoman Divacky       continue;
18262cab237bSDimitry Andric     }
18272cab237bSDimitry Andric     if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
18282cab237bSDimitry Andric         MODef.isEarlyClobber() || MODef.isDebug())
18292cab237bSDimitry Andric       report("Unexpected flag on PHI operand", &MODef, 0);
18302cab237bSDimitry Andric     unsigned DefReg = MODef.getReg();
18312cab237bSDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(DefReg))
18322cab237bSDimitry Andric       report("Expected first PHI operand to be a virtual register", &MODef, 0);
18332cab237bSDimitry Andric 
18342cab237bSDimitry Andric     for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
18352cab237bSDimitry Andric       const MachineOperand &MO0 = Phi.getOperand(I);
18362cab237bSDimitry Andric       if (!MO0.isReg()) {
18372cab237bSDimitry Andric         report("Expected PHI operand to be a register", &MO0, I);
18382cab237bSDimitry Andric         continue;
18392cab237bSDimitry Andric       }
18402cab237bSDimitry Andric       if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
18412cab237bSDimitry Andric           MO0.isDebug() || MO0.isTied())
18422cab237bSDimitry Andric         report("Unexpected flag on PHI operand", &MO0, I);
18432cab237bSDimitry Andric 
18442cab237bSDimitry Andric       const MachineOperand &MO1 = Phi.getOperand(I + 1);
18452cab237bSDimitry Andric       if (!MO1.isMBB()) {
18462cab237bSDimitry Andric         report("Expected PHI operand to be a basic block", &MO1, I + 1);
18472cab237bSDimitry Andric         continue;
18482cab237bSDimitry Andric       }
18492cab237bSDimitry Andric 
18502cab237bSDimitry Andric       const MachineBasicBlock &Pre = *MO1.getMBB();
18512cab237bSDimitry Andric       if (!Pre.isSuccessor(&MBB)) {
18522cab237bSDimitry Andric         report("PHI input is not a predecessor block", &MO1, I + 1);
18532cab237bSDimitry Andric         continue;
18542cab237bSDimitry Andric       }
18552cab237bSDimitry Andric 
18562cab237bSDimitry Andric       if (MInfo.reachable) {
18572cab237bSDimitry Andric         seen.insert(&Pre);
18582cab237bSDimitry Andric         BBInfo &PrInfo = MBBInfoMap[&Pre];
18592cab237bSDimitry Andric         if (!MO0.isUndef() && PrInfo.reachable &&
18602cab237bSDimitry Andric             !PrInfo.isLiveOut(MO0.getReg()))
18612cab237bSDimitry Andric           report("PHI operand is not live-out from predecessor", &MO0, I);
18622cab237bSDimitry Andric       }
1863f22ef01cSRoman Divacky     }
1864f22ef01cSRoman Divacky 
1865f22ef01cSRoman Divacky     // Did we see all predecessors?
18662cab237bSDimitry Andric     if (MInfo.reachable) {
18672cab237bSDimitry Andric       for (MachineBasicBlock *Pred : MBB.predecessors()) {
18682cab237bSDimitry Andric         if (!seen.count(Pred)) {
18692cab237bSDimitry Andric           report("Missing PHI operand", &Phi);
18702cab237bSDimitry Andric           errs() << printMBBReference(*Pred)
1871f22ef01cSRoman Divacky                  << " is a predecessor according to the CFG.\n";
1872f22ef01cSRoman Divacky         }
1873f22ef01cSRoman Divacky       }
1874f22ef01cSRoman Divacky     }
1875f22ef01cSRoman Divacky   }
18762cab237bSDimitry Andric }
1877f22ef01cSRoman Divacky 
visitMachineFunctionAfter()1878f22ef01cSRoman Divacky void MachineVerifier::visitMachineFunctionAfter() {
1879f22ef01cSRoman Divacky   calcRegsPassed();
1880f22ef01cSRoman Divacky 
18812cab237bSDimitry Andric   for (const MachineBasicBlock &MBB : *MF)
18822cab237bSDimitry Andric     checkPHIOps(MBB);
1883f22ef01cSRoman Divacky 
1884e580952dSDimitry Andric   // Now check liveness info if available
1885f22ef01cSRoman Divacky   calcRegsRequired();
1886dff0c46cSDimitry Andric 
18877ae0e2c9SDimitry Andric   // Check for killed virtual registers that should be live out.
188891bc56edSDimitry Andric   for (const auto &MBB : *MF) {
188991bc56edSDimitry Andric     BBInfo &MInfo = MBBInfoMap[&MBB];
18907ae0e2c9SDimitry Andric     for (RegSet::iterator
18917ae0e2c9SDimitry Andric          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
18927ae0e2c9SDimitry Andric          ++I)
18937ae0e2c9SDimitry Andric       if (MInfo.regsKilled.count(*I)) {
189491bc56edSDimitry Andric         report("Virtual register killed in block, but needed live out.", &MBB);
18952cab237bSDimitry Andric         errs() << "Virtual register " << printReg(*I)
18967ae0e2c9SDimitry Andric                << " is used after the block.\n";
18977ae0e2c9SDimitry Andric       }
18987ae0e2c9SDimitry Andric   }
18997ae0e2c9SDimitry Andric 
19007ae0e2c9SDimitry Andric   if (!MF->empty()) {
1901dff0c46cSDimitry Andric     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1902dff0c46cSDimitry Andric     for (RegSet::iterator
1903dff0c46cSDimitry Andric          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
19043ca95b02SDimitry Andric          ++I) {
19053ca95b02SDimitry Andric       report("Virtual register defs don't dominate all uses.", MF);
19063ca95b02SDimitry Andric       report_context_vreg(*I);
19073ca95b02SDimitry Andric     }
1908dff0c46cSDimitry Andric   }
1909dff0c46cSDimitry Andric 
1910e580952dSDimitry Andric   if (LiveVars)
1911f22ef01cSRoman Divacky     verifyLiveVariables();
1912e580952dSDimitry Andric   if (LiveInts)
1913e580952dSDimitry Andric     verifyLiveIntervals();
1914f22ef01cSRoman Divacky }
1915f22ef01cSRoman Divacky 
verifyLiveVariables()1916f22ef01cSRoman Divacky void MachineVerifier::verifyLiveVariables() {
1917f22ef01cSRoman Divacky   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
19182754fe60SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
19192754fe60SDimitry Andric     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1920f22ef01cSRoman Divacky     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
192191bc56edSDimitry Andric     for (const auto &MBB : *MF) {
192291bc56edSDimitry Andric       BBInfo &MInfo = MBBInfoMap[&MBB];
1923f22ef01cSRoman Divacky 
1924f22ef01cSRoman Divacky       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1925f22ef01cSRoman Divacky       if (MInfo.vregsRequired.count(Reg)) {
192691bc56edSDimitry Andric         if (!VI.AliveBlocks.test(MBB.getNumber())) {
192791bc56edSDimitry Andric           report("LiveVariables: Block missing from AliveBlocks", &MBB);
19282cab237bSDimitry Andric           errs() << "Virtual register " << printReg(Reg)
1929f22ef01cSRoman Divacky                  << " must be live through the block.\n";
1930f22ef01cSRoman Divacky         }
1931f22ef01cSRoman Divacky       } else {
193291bc56edSDimitry Andric         if (VI.AliveBlocks.test(MBB.getNumber())) {
193391bc56edSDimitry Andric           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
19342cab237bSDimitry Andric           errs() << "Virtual register " << printReg(Reg)
1935f22ef01cSRoman Divacky                  << " is not needed live through the block.\n";
1936f22ef01cSRoman Divacky         }
1937f22ef01cSRoman Divacky       }
1938f22ef01cSRoman Divacky     }
1939f22ef01cSRoman Divacky   }
1940f22ef01cSRoman Divacky }
1941f22ef01cSRoman Divacky 
verifyLiveIntervals()1942e580952dSDimitry Andric void MachineVerifier::verifyLiveIntervals() {
1943e580952dSDimitry Andric   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
19447ae0e2c9SDimitry Andric   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
19457ae0e2c9SDimitry Andric     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
19462754fe60SDimitry Andric 
19472754fe60SDimitry Andric     // Spilling and splitting may leave unused registers around. Skip them.
19487ae0e2c9SDimitry Andric     if (MRI->reg_nodbg_empty(Reg))
19492754fe60SDimitry Andric       continue;
19502754fe60SDimitry Andric 
19517ae0e2c9SDimitry Andric     if (!LiveInts->hasInterval(Reg)) {
19527ae0e2c9SDimitry Andric       report("Missing live interval for virtual register", MF);
19532cab237bSDimitry Andric       errs() << printReg(Reg, TRI) << " still has defs or uses\n";
19542754fe60SDimitry Andric       continue;
19557ae0e2c9SDimitry Andric     }
19562754fe60SDimitry Andric 
19577ae0e2c9SDimitry Andric     const LiveInterval &LI = LiveInts->getInterval(Reg);
19587ae0e2c9SDimitry Andric     assert(Reg == LI.reg && "Invalid reg to interval mapping");
19597ae0e2c9SDimitry Andric     verifyLiveInterval(LI);
19607ae0e2c9SDimitry Andric   }
1961e580952dSDimitry Andric 
19627ae0e2c9SDimitry Andric   // Verify all the cached regunit intervals.
19637ae0e2c9SDimitry Andric   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1964f785676fSDimitry Andric     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1965f785676fSDimitry Andric       verifyLiveRange(*LR, i);
19667ae0e2c9SDimitry Andric }
19677ae0e2c9SDimitry Andric 
verifyLiveRangeValue(const LiveRange & LR,const VNInfo * VNI,unsigned Reg,LaneBitmask LaneMask)1968f785676fSDimitry Andric void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
196939d628a0SDimitry Andric                                            const VNInfo *VNI, unsigned Reg,
19707d523365SDimitry Andric                                            LaneBitmask LaneMask) {
19717ae0e2c9SDimitry Andric   if (VNI->isUnused())
19727ae0e2c9SDimitry Andric     return;
19737ae0e2c9SDimitry Andric 
1974f785676fSDimitry Andric   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1975e580952dSDimitry Andric 
19762754fe60SDimitry Andric   if (!DefVNI) {
19777d523365SDimitry Andric     report("Value not live at VNInfo def and not marked unused", MF);
19787d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
19797d523365SDimitry Andric     report_context(*VNI);
19807ae0e2c9SDimitry Andric     return;
1981e580952dSDimitry Andric   }
1982e580952dSDimitry Andric 
19832754fe60SDimitry Andric   if (DefVNI != VNI) {
19847d523365SDimitry Andric     report("Live segment at def has different VNInfo", MF);
19857d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
19867d523365SDimitry Andric     report_context(*VNI);
19877ae0e2c9SDimitry Andric     return;
1988e580952dSDimitry Andric   }
1989e580952dSDimitry Andric 
19902754fe60SDimitry Andric   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
19912754fe60SDimitry Andric   if (!MBB) {
19927d523365SDimitry Andric     report("Invalid VNInfo definition index", MF);
19937d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
19947d523365SDimitry Andric     report_context(*VNI);
19957ae0e2c9SDimitry Andric     return;
19962754fe60SDimitry Andric   }
19972754fe60SDimitry Andric 
19982754fe60SDimitry Andric   if (VNI->isPHIDef()) {
19992754fe60SDimitry Andric     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
20007d523365SDimitry Andric       report("PHIDef VNInfo is not defined at MBB start", MBB);
20017d523365SDimitry Andric       report_context(LR, Reg, LaneMask);
20027d523365SDimitry Andric       report_context(*VNI);
20032754fe60SDimitry Andric     }
20047ae0e2c9SDimitry Andric     return;
20057ae0e2c9SDimitry Andric   }
20067ae0e2c9SDimitry Andric 
20072754fe60SDimitry Andric   // Non-PHI def.
20082754fe60SDimitry Andric   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
20092754fe60SDimitry Andric   if (!MI) {
20107d523365SDimitry Andric     report("No instruction at VNInfo def index", MBB);
20117d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
20127d523365SDimitry Andric     report_context(*VNI);
20137ae0e2c9SDimitry Andric     return;
20142754fe60SDimitry Andric   }
20152754fe60SDimitry Andric 
2016f785676fSDimitry Andric   if (Reg != 0) {
2017dff0c46cSDimitry Andric     bool hasDef = false;
20182754fe60SDimitry Andric     bool isEarlyClobber = false;
20193ca95b02SDimitry Andric     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
2020dff0c46cSDimitry Andric       if (!MOI->isReg() || !MOI->isDef())
2021dff0c46cSDimitry Andric         continue;
2022f785676fSDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2023f785676fSDimitry Andric         if (MOI->getReg() != Reg)
2024dff0c46cSDimitry Andric           continue;
2025dff0c46cSDimitry Andric       } else {
2026dff0c46cSDimitry Andric         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
2027f785676fSDimitry Andric             !TRI->hasRegUnit(MOI->getReg(), Reg))
2028dff0c46cSDimitry Andric           continue;
2029dff0c46cSDimitry Andric       }
2030d88c1a5aSDimitry Andric       if (LaneMask.any() &&
2031d88c1a5aSDimitry Andric           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
203239d628a0SDimitry Andric         continue;
2033dff0c46cSDimitry Andric       hasDef = true;
2034dff0c46cSDimitry Andric       if (MOI->isEarlyClobber())
20352754fe60SDimitry Andric         isEarlyClobber = true;
20362754fe60SDimitry Andric     }
2037dff0c46cSDimitry Andric 
2038dff0c46cSDimitry Andric     if (!hasDef) {
2039dff0c46cSDimitry Andric       report("Defining instruction does not modify register", MI);
20407d523365SDimitry Andric       report_context(LR, Reg, LaneMask);
20417d523365SDimitry Andric       report_context(*VNI);
20422754fe60SDimitry Andric     }
20432754fe60SDimitry Andric 
20442754fe60SDimitry Andric     // Early clobber defs begin at USE slots, but other defs must begin at
20452754fe60SDimitry Andric     // DEF slots.
20462754fe60SDimitry Andric     if (isEarlyClobber) {
2047dff0c46cSDimitry Andric       if (!VNI->def.isEarlyClobber()) {
20487d523365SDimitry Andric         report("Early clobber def must be at an early-clobber slot", MBB);
20497d523365SDimitry Andric         report_context(LR, Reg, LaneMask);
20507d523365SDimitry Andric         report_context(*VNI);
20512754fe60SDimitry Andric       }
2052dff0c46cSDimitry Andric     } else if (!VNI->def.isRegister()) {
20537d523365SDimitry Andric       report("Non-PHI, non-early clobber def must be at a register slot", MBB);
20547d523365SDimitry Andric       report_context(LR, Reg, LaneMask);
20557d523365SDimitry Andric       report_context(*VNI);
20562754fe60SDimitry Andric     }
2057e580952dSDimitry Andric   }
2058f785676fSDimitry Andric }
2059e580952dSDimitry Andric 
verifyLiveRangeSegment(const LiveRange & LR,const LiveRange::const_iterator I,unsigned Reg,LaneBitmask LaneMask)2060f785676fSDimitry Andric void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
2061f785676fSDimitry Andric                                              const LiveRange::const_iterator I,
20627d523365SDimitry Andric                                              unsigned Reg, LaneBitmask LaneMask)
20637d523365SDimitry Andric {
2064f785676fSDimitry Andric   const LiveRange::Segment &S = *I;
2065f785676fSDimitry Andric   const VNInfo *VNI = S.valno;
2066f785676fSDimitry Andric   assert(VNI && "Live segment has no valno");
2067e580952dSDimitry Andric 
2068f785676fSDimitry Andric   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
20697d523365SDimitry Andric     report("Foreign valno in live segment", MF);
20707d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
20717d523365SDimitry Andric     report_context(S);
20727d523365SDimitry Andric     report_context(*VNI);
2073e580952dSDimitry Andric   }
2074e580952dSDimitry Andric 
20752754fe60SDimitry Andric   if (VNI->isUnused()) {
20767d523365SDimitry Andric     report("Live segment valno is marked unused", MF);
20777d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
20787d523365SDimitry Andric     report_context(S);
2079e580952dSDimitry Andric   }
2080e580952dSDimitry Andric 
2081f785676fSDimitry Andric   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
20822754fe60SDimitry Andric   if (!MBB) {
20837d523365SDimitry Andric     report("Bad start of live segment, no basic block", MF);
20847d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
20857d523365SDimitry Andric     report_context(S);
20867ae0e2c9SDimitry Andric     return;
20872754fe60SDimitry Andric   }
20882754fe60SDimitry Andric   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
2089f785676fSDimitry Andric   if (S.start != MBBStartIdx && S.start != VNI->def) {
20907d523365SDimitry Andric     report("Live segment must begin at MBB entry or valno def", MBB);
20917d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
20927d523365SDimitry Andric     report_context(S);
20932754fe60SDimitry Andric   }
20942754fe60SDimitry Andric 
20952754fe60SDimitry Andric   const MachineBasicBlock *EndMBB =
2096f785676fSDimitry Andric     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
20972754fe60SDimitry Andric   if (!EndMBB) {
20987d523365SDimitry Andric     report("Bad end of live segment, no basic block", MF);
20997d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
21007d523365SDimitry Andric     report_context(S);
21017ae0e2c9SDimitry Andric     return;
21022754fe60SDimitry Andric   }
2103dff0c46cSDimitry Andric 
2104dff0c46cSDimitry Andric   // No more checks for live-out segments.
2105f785676fSDimitry Andric   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
21067ae0e2c9SDimitry Andric     return;
21077ae0e2c9SDimitry Andric 
21087ae0e2c9SDimitry Andric   // RegUnit intervals are allowed dead phis.
2109f785676fSDimitry Andric   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
2110f785676fSDimitry Andric       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
21117ae0e2c9SDimitry Andric     return;
2112dff0c46cSDimitry Andric 
21132754fe60SDimitry Andric   // The live segment is ending inside EndMBB
21142754fe60SDimitry Andric   const MachineInstr *MI =
2115f785676fSDimitry Andric     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
21162754fe60SDimitry Andric   if (!MI) {
21177d523365SDimitry Andric     report("Live segment doesn't end at a valid instruction", EndMBB);
21187d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
21197d523365SDimitry Andric     report_context(S);
21207ae0e2c9SDimitry Andric     return;
2121dff0c46cSDimitry Andric   }
2122dff0c46cSDimitry Andric 
2123dff0c46cSDimitry Andric   // The block slot must refer to a basic block boundary.
2124f785676fSDimitry Andric   if (S.end.isBlock()) {
21257d523365SDimitry Andric     report("Live segment ends at B slot of an instruction", EndMBB);
21267d523365SDimitry Andric     report_context(LR, Reg, LaneMask);
21277d523365SDimitry Andric     report_context(S);
2128dff0c46cSDimitry Andric   }
2129dff0c46cSDimitry Andric 
2130f785676fSDimitry Andric   if (S.end.isDead()) {
2131dff0c46cSDimitry Andric     // Segment ends on the dead slot.
2132dff0c46cSDimitry Andric     // That means there must be a dead def.
2133f785676fSDimitry Andric     if (!SlotIndex::isSameInstr(S.start, S.end)) {
21347d523365SDimitry Andric       report("Live segment ending at dead slot spans instructions", EndMBB);
21357d523365SDimitry Andric       report_context(LR, Reg, LaneMask);
21367d523365SDimitry Andric       report_context(S);
21372754fe60SDimitry Andric     }
21382754fe60SDimitry Andric   }
21392754fe60SDimitry Andric 
2140dff0c46cSDimitry Andric   // A live segment can only end at an early-clobber slot if it is being
2141dff0c46cSDimitry Andric   // redefined by an early-clobber def.
2142f785676fSDimitry Andric   if (S.end.isEarlyClobber()) {
2143f785676fSDimitry Andric     if (I+1 == LR.end() || (I+1)->start != S.end) {
2144dff0c46cSDimitry Andric       report("Live segment ending at early clobber slot must be "
21457d523365SDimitry Andric              "redefined by an EC def in the same instruction", EndMBB);
21467d523365SDimitry Andric       report_context(LR, Reg, LaneMask);
21477d523365SDimitry Andric       report_context(S);
2148dff0c46cSDimitry Andric     }
2149dff0c46cSDimitry Andric   }
2150dff0c46cSDimitry Andric 
2151dff0c46cSDimitry Andric   // The following checks only apply to virtual registers. Physreg liveness
2152dff0c46cSDimitry Andric   // is too weird to check.
2153f785676fSDimitry Andric   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2154f785676fSDimitry Andric     // A live segment can end with either a redefinition, a kill flag on a
2155dff0c46cSDimitry Andric     // use, or a dead flag on a def.
2156dff0c46cSDimitry Andric     bool hasRead = false;
215739d628a0SDimitry Andric     bool hasSubRegDef = false;
21583ca95b02SDimitry Andric     bool hasDeadDef = false;
21593ca95b02SDimitry Andric     for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
2160f785676fSDimitry Andric       if (!MOI->isReg() || MOI->getReg() != Reg)
2161dff0c46cSDimitry Andric         continue;
2162d88c1a5aSDimitry Andric       unsigned Sub = MOI->getSubReg();
2163d88c1a5aSDimitry Andric       LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
2164d88c1a5aSDimitry Andric                                  : LaneBitmask::getAll();
21653ca95b02SDimitry Andric       if (MOI->isDef()) {
2166d88c1a5aSDimitry Andric         if (Sub != 0) {
216739d628a0SDimitry Andric           hasSubRegDef = true;
21682cab237bSDimitry Andric           // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2169d88c1a5aSDimitry Andric           // mask for subregister defs. Read-undef defs will be handled by
2170d88c1a5aSDimitry Andric           // readsReg below.
2171d88c1a5aSDimitry Andric           SLM = ~SLM;
2172d88c1a5aSDimitry Andric         }
21733ca95b02SDimitry Andric         if (MOI->isDead())
21743ca95b02SDimitry Andric           hasDeadDef = true;
21753ca95b02SDimitry Andric       }
2176d88c1a5aSDimitry Andric       if (LaneMask.any() && (LaneMask & SLM).none())
2177d88c1a5aSDimitry Andric         continue;
2178dff0c46cSDimitry Andric       if (MOI->readsReg())
2179dff0c46cSDimitry Andric         hasRead = true;
2180dff0c46cSDimitry Andric     }
21813ca95b02SDimitry Andric     if (S.end.isDead()) {
21823ca95b02SDimitry Andric       // Make sure that the corresponding machine operand for a "dead" live
21833ca95b02SDimitry Andric       // range has the dead flag. We cannot perform this check for subregister
21843ca95b02SDimitry Andric       // liveranges as partially dead values are allowed.
2185d88c1a5aSDimitry Andric       if (LaneMask.none() && !hasDeadDef) {
21863ca95b02SDimitry Andric         report("Instruction ending live segment on dead slot has no dead flag",
21873ca95b02SDimitry Andric                MI);
21883ca95b02SDimitry Andric         report_context(LR, Reg, LaneMask);
21893ca95b02SDimitry Andric         report_context(S);
21903ca95b02SDimitry Andric       }
21913ca95b02SDimitry Andric     } else {
2192dff0c46cSDimitry Andric       if (!hasRead) {
219339d628a0SDimitry Andric         // When tracking subregister liveness, the main range must start new
219439d628a0SDimitry Andric         // values on partial register writes, even if there is no read.
2195d88c1a5aSDimitry Andric         if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
2196ff0cc061SDimitry Andric             !hasSubRegDef) {
219739d628a0SDimitry Andric           report("Instruction ending live segment doesn't read the register",
219839d628a0SDimitry Andric                  MI);
21997d523365SDimitry Andric           report_context(LR, Reg, LaneMask);
22007d523365SDimitry Andric           report_context(S);
22012754fe60SDimitry Andric         }
22022754fe60SDimitry Andric       }
22032754fe60SDimitry Andric     }
220439d628a0SDimitry Andric   }
22052754fe60SDimitry Andric 
22062754fe60SDimitry Andric   // Now check all the basic blocks in this live segment.
22077d523365SDimitry Andric   MachineFunction::const_iterator MFI = MBB->getIterator();
2208f785676fSDimitry Andric   // Is this live segment the beginning of a non-PHIDef VN?
2209f785676fSDimitry Andric   if (S.start == VNI->def && !VNI->isPHIDef()) {
22102754fe60SDimitry Andric     // Not live-in to any blocks.
22112754fe60SDimitry Andric     if (MBB == EndMBB)
22127ae0e2c9SDimitry Andric       return;
22132754fe60SDimitry Andric     // Skip this block.
22142754fe60SDimitry Andric     ++MFI;
22152754fe60SDimitry Andric   }
2216*b5893f02SDimitry Andric 
2217*b5893f02SDimitry Andric   SmallVector<SlotIndex, 4> Undefs;
2218*b5893f02SDimitry Andric   if (LaneMask.any()) {
2219*b5893f02SDimitry Andric     LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
2220*b5893f02SDimitry Andric     OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
2221*b5893f02SDimitry Andric   }
2222*b5893f02SDimitry Andric 
22232cab237bSDimitry Andric   while (true) {
22247d523365SDimitry Andric     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
22252754fe60SDimitry Andric     // We don't know how to track physregs into a landing pad.
2226f785676fSDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
22277d523365SDimitry Andric         MFI->isEHPad()) {
22282754fe60SDimitry Andric       if (&*MFI == EndMBB)
22292754fe60SDimitry Andric         break;
22302754fe60SDimitry Andric       ++MFI;
22312754fe60SDimitry Andric       continue;
22322754fe60SDimitry Andric     }
22337ae0e2c9SDimitry Andric 
22347ae0e2c9SDimitry Andric     // Is VNI a PHI-def in the current block?
22357ae0e2c9SDimitry Andric     bool IsPHI = VNI->isPHIDef() &&
22367d523365SDimitry Andric       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
22377ae0e2c9SDimitry Andric 
22382754fe60SDimitry Andric     // Check that VNI is live-out of all predecessors.
22392754fe60SDimitry Andric     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
22402754fe60SDimitry Andric          PE = MFI->pred_end(); PI != PE; ++PI) {
2241dff0c46cSDimitry Andric       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
2242f785676fSDimitry Andric       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
22432754fe60SDimitry Andric 
2244db17bf38SDimitry Andric       // All predecessors must have a live-out value. However for a phi
2245db17bf38SDimitry Andric       // instruction with subregister intervals
2246db17bf38SDimitry Andric       // only one of the subregisters (not necessarily the current one) needs to
2247db17bf38SDimitry Andric       // be defined.
2248db17bf38SDimitry Andric       if (!PVNI && (LaneMask.none() || !IsPHI)) {
2249*b5893f02SDimitry Andric         if (LiveRangeCalc::isJointlyDominated(*PI, Undefs, *Indexes))
2250*b5893f02SDimitry Andric           continue;
22517d523365SDimitry Andric         report("Register not marked live out of predecessor", *PI);
22527d523365SDimitry Andric         report_context(LR, Reg, LaneMask);
22537d523365SDimitry Andric         report_context(*VNI);
22542cab237bSDimitry Andric         errs() << " live into " << printMBBReference(*MFI) << '@'
22552cab237bSDimitry Andric                << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
22567ae0e2c9SDimitry Andric                << PEnd << '\n';
22572754fe60SDimitry Andric         continue;
22582754fe60SDimitry Andric       }
22592754fe60SDimitry Andric 
22607ae0e2c9SDimitry Andric       // Only PHI-defs can take different predecessor values.
22617ae0e2c9SDimitry Andric       if (!IsPHI && PVNI != VNI) {
22627d523365SDimitry Andric         report("Different value live out of predecessor", *PI);
22637d523365SDimitry Andric         report_context(LR, Reg, LaneMask);
22642cab237bSDimitry Andric         errs() << "Valno #" << PVNI->id << " live out of "
22652cab237bSDimitry Andric                << printMBBReference(*(*PI)) << '@' << PEnd << "\nValno #"
22662cab237bSDimitry Andric                << VNI->id << " live into " << printMBBReference(*MFI) << '@'
22677d523365SDimitry Andric                << LiveInts->getMBBStartIdx(&*MFI) << '\n';
22682754fe60SDimitry Andric       }
22692754fe60SDimitry Andric     }
22702754fe60SDimitry Andric     if (&*MFI == EndMBB)
22712754fe60SDimitry Andric       break;
22722754fe60SDimitry Andric     ++MFI;
22732754fe60SDimitry Andric   }
22742754fe60SDimitry Andric }
22752754fe60SDimitry Andric 
verifyLiveRange(const LiveRange & LR,unsigned Reg,LaneBitmask LaneMask)227639d628a0SDimitry Andric void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
22777d523365SDimitry Andric                                       LaneBitmask LaneMask) {
227839d628a0SDimitry Andric   for (const VNInfo *VNI : LR.valnos)
227939d628a0SDimitry Andric     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
22807ae0e2c9SDimitry Andric 
2281f785676fSDimitry Andric   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
228239d628a0SDimitry Andric     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
2283f785676fSDimitry Andric }
2284f785676fSDimitry Andric 
verifyLiveInterval(const LiveInterval & LI)2285f785676fSDimitry Andric void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
228639d628a0SDimitry Andric   unsigned Reg = LI.reg;
2287ff0cc061SDimitry Andric   assert(TargetRegisterInfo::isVirtualRegister(Reg));
2288ff0cc061SDimitry Andric   verifyLiveRange(LI, Reg);
2289ff0cc061SDimitry Andric 
2290d88c1a5aSDimitry Andric   LaneBitmask Mask;
22917d523365SDimitry Andric   LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
229239d628a0SDimitry Andric   for (const LiveInterval::SubRange &SR : LI.subranges()) {
2293d88c1a5aSDimitry Andric     if ((Mask & SR.LaneMask).any()) {
22947d523365SDimitry Andric       report("Lane masks of sub ranges overlap in live interval", MF);
22957d523365SDimitry Andric       report_context(LI);
22967d523365SDimitry Andric     }
2297d88c1a5aSDimitry Andric     if ((SR.LaneMask & ~MaxMask).any()) {
22987d523365SDimitry Andric       report("Subrange lanemask is invalid", MF);
22997d523365SDimitry Andric       report_context(LI);
23007d523365SDimitry Andric     }
23017d523365SDimitry Andric     if (SR.empty()) {
23027d523365SDimitry Andric       report("Subrange must not be empty", MF);
23037d523365SDimitry Andric       report_context(SR, LI.reg, SR.LaneMask);
23047d523365SDimitry Andric     }
230539d628a0SDimitry Andric     Mask |= SR.LaneMask;
230639d628a0SDimitry Andric     verifyLiveRange(SR, LI.reg, SR.LaneMask);
23077d523365SDimitry Andric     if (!LI.covers(SR)) {
23087d523365SDimitry Andric       report("A Subrange is not covered by the main range", MF);
23097d523365SDimitry Andric       report_context(LI);
23107d523365SDimitry Andric     }
231139d628a0SDimitry Andric   }
231239d628a0SDimitry Andric 
23132754fe60SDimitry Andric   // Check the LI only has one connected component.
23142754fe60SDimitry Andric   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
2315444ed5c5SDimitry Andric   unsigned NumComp = ConEQ.Classify(LI);
23162754fe60SDimitry Andric   if (NumComp > 1) {
23177d523365SDimitry Andric     report("Multiple connected components in live interval", MF);
23187d523365SDimitry Andric     report_context(LI);
23192754fe60SDimitry Andric     for (unsigned comp = 0; comp != NumComp; ++comp) {
2320ff0cc061SDimitry Andric       errs() << comp << ": valnos";
23212754fe60SDimitry Andric       for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
23222754fe60SDimitry Andric            E = LI.vni_end(); I!=E; ++I)
23232754fe60SDimitry Andric         if (comp == ConEQ.getEqClass(*I))
2324ff0cc061SDimitry Andric           errs() << ' ' << (*I)->id;
2325ff0cc061SDimitry Andric       errs() << '\n';
23262754fe60SDimitry Andric     }
2327e580952dSDimitry Andric   }
2328e580952dSDimitry Andric }
2329f785676fSDimitry Andric 
2330f785676fSDimitry Andric namespace {
23312cab237bSDimitry Andric 
2332f785676fSDimitry Andric   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2333f785676fSDimitry Andric   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2334f785676fSDimitry Andric   // value is zero.
2335f785676fSDimitry Andric   // We use a bool plus an integer to capture the stack state.
2336f785676fSDimitry Andric   struct StackStateOfBB {
23372cab237bSDimitry Andric     StackStateOfBB() = default;
StackStateOfBB__anon68d9c28a0411::StackStateOfBB2338f785676fSDimitry Andric     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
2339f785676fSDimitry Andric       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
2340f785676fSDimitry Andric       ExitIsSetup(ExitSetup) {}
23412cab237bSDimitry Andric 
2342f785676fSDimitry Andric     // Can be negative, which means we are setting up a frame.
23432cab237bSDimitry Andric     int EntryValue = 0;
23442cab237bSDimitry Andric     int ExitValue = 0;
23452cab237bSDimitry Andric     bool EntryIsSetup = false;
23462cab237bSDimitry Andric     bool ExitIsSetup = false;
2347f785676fSDimitry Andric   };
23482cab237bSDimitry Andric 
23492cab237bSDimitry Andric } // end anonymous namespace
2350f785676fSDimitry Andric 
2351f785676fSDimitry Andric /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2352f785676fSDimitry Andric /// by a FrameDestroy <n>, stack adjustments are identical on all
2353f785676fSDimitry Andric /// CFG edges to a merge point, and frame is destroyed at end of a return block.
verifyStackFrame()2354f785676fSDimitry Andric void MachineVerifier::verifyStackFrame() {
2355ff0cc061SDimitry Andric   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
2356ff0cc061SDimitry Andric   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
23576bc11b14SDimitry Andric   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
23586bc11b14SDimitry Andric     return;
2359f785676fSDimitry Andric 
2360f785676fSDimitry Andric   SmallVector<StackStateOfBB, 8> SPState;
2361f785676fSDimitry Andric   SPState.resize(MF->getNumBlockIDs());
2362d88c1a5aSDimitry Andric   df_iterator_default_set<const MachineBasicBlock*> Reachable;
2363f785676fSDimitry Andric 
2364f785676fSDimitry Andric   // Visit the MBBs in DFS order.
2365f785676fSDimitry Andric   for (df_ext_iterator<const MachineFunction *,
2366d88c1a5aSDimitry Andric                        df_iterator_default_set<const MachineBasicBlock *>>
2367f785676fSDimitry Andric        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
2368f785676fSDimitry Andric        DFI != DFE; ++DFI) {
2369f785676fSDimitry Andric     const MachineBasicBlock *MBB = *DFI;
2370f785676fSDimitry Andric 
2371f785676fSDimitry Andric     StackStateOfBB BBState;
2372f785676fSDimitry Andric     // Check the exit state of the DFS stack predecessor.
2373f785676fSDimitry Andric     if (DFI.getPathLength() >= 2) {
2374f785676fSDimitry Andric       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
2375f785676fSDimitry Andric       assert(Reachable.count(StackPred) &&
2376f785676fSDimitry Andric              "DFS stack predecessor is already visited.\n");
2377f785676fSDimitry Andric       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
2378f785676fSDimitry Andric       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
2379f785676fSDimitry Andric       BBState.ExitValue = BBState.EntryValue;
2380f785676fSDimitry Andric       BBState.ExitIsSetup = BBState.EntryIsSetup;
2381f785676fSDimitry Andric     }
2382f785676fSDimitry Andric 
2383f785676fSDimitry Andric     // Update stack state by checking contents of MBB.
238491bc56edSDimitry Andric     for (const auto &I : *MBB) {
238591bc56edSDimitry Andric       if (I.getOpcode() == FrameSetupOpcode) {
2386f785676fSDimitry Andric         if (BBState.ExitIsSetup)
238791bc56edSDimitry Andric           report("FrameSetup is after another FrameSetup", &I);
23885517e702SDimitry Andric         BBState.ExitValue -= TII->getFrameTotalSize(I);
2389f785676fSDimitry Andric         BBState.ExitIsSetup = true;
2390f785676fSDimitry Andric       }
2391f785676fSDimitry Andric 
239291bc56edSDimitry Andric       if (I.getOpcode() == FrameDestroyOpcode) {
23935517e702SDimitry Andric         int Size = TII->getFrameTotalSize(I);
2394f785676fSDimitry Andric         if (!BBState.ExitIsSetup)
239591bc56edSDimitry Andric           report("FrameDestroy is not after a FrameSetup", &I);
2396f785676fSDimitry Andric         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
2397f785676fSDimitry Andric                                                BBState.ExitValue;
2398f785676fSDimitry Andric         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
239991bc56edSDimitry Andric           report("FrameDestroy <n> is after FrameSetup <m>", &I);
2400ff0cc061SDimitry Andric           errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
2401f785676fSDimitry Andric               << AbsSPAdj << ">.\n";
2402f785676fSDimitry Andric         }
2403f785676fSDimitry Andric         BBState.ExitValue += Size;
2404f785676fSDimitry Andric         BBState.ExitIsSetup = false;
2405f785676fSDimitry Andric       }
2406f785676fSDimitry Andric     }
2407f785676fSDimitry Andric     SPState[MBB->getNumber()] = BBState;
2408f785676fSDimitry Andric 
2409f785676fSDimitry Andric     // Make sure the exit state of any predecessor is consistent with the entry
2410f785676fSDimitry Andric     // state.
2411f785676fSDimitry Andric     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
2412f785676fSDimitry Andric          E = MBB->pred_end(); I != E; ++I) {
2413f785676fSDimitry Andric       if (Reachable.count(*I) &&
2414f785676fSDimitry Andric           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
2415f785676fSDimitry Andric            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
2416f785676fSDimitry Andric         report("The exit stack state of a predecessor is inconsistent.", MBB);
24172cab237bSDimitry Andric         errs() << "Predecessor " << printMBBReference(*(*I))
24182cab237bSDimitry Andric                << " has exit state (" << SPState[(*I)->getNumber()].ExitValue
24192cab237bSDimitry Andric                << ", " << SPState[(*I)->getNumber()].ExitIsSetup << "), while "
24202cab237bSDimitry Andric                << printMBBReference(*MBB) << " has entry state ("
2421f785676fSDimitry Andric                << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
2422f785676fSDimitry Andric       }
2423f785676fSDimitry Andric     }
2424f785676fSDimitry Andric 
2425f785676fSDimitry Andric     // Make sure the entry state of any successor is consistent with the exit
2426f785676fSDimitry Andric     // state.
2427f785676fSDimitry Andric     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
2428f785676fSDimitry Andric          E = MBB->succ_end(); I != E; ++I) {
2429f785676fSDimitry Andric       if (Reachable.count(*I) &&
2430f785676fSDimitry Andric           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
2431f785676fSDimitry Andric            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
2432f785676fSDimitry Andric         report("The entry stack state of a successor is inconsistent.", MBB);
24332cab237bSDimitry Andric         errs() << "Successor " << printMBBReference(*(*I))
24342cab237bSDimitry Andric                << " has entry state (" << SPState[(*I)->getNumber()].EntryValue
24352cab237bSDimitry Andric                << ", " << SPState[(*I)->getNumber()].EntryIsSetup << "), while "
24362cab237bSDimitry Andric                << printMBBReference(*MBB) << " has exit state ("
2437f785676fSDimitry Andric                << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
2438f785676fSDimitry Andric       }
2439f785676fSDimitry Andric     }
2440f785676fSDimitry Andric 
2441f785676fSDimitry Andric     // Make sure a basic block with return ends with zero stack adjustment.
2442f785676fSDimitry Andric     if (!MBB->empty() && MBB->back().isReturn()) {
2443f785676fSDimitry Andric       if (BBState.ExitIsSetup)
2444f785676fSDimitry Andric         report("A return block ends with a FrameSetup.", MBB);
2445f785676fSDimitry Andric       if (BBState.ExitValue)
2446f785676fSDimitry Andric         report("A return block ends with a nonzero stack adjustment.", MBB);
2447f785676fSDimitry Andric     }
2448f785676fSDimitry Andric   }
2449f785676fSDimitry Andric }
2450