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