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