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